Repository Public
1"use client";2import { useEffect, useMemo, useRef, useState } from "react";3import { Icon } from "@/components/ui/Icon";4import { Tabs } from "@/components/ui/Tabs";5import { downloadText, readTextFile } from "@/lib/client/files";6import { update, useAtlas, useHydrated } from "@/lib/client/store";7import { formatTime, watchPath } from "@/modules/content-schema/urls";8import { addBookmark, capsuleKey, notesFromMarkdown, notesToMarkdown, removeBookmark, setNote } from "@/modules/learning-engine/state";9import { fold } from "@/modules/learning-engine/text";10import { activeChapter, activeSegment, transcriptToText } from "@/modules/learning-engine/vtt";11import { highlight, queryTerms } from "@/modules/search";12import type { PlayerCapsule, PlayerSession } from "./types";1314interface Props { session: PlayerSession; capsule: PlayerCapsule; time: number; seek: (t: number) => void }1516function Transcript({ session, capsule, time, seek }: Props) {17 const segments = useMemo(() => capsule.transcript ?? [], [capsule.transcript]);18 const [q, setQ] = useState("");19 const [follow, setFollow] = useState(true);20 const list = useRef<HTMLOListElement>(null);21 const current = activeSegment(segments, time);22 const terms = useMemo(() => queryTerms(q), [q]);23 const shown = useMemo(() => {24 const needle = fold(q);25 return segments.map((s, i) => ({ s, i })).filter(({ s }) => !needle || needle.split(" ").every((w) => fold(s.text).includes(w)));26 }, [segments, q]);2728 useEffect(() => {29 if (!follow || q || current < 0) return;30 const el = list.current?.querySelector<HTMLElement>(`[data-index="${current}"]`), box = list.current;31 // Scroll inside the panel only: the page itself never moves under the reader.32 if (el && box) box.scrollTo({ top: el.offsetTop - box.offsetTop - box.clientHeight / 3, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });33 }, [current, follow, q]);3435 if (!segments.length) return <p className="p-2 text-muted">Aucune transcription n’accompagne cette vidéo pour l’instant.</p>;36 return (37 <div data-testid="transcript">38 <div className="flex flex-wrap items-center gap-2">39 <label className="relative grow">40 <span className="sr-only">Chercher dans la transcription</span>41 <Icon name="search" size={16} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-faint" />42 <input type="search" className="field !min-h-10 !py-1 !pl-9 text-[0.95rem]" placeholder="Chercher un mot" value={q} onChange={(e) => setQ(e.target.value)} data-testid="transcript-search" />43 </label>44 <button type="button" className="btn btn-quiet btn-sm" onClick={() => downloadText(`atlas-ia-${session.id}-${capsule.id}-transcription.txt`, transcriptToText(`${session.title} — ${capsule.title}`, segments))} data-testid="transcript-export"><Icon name="download" size={16} />Exporter</button>45 </div>46 <div className="mt-2 flex items-center justify-between gap-3 text-sm text-muted">47 <span role="status" aria-live="polite" data-testid="transcript-count">{q ? `${shown.length} passage${shown.length > 1 ? "s" : ""} trouvé${shown.length > 1 ? "s" : ""}` : `${segments.length} passages`}</span>48 <label className="flex items-center gap-2"><input type="checkbox" className="size-4 accent-(--blue)" checked={follow} onChange={(e) => setFollow(e.target.checked)} />Suivre la lecture</label>49 </div>50 <ol ref={list} className="mt-2 max-h-[26rem] overflow-y-auto pr-1" tabIndex={0} aria-label="Transcription horodatée">51 {shown.map(({ s, i }) => (52 <li key={i}>53 <button type="button" data-index={i} aria-current={i === current ? "true" : undefined} onClick={() => seek(s.start)}54 className="flex w-full gap-3 rounded-lg border-l-[3px] border-transparent px-2 py-2 text-left text-[0.95rem] hover:bg-panel aria-[current=true]:border-blue aria-[current=true]:bg-blue-soft" data-testid="transcript-segment">55 <span className="w-10 shrink-0 pt-0.5 font-mono text-[0.8rem] text-blue">{formatTime(s.start)}</span>56 <span>{q ? highlight(s.text, terms).map((f, j) => (f.hit ? <mark key={j}>{f.text}</mark> : <span key={j}>{f.text}</span>)) : s.text}{i === current && <span className="sr-only"> (passage en cours)</span>}</span>57 </button>58 </li>59 ))}60 </ol>61 {q && shown.length === 0 && <p className="p-2 text-muted">Aucun passage ne contient « {q} ».</p>}62 </div>63 );64}6566function ChaptersPanel({ capsule, time, seek }: Props) {67 const chapters = capsule.chapters ?? [];68 const current = activeChapter(chapters, time);69 if (!chapters.length) return <p className="p-2 text-muted">Cette vidéo n’est pas découpée en chapitres.</p>;70 return (71 <ol className="grid gap-1" data-testid="chapters">72 {chapters.map((c, i) => (73 <li key={c.start}>74 <button type="button" onClick={() => seek(c.start)} aria-current={i === current ? "true" : undefined} className="flex w-full items-baseline gap-3 rounded-lg border-l-[3px] border-transparent px-2 py-2.5 text-left hover:bg-panel aria-[current=true]:border-blue aria-[current=true]:bg-blue-soft" data-testid="chapter">75 <span className="w-10 shrink-0 font-mono text-[0.8rem] text-blue">{formatTime(c.start)}</span>76 <span className="grow">{c.title}{i === current && <span className="sr-only"> (chapitre en cours)</span>}</span>77 <span className="font-mono text-xs text-faint">{formatTime((chapters[i + 1]?.start ?? capsule.durationSeconds) - c.start)}</span>78 </button>79 </li>80 ))}81 </ol>82 );83}8485function BookmarksPanel({ session, capsule, time, seek }: Props) {86 const key = capsuleKey(session.id, capsule.id);87 const marks = useAtlas().bookmarks[key] ?? [];88 const hydrated = useHydrated();89 const [label, setLabel] = useState("");90 return (91 <div data-testid="bookmarks">92 <form className="flex gap-2" onSubmit={(e) => { e.preventDefault(); update((s) => addBookmark(s, key, time, label || "Signet")); setLabel(""); }}>93 <label className="grow"><span className="sr-only">Libellé du signet</span><input className="field !min-h-10 !py-1 text-[0.95rem]" placeholder="Libellé (facultatif)" value={label} maxLength={200} onChange={(e) => setLabel(e.target.value)} data-testid="bookmark-label" /></label>94 <button type="submit" className="btn btn-primary btn-sm shrink-0" data-testid="bookmark-add">Ajouter à {formatTime(time)}</button>95 </form>96 {hydrated && marks.length === 0 && <p className="mt-4 text-muted">Aucun signet. Un signet retient un instant de la vidéo pour y revenir d’un clic. Les signets restent dans votre navigateur.</p>}97 <ul className="mt-3 grid gap-1">98 {hydrated && marks.map((b) => (99 <li key={b.id} className="flex items-center gap-1" data-testid="bookmark">100 <button type="button" onClick={() => seek(b.t)} className="flex grow items-baseline gap-3 rounded-lg px-2 py-2 text-left hover:bg-panel">101 <span className="w-10 shrink-0 font-mono text-[0.8rem] text-blue">{formatTime(b.t)}</span><span>{b.label}</span>102 </button>103 <a href={watchPath(session.slug, { capsule: capsule.id, t: b.t })} className="btn btn-quiet btn-sm !px-2" aria-label={`Lien direct vers le signet « ${b.label} » à ${formatTime(b.t)}`}><Icon name="link" size={16} /></a>104 <button type="button" className="btn btn-quiet btn-sm !px-2" onClick={() => update((s) => removeBookmark(s, key, b.id))} aria-label={`Supprimer le signet « ${b.label} » à ${formatTime(b.t)}`}><Icon name="trash" size={16} /></button>105 </li>106 ))}107 </ul>108 </div>109 );110}111112function NotesPanel({ session, time }: Props) {113 const stored = useAtlas().notes[session.id]?.text ?? "";114 const hydrated = useHydrated();115 const [draft, setDraft] = useState<string | null>(null);116 const [status, setStatus] = useState("");117 const area = useRef<HTMLTextAreaElement>(null), file = useRef<HTMLInputElement>(null);118 const value = draft ?? stored;119120 useEffect(() => {121 if (draft === null || draft === stored) return;122 const id = window.setTimeout(() => { const ok = update((s) => setNote(s, session.id, draft)); setStatus(ok ? "Notes enregistrées dans votre navigateur." : "Votre navigateur refuse l’enregistrement local : exportez vos notes pour ne pas les perdre."); }, 400);123 return () => window.clearTimeout(id);124 }, [draft, stored, session.id]);125126 // Leaving the tab or the page within the debounce delay must not lose the last keystrokes.127 const latest = useRef<string | null>(null);128 useEffect(() => { latest.current = draft; }, [draft]);129 useEffect(() => () => { const text = latest.current; if (text !== null) update((s) => (s.notes[session.id]?.text ?? "") === text ? s : setNote(s, session.id, text)); }, [session.id]);130131 const insertTime = () => {132 const el = area.current, stamp = `[${formatTime(time)}] `;133 const at = el ? el.selectionStart : value.length;134 setDraft(`${value.slice(0, at)}${stamp}${value.slice(at)}`);135 requestAnimationFrame(() => { el?.focus(); el?.setSelectionRange(at + stamp.length, at + stamp.length); });136 };137 const onImport = async (f: File | undefined) => {138 if (!f) return;139 const text = await readTextFile(f, 1_000_000);140 if (text === null) { setStatus("Fichier trop volumineux."); return; }141 const mine = notesFromMarkdown(text)[session.id];142 if (!mine) { setStatus("Ce fichier ne contient pas de notes pour cette séance."); return; }143 setDraft(value.trim() ? `${value.trim()}\n\n${mine}` : mine);144 setStatus("Notes importées et ajoutées à la suite des vôtres.");145 };146147 return (148 <div data-testid="notes">149 <label htmlFor={`notes-${session.id}`} className="text-sm font-medium">Mes notes pour cette séance</label>150 <textarea ref={area} id={`notes-${session.id}`} className="field mt-1 min-h-56 text-[0.97rem] leading-relaxed" value={hydrated ? value : ""} onChange={(e) => setDraft(e.target.value)} placeholder="Écrivez ici. Vos notes restent sur cet appareil." data-testid="notes-area" />151 <div className="mt-2 flex flex-wrap gap-2">152 <button type="button" className="btn btn-quiet btn-sm" onClick={insertTime}><Icon name="clock" size={16} />Insérer {formatTime(time)}</button>153 <button type="button" className="btn btn-quiet btn-sm" disabled={!value.trim()} onClick={() => downloadText(`atlas-ia-${session.id}-notes.md`, notesToMarkdown({ v: 1, updatedAt: "", prefs: {}, capsules: {}, bookmarks: {}, quizzes: {}, done: {}, slides: {}, lessons: {}, notes: { [session.id]: { text: value, updatedAt: "" } } }, { [session.id]: session.title }), "text/markdown")} data-testid="notes-export"><Icon name="download" size={16} />Exporter (.md)</button>154 <button type="button" className="btn btn-quiet btn-sm" onClick={() => file.current?.click()}><Icon name="upload" size={16} />Importer (.md)</button>155 <input ref={file} type="file" accept=".md,text/markdown,text/plain" className="hidden" onChange={(e) => { void onImport(e.target.files?.[0]); e.target.value = ""; }} aria-label="Importer un fichier de notes" />156 </div>157 <p className="mt-2 min-h-5 text-sm text-muted" role="status" aria-live="polite" data-testid="notes-status">{status}</p>158 </div>159 );160}161162export function Panels(props: Props) {163 const [tab, setTab] = useState("transcription");164 const count = useAtlas().bookmarks[capsuleKey(props.session.id, props.capsule.id)]?.length ?? 0;165 const hydrated = useHydrated();166 return (167 <Tabs label="Outils d’étude" active={tab} onChange={setTab} tabs={[168 { id: "transcription", label: <><Icon name="text" size={16} />Transcription</>, panel: <Transcript {...props} /> },169 { id: "chapitres", label: <><Icon name="list" size={16} />Chapitres</>, panel: <ChaptersPanel {...props} /> },170 { id: "signets", label: <><Icon name="bookmark" size={16} />Signets{hydrated && count > 0 ? ` (${count})` : ""}</>, panel: <BookmarksPanel {...props} /> },171 { id: "notes", label: <><Icon name="note" size={16} />Notes</>, panel: <NotesPanel {...props} /> },172 ]} />173 );174}175