SPB Git

Repository Public

vod-player.tsx 27.8 KB 265 lines tsx

1"use client";2import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";3import type Hls from "hls.js";4import { Airplay, AlertTriangle, Captions, ChevronDown, ExternalLink, Gauge, Languages, Maximize, Minimize, Pause, PictureInPicture2, Play, RotateCcw, RotateCw, SkipForward, Volume2, VolumeX, X } from "lucide-react";5import { api, clock, cn, type PlayInfo } from "@/lib/client";67// On-demand player (films, episodes, personal files). Remote titles are read straight from their host (Internet8// Archive, Wikimedia Commons); library files come from this server's authenticated routes, as they are or through an9// HLS rendition when the browser cannot read the original container or codec.1011interface VodApi { playMedia: (mediaId: number) => void; playing: number | null; version: number }12const Ctx = createContext<VodApi | null>(null);13export const useVod = () => useContext(Ctx)!;1415type Phase = "loading" | "playing" | "paused" | "buffering" | "ended" | "error";16const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2];17const nativeHls = () => !!document.createElement("video").canPlayType("application/vnd.apple.mpegurl");1819export function VodProvider({ children, onStart }: { children: React.ReactNode; onStart: () => void }) {20  const [mediaId, setMediaId] = useState<number | null>(null);21  const [version, setVersion] = useState(0);22  const ref = useRef<number | null>(null); ref.current = mediaId;23  const playMedia = useCallback((id: number) => { onStart(); if (ref.current === null) history.pushState({ sptv: "vod" }, ""); setMediaId(id); }, [onStart]);24  const close = useCallback((viaHistory: boolean) => { if (ref.current !== null && !viaHistory) history.back(); setMediaId(null); setVersion((v) => v + 1); }, []);25  useEffect(() => { const pop = () => { if (ref.current !== null) { setMediaId(null); setVersion((v) => v + 1); } }; addEventListener("popstate", pop); return () => removeEventListener("popstate", pop); }, []);26  // The live player and this one never play together.27  useEffect(() => { const stop = () => { if (ref.current !== null) close(false); }; addEventListener("sptv:live-start", stop); return () => removeEventListener("sptv:live-start", stop); }, [close]);28  const value = useMemo(() => ({ playMedia, playing: mediaId, version }), [playMedia, mediaId, version]);29  return <Ctx.Provider value={value}>{children}{mediaId !== null && <VodView key="vod" mediaId={mediaId} onClose={() => close(false)} onNext={(id) => setMediaId(id)} />}</Ctx.Provider>;30}3132function VodView({ mediaId, onClose, onNext }: { mediaId: number; onClose: () => void; onNext: (id: number) => void }) {33  const video = useRef<HTMLVideoElement>(null); const box = useRef<HTMLDivElement>(null); const hls = useRef<Hls | null>(null);34  const [info, setInfo] = useState<PlayInfo | null>(null);35  const [phase, setPhase] = useState<Phase>("loading");36  const [error, setError] = useState<{ title: string; detail: string } | null>(null);37  const [time, setTime] = useState(0); const [dur, setDur] = useState(0); const [buffered, setBuffered] = useState(0);38  const [chrome, setChrome] = useState(true); const [menu, setMenu] = useState<"none" | "subs" | "audio" | "speed">("none");39  const [sub, setSub] = useState(-1); const [audio, setAudio] = useState(0); const [speed, setSpeed] = useState(1);40  const [muted, setMuted] = useState(false); const [volume, setVolume] = useState(1); const [needsUnmute, setNeedsUnmute] = useState(false);41  const [isFs, setIsFs] = useState(false); const [airplay, setAirplay] = useState(false); const [viaHls, setViaHls] = useState(false); const [countdown, setCountdown] = useState<number | null>(null);42  const [seeking, setSeeking] = useState<number | null>(null);43  const lastSaved = useRef(0); const startAt = useRef(0); const infoRef = useRef<PlayInfo | null>(null); infoRef.current = info;4445  useEffect(() => { const v = Number(localStorage.getItem("sptv:volume") ?? "1"); setVolume(Number.isFinite(v) ? v : 1); setMuted(localStorage.getItem("sptv:muted") === "1"); }, []);46  useEffect(() => { const el = video.current; if (el) { el.volume = volume; el.muted = muted; } }, [volume, muted, info]);4748  // `from` is passed by effect clean-ups: by then React has already detached the ref.49  const save = useCallback((completed?: boolean, from?: HTMLVideoElement) => {50    const el = from ?? video.current, i = infoRef.current; if (!el || !i || !el.currentTime) return;51    const d = Number.isFinite(el.duration) && el.duration > 0 ? el.duration : i.duration;52    lastSaved.current = Date.now();53    api("/progress", { body: { mediaId: i.mediaId, position: Math.round(el.currentTime), duration: d ? Math.round(d) : null, completed } }).catch(() => {});54  }, []);5556  // Load the media description, then start it.57  useEffect(() => {58    let dead = false;59    setInfo(null); setPhase("loading"); setError(null); setTime(0); setDur(0); setSub(-1); setAudio(0); setCountdown(null); setMenu("none");60    api<PlayInfo>(`/play/${mediaId}`).then((i) => { if (!dead) { startAt.current = i.position > 15 && (!i.duration || i.position < i.duration - 20) ? i.position : 0; setDur(i.duration ?? 0); setInfo(i); } })61      .catch((e) => { if (!dead) { setPhase("error"); setError({ title: "Lecture impossible", detail: (e as Error).message }); } });62    return () => { dead = true; };63  }, [mediaId]);6465  useEffect(() => {66    const el = video.current; if (!el || !info || info.embed) return;67    let cancelled = false, triedHls = false;68    const teardown = () => { hls.current?.destroy(); hls.current = null; el.pause(); el.removeAttribute("src"); el.load(); };69    const fail = (title: string, detail: string) => { if (cancelled) return; teardown(); setError({ title, detail }); setPhase("error"); };70    const begin = () => el.play().catch((e: DOMException) => { if (cancelled || e.name !== "NotAllowedError") return; el.muted = true; setNeedsUnmute(true); el.play().catch(() => setPhase("paused")); });71    const playHls = (url: string) => {72      triedHls = true; setViaHls(true);73      const src = audio ? `${url}?audio=${audio}` : url;74      if (nativeHls()) { el.src = src; el.addEventListener("loadedmetadata", () => { if (startAt.current) el.currentTime = startAt.current; }, { once: true }); begin(); return; }75      import("hls.js").then(({ default: H }) => {76        if (cancelled) return;77        if (!H.isSupported()) return fail("Format non pris en charge", "Ce navigateur ne peut lire ni le fichier d'origine ni sa conversion HLS.");78        const h = new H({ startPosition: startAt.current || 0, maxBufferLength: 40, manifestLoadingTimeOut: 45_000, manifestLoadingMaxRetry: 2, fragLoadingTimeOut: 60_000, // Library renditions need the session cookie; provider addresses redirect to another origin and must go without (they carry a ticket).79          xhrSetup: (xhr, u) => { xhr.withCredentials = !u.includes("/api/provider/") && (u.startsWith(location.origin) || u.startsWith("/")); } });80        hls.current = h;81        h.on(H.Events.MANIFEST_PARSED, begin);82        h.on(H.Events.ERROR, (_e, d) => {83          if (!d.fatal) return;84          if (d.type === H.ErrorTypes.MEDIA_ERROR) { h.recoverMediaError(); return; }85          fail("Lecture impossible", d.response?.code === 503 ? "La conversion du fichier n'a pas pu démarrer sur le serveur (voir Admin → Bibliothèque)." : `Erreur ${d.details}${d.response?.code ? ` (HTTP ${d.response.code})` : ""}.`);86        });87        h.loadSource(src); h.attachMedia(el);88      }).catch(() => fail("Lecture impossible", "Le lecteur HLS n'a pas pu être chargé."));89    };90    const playDirect = (url: string) => {91      setViaHls(false); el.src = url;92      el.addEventListener("loadedmetadata", () => { if (startAt.current && Number.isFinite(el.duration) && startAt.current < el.duration - 5) el.currentTime = startAt.current; }, { once: true });93      begin();94    };95    setPhase("loading"); setError(null);96    const hevcOk = !!el.canPlayType('video/mp4; codecs="hvc1.1.6.L93.B0"');97    const webmOk = !!el.canPlayType('video/webm; codecs="vp9"') || !!el.canPlayType('video/webm; codecs="vp8"');98    if (info.container === "webm" && !webmOk) fail("Format WebM non pris en charge", "Ce film est distribué en WebM par Wikimedia Commons, que ce navigateur ne lit pas. Il reste lisible depuis un navigateur compatible (Chrome, Firefox, Safari récent).");99    else if (audio > 0 && info.hls) playHls(info.hls);100    else if (info.direct && (info.playback !== "direct-hevc" || hevcOk)) playDirect(info.direct);101    else if (info.hls) playHls(info.hls);102    else fail("Aucune source lisible", "Ce média n'a pas de source que ce navigateur peut lire.");103104    const onTime = () => { setTime(el.currentTime); if (el.buffered.length) setBuffered(el.buffered.end(el.buffered.length - 1)); if (Date.now() - lastSaved.current > 10_000 && !el.paused) save(); };105    const onDur = () => { if (Number.isFinite(el.duration) && el.duration > 0) setDur((d) => (info.hls && viaHlsRef.current && info.duration ? Math.max(d, info.duration) : el.duration)); };106    const onPlaying = () => { setPhase("playing"); el.playbackRate = speedRef.current; };107    const onWaiting = () => setPhase((p) => (p === "playing" ? "buffering" : p));108    const onPause = () => { if (!el.ended) { setPhase((p) => (p === "error" ? p : "paused")); save(); } };109    const onEnded = () => { save(true); setPhase("ended"); if (info.next) setCountdown(8); };110    const onError = () => {111      if (cancelled || hls.current) return;112      // A file the browser refuses as is (codec profile, container quirk): fall back to the converted rendition once.113      if (info.hls && !triedHls) { startAt.current = el.currentTime || startAt.current; playHls(info.hls); return; }114      fail("Lecture impossible", info.external ? "La source a refusé ou interrompu la lecture. Réessayez, ou ouvrez le titre sur le site de la source." : "Le fichier n'a pas pu être lu (format non pris en charge ou fichier illisible).");115    };116    el.addEventListener("timeupdate", onTime); el.addEventListener("durationchange", onDur); el.addEventListener("playing", onPlaying); el.addEventListener("waiting", onWaiting);117    el.addEventListener("pause", onPause); el.addEventListener("ended", onEnded); el.addEventListener("error", onError);118    const onSeeked = () => save();119    el.addEventListener("seeked", onSeeked);120    return () => { cancelled = true; save(undefined, el); el.removeEventListener("seeked", onSeeked); for (const [n, f] of [["timeupdate", onTime], ["durationchange", onDur], ["playing", onPlaying], ["waiting", onWaiting], ["pause", onPause], ["ended", onEnded], ["error", onError]] as const) el.removeEventListener(n, f); teardown(); };121  }, [info, audio]); // eslint-disable-line react-hooks/exhaustive-deps122  const speedRef = useRef(speed); speedRef.current = speed; const viaHlsRef = useRef(viaHls); viaHlsRef.current = viaHls;123124  // Subtitles: one <track> per language, shown on demand.125  useEffect(() => { const el = video.current; if (!el) return; for (let i = 0; i < el.textTracks.length; i++) el.textTracks[i].mode = i === sub ? "showing" : "disabled"; }, [sub, info, phase]);126  useEffect(() => { const el = video.current; if (el) el.playbackRate = speed; }, [speed]);127  useEffect(() => { if (countdown === null) return; if (countdown <= 0) { if (info?.next) onNext(info.next.mediaId); return; } const t = setTimeout(() => setCountdown((c) => (c === null ? c : c - 1)), 1000); return () => clearTimeout(t); }, [countdown, info, onNext]);128  useEffect(() => { const f = () => setIsFs(!!document.fullscreenElement); document.addEventListener("fullscreenchange", f); return () => document.removeEventListener("fullscreenchange", f); }, []);129  useEffect(() => {130    const el = video.current; if (!el || !("WebKitPlaybackTargetAvailabilityEvent" in window)) return;131    const f = (e: Event) => setAirplay((e as Event & { availability: string }).availability === "available");132    el.addEventListener("webkitplaybacktargetavailabilitychanged", f); return () => el.removeEventListener("webkitplaybacktargetavailabilitychanged", f);133  }, [info]);134  useEffect(() => { const f = () => save(); addEventListener("pagehide", f); return () => removeEventListener("pagehide", f); }, [save]);135136  const toggle = useCallback(() => { const el = video.current; if (!el) return; if (el.paused || el.ended) el.play().catch(() => {}); else el.pause(); }, []);137  const seekBy = useCallback((d: number) => { const el = video.current; if (!el) return; el.currentTime = Math.max(0, Math.min((Number.isFinite(el.duration) ? el.duration : dur) - 1, el.currentTime + d)); setTime(el.currentTime); }, [dur]);138  const fullscreen = useCallback(() => {139    const el = video.current as (HTMLVideoElement & { webkitEnterFullscreen?: () => void }) | null;140    if (document.fullscreenElement) document.exitFullscreen(); else if (box.current?.requestFullscreen) box.current.requestFullscreen().catch(() => {}); else el?.webkitEnterFullscreen?.();141  }, []);142  const toggleMute = useCallback(() => { setMuted((m) => { localStorage.setItem("sptv:muted", m ? "0" : "1"); return !m; }); setNeedsUnmute(false); }, []);143144  const wake = useCallback(() => setChrome(true), []);145  useEffect(() => { if (!chrome || phase !== "playing" || menu !== "none") return; const t = setTimeout(() => setChrome(false), 3500); return () => clearTimeout(t); }, [chrome, phase, menu, time > 0]); // eslint-disable-line react-hooks/exhaustive-deps146  useEffect(() => {147    const onKey = (e: KeyboardEvent) => {148      const tag = (e.target as HTMLElement).tagName; wake();149      if (e.key === "Escape" || e.key === "BrowserBack" || e.key === "GoBack") { e.preventDefault(); e.stopPropagation(); if (menu !== "none") setMenu("none"); else if (document.fullscreenElement) document.exitFullscreen(); else onClose(); return; }150      if (menu !== "none" || tag === "INPUT") return;151      if (e.key === "ArrowLeft" && tag !== "BUTTON") { e.preventDefault(); e.stopPropagation(); seekBy(-10); }152      else if (e.key === "ArrowRight" && tag !== "BUTTON") { e.preventDefault(); e.stopPropagation(); seekBy(10); }153      else if ((e.key === " " || e.key === "k" || e.key === "MediaPlayPause") && tag !== "BUTTON") { e.preventDefault(); toggle(); }154      else if (e.key === "j") seekBy(-10); else if (e.key === "l") seekBy(10); else if (e.key === "f") fullscreen(); else if (e.key === "m") toggleMute();155    };156    addEventListener("keydown", onKey, true); return () => removeEventListener("keydown", onKey, true);157  }, [menu, onClose, seekBy, toggle, fullscreen, toggleMute, wake]);158  useEffect(() => {159    if (!("mediaSession" in navigator) || !info) return;160    navigator.mediaSession.metadata = new MediaMetadata({ title: info.episode ? `${info.title} — S${info.episode.season} É${info.episode.episode}` : info.title, artist: "SP TV", artwork: info.poster?.startsWith("http") ? [{ src: info.poster }] : [] });161    navigator.mediaSession.setActionHandler("seekbackward", () => seekBy(-10)); navigator.mediaSession.setActionHandler("seekforward", () => seekBy(10));162    navigator.mediaSession.setActionHandler("nexttrack", info.next ? () => onNext(info.next!.mediaId) : null);163  }, [info, seekBy, onNext]);164165  // Titles watched in their publisher's official player: an iframe, with the required link back to the publisher.166  if (info?.embed) return (167    <div data-player="full" data-vod className="fixed inset-0 z-[60] flex flex-col bg-black">168      <div className="flex items-center gap-3 p-3 pt-[max(0.75rem,env(safe-area-inset-top))] sm:px-5">169        <button autoFocus aria-label="Fermer le lecteur (Retour)" onClick={onClose} className="grid h-12 w-12 shrink-0 place-items-center rounded-full text-white hover:bg-white/15"><ChevronDown className="h-7 w-7" /></button>170        <div className="min-w-0 flex-1"><h2 className="truncate text-lg font-semibold">{info.title}{info.episode ? ` — S${info.episode.season} É${info.episode.episode}` : ""}</h2><p className="truncate text-xs text-dim">Lecteur officiel · {info.sourceName}</p></div>171        {info.next && <button onClick={() => onNext(info.next!.mediaId)} className="hidden h-10 shrink-0 items-center gap-1.5 rounded-full bg-white/10 px-4 text-sm font-medium hover:bg-white/15 sm:inline-flex"><SkipForward className="h-4 w-4" />Épisode suivant</button>}172        {info.sourceUrl && <a href={info.sourceUrl} target="_blank" rel="noreferrer" className="inline-flex h-10 shrink-0 items-center gap-1.5 rounded-full bg-white/10 px-4 text-sm font-medium hover:bg-white/15"><ExternalLink className="h-4 w-4" />Voir sur {new URL(info.sourceUrl).hostname.replace(/^www\./, "")}</a>}173      </div>174      <iframe src={info.embed} title={info.title} allow="autoplay; fullscreen; encrypted-media; picture-in-picture" allowFullScreen referrerPolicy="origin" className="min-h-0 w-full flex-1 border-0" />175    </div>176  );177  const show = chrome || phase !== "playing" || menu !== "none";178  const shown = seeking ?? time; const total = dur || info?.duration || 0;179  const Btn = "grid h-12 w-12 shrink-0 place-items-center rounded-full text-white transition hover:bg-white/15 active:scale-95";180  const item = (active: boolean) => cn("flex h-12 w-full items-center justify-between rounded-xl px-4 text-left text-sm font-medium hover:bg-white/10", active && "bg-white/15");181182  return (183    <div ref={box} data-player="full" data-vod onPointerMove={wake} onPointerDown={wake} className={cn("fixed inset-0 z-[60] bg-black", !show && "cursor-none")}>184      <video ref={video} playsInline x-webkit-airplay="allow" crossOrigin={undefined} className="h-full w-full bg-black object-contain" onClick={() => (chrome ? toggle() : wake())}>185        {info?.subtitles.map((s, i) => <track key={`${info.mediaId}-${i}`} kind="subtitles" label={s.label} srcLang={s.lang === "und" ? undefined : s.lang} src={s.url} />)}186      </video>187188      {(phase === "loading" || phase === "buffering") && <div className="pointer-events-none absolute inset-0 grid place-items-center" role="status" aria-label="Chargement"><div className="spinner" />{viaHls && phase === "loading" && <p className="absolute mt-28 text-sm text-dim">Préparation du fichier sur le serveur…</p>}</div>}189      {needsUnmute && phase !== "error" && <button onClick={() => { setMuted(false); setNeedsUnmute(false); if (video.current) video.current.muted = false; }} className="absolute left-1/2 top-24 -translate-x-1/2 rounded-full bg-white px-4 py-2 text-sm font-semibold text-black shadow-xl"><VolumeX className="mr-1.5 inline h-4 w-4" />Activer le son</button>}190191      {phase === "error" && error && (192        <div className="absolute inset-0 grid place-items-center bg-black/85 p-5" role="alert">193          <div className="w-full max-w-lg rounded-3xl bg-panel p-6 ring-1 ring-line">194            <div className="flex items-start gap-3"><AlertTriangle className="mt-0.5 h-6 w-6 shrink-0 text-amber-400" /><div><h2 className="text-lg font-semibold">{error.title}</h2><p className="mt-1 text-sm leading-relaxed text-dim">{error.detail}</p></div></div>195            <div className="mt-5 flex flex-wrap gap-2">196              <button autoFocus onClick={() => setInfo((i) => (i ? { ...i } : i))} className="grad inline-flex h-11 items-center gap-2 rounded-full px-5 text-sm font-semibold">Réessayer</button>197              {info?.external && info.direct && <a href={info.direct} target="_blank" rel="noreferrer" className="inline-flex h-11 items-center gap-2 rounded-full bg-white/10 px-5 text-sm font-medium"><ExternalLink className="h-4 w-4" />Ouvrir le fichier à la source</a>}198              <button onClick={onClose} className="inline-flex h-11 items-center rounded-full bg-white/10 px-5 text-sm font-medium">Fermer</button>199            </div>200          </div>201        </div>202      )}203204      {phase === "ended" && (205        <div className="absolute inset-0 grid place-items-center bg-black/80 p-5">206          <div className="text-center">207            {info?.next ? <><p className="text-sm text-dim">Épisode suivant{countdown !== null ? ` dans ${countdown} s` : ""}</p><p className="mt-1 text-xl font-semibold">{info.next.label}</p>208              <div className="mt-5 flex justify-center gap-2"><button autoFocus onClick={() => onNext(info.next!.mediaId)} className="inline-flex h-12 items-center gap-2 rounded-full bg-white px-6 font-bold text-black"><SkipForward className="h-5 w-5" />Lire maintenant</button><button onClick={() => { setCountdown(null); onClose(); }} className="h-12 rounded-full bg-white/10 px-6 font-medium">Arrêter</button></div></>209              : <><p className="text-xl font-semibold">Terminé</p><div className="mt-5 flex justify-center gap-2"><button autoFocus onClick={() => { const el = video.current; if (el) { el.currentTime = 0; el.play().catch(() => {}); } }} className="h-12 rounded-full bg-white/10 px-6 font-medium">Revoir</button><button onClick={onClose} className="h-12 rounded-full bg-white px-6 font-bold text-black">Fermer</button></div></>}210          </div>211        </div>212      )}213214      <div className={cn("pointer-events-none absolute inset-0 flex flex-col justify-between transition-opacity duration-300", show && phase !== "ended" ? "opacity-100" : "opacity-0")} aria-hidden={!show}>215        <div className="pointer-events-auto flex items-center gap-3 bg-gradient-to-b from-black/85 to-transparent p-3 pb-12 pt-[max(0.75rem,env(safe-area-inset-top))] sm:p-5 sm:pb-14">216          <button aria-label="Fermer le lecteur (Retour)" onClick={onClose} className={Btn}><ChevronDown className="h-7 w-7" /></button>217          <div className="min-w-0 flex-1"><h2 className="truncate text-lg font-semibold sm:text-xl">{info?.title ?? "…"}</h2>{info?.episode && <p className="truncate text-sm text-dim">Saison {info.episode.season} · Épisode {info.episode.episode}{info.episode.name ? ` — ${info.episode.name}` : ""}</p>}</div>218          <button aria-label="Fermer" onClick={onClose} className={cn(Btn, "hidden sm:grid")}><X className="h-6 w-6" /></button>219        </div>220221        {phase !== "error" && <div className="pointer-events-auto absolute inset-x-0 top-1/2 flex -translate-y-1/2 items-center justify-center gap-6 sm:gap-10">222          <button aria-label="Reculer de 10 secondes" onClick={() => seekBy(-10)} className="grid h-14 w-14 place-items-center rounded-full bg-black/45 backdrop-blur active:scale-95"><RotateCcw className="h-7 w-7" /></button>223          <button aria-label={phase === "playing" || phase === "buffering" ? "Pause" : "Lecture"} onClick={toggle} className="grid h-20 w-20 place-items-center rounded-full bg-white text-black shadow-2xl active:scale-95">{phase === "playing" || phase === "buffering" ? <Pause className="h-9 w-9 fill-current" /> : <Play className="ml-1 h-9 w-9 fill-current" />}</button>224          <button aria-label="Avancer de 10 secondes" onClick={() => seekBy(10)} className="grid h-14 w-14 place-items-center rounded-full bg-black/45 backdrop-blur active:scale-95"><RotateCw className="h-7 w-7" /></button>225        </div>}226227        <div className="pointer-events-auto bg-gradient-to-t from-black/90 to-transparent p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-14 sm:p-5 sm:pt-16">228          <div className="flex items-center gap-3 px-1 text-xs tabular-nums text-dim">229            <span className="w-12 text-right text-ink">{clock(shown)}</span>230            <input type="range" className="seek" min={0} max={Math.max(1, Math.round(total))} step={1} value={Math.min(Math.round(shown), Math.round(total))} aria-label="Position de lecture" aria-valuetext={`${clock(shown)} sur ${clock(total)}`}231              style={{ ["--p" as string]: `${total ? (shown / total) * 100 : 0}%` }}232              onChange={(e) => setSeeking(Number(e.target.value))} onPointerUp={() => { if (seeking !== null && video.current) { video.current.currentTime = seeking; setTime(seeking); } setSeeking(null); }}233              onKeyUp={() => { if (seeking !== null && video.current) { video.current.currentTime = seeking; setTime(seeking); setSeeking(null); } }} />234            <span className="w-12">{total ? clock(total) : "--:--"}</span>235          </div>236          {viaHls && buffered > 0 && total > 0 && buffered < total - 30 && <p className="px-1 pb-1 text-center text-[11px] text-faint">Fichier converti à la volée pour ce navigateur</p>}237          <div className="mt-1 flex items-center gap-1 sm:gap-2">238            <button aria-label={muted ? "Rétablir le son" : "Couper le son"} onClick={toggleMute} className={Btn}>{muted || volume === 0 ? <VolumeX className="h-6 w-6" /> : <Volume2 className="h-6 w-6" />}</button>239            <input type="range" min={0} max={1} step={0.05} value={muted ? 0 : volume} onChange={(e) => { const v = Number(e.target.value); setVolume(v); setMuted(v === 0); localStorage.setItem("sptv:volume", String(v)); localStorage.setItem("sptv:muted", v === 0 ? "1" : "0"); }} aria-label="Volume" className="hidden w-24 sm:block" />240            <div className="flex-1" />241            {info?.next && <button onClick={() => onNext(info.next!.mediaId)} className="flex h-12 items-center gap-2 rounded-full px-3 text-sm font-semibold hover:bg-white/15" aria-label={`Épisode suivant : ${info.next.label}`}><SkipForward className="h-6 w-6" /><span className="hidden md:inline">Épisode suivant</span></button>}242            {!!info?.subtitles.length && <button aria-label="Sous-titres" onClick={() => setMenu(menu === "subs" ? "none" : "subs")} className={cn(Btn, sub >= 0 && "bg-white/20")}><Captions className="h-6 w-6" /></button>}243            {(info?.audio.length ?? 0) > 1 && <button aria-label="Piste audio" onClick={() => setMenu(menu === "audio" ? "none" : "audio")} className={Btn}><Languages className="h-6 w-6" /></button>}244            <button aria-label="Vitesse de lecture" onClick={() => setMenu(menu === "speed" ? "none" : "speed")} className={cn(Btn, speed !== 1 && "bg-white/20")}><Gauge className="h-6 w-6" /></button>245            {airplay && <button aria-label="AirPlay" onClick={() => (video.current as HTMLVideoElement & { webkitShowPlaybackTargetPicker?: () => void })?.webkitShowPlaybackTargetPicker?.()} className={Btn}><Airplay className="h-6 w-6" /></button>}246            {typeof document !== "undefined" && document.pictureInPictureEnabled && <button aria-label="Image dans l'image" onClick={() => { if (document.pictureInPictureElement) document.exitPictureInPicture(); else video.current?.requestPictureInPicture().catch(() => {}); }} className={cn(Btn, "hidden sm:grid")}><PictureInPicture2 className="h-6 w-6" /></button>}247            <button aria-label={isFs ? "Quitter le plein écran" : "Plein écran"} onClick={fullscreen} className={Btn}>{isFs ? <Minimize className="h-6 w-6" /> : <Maximize className="h-6 w-6" />}</button>248          </div>249        </div>250      </div>251252      {menu !== "none" && info && (253        <div className="absolute inset-0 z-10 flex items-end justify-center bg-black/50 sm:items-center" onClick={() => setMenu("none")}>254          <div className="sheet glass max-h-[70dvh] w-full max-w-sm overflow-y-auto rounded-t-3xl p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] ring-1 ring-line sm:rounded-3xl" onClick={(e) => e.stopPropagation()} role="dialog" aria-label={menu === "subs" ? "Sous-titres" : menu === "audio" ? "Piste audio" : "Vitesse"}>255            <h3 className="px-4 py-2 text-xs font-semibold uppercase tracking-wide text-faint">{menu === "subs" ? "Sous-titres" : menu === "audio" ? "Piste audio" : "Vitesse de lecture"}</h3>256            {menu === "subs" && <><button autoFocus className={item(sub === -1)} onClick={() => { setSub(-1); setMenu("none"); }}>Désactivés</button>{info.subtitles.map((s, i) => <button key={i} className={item(sub === i)} onClick={() => { setSub(i); setMenu("none"); }}>{s.label}</button>)}</>}257            {menu === "audio" && info.audio.map((a) => <button key={a.index} autoFocus={a.index === audio} className={item(audio === a.index)} onClick={() => { startAt.current = video.current?.currentTime ?? 0; setAudio(a.index); setMenu("none"); }}>{a.label}<span className="text-xs text-faint">{a.lang !== "und" ? a.lang.toUpperCase() : ""}</span></button>)}258            {menu === "speed" && SPEEDS.map((s) => <button key={s} autoFocus={s === speed} className={item(speed === s)} onClick={() => { setSpeed(s); setMenu("none"); }}>{s === 1 ? "Normale" : `${s}×`}</button>)}259          </div>260        </div>261      )}262    </div>263  );264}265
Files main
Menu

Theme