Repository Public
1"use client";2import { Suspense, useCallback, useEffect, useRef, useState } from "react";3import { useRouter, useSearchParams } from "next/navigation";4import { X } from "lucide-react";5import { api, cn, langLabel, useApi, type Title } from "@/lib/client";6import { Empty, PageHeader, Sentinel, TitleCard, inputCls } from "@/components/ui";78const KEYS = ["q", "kind", "genre", "language", "source", "rights", "doc", "animation", "library", "shorts", "from", "to", "sort", "fav"] as const;9type F = Record<(typeof KEYS)[number], string>;10interface Res { total: number; items: Title[]; tookMs: number }11interface Facets { genres: { id: string; count: number }[]; languages: { id: string; count: number }[]; sources: { id: string; count: number }[]; years: [number, number] | null }12const PAGE = 60;1314function Catalogue() {15 const sp = useSearchParams(); const router = useRouter();16 const [f, setF] = useState<F>(() => Object.fromEntries(KEYS.map((k) => [k, sp.get(k) ?? ""])) as F);17 const { data: facets } = useApi<Facets>(`/titles/facets${f.kind ? `?kind=${f.kind}` : ""}`);18 const [res, setRes] = useState<Res | null>(null); const [more, setMore] = useState(false); const seq = useRef(0);19 const query = new URLSearchParams(Object.entries(f).filter(([, v]) => v)).toString();20 useEffect(() => {21 const my = ++seq.current; router.replace(query ? `/catalogue?${query}` : "/catalogue", { scroll: false });22 api<Res>(`/titles?${query}&limit=${PAGE}`).then((r) => { if (my === seq.current) setRes(r); }).catch(() => {});23 }, [query]); // eslint-disable-line react-hooks/exhaustive-deps24 const loadMore = useCallback(async () => {25 if (!res || more || res.items.length >= res.total) return; const my = seq.current; setMore(true);26 try { const r = await api<Res>(`/titles?${query}&limit=${PAGE}&offset=${res.items.length}`); if (my === seq.current) setRes((p) => (p ? { ...p, items: [...p.items, ...r.items] } : p)); } finally { setMore(false); }27 }, [res, more, query]);28 const set = (k: keyof F, v: string) => setF((p) => ({ ...p, [k]: v }));29 const sel = cn(inputCls, "w-44 shrink-0");30 const chip = (k: keyof F, on: string, label: string) => <button key={k + on} type="button" aria-pressed={f[k] === on} onClick={() => set(k, f[k] === on ? "" : on)} className={cn("h-11 shrink-0 rounded-xl px-3.5 text-sm font-medium ring-1 ring-line", f[k] === on ? "bg-white text-black" : "bg-raised text-dim hover:text-ink")}>{label}</button>;31 const decades = facets?.years ? Array.from({ length: Math.floor(facets.years[1] / 10) - Math.floor(facets.years[0] / 10) + 1 }, (_, i) => Math.floor(facets.years![1] / 10) * 10 - i * 10) : [];32 const heading = f.library ? "Ma bibliothèque" : f.doc ? "Documentaires" : f.kind === "series" ? "Séries" : f.kind === "movie" ? "Films" : "Catalogue";33 return (34 <div>35 <PageHeader title={heading} sub={res ? `${res.total.toLocaleString("fr-CA")} titre${res.total > 1 ? "s" : ""} · tous ont une source vidéo vérifiée à l'import` : "Chargement…"} />36 <div className="sticky top-14 z-20 space-y-2 bg-bg/90 px-4 pb-3 pt-2 backdrop-blur lg:top-0 lg:px-8">37 <input data-nav type="search" value={f.q} onChange={(e) => set("q", e.target.value)} placeholder="Titre, réalisateur, interprète…" aria-label="Rechercher dans le catalogue" className={cn(inputCls, "h-12 text-base")} />38 <div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4 lg:mx-0 lg:flex-wrap lg:px-0">39 <select aria-label="Type" value={f.kind} onChange={(e) => set("kind", e.target.value)} className={sel}><option value="">Films et séries</option><option value="movie">Films</option><option value="series">Séries</option></select>40 <select aria-label="Genre" value={f.genre} onChange={(e) => set("genre", e.target.value)} className={sel}><option value="">Tous les genres</option>{facets?.genres.map((g) => <option key={g.id} value={g.id}>{g.id} ({g.count})</option>)}</select>41 <select aria-label="Décennie" value={f.from} onChange={(e) => setF((p) => ({ ...p, from: e.target.value, to: e.target.value ? String(Number(e.target.value) + 9) : "" }))} className={sel}><option value="">Toutes les années</option>{decades.map((d) => <option key={d} value={d}>Années {d}</option>)}</select>42 <select aria-label="Langue" value={f.language} onChange={(e) => set("language", e.target.value)} className={sel}><option value="">Toutes les langues</option>{facets?.languages.map((l) => <option key={l.id} value={l.id}>{langLabel(l.id)} ({l.count})</option>)}</select>43 <select aria-label="Source" value={f.source} onChange={(e) => set("source", e.target.value)} className={sel}><option value="">Toutes les sources</option>{facets?.sources.map((s) => <option key={s.id} value={s.id}>{s.id} ({s.count})</option>)}</select>44 <select aria-label="Tri" value={f.sort} onChange={(e) => set("sort", e.target.value)} className={sel}><option value="">Tri : titre</option><option value="recent">Ajouts récents</option><option value="year">Année (récent d'abord)</option><option value="popular">Les plus regardés ici</option></select>45 {chip("shorts", "exclude", "Longs métrages")}{chip("shorts", "only", "Courts métrages")}{chip("doc", "1", "Documentaires")}{chip("animation", "1", "Animation")}{chip("library", "1", "Ma bibliothèque")}{chip("fav", "1", "Ma liste")}46 {Object.values(f).some(Boolean) && <button type="button" onClick={() => setF(Object.fromEntries(KEYS.map((k) => [k, ""])) as F)} className="flex h-11 shrink-0 items-center gap-1 rounded-xl px-3 text-sm font-medium text-dim hover:text-ink"><X className="h-4 w-4" />Effacer</button>}47 </div>48 </div>49 {res && !res.items.length && <Empty title="Aucun titre ne correspond">Modifiez la recherche ou retirez un filtre.</Empty>}50 <div className="grid grid-cols-3 gap-x-3 gap-y-5 px-4 pt-2 sm:grid-cols-4 md:grid-cols-5 lg:gap-x-4 lg:px-8 xl:grid-cols-6 2xl:grid-cols-8">51 {res?.items.map((t) => <TitleCard key={t.id} title={t} />)}52 {!res && Array.from({ length: 18 }, (_, i) => <div key={i} className="skeleton aspect-[2/3] rounded-2xl" />)}53 </div>54 <Sentinel onVisible={loadMore} disabled={!res || res.items.length >= res.total} />55 </div>56 );57}58export default function Page() { return <Suspense><Catalogue /></Suspense>; }59