Repository Public
1"use client";2import { useCallback, useEffect, useRef, useState } from "react";3import type HlsType from "hls.js";4import { formatDuration, type PlayerLabels } from "@/lib/i18n";5import { emitTime, onSeekRequest } from "./bus";67export interface PlayerProps {8 slug: string; title: string;9 hls: string | null; mp4: string | null;10 poster: string | null; captions: string | null; captionsLang: string; captionsLabel: string;11 duration: number; width: number; height: number;12 labels: PlayerLabels;13 autoPlay?: boolean;14 /** Posé dans un cadre déjà arrondi (héros de l'accueil) : pas de coins ni d'ombre propres. */15 embedded?: boolean;16}17interface Level { index: number; height: number; bitrate: number }1819const Icon = ({ d, fill = false }: { d: string; fill?: boolean }) => (20 <svg width="22" height="22" viewBox="0 0 24 24" fill={fill ? "currentColor" : "none"} stroke={fill ? "none" : "currentColor"} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={d} /></svg>21);2223function showCaptions(v: HTMLVideoElement | null, on: boolean) {24 const t = v?.textTracks?.[0];25 if (t) t.mode = on ? "showing" : "hidden";26}2728/**29 * Lecteur HLS adaptatif. hls.js n'est chargé (import dynamique) que lorsque ce composant est monté ; Safari lit le HLS nativement.30 * Commandes HTML réelles (boutons, curseurs) : tout est atteignable au clavier et annoncé aux lecteurs d'écran.31 */32export default function Player(p: PlayerProps) {33 const box = useRef<HTMLDivElement>(null);34 const video = useRef<HTMLVideoElement>(null);35 const hlsRef = useRef<HlsType | null>(null);36 const viewed = useRef(false);37 const [playing, setPlaying] = useState(false);38 const [started, setStarted] = useState(false);39 const [time, setTime] = useState(0);40 const [dur, setDur] = useState(p.duration);41 const [muted, setMuted] = useState(false);42 const [volume, setVolume] = useState(1);43 const [cc, setCc] = useState(false);44 const [levels, setLevels] = useState<Level[]>([]);45 const [level, setLevel] = useState(-1);46 const [autoHeight, setAutoHeight] = useState<number | null>(null);47 const [full, setFull] = useState(false);48 const [failed, setFailed] = useState(false);49 const [engine, setEngine] = useState<"" | "hls.js" | "native" | "mp4">("");5051 // ── source ──52 useEffect(() => {53 const v = video.current;54 if (!v) return;55 let cancelled = false;56 const nativeHls = v.canPlayType("application/vnd.apple.mpegurl") !== "";57 const safari = /^((?!chrome|chromium|android|crios|fxios|edg).)*safari/i.test(navigator.userAgent);58 const playNative = (src: string, kind: "native" | "mp4") => { v.src = src; setEngine(kind); if (p.autoPlay) v.play().catch(() => {}); };59 if (!p.hls) { if (p.mp4) playNative(p.mp4, "mp4"); else setFailed(true); return; }60 if (nativeHls && safari) { playNative(p.hls, "native"); return; }61 import("hls.js").then(({ default: Hls }) => {62 if (cancelled) return;63 if (!Hls.isSupported()) { if (nativeHls) playNative(p.hls!, "native"); else if (p.mp4) playNative(p.mp4, "mp4"); else setFailed(true); return; }64 // Pas de worker : la CSP du site n'autorise pas les scripts blob:.65 const hls = new Hls({ enableWorker: false, capLevelToPlayerSize: true, startLevel: -1, maxBufferLength: 20 });66 hlsRef.current = hls;67 hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {68 setLevels(data.levels.map((l, index) => ({ index, height: l.height, bitrate: l.bitrate })).sort((a, b) => b.height - a.height || b.bitrate - a.bitrate));69 hls.subtitleDisplay = false; // les sous-titres viennent de la piste <track> (captions.vtt)70 if (p.autoPlay) v.play().catch(() => {});71 });72 hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => setAutoHeight(hls.levels[data.level]?.height ?? null));73 hls.on(Hls.Events.ERROR, (_e, data) => {74 if (!data.fatal) return;75 if (data.type === Hls.ErrorTypes.NETWORK_ERROR && data.details !== Hls.ErrorDetails.MANIFEST_LOAD_ERROR) hls.startLoad();76 else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError();77 else { hls.destroy(); hlsRef.current = null; setFailed(true); }78 });79 hls.loadSource(p.hls!);80 hls.attachMedia(v);81 setEngine("hls.js");82 }).catch(() => { if (!cancelled) setFailed(true); });83 return () => { cancelled = true; hlsRef.current?.destroy(); hlsRef.current = null; };84 }, [p.hls, p.mp4, p.autoPlay]);8586 // ── actions ──87 const toggle = useCallback(() => { const v = video.current; if (!v) return; if (v.paused) v.play().catch(() => {}); else v.pause(); }, []);88 const seekTo = useCallback((s: number) => {89 const v = video.current; if (!v) return;90 const max = Number.isFinite(v.duration) ? v.duration : p.duration;91 v.currentTime = Math.min(Math.max(0, s), Math.max(0, max - 0.05));92 setTime(v.currentTime); emitTime(v.currentTime);93 }, [p.duration]);94 const toggleMute = useCallback(() => { const v = video.current; if (v) v.muted = !v.muted; }, []);95 const changeVolume = useCallback((x: number) => { const v = video.current; if (!v) return; v.volume = Math.min(1, Math.max(0, x)); if (v.volume > 0) v.muted = false; }, []);96 const toggleCc = useCallback(() => setCc((x) => !x), []);97 const toggleFull = useCallback(() => {98 const el = box.current, v = video.current as (HTMLVideoElement & { webkitEnterFullscreen?: () => void }) | null;99 if (!el || !v) return;100 if (document.fullscreenElement) document.exitFullscreen().catch(() => {});101 else if (el.requestFullscreen) el.requestFullscreen().catch(() => {});102 else v.webkitEnterFullscreen?.(); // iPhone : plein écran natif de la vidéo103 }, []);104105 useEffect(() => {106 showCaptions(video.current, cc);107 }, [cc, engine]);108 useEffect(() => { const h = hlsRef.current; if (h) h.currentLevel = level; }, [level]);109 useEffect(() => {110 const f = () => setFull(document.fullscreenElement === box.current);111 document.addEventListener("fullscreenchange", f);112 return () => document.removeEventListener("fullscreenchange", f);113 }, []);114 useEffect(() => onSeekRequest((s) => {115 seekTo(s);116 video.current?.play().catch(() => {});117 box.current?.scrollIntoView({ block: "nearest", behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });118 }), [seekTo]);119120 // ── raccourcis clavier (hors champs de saisie) ──121 useEffect(() => {122 function key(e: KeyboardEvent) {123 if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;124 const el = e.target as HTMLElement | null;125 const tag = el?.tagName ?? "";126 if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || el?.isContentEditable) return;127 const onControl = tag === "BUTTON" || tag === "A" || tag === "SUMMARY";128 const v = video.current; if (!v) return;129 const k = e.key.toLowerCase();130 if (k === " " || k === "spacebar") { if (onControl) return; e.preventDefault(); toggle(); }131 else if (k === "k") toggle();132 else if (k === "arrowleft") { e.preventDefault(); seekTo(v.currentTime - 5); }133 else if (k === "arrowright") { e.preventDefault(); seekTo(v.currentTime + 5); }134 else if (k === "arrowup") { if (!box.current?.contains(el)) return; e.preventDefault(); changeVolume(v.volume + 0.1); }135 else if (k === "arrowdown") { if (!box.current?.contains(el)) return; e.preventDefault(); changeVolume(v.volume - 0.1); }136 else if (k === "m") toggleMute();137 else if (k === "f") toggleFull();138 else if (k === "c") { if (p.captions) toggleCc(); }139 }140 document.addEventListener("keydown", key);141 return () => document.removeEventListener("keydown", key);142 }, [toggle, seekTo, changeVolume, toggleMute, toggleFull, toggleCc, p.captions]);143144 function onPlaying() {145 setPlaying(true); setStarted(true);146 if (!viewed.current) {147 viewed.current = true;148 fetch(`/api/public/videos/${encodeURIComponent(p.slug)}/view`, { method: "POST", keepalive: true }).catch(() => {});149 }150 }151152 const vertical = p.height > p.width;153 const pct = dur > 0 ? Math.min(100, (time / dur) * 100) : 0;154 const L = p.labels;155 return (156 <div ref={box} className={`player on-dark overflow-hidden ${p.embedded ? "" : "sm:rounded-3xl sm:shadow-[var(--shadow-lift)]"}`} role="region" aria-label={`${L.region} — ${p.title}`} data-testid="player" data-engine={engine}>157 <div className="player-stage relative mx-auto bg-black" style={{ aspectRatio: `${p.width} / ${p.height}`, maxHeight: vertical ? "78vh" : "80vh", width: vertical ? "auto" : "100%" }}>158 <video ref={video} className="h-full w-full" playsInline preload="metadata" poster={p.poster ?? undefined} width={p.width} height={p.height}159 onClick={toggle} onPlaying={onPlaying} onPause={() => setPlaying(false)} onEnded={() => setPlaying(false)}160 onTimeUpdate={(e) => { setTime(e.currentTarget.currentTime); emitTime(e.currentTarget.currentTime); }}161 onDurationChange={(e) => { if (Number.isFinite(e.currentTarget.duration)) setDur(e.currentTarget.duration); }}162 onVolumeChange={(e) => { setMuted(e.currentTarget.muted); setVolume(e.currentTarget.volume); }}163 onError={() => { if (engine !== "hls.js") setFailed(true); }}>164 {p.captions && <track kind="subtitles" src={p.captions} srcLang={p.captionsLang} label={p.captionsLabel} />}165 </video>166 {!started && !failed && (167 <button type="button" onClick={toggle} aria-label={`${L.play} — ${p.title}`} data-testid="big-play"168 className="absolute inset-0 flex items-center justify-center bg-black/20 transition-colors hover:bg-black/10">169 <span className="play-disc" style={{ width: 76, height: 76 }}>170 <svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5.14v13.72a1 1 0 0 0 1.53.85l10.8-6.86a1 1 0 0 0 0-1.7L9.53 4.3A1 1 0 0 0 8 5.14Z" /></svg>171 </span>172 </button>173 )}174 {failed && <p role="alert" className="absolute inset-0 flex items-center justify-center bg-black/80 p-6 text-center text-sm text-ink">{L.error}</p>}175 </div>176177 <div className="bg-[#0d0e12] px-2 pb-1 sm:px-3">178 <input type="range" className="seek block" min={0} max={Math.max(dur, 0.1)} step={0.1} value={Math.min(time, dur)} aria-label={L.seek}179 aria-valuetext={`${formatDuration(time)} / ${formatDuration(dur)}`} style={{ ["--seek" as string]: `${pct}%` }}180 onChange={(e) => seekTo(Number(e.target.value))} data-testid="seek" />181 <div className="-mt-1 flex items-center gap-0.5 sm:gap-1">182 <button type="button" className="ctl" onClick={toggle} aria-label={playing ? L.pause : L.play} data-testid="play-toggle">183 {playing ? <Icon fill d="M7 5h3.5v14H7zM13.5 5H17v14h-3.5z" /> : <Icon fill d="M8 5.14v13.72a1 1 0 0 0 1.53.85l10.8-6.86a1 1 0 0 0 0-1.7L9.53 4.3A1 1 0 0 0 8 5.14Z" />}184 </button>185 <button type="button" className="ctl" onClick={toggleMute} aria-label={muted || volume === 0 ? L.unmute : L.mute} aria-pressed={muted} data-testid="mute-toggle">186 {muted || volume === 0 ? <Icon d="M11 5 6 9H2v6h4l5 4V5ZM22 9l-6 6M16 9l6 6" /> : <Icon d="M11 5 6 9H2v6h4l5 4V5ZM15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13" />}187 </button>188 <input type="range" min={0} max={1} step={0.05} value={muted ? 0 : volume} onChange={(e) => changeVolume(Number(e.target.value))} aria-label={L.volume}189 aria-valuetext={`${Math.round((muted ? 0 : volume) * 100)} %`} className="seek hidden !w-20 md:block" style={{ ["--seek" as string]: `${(muted ? 0 : volume) * 100}%` }} />190 <span className="ml-1 whitespace-nowrap text-xs tabular-nums text-ink/90 sm:text-sm" data-testid="time"><span>{formatDuration(time)}</span> <span className="text-muted">/ {formatDuration(dur)}</span></span>191 <span className="flex-1" />192 {p.captions && (193 <button type="button" className="ctl" onClick={toggleCc} aria-pressed={cc} aria-label={cc ? L.captionsOff : L.captionsOn} data-testid="cc-toggle">194 <span className={`rounded border-2 px-1 text-[0.7rem] font-bold leading-4 ${cc ? "border-accent" : "border-current"}`} aria-hidden="true">CC</span>195 </button>196 )}197 {levels.length > 0 && (198 <label className="relative inline-flex h-11 items-center">199 <span className="sr-only">{L.quality}</span>200 <select value={level} onChange={(e) => setLevel(Number(e.target.value))} data-testid="quality"201 className="h-9 cursor-pointer rounded-lg border border-line bg-surface-2 px-2 text-xs font-medium text-ink sm:text-sm">202 <option value={-1}>{L.auto}{level === -1 && autoHeight ? ` (${autoHeight}p)` : ""}</option>203 {levels.map((l) => <option key={l.index} value={l.index}>{l.height}p</option>)}204 </select>205 </label>206 )}207 <button type="button" className="ctl" onClick={toggleFull} aria-label={full ? L.exitFullscreen : L.fullscreen} data-testid="fullscreen">208 {full ? <Icon d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5" /> : <Icon d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />}209 </button>210 </div>211 </div>212 <p className="sr-only">{L.shortcuts}</p>213 </div>214 );215}216