SPB Git

Repository Public

page.tsx 8.9 KB 104 lines tsx

1"use client";2import { useEffect, useMemo, useRef, useState } from "react";3import { Play, X } from "lucide-react";4import { ago, cn, hm, useApi, useDebounced, useNow, type Channel, type Prog } from "@/lib/client";5import { usePlayer } from "@/components/player";6import { Empty, Logo, PageHeader, StatusDot, inputCls, btnCls } from "@/components/ui";78interface Guide { total: number; channels: Channel[]; programmes: Record<string, Prog[]>; from: number; to: number; withData: number; lastEpgAt: number | null }9const HOUR = 3600_000, PX = 260, HOURS = 24, ROW = 68;1011export default function GuidePage() {12  const [scope, setScope] = useState<"data" | "fav">("data");13  const [search, setSearch] = useState("");14  const q = useDebounced(search, 200);15  // Window: from the last half hour, 24 h ahead, in the device's time zone.16  const from = useMemo(() => Math.floor((Date.now() - 30 * 60_000) / (30 * 60_000)) * 30 * 60_000, []);17  const { data, error, loading } = useApi<Guide>(`/guide?scope=${q ? "all" : scope}&from=${from}&to=${from + HOURS * HOUR}${q ? `&q=${encodeURIComponent(q)}` : ""}`);18  const { play } = usePlayer();19  const t = useNow(30_000);20  const scroller = useRef<HTMLDivElement>(null);21  const [sel, setSel] = useState<{ c: Channel; p: Prog } | null>(null);22  const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;23  const x = (time: number) => ((time - from) / HOUR) * PX;24  const toNow = () => scroller.current?.scrollTo({ left: Math.max(0, x(Date.now()) - 120), behavior: "smooth" });25  useEffect(() => { if (data) scroller.current?.scrollTo({ left: Math.max(0, x(Date.now()) - 120) }); }, [!!data]); // eslint-disable-line react-hooks/exhaustive-deps26  const slots = Array.from({ length: HOURS * 2 }, (_, i) => from + i * 30 * 60_000);27  const day = new Intl.DateTimeFormat("fr-CA", { weekday: "short", day: "numeric", month: "short" });2829  return (30    <div>31      <PageHeader title="Guide TV" sub={<>Horaires dans votre fuseau ({tz}){data ? ` · ${data.withData} chaîne${data.withData > 1 ? "s" : ""} avec programmes · mis à jour ${ago(data.lastEpgAt)}` : ""}</>} />32      <div className="flex flex-wrap items-center gap-2 px-4 pb-3 lg:px-8">33        <div className="flex rounded-xl bg-raised p-1 ring-1 ring-line" role="tablist">34          {([["data", "Avec programmes"], ["fav", "Favoris"]] as const).map(([k, l]) => <button key={k} role="tab" aria-selected={scope === k} onClick={() => setScope(k)} className={cn("h-9 rounded-lg px-3.5 text-sm font-medium", scope === k ? "bg-white text-black" : "text-dim")}>{l}</button>)}35        </div>36        <input type="search" value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Filtrer les chaînes" aria-label="Filtrer les chaînes du guide" className={cn(inputCls, "max-w-56")} />37        <button onClick={toNow} className={cn(btnCls, "h-11 bg-white/10 hover:bg-white/15")}>Maintenant</button>38      </div>39      {error && <Empty title="Guide indisponible">{error}</Empty>}40      {loading && !data && <div className="space-y-2 px-4 lg:px-8">{Array.from({ length: 8 }, (_, i) => <div key={i} className="skeleton h-16 rounded-xl" />)}</div>}41      {data && !data.channels.length && (42        <Empty title={scope === "fav" ? "Aucun favori" : "Aucun programme disponible pour l'instant"}>43          {scope === "fav" ? "Ajoutez des chaînes à vos favoris : elles sont ajoutées à la collecte du guide." : "Le guide est collecté auprès de sources réelles par le worker (Admin → Aperçu → Mettre à jour le guide). Aucune donnée n'est inventée : sans source, une chaîne affiche « Programme indisponible »."}44        </Empty>45      )}46      {data && data.channels.length > 0 && (47        <div ref={scroller} className="relative mx-0 max-h-[calc(100dvh-13rem)] overflow-auto border-y border-line lg:mx-8 lg:rounded-2xl lg:border" tabIndex={-1}>48          <div className="relative w-max">49            <div style={{ width: `calc(var(--chw) + ${HOURS * PX}px)` }} className="[--chw:5.5rem] sm:[--chw:13rem]">50              {/* time header */}51              <div className="sticky top-0 z-20 flex h-10 bg-panel">52                <div className="sticky left-0 z-30 w-[var(--chw)] shrink-0 border-b border-r border-line bg-panel" />53                <div className="relative flex-1 border-b border-line">54                  {slots.map((s) => <span key={s} className="absolute top-0 flex h-10 items-center border-l border-line pl-2 text-xs font-medium text-dim" style={{ left: x(s), width: PX / 2 }}>{new Date(s).getHours() === 0 && new Date(s).getMinutes() === 0 ? `${day.format(s)} · ` : ""}{hm(s)}</span>)}55                </div>56              </div>57              {data.channels.map((c) => {58                const progs = data.programmes[c.id];59                return (60                  <div key={c.id} className="flex border-b border-line" style={{ height: ROW }}>61                    <button onClick={() => play(c, data.channels)} aria-label={`Regarder ${c.name}`} className="sticky left-0 z-10 flex w-[var(--chw)] shrink-0 items-center gap-2 border-r border-line bg-panel px-2 text-left hover:bg-raised">62                      <Logo channel={c} className="h-10 w-14 shrink-0 rounded-lg [container-type:size]" />63                      <span className="hidden min-w-0 flex-1 sm:block"><span className="flex items-center gap-1.5"><StatusDot status={c.status} /><span className="truncate text-sm font-semibold">{c.name}</span></span></span>64                    </button>65                    <div className="relative flex-1">66                      {!progs && <span className="absolute inset-y-2 left-2 flex items-center rounded-lg px-3 text-sm text-faint" style={{ left: Math.max(8, x(t) - 100) }}>Programme indisponible</span>}67                      {progs?.map((p) => {68                        const l = Math.max(0, x(p.start)), r = Math.min(HOURS * PX, x(p.stop)); if (r - l < 3) return null;69                        const live = p.start <= t && p.stop > t;70                        return (71                          <button key={p.start} onClick={() => setSel({ c, p })} title={`${hm(p.start)} – ${hm(p.stop)} · ${p.title}`} className={cn("absolute inset-y-1.5 overflow-clip rounded-lg px-2.5 text-left ring-1 ring-line transition hover:bg-white/15", live ? "bg-accent/25 ring-accent/60" : p.stop <= t ? "bg-white/[0.03] text-faint" : "bg-raised")} style={{ left: l + 2, width: r - l - 4 }}>72                            <span className="sticky left-[calc(var(--chw)+0.6rem)] block w-max max-w-full"><span className="block truncate text-[13px] font-semibold leading-tight">{p.title}</span>73                            <span className="block truncate text-[11px] text-dim">{hm(p.start)} – {hm(p.stop)}</span></span>74                            {live && <span className="absolute inset-x-0 bottom-0 h-[3px] bg-white/10"><span className="grad block h-full" style={{ width: `${((t - p.start) / (p.stop - p.start)) * 100}%` }} /></span>}75                          </button>76                        );77                      })}78                    </div>79                  </div>80                );81              })}82              {/* now line */}83              {t >= from && t <= from + HOURS * HOUR && <div className="pointer-events-none absolute bottom-0 top-0 z-10 w-0.5 bg-down" style={{ left: `calc(var(--chw) + ${x(t)}px)` }} aria-hidden />}84            </div>85          </div>86        </div>87      )}88      {data && data.total > data.channels.length && <p className="px-4 py-4 text-center text-sm text-dim lg:px-8">{data.channels.length} chaînes affichées sur {data.total}. Utilisez le filtre pour en trouver d'autres.</p>}8990      {sel && (91        <div className="fixed inset-0 z-40 grid place-items-end bg-black/70 sm:place-items-center" onClick={() => setSel(null)} role="dialog" aria-modal aria-label={sel.p.title}>92          <div className="fadein w-full max-w-lg rounded-t-3xl bg-panel p-6 ring-1 ring-line safe-b sm:rounded-3xl" onClick={(e) => e.stopPropagation()}>93            <div className="flex items-start justify-between gap-3"><div><p className="text-xs font-semibold uppercase tracking-wide text-accent2">{sel.c.name} · {day.format(sel.p.start)} {hm(sel.p.start)} – {hm(sel.p.stop)}</p><h2 className="mt-1 text-xl font-bold">{sel.p.title}</h2>{sel.p.subtitle && <p className="text-sm text-dim">{sel.p.subtitle}</p>}</div>94              <button onClick={() => setSel(null)} aria-label="Fermer" className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-white/10"><X className="h-5 w-5" /></button></div>95            {sel.p.category && <p className="mt-2 text-xs text-faint">{sel.p.category}</p>}96            <p className="mt-3 max-h-48 overflow-y-auto text-sm leading-relaxed text-dim">{sel.p.description ?? "Aucune description fournie par la source du guide."}</p>97            <button autoFocus onClick={() => { play(sel.c, data?.channels); setSel(null); }} className={cn(btnCls, "grad mt-5 w-full")}><Play className="h-4 w-4 fill-current" />Regarder {sel.c.name}</button>98          </div>99        </div>100      )}101    </div>102  );103}104
Files main
Menu

Theme