SPB Git

Repository Public

page.tsx 8.8 KB 76 lines tsx

1"use client";2import { Suspense, useEffect, useRef, useState } from "react";3import Link from "next/link";4import { useRouter, useSearchParams } from "next/navigation";5import { Play, Search } from "lucide-react";6import { api, cn, countryName, flag, langLabel, useApi, useDebounced, type Channel, type Title } from "@/lib/client";7import { ChannelCard, Empty, Poster, TitleCard, inputCls } from "@/components/ui";8import { useVod } from "@/components/vod-player";910interface Ep { mediaId: number; titleId: number; series: string; poster: string | null; season: number; episode: number; name: string }11interface Res { q: string; channels: { total: number; items: Channel[] }; movies: { total: number; items: Title[] }; series: { total: number; items: Title[] }; docs: { total: number; items: Title[] }; library: { total: number; items: Title[] }; episodes: Ep[]; tookMs: number;12  facets: { genres: { id: string; count: number }[]; languages: { id: string; count: number }[]; sources: { id: string; count: number }[]; years: [number, number] | null } }13const TYPES = [["", "Tout"], ["channel", "Chaînes TV"], ["movie", "Films"], ["series", "Séries"], ["episode", "Épisodes"], ["doc", "Documentaires"], ["library", "Ma bibliothèque"]] as const;14const KEYS = ["q", "type", "genre", "from", "language", "country", "status", "source"] as const;15type F = Record<(typeof KEYS)[number], string>;1617function SearchPage() {18  const sp = useSearchParams(); const router = useRouter(); const { playMedia } = useVod();19  const [f, setF] = useState<F>(() => Object.fromEntries(KEYS.map((k) => [k, sp.get(k) ?? ""])) as F);20  const q = useDebounced(f.q, 160);21  const { data: meta } = useApi<{ countries: { code: string; name: string; count: number }[] }>("/meta");22  const [res, setRes] = useState<Res | null>(null); const seq = useRef(0); const input = useRef<HTMLInputElement>(null);23  const params = new URLSearchParams(Object.entries({ ...f, q, to: f.from ? String(Number(f.from) + 9) : "" }).filter(([, v]) => v)).toString();24  useEffect(() => { input.current?.focus(); }, []);25  useEffect(() => {26    const my = ++seq.current; router.replace(params ? `/recherche?${params}` : "/recherche", { scroll: false });27    api<Res>(`/search?${params}`).then((r) => { if (my === seq.current) setRes(r); }).catch(() => {});28  }, [params]); // eslint-disable-line react-hooks/exhaustive-deps29  const set = (k: keyof F, v: string) => setF((p) => ({ ...p, [k]: v }));30  const sel = cn(inputCls, "w-44 shrink-0");31  const active = !!(q || f.genre || f.from || f.language || f.country || f.status || f.source);32  const total = res ? res.channels.total + res.movies.total + res.series.total + res.docs.total + res.library.total + res.episodes.length : 0;33  const decades = res?.facets.years ? Array.from({ length: Math.floor(res.facets.years[1] / 10) - Math.floor(res.facets.years[0] / 10) + 1 }, (_, i) => Math.floor(res.facets.years![1] / 10) * 10 - i * 10) : [];34  const grid = "grid grid-cols-3 gap-x-3 gap-y-5 sm:grid-cols-4 md:grid-cols-5 lg:gap-x-4 xl:grid-cols-6 2xl:grid-cols-8";35  const section = (title: string, n: number, type: string, children: React.ReactNode) => n > 0 && (36    <section key={title}><div className="mb-3 flex items-end justify-between"><h2 className="text-lg font-semibold">{title} <span className="text-sm font-normal text-dim">{n.toLocaleString("fr-CA")}</span></h2>{!f.type && n > 12 && <button onClick={() => set("type", type)} className="h-9 rounded-full px-3 text-sm font-medium text-dim hover:text-ink">Tout voir</button>}</div>{children}</section>37  );38  return (39    <div className="px-4 pb-8 pt-5 lg:px-8 lg:pt-8">40      <div className="relative"><Search className="pointer-events-none absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-faint" />41        <input ref={input} data-nav type="search" inputMode="search" enterKeyHint="search" value={f.q} onChange={(e) => set("q", e.target.value)} placeholder="Chaînes, films, séries, épisodes, bibliothèque…" aria-label="Recherche globale" className={cn(inputCls, "h-14 rounded-2xl pl-12 text-lg")} /></div>42      <div className="no-scrollbar -mx-4 mt-3 flex gap-2 overflow-x-auto px-4 lg:mx-0 lg:flex-wrap lg:px-0" role="tablist" aria-label="Type de contenu">43        {TYPES.map(([k, l]) => <button key={k} role="tab" aria-selected={f.type === k} onClick={() => set("type", k)} className={cn("h-10 shrink-0 rounded-full px-4 text-sm font-medium ring-1 ring-line", f.type === k ? "bg-white text-black" : "bg-raised text-dim hover:text-ink")}>{l}</button>)}44      </div>45      <div className="no-scrollbar -mx-4 mt-2 flex gap-2 overflow-x-auto px-4 lg:mx-0 lg:flex-wrap lg:px-0">46        <select aria-label="Genre" value={f.genre} onChange={(e) => set("genre", e.target.value)} className={sel}><option value="">Tous les genres</option>{res?.facets.genres.map((g) => <option key={g.id} value={g.id}>{g.id}</option>)}</select>47        <select aria-label="Année" value={f.from} onChange={(e) => set("from", e.target.value)} className={sel}><option value="">Toutes les années</option>{decades.map((d) => <option key={d} value={d}>Années {d}</option>)}</select>48        <select aria-label="Langue" value={f.language} onChange={(e) => set("language", e.target.value)} className={sel}><option value="">Toutes les langues</option>{["fr", "en", "es", "de", "it", ...(res?.facets.languages.map((l) => l.id).filter((l) => !["fr", "en", "es", "de", "it"].includes(l)) ?? [])].map((l) => <option key={l} value={l}>{langLabel(l)}</option>)}</select>49        <select aria-label="Pays" value={f.country} onChange={(e) => set("country", e.target.value)} className={sel}><option value="">Tous les pays</option>{meta?.countries.map((c) => ({ ...c, label: countryName(c.code, c.name) })).sort((a, b) => a.label.localeCompare(b.label, "fr")).map((c) => <option key={c.code} value={c.code}>{flag(c.code)} {c.label}</option>)}</select>50        <select aria-label="Disponibilité" value={f.status} onChange={(e) => set("status", e.target.value)} className={sel}><option value="">Toute disponibilité</option><option value="up">Chaînes disponibles au dernier test</option></select>51        <select aria-label="Source" value={f.source} onChange={(e) => set("source", e.target.value)} className={sel}><option value="">Toutes les sources</option>{res?.facets.sources.map((s) => <option key={s.id} value={s.id}>{s.id}</option>)}</select>52      </div>5354      {!active && <Empty title="Que voulez-vous regarder ?">Une seule recherche pour les chaînes en direct, les films, les séries et leurs épisodes, les documentaires et votre bibliothèque. Les fautes de frappe sont tolérées.</Empty>}55      {active && res && total === 0 && <Empty title="Aucun résultat">Essayez un autre mot, ou retirez un filtre.</Empty>}56      {active && res && total > 0 && (57        <div className="mt-6 space-y-9">58          <p className="-mb-4 text-xs text-faint">{total.toLocaleString("fr-CA")} résultat{total > 1 ? "s" : ""} en {res.tookMs} ms</p>59          {section("Chaînes TV", res.channels.total, "channel", <div className="grid grid-cols-2 gap-x-3 gap-y-5 sm:grid-cols-3 md:grid-cols-4 lg:gap-x-4 xl:grid-cols-6">{res.channels.items.slice(0, f.type ? 60 : 12).map((c) => <ChannelCard key={c.id} channel={c} queue={res.channels.items} />)}</div>)}60          {section("Films", res.movies.total, "movie", <div className={grid}>{res.movies.items.slice(0, f.type ? 60 : 16).map((t) => <TitleCard key={t.id} title={t} />)}</div>)}61          {section("Séries", res.series.total, "series", <div className={grid}>{res.series.items.map((t) => <TitleCard key={t.id} title={t} />)}</div>)}62          {section("Épisodes", res.episodes.length, "episode", <ul className="grid gap-2 md:grid-cols-2">{res.episodes.map((e) => (63            <li key={e.mediaId} className="flex items-center gap-3 rounded-2xl bg-panel p-2 ring-1 ring-line">64              <Poster title={{ title: e.series, poster: e.poster, backdrop: null, kind: "series", year: null }} className="h-16 w-11 shrink-0 rounded-lg" />65              <Link href={`/titre/${e.titleId}`} className="min-w-0 flex-1"><span className="block truncate text-sm font-semibold">{e.name}</span><span className="block truncate text-xs text-dim">{e.series} · S{e.season} É{e.episode}</span></Link>66              <button onClick={() => playMedia(e.mediaId)} aria-label={`Lire ${e.name}`} className="grid h-11 w-11 shrink-0 place-items-center rounded-full bg-white text-black"><Play className="ml-0.5 h-5 w-5 fill-current" /></button>67            </li>))}</ul>)}68          {section("Documentaires", res.docs.total, "doc", <div className={grid}>{res.docs.items.map((t) => <TitleCard key={t.id} title={t} />)}</div>)}69          {section("Ma bibliothèque", res.library.total, "library", <div className={grid}>{res.library.items.map((t) => <TitleCard key={t.id} title={t} />)}</div>)}70        </div>71      )}72    </div>73  );74}75export default function Page() { return <Suspense><SearchPage /></Suspense>; }76
Files main
Menu

Theme