Repository Public
1"use client";2import Link from "next/link";3import { useRouter, useSearchParams } from "next/navigation";4import { useEffect, useMemo, useState } from "react";5import { Icon } from "@/components/ui/Icon";6import { LEVEL_LABEL } from "@/lib/labels";7import { formatTime } from "@/modules/content-schema/urls";8import { DOC_TYPES, DOC_TYPE_LABELS, DOC_TYPE_SINGULAR, createEngine, highlight, snippet, type DocType, type Engine, type Filters, type SearchDoc } from "@/modules/search";910type Load = { state: "chargement" } | { state: "erreur" } | { state: "pret"; engine: Engine };11interface Opt { id: string; label: string }1213function Marked({ text, terms }: { text: string; terms: string[] }) {14 return <>{highlight(text, terms).map((f, i) => (f.hit ? <mark key={i}>{f.text}</mark> : <span key={i}>{f.text}</span>))}</>;15}1617export function SearchClient({ parts, sessions, suggestions }: { parts: Opt[]; sessions: Opt[]; suggestions: string[] }) {18 const params = useSearchParams(), router = useRouter();19 const [load, setLoad] = useState<Load>({ state: "chargement" });20 const [attempt, setAttempt] = useState(0);21 const [q, setQ] = useState(params.get("q") ?? "");22 const [filters, setFilters] = useState<Filters>({});2324 useEffect(() => {25 let cancelled = false;26 fetch("/recherche/index.json").then((r) => { if (!r.ok) throw new Error(String(r.status)); return r.json() as Promise<{ docs: SearchDoc[] }>; })27 .then((data) => { if (!cancelled) setLoad({ state: "pret", engine: createEngine(data.docs) }); })28 .catch(() => { if (!cancelled) setLoad({ state: "erreur" }); });29 return () => { cancelled = true; };30 }, [attempt]);3132 // Keep the address shareable (?q=…) without adding a history entry per keystroke.33 useEffect(() => {34 const id = window.setTimeout(() => { const next = q.trim() ? `/recherche?q=${encodeURIComponent(q.trim())}` : "/recherche"; if (next !== `${window.location.pathname}${window.location.search}`) router.replace(next, { scroll: false }); }, 350);35 return () => window.clearTimeout(id);36 }, [q, router]);3738 const result = useMemo(() => (load.state === "pret" ? load.engine.search(q, filters) : null), [load, q, filters]);39 const set = (patch: Filters) => setFilters((f) => { const n = { ...f, ...patch }; for (const k of Object.keys(n) as (keyof Filters)[]) if (!n[k]) delete n[k]; return n; });40 const hasFilter = Object.keys(filters).length > 0;41 const label = (opts: Opt[], id: string) => opts.find((o) => o.id === id)?.label ?? id;4243 return (44 <div className="grid gap-8 lg:grid-cols-[17rem_1fr]" data-testid="search" data-state={load.state}>45 <div className="lg:col-span-2">46 <form role="search" onSubmit={(e) => e.preventDefault()}>47 <label htmlFor="q" className="sr-only">Rechercher dans le cours</label>48 <div className="relative max-w-3xl">49 <Icon name="search" size={22} className="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-faint" />50 <input id="q" type="search" autoComplete="off" spellCheck={false} className="field !min-h-14 !rounded-2xl !pl-12 text-[1.15rem]" placeholder="fenêtre de contexte, agent, jeton…" value={q} onChange={(e) => setQ(e.target.value)} data-testid="search-input" />51 </div>52 </form>53 {load.state === "erreur" && (54 <div role="alert" className="mt-5 flex flex-wrap items-center gap-3 rounded-2xl border border-coral bg-coral-soft p-4" data-testid="search-error">55 <p className="grow">L’index de recherche n’a pas pu être chargé. Vérifiez votre connexion.</p>56 <button type="button" className="btn btn-ghost btn-sm" onClick={() => { setLoad({ state: "chargement" }); setAttempt((n) => n + 1); }}><Icon name="retry" size={16} />Réessayer</button>57 </div>58 )}59 </div>6061 <aside aria-label="Filtres" className="space-y-5">62 <fieldset disabled={!result || !result.terms.length}>63 <legend className="eyebrow">Type de contenu</legend>64 <ul className="mt-2 grid gap-1">65 {DOC_TYPES.filter((t) => result?.facets.type[t]).map((t) => (66 <li key={t}><button type="button" aria-pressed={filters.type === t} onClick={() => set({ type: filters.type === t ? undefined : (t as DocType) })} className="flex w-full items-center justify-between rounded-lg px-2.5 py-1.5 text-left text-[0.95rem] hover:bg-panel aria-pressed:bg-blue-soft aria-pressed:font-medium" data-facet={t}><span>{DOC_TYPE_LABELS[t]}</span><span className="font-mono text-sm text-faint">{result?.facets.type[t]}</span></button></li>67 ))}68 {(!result || !Object.keys(result.facets.type).length) && <li className="px-2.5 text-sm text-faint">Les filtres apparaissent avec les résultats.</li>}69 </ul>70 </fieldset>71 {result && Object.keys(result.facets.part).length > 0 && (72 <label className="grid gap-1 text-sm font-medium">Partie73 <select className="field" value={filters.part ?? ""} onChange={(e) => set({ part: e.target.value || undefined })}><option value="">Toutes ({Object.values(result.facets.part).reduce((a, b) => a + b, 0)})</option>{parts.filter((p) => result.facets.part[p.id]).map((p) => <option key={p.id} value={p.id}>{p.label} ({result.facets.part[p.id]})</option>)}</select>74 </label>75 )}76 {result && Object.keys(result.facets.session).length > 0 && (77 <label className="grid gap-1 text-sm font-medium">Séance78 <select className="field" value={filters.session ?? ""} onChange={(e) => set({ session: e.target.value || undefined })}><option value="">Toutes</option>{sessions.filter((s) => result.facets.session[s.id]).map((s) => <option key={s.id} value={s.id}>{s.label} ({result.facets.session[s.id]})</option>)}</select>79 </label>80 )}81 {result && Object.keys(result.facets.level).length > 0 && (82 <label className="grid gap-1 text-sm font-medium">Niveau83 <select className="field" value={filters.level ?? ""} onChange={(e) => set({ level: e.target.value || undefined })}><option value="">Tous</option>{Object.keys(LEVEL_LABEL).filter((l) => result.facets.level[l]).map((l) => <option key={l} value={l}>{LEVEL_LABEL[l as keyof typeof LEVEL_LABEL]} ({result.facets.level[l]})</option>)}</select>84 </label>85 )}86 {hasFilter && <button type="button" className="btn btn-ghost btn-sm" onClick={() => setFilters({})}>Retirer les filtres</button>}87 </aside>8889 <section aria-label="Résultats" aria-busy={load.state === "chargement"}>90 <p role="status" aria-live="polite" className="text-sm text-muted" data-testid="search-status">91 {load.state === "chargement" ? "Chargement de l’index…" : !result || !result.terms.length ? "Tapez un ou plusieurs mots." : `${result.hits.length} résultat${result.hits.length > 1 ? "s" : ""}${hasFilter ? ` (filtres : ${[filters.type && DOC_TYPE_LABELS[filters.type], filters.part && label(parts, filters.part), filters.session && label(sessions, filters.session), filters.level].filter(Boolean).join(", ")})` : ""}`}92 </p>9394 {result && !result.terms.length && (95 <div className="mt-5">96 <p className="font-medium">Quelques thèmes du cours</p>97 <ul className="mt-3 flex flex-wrap gap-2">{suggestions.map((s) => <li key={s}><button type="button" className="chip hover:border-line-strong" onClick={() => setQ(s)}>{s}</button></li>)}</ul>98 </div>99 )}100101 {result && result.terms.length > 0 && result.hits.length === 0 && (102 <div className="card mt-5 p-7" data-testid="search-empty">103 <p className="font-display text-xl">Aucun résultat pour « {q} ».</p>104 <p className="mt-2 text-muted">Seul le matériel déjà publié est indexé, avec le plan des séances à venir. Essayez un terme plus général{hasFilter ? ", ou retirez les filtres" : ""}.</p>105 </div>106 )}107108 <ol className="mt-4 divide-y divide-line border-y border-line empty:hidden">109 {result?.hits.map(({ doc }) => (110 <li key={doc.id} className="py-4" data-testid="search-hit" data-type={doc.type}>111 <p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-faint"><span className="chip">{DOC_TYPE_SINGULAR[doc.type]}</span>{doc.context && <span>{doc.context}</span>}{doc.t !== undefined && <span className="inline-flex items-center gap-1 font-mono text-blue"><Icon name="play" size={12} />{formatTime(doc.t)}</span>}</p>112 <h2 className="mt-1.5 font-display text-[1.2rem]"><Link href={doc.url} className="hover:underline"><Marked text={doc.title} terms={result.terms} /></Link></h2>113 {doc.text && <p className="mt-1 text-[0.97rem] text-muted"><Marked text={snippet(doc.text, result.terms)} terms={result.terms} /></p>}114 </li>115 ))}116 </ol>117 </section>118 </div>119 );120}121