Repository Public
1"use client";2import Link from "next/link";3import { useCallback, useEffect, useRef, useState } from "react";4import { formatDuration, type FeedLabels, type Locale } from "@/lib/i18n";5import type { VideoCard, Variant } from "@/lib/publications";6import { LogoMark } from "./Logo";7import { IconCc, IconDoc, IconDown, IconMuted, IconPlay, IconSearch, IconShare, IconSound, IconUp } from "./icons";89export interface FeedProps {10 initial: VideoCard[];11 /** Nombre total de publications visibles et nombre de pages de l'API (`/api/public/videos?limit=pageSize`). */12 total: number; pages: number; pageSize: number;13 locale: Locale; labels: FeedLabels;14 /** Le fil a été ouvert sur une vidéo précise (`?v=slug`). */15 pinned: boolean;16 feedHref: string; homeHref: string; searchHref: string;17}1819/** Variante lue dans le fil : la verticale si elle existe, sinon la carrée, sinon la 16:9 (l'ordre vient du serveur). */20const pick = (v: VideoCard): Variant | null => v.variants.find((x) => x.ratio === "9:16") ?? v.variants.find((x) => x.ratio === "1:1") ?? v.variants[0] ?? null;21const ratioOf = (w: number, h: number) => (w / h < 0.8 ? "9:16" : w / h < 1.25 ? "1:1" : "16:9");22/** Secondes réellement lues (somme des plages `played`) : sert au compteur de vues. */23const playedSeconds = (v: HTMLVideoElement) => { let s = 0; for (let i = 0; i < v.played.length; i++) s += v.played.end(i) - v.played.start(i); return s; };24const VIEW_AFTER = 3;25const reducedMotion = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;2627/**28 * Fil vertical : une vidéo par écran, défilement à cran. Seules trois balises <video> existent à la fois29 * (précédente en pause, courante en lecture, suivante préchargée) ; les autres écrans ne montrent qu'une image.30 * Le son est coupé au départ (les navigateurs bloquent la lecture automatique sonore) ; le choix du visiteur31 * est gardé en mémoire pour la suite du fil, sans cookie ni stockage local.32 */33export function Feed(p: FeedProps) {34 const L = p.labels;35 const [items, setItems] = useState(p.initial);36 const [active, setActive] = useState(0);37 const [muted, setMuted] = useState(true);38 const [cc, setCc] = useState(false);39 const [paused, setPaused] = useState(false);40 const [expanded, setExpanded] = useState<string | null>(null);41 const [toast, setToast] = useState("");42 const [loading, setLoading] = useState(false);43 const [failed, setFailed] = useState<Record<string, boolean>>({});44 const [ready, setReady] = useState<Record<string, boolean>>({});4546 const scroller = useRef<HTMLDivElement>(null);47 const videos = useRef(new Map<string, HTMLVideoElement>());48 const bars = useRef(new Map<string, HTMLSpanElement>());49 const viewed = useRef(new Set<string>());50 const nextPage = useRef(2);51 const moved = useRef(p.pinned);52 const mutedRef = useRef(true);53 const pausedRef = useRef(false);54 const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);55 const current = items[active];5657 const say = useCallback((text: string) => {58 setToast(text);59 if (toastTimer.current) clearTimeout(toastTimer.current);60 toastTimer.current = setTimeout(() => setToast(""), 2200);61 }, []);62 useEffect(() => () => { if (toastTimer.current) clearTimeout(toastTimer.current); }, []);6364 /** Lance la lecture ; si le navigateur refuse la lecture sonore (pas de geste récent), on repasse en muet plutôt que de rester figé. */65 const play = useCallback((v: HTMLVideoElement) => {66 v.play().catch(() => {67 if (v.muted) return;68 v.muted = true; mutedRef.current = true; setMuted(true);69 v.play().catch(() => {});70 });71 }, []);7273 // ── vidéo visible : IntersectionObserver sur chaque écran ──74 useEffect(() => {75 const root = scroller.current;76 if (!root) return;77 const io = new IntersectionObserver((entries) => {78 for (const e of entries) if (e.isIntersecting && e.intersectionRatio >= 0.6) setActive(Number((e.target as HTMLElement).dataset.index));79 }, { root, threshold: [0.6] });80 root.querySelectorAll<HTMLElement>("[data-index]").forEach((el) => io.observe(el));81 return () => io.disconnect();82 }, [items.length]);8384 // ── lecture de la vidéo courante, pause (et retour au début) des autres ──85 useEffect(() => { pausedRef.current = false; setPaused(false); }, [active]);86 useEffect(() => {87 const slug = items[active]?.slug;88 videos.current.forEach((v, key) => {89 if (key === slug) { v.muted = mutedRef.current; if (!pausedRef.current && v.paused) play(v); }90 else { v.pause(); if (v.currentTime > 0) v.currentTime = 0; bars.current.get(key)?.style.setProperty("--p", "0"); }91 });92 // eslint-disable-next-line react-hooks/exhaustive-deps93 }, [active, items.length, play]);9495 // ── adresse partageable de la position ──96 useEffect(() => {97 const slug = items[active]?.slug;98 if (!slug) return;99 if (!moved.current) { if (active === 0) return; moved.current = true; }100 window.history.replaceState(window.history.state, "", `${p.feedHref}?v=${encodeURIComponent(slug)}`);101 // eslint-disable-next-line react-hooks/exhaustive-deps102 }, [active]);103104 // ── défilement infini : la page suivante de l'API publique quand il reste moins de trois vidéos ──105 useEffect(() => {106 if (loading || nextPage.current > p.pages || active < items.length - 3) return;107 const page = nextPage.current;108 const ctl = new AbortController();109 setLoading(true);110 fetch(`/api/public/videos?page=${page}&limit=${p.pageSize}&locale=${p.locale}`, { signal: ctl.signal })111 .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))112 .then((data: { items: VideoCard[] }) => {113 nextPage.current = page + 1;114 setItems((prev) => { const seen = new Set(prev.map((x) => x.slug)); return [...prev, ...data.items.filter((x) => !seen.has(x.slug))]; });115 })116 .catch(() => { /* on réessaiera au prochain changement de vidéo */ })117 .finally(() => { if (!ctl.signal.aborted) setLoading(false); });118 return () => ctl.abort();119 // eslint-disable-next-line react-hooks/exhaustive-deps120 }, [active, items.length]);121122 // ── sous-titres : piste de la vidéo courante seulement ──123 useEffect(() => {124 const slug = items[active]?.slug;125 videos.current.forEach((v, key) => { const t = v.textTracks?.[0]; if (t) t.mode = cc && key === slug ? "showing" : "hidden"; });126 }, [cc, active, items, ready]);127128 // ── actions ──129 const go = useCallback((i: number) => {130 const root = scroller.current;131 if (!root) return;132 const n = Math.max(0, Math.min(items.length - 1, i));133 root.scrollTo({ top: n * root.clientHeight, behavior: reducedMotion() ? "auto" : "smooth" });134 }, [items.length]);135 const toggle = useCallback(() => {136 const v = current ? videos.current.get(current.slug) : null;137 if (!v) return;138 if (v.paused) { pausedRef.current = false; setPaused(false); play(v); } else { pausedRef.current = true; setPaused(true); v.pause(); }139 }, [current, play]);140 const toggleSound = useCallback(() => {141 const next = !mutedRef.current;142 mutedRef.current = next; setMuted(next);143 const v = current ? videos.current.get(current.slug) : null;144 if (v) { v.muted = next; if (!next && v.paused && !pausedRef.current) play(v); }145 }, [current, play]);146 const share = useCallback(async () => {147 if (!current) return;148 const url = `${window.location.origin}${p.feedHref}?v=${encodeURIComponent(current.slug)}`;149 if (typeof navigator.share === "function") {150 try { await navigator.share({ title: current.title, url }); return; } catch (e) { if ((e as Error).name === "AbortError") return; }151 }152 try { await navigator.clipboard.writeText(url); }153 catch {154 const ta = document.createElement("textarea");155 ta.value = url; ta.setAttribute("readonly", ""); ta.style.position = "fixed"; ta.style.opacity = "0";156 document.body.appendChild(ta); ta.select();157 try { document.execCommand("copy"); } finally { ta.remove(); }158 }159 say(L.copied);160 }, [current, p.feedHref, say, L.copied]);161162 // ── clavier : flèches et J/K changent de vidéo, espace = pause, M = son, C = sous-titres ──163 useEffect(() => {164 function key(e: KeyboardEvent) {165 if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;166 const el = e.target as HTMLElement | null;167 const tag = el?.tagName ?? "";168 if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || el?.isContentEditable) return;169 const k = e.key.toLowerCase();170 if (k === "arrowdown" || k === "j" || k === "pagedown") { e.preventDefault(); go(active + 1); }171 else if (k === "arrowup" || k === "k" || k === "pageup") { e.preventDefault(); go(active - 1); }172 else if (k === "home") { e.preventDefault(); go(0); }173 else if (k === "end") { e.preventDefault(); go(items.length - 1); }174 else if (k === " " || k === "spacebar") { if (tag === "BUTTON" || tag === "A" || tag === "SUMMARY") return; e.preventDefault(); toggle(); }175 else if (k === "m") toggleSound();176 else if (k === "c") { if (current?.captions) setCc((x) => !x); }177 }178 document.addEventListener("keydown", key);179 return () => document.removeEventListener("keydown", key);180 }, [active, items.length, go, toggle, toggleSound, current]);181182 function onTime(slug: string, v: HTMLVideoElement) {183 if (Number.isFinite(v.duration) && v.duration > 0) bars.current.get(slug)?.style.setProperty("--p", String(Math.min(1, v.currentTime / v.duration)));184 // Une vue n'est comptée que si la vidéo a réellement été lue quelques secondes (même route que la page de lecture).185 if (!viewed.current.has(slug) && playedSeconds(v) >= VIEW_AFTER) {186 viewed.current.add(slug);187 fetch(`/api/public/videos/${encodeURIComponent(slug)}/view`, { method: "POST", keepalive: true }).catch(() => {});188 }189 }190191 return (192 <section className="feed" aria-label={L.region} data-testid="feed" data-muted={muted} data-active-slug={current?.slug ?? ""}>193 <div className="feed-topbar on-dark">194 <Link href={p.homeHref} className="inline-flex min-h-11 items-center gap-2 rounded-full pr-3 text-[0.95rem] font-semibold text-white" aria-label={`SP CLIP — ${L.backHome}`}>195 <LogoMark size={30} /><span className="h-display tracking-tight drop-shadow">{L.title}</span>196 </Link>197 <Link href={p.searchHref} className="inline-flex h-11 w-11 items-center justify-center rounded-full text-white" aria-label={L.search}><IconSearch size={22} /></Link>198 </div>199200 <div ref={scroller} className="feed-scroller" tabIndex={-1} data-testid="feed-scroller">201 {items.map((v, i) => {202 const variant = pick(v);203 const isActive = i === active;204 const mounted = !!variant && Math.abs(i - active) <= 1;205 const posterFits = !!variant && ratioOf(v.width, v.height) === variant.ratio;206 const open = expanded === v.slug;207 const long = v.summary.length > 96;208 const still = v.poster ?? v.thumbnail;209 return (210 <article key={v.slug} className="feed-item" data-index={i} data-testid="feed-item" data-slug={v.slug} data-active={isActive} data-ratio={variant?.ratio ?? "none"}211 aria-label={`${L.item.replace("{n}", String(i + 1)).replace("{total}", String(Math.max(p.total, items.length)))} — ${v.title}`} inert={!isActive}>212 <div className="feed-frame">213 <div className="feed-stage on-dark">214 {still && <img src={v.thumbnail ?? still} alt="" className="feed-backdrop" loading={i < 2 ? "eager" : "lazy"} decoding="async" aria-hidden="true" />}215 {still && (posterFits || !variant) && <img src={still} alt="" className="feed-media" data-ratio={variant?.ratio} loading={i < 2 ? "eager" : "lazy"} decoding="async" />}216 {mounted && variant && (217 <video218 ref={(el) => {219 if (!el) { videos.current.delete(v.slug); return; }220 videos.current.set(v.slug, el);221 // La première vidéo vient du HTML du serveur : elle peut être déjà chargée avant l'hydratation (pas d'événement à attendre).222 if (el.readyState >= 2) el.dataset.ready = "true";223 }}224 className="feed-media feed-video" data-testid="feed-video" data-ratio={variant.ratio} data-ready={ready[v.slug] ? "true" : undefined}225 src={variant.url} muted loop playsInline preload={i >= active ? "auto" : "metadata"} width={variant.width} height={variant.height}226 aria-label={v.title} disablePictureInPicture227 onLoadedData={() => setReady((r) => (r[v.slug] ? r : { ...r, [v.slug]: true }))}228 onTimeUpdate={(e) => onTime(v.slug, e.currentTarget)}229 onError={() => setFailed((f) => ({ ...f, [v.slug]: true }))}>230 {v.captions && <track kind="subtitles" src={v.captions} srcLang={v.language} label={L.captions} />}231 </video>232 )}233 <div className="feed-shade-top" aria-hidden="true" />234 <div className="feed-shade" aria-hidden="true" />235236 {variant && !failed[v.slug] && <button type="button" className="feed-tap" onClick={toggle} aria-label={`${paused && isActive ? L.play : L.pause} — ${v.title}`} data-testid="feed-tap" />}237 {isActive && paused && <span className="feed-pulse" aria-hidden="true"><IconPlay size={34} /></span>}238 {(!variant || failed[v.slug]) && (239 <p className="absolute inset-x-6 top-1/2 -translate-y-1/2 rounded-2xl bg-black/70 px-4 py-3 text-center text-sm font-medium text-white" role={failed[v.slug] ? "alert" : undefined} data-testid="feed-unavailable">240 {failed[v.slug] ? L.error : L.unavailable}241 </p>242 )}243244 {isActive && muted && variant && !failed[v.slug] && (245 <button type="button" className="feed-pill absolute left-3 top-[calc(env(safe-area-inset-top,0px)+3.6rem)] z-[3] md:left-4 md:top-4" onClick={toggleSound} data-testid="feed-unmute">246 <IconMuted size={18} />{L.soundOn}247 </button>248 )}249250 <div className="feed-info">251 <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs font-semibold text-white/90">252 {v.category && <span className="rounded-full bg-white/18 px-2.5 py-1 backdrop-blur-sm">{v.category.name}</span>}253 <span className="tabular-nums">{formatDuration(v.duration)}</span>254 </p>255 <h2 className="mt-2 line-clamp-2 text-[1.12rem] font-semibold leading-snug tracking-[-0.01em] text-white drop-shadow-sm md:text-xl" data-testid="feed-title">{v.title}</h2>256 {v.summary && (257 <p className="mt-1.5 text-sm leading-5 text-white/85">258 <span id={`sum-${v.slug}`} className={open ? "" : "line-clamp-2"}>{v.summary}</span>259 {long && (260 <button type="button" className="-my-2 ml-0 inline-flex min-h-9 items-center font-semibold text-white underline decoration-white/50 underline-offset-2" aria-expanded={open} aria-controls={`sum-${v.slug}`}261 aria-label={open ? L.lessLabel : L.moreLabel} onClick={() => setExpanded(open ? null : v.slug)} data-testid="feed-more">{open ? L.less : L.more}</button>262 )}263 </p>264 )}265 </div>266 <div className="feed-progress" aria-hidden="true"><span ref={(el) => { if (el) bars.current.set(v.slug, el); else bars.current.delete(v.slug); }} /></div>267 </div>268269 <div className="feed-actions">270 {variant && (271 <button type="button" className="feed-act" onClick={toggleSound} aria-pressed={!muted} aria-label={muted ? L.soundOn : L.soundOff} data-testid="feed-sound">272 <span className="disc">{muted ? <IconMuted size={22} /> : <IconSound size={22} />}</span><span aria-hidden="true">{muted ? L.muted : L.sound}</span>273 </button>274 )}275 {variant && v.captions && (276 <button type="button" className="feed-act" onClick={() => setCc((x) => !x)} aria-pressed={cc} aria-label={cc ? L.captionsOff : L.captionsOn} data-testid="feed-cc">277 <span className="disc"><IconCc size={22} /></span><span aria-hidden="true">{L.captions}</span>278 </button>279 )}280 <button type="button" className="feed-act" onClick={share} aria-label={`${L.share} — ${v.title}`} data-testid="feed-share">281 <span className="disc"><IconShare size={21} /></span><span aria-hidden="true">{L.share}</span>282 </button>283 <Link href={v.url} className="feed-act" aria-label={`${L.details} — ${v.title}`} data-testid="feed-details">284 <span className="disc"><IconDoc size={21} /></span><span aria-hidden="true">{L.detailsShort}</span>285 </Link>286 </div>287 </div>288 </article>289 );290 })}291 </div>292293 <div className="feed-nav">294 <button type="button" onClick={() => go(active - 1)} disabled={active === 0} aria-label={L.prev} data-testid="feed-prev"><IconUp size={24} /></button>295 <button type="button" onClick={() => go(active + 1)} disabled={active >= items.length - 1} aria-label={L.next} data-testid="feed-next"><IconDown size={24} /></button>296 </div>297 <p className="feed-hint text-xs leading-5 text-muted">{L.hint}</p>298299 {toast && <p className="feed-toast" data-testid="feed-toast">{toast}</p>}300 <p className="sr-only" role="status" aria-live="polite">301 {toast || (current ? `${L.item.replace("{n}", String(active + 1)).replace("{total}", String(Math.max(p.total, items.length)))} — ${current.title}` : "")}{loading ? ` — ${L.loading}` : ""}302 </p>303 </section>304 );305}306