SPB Git

Repository Public

SlideDeck.tsx 15.3 KB 187 lines tsx

1"use client";2import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type TouchEvent } from "react";3import { Icon } from "@/components/ui/Icon";4import { update, useAtlas, useHydrated } from "@/lib/client/store";5import { setSlide } from "@/modules/learning-engine/state";67export interface DeckSlide {8  n: number; id: string | null; kind: "title" | "section" | "content" | "references" | "closing"; title: string; section: string | null; text: string;9  figures: { id: string; alt: string }[]; dark: string; light: string; thumbDark: string; thumbLight: string;10}11type Variant = "site" | "dark" | "light";12const VARIANT_LABEL: Record<Variant, string> = { site: "comme le site", dark: "sombre", light: "clair" };13const KIND_LABEL: Record<DeckSlide["kind"], string> = { title: "Page de titre", section: "Intertitre", content: "", references: "Références", closing: "Clôture" };1415/** Reads a slide from an address fragment: #diapositive-12, or a slide identifier such as #S01-D09. */16function fromHash(hash: string, slides: DeckSlide[]): number | null {17  const h = decodeURIComponent(hash.replace(/^#/, ""));18  const m = /^diapositive-(\d{1,4})$/.exec(h);19  if (m) { const n = Number(m[1]); return n >= 1 && n <= slides.length ? n : null; }20  return slides.find((s) => s.id === h)?.n ?? null;21}22const useSiteTheme = (): "dark" | "light" => {23  const [t, setT] = useState<"dark" | "light">("light");24  useEffect(() => {25    const read = () => setT(document.documentElement.dataset.theme === "dark" ? "dark" : "light");26    read();27    const o = new MutationObserver(read);28    o.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });29    return () => o.disconnect();30  }, []);31  return t;32};3334/**35 * The slide viewer: one slide at a time, with everything needed to move through a deck by mouse, keyboard36 * or touch, and a real text alternative for each slide. Slides are vector images, one per theme.37 */38export function SlideDeck({ sessionId, sessionTitle, slides, path, ratio, pdfHref = null, heading = "h2", lessonSlides }: { sessionId: string; sessionTitle: string; slides: DeckSlide[]; path: string; ratio: number; pdfHref?: string | null; heading?: "h2" | "h3"; lessonSlides?: string[] }) {39  const uid = useId(), root = useRef<HTMLDivElement>(null), hydrated = useHydrated(), stored = useAtlas().slides?.[sessionId]?.n ?? null, site = useSiteTheme();40  const [n, setN] = useState(1), [variant, setVariant] = useState<Variant>("site"), [overview, setOverview] = useState(false), [textOpen, setTextOpen] = useState(false);41  const [full, setFull] = useState(false), [typed, setTyped] = useState(""), [message, setMessage] = useState(""), [resumed, setResumed] = useState<number | null>(null), [started, setStarted] = useState(false);42  const total = slides.length, slide = slides[n - 1]!, theme = variant === "site" ? site : variant;43  const sections = useMemo(() => slides.filter((s) => s.kind === "section"), [slides]);44  const Heading = heading;4546  const go = useCallback((to: number, o: { silent?: boolean } = {}) => {47    const next = Math.max(1, Math.min(total, Math.round(to)));48    setN(next); setTyped("");49    if (!o.silent) { window.history.replaceState(null, "", `#diapositive-${next}`); update((s) => setSlide(s, sessionId, next)); }50  }, [sessionId, total]);5152  // Where to start: the slide named by the address, else the last one viewed in this browser, else the first.53  useEffect(() => {54    if (!hydrated || started) return;55    const linked = fromHash(window.location.hash, slides);56    if (linked) { setN(linked); window.setTimeout(() => root.current?.scrollIntoView({ block: "start" }), 60); } // after the page has settled57    else if (stored && stored > 1 && stored <= total) { setN(stored); setResumed(stored); }58    setStarted(true);59  }, [hydrated, started, slides, stored, total]);60  useEffect(() => {61    const onHash = () => { const linked = fromHash(window.location.hash, slides); if (linked) { go(linked, { silent: true }); root.current?.scrollIntoView({ block: "start" }); } };62    window.addEventListener("hashchange", onHash);63    return () => window.removeEventListener("hashchange", onHash);64  }, [go, slides]);65  // The neighbours are fetched ahead, so moving on is instant.66  useEffect(() => { for (const s of [slides[n], slides[n - 2]]) if (s) { const img = new Image(); img.src = s[theme]; } }, [n, slides, theme]);67  useEffect(() => {68    const onFs = () => setFull(document.fullscreenElement === root.current);69    document.addEventListener("fullscreenchange", onFs);70    return () => document.removeEventListener("fullscreenchange", onFs);71  }, []);7273  const toggleFull = () => {74    const el = root.current; if (!el) return;75    if (document.fullscreenElement) void document.exitFullscreen();76    else if (el.requestFullscreen) el.requestFullscreen().catch(() => setFull((v) => !v)); // some phones refuse: fall back to a page-filling layout77    else setFull((v) => !v);78  };79  const copy = () => {80    const url = `${window.location.origin}${path}#${slide.id ?? `diapositive-${n}`}`;81    navigator.clipboard?.writeText(url).then(() => setMessage("Lien vers cette diapositive copié."), () => setMessage(url));82  };83  const onKey = (e: KeyboardEvent) => {84    const t = e.target as HTMLElement;85    if (e.altKey || e.ctrlKey || e.metaKey || ["INPUT", "SELECT", "TEXTAREA"].includes(t.tagName)) return;86    const act = (fn: () => void) => { e.preventDefault(); fn(); };87    if (e.key === "ArrowRight" || e.key === "PageDown") act(() => go(n + 1));88    else if (e.key === "ArrowLeft" || e.key === "PageUp") act(() => go(n - 1));89    else if (e.key === "Home") act(() => go(1));90    else if (e.key === "End") act(() => go(total));91    else if (/^\d$/.test(e.key)) act(() => setTyped((v) => (v + e.key).slice(-4)));92    else if (e.key === "Enter" && typed) act(() => go(Number(typed))); // a number was typed: Enter goes there, whatever has the focus93    else if (e.key === "Escape" && (overview || typed || (full && !document.fullscreenElement))) act(() => { setOverview(false); setTyped(""); if (!document.fullscreenElement) setFull(false); });94    else if (e.key.toLowerCase() === "f") act(toggleFull);95    else if (e.key.toLowerCase() === "g") act(() => setOverview((v) => !v));96  };97  const touch = useRef<{ x: number; y: number } | null>(null);98  const onTouchStart = (e: TouchEvent) => { const p = e.touches[0]; touch.current = p ? { x: p.clientX, y: p.clientY } : null; };99  const onTouchEnd = (e: TouchEvent) => {100    const p = e.changedTouches[0], s = touch.current; touch.current = null;101    if (!p || !s) return;102    const dx = p.clientX - s.x, dy = p.clientY - s.y;103    if (Math.abs(dx) > 45 && Math.abs(dx) > Math.abs(dy) * 1.5) go(n + (dx < 0 ? 1 : -1));104  };105  // Previous/next stay focusable at the ends of the deck (aria-disabled): a disabled button would drop the keyboard focus.106  const btn = "btn btn-quiet btn-sm !min-h-11 !min-w-11 !px-2.5";107  const describedBy = `${uid}-texte`;108109  return (110    <div ref={root} className="deck card overflow-hidden" data-testid="slide-deck" data-slide={n} data-theme-variant={theme} data-full={full ? "1" : undefined} onKeyDown={onKey} role="group" aria-roledescription="visionneuse de diapositives" aria-label={`Diapositives — ${sessionTitle}`}>111      <div className="deck-bar flex flex-wrap items-center gap-x-3 gap-y-1 border-b border-line px-3 py-2">112        <Heading className="!text-base font-sans font-semibold">Diapositive <span data-testid="deck-counter">{n} sur {total}</span></Heading>113        <p className="min-w-0 grow truncate text-sm text-muted">{slide.section && slide.kind !== "section" ? `${slide.section} · ` : ""}{KIND_LABEL[slide.kind] || slide.title}</p>114        {slide.id && lessonSlides?.includes(slide.id) && <a href={`#lecon-${slide.id}`} className="link text-sm" data-testid="deck-to-lesson">Lire dans la leçon</a>}115        {slide.id && <span className="chip font-mono !text-[0.72rem]" title="Identifiant de la diapositive">{slide.id}</span>}116      </div>117118      <div className="deck-stage relative" style={{ aspectRatio: String(ratio), background: theme === "dark" ? "#0b1426" : "#ffffff" }} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>119        {/* eslint-disable-next-line @next/next/no-img-element -- vector slide served by a permission-checked route */}120        <img key={`${n}-${theme}`} src={slide[theme]} alt={`Diapositive ${n} sur ${total} : ${slide.title}`} aria-describedby={describedBy} className="absolute inset-0 size-full object-contain" draggable={false} decoding="async" data-testid="deck-image" />121        <button type="button" className="deck-edge left-0" onClick={() => go(n - 1)} disabled={n === 1} aria-label="Diapositive précédente" tabIndex={-1}><Icon name="back" size={22} /></button>122        <button type="button" className="deck-edge right-0" onClick={() => go(n + 1)} disabled={n === total} aria-label="Diapositive suivante" tabIndex={-1}><Icon name="arrow" size={22} /></button>123      </div>124      <div className="h-1 bg-panel" role="progressbar" aria-label="Avancement dans les diapositives" aria-valuemin={1} aria-valuemax={total} aria-valuenow={n}><div className="h-full bg-blue" style={{ width: `${(n / total) * 100}%` }} /></div>125126      <div className="deck-bar flex flex-wrap items-center gap-1.5 px-2 py-2">127        <button type="button" className={btn} onClick={() => go(n - 1)} aria-disabled={n === 1} data-testid="deck-prev"><Icon name="back" size={18} /><span className="max-sm:sr-only">Précédente</span></button>128        <button type="button" className={`${btn} !bg-fg !text-bg`} onClick={() => go(n + 1)} aria-disabled={n === total} data-testid="deck-next"><span className="max-sm:sr-only">Suivante</span><Icon name="arrow" size={18} /></button>129        <form className="flex items-center gap-1.5" onSubmit={(e) => { e.preventDefault(); const v = Number(new FormData(e.currentTarget).get("n")); if (v) go(v); e.currentTarget.reset(); }}>130          <label htmlFor={`${uid}-aller`} className="text-sm text-muted">Aller à</label>131          <input id={`${uid}-aller`} name="n" type="number" min={1} max={total} inputMode="numeric" placeholder={String(n)} className="field !min-h-11 !w-[4.5rem] !px-2 text-center" data-testid="deck-goto" />132        </form>133        {sections.length > 0 && (134          <select className="field !min-h-11 !w-auto max-w-[13rem] !py-1 text-sm" aria-label="Aller à une section" value="" onChange={(e) => { if (e.target.value) go(Number(e.target.value)); }} data-testid="deck-outline">135            <option value="">Plan…</option>136            {sections.map((s, i) => <option key={s.n} value={s.n}>{i + 1}. {s.title}</option>)}137          </select>138        )}139        <span className="grow" />140        <button type="button" className={btn} onClick={() => setOverview((v) => !v)} aria-expanded={overview} aria-controls={`${uid}-grille`} data-testid="deck-overview"><Icon name="layers" size={18} /><span className="max-md:sr-only">Vue d’ensemble</span></button>141        <button type="button" className={btn} onClick={() => setTextOpen((v) => !v)} aria-expanded={textOpen} aria-controls={describedBy} data-testid="deck-text-toggle"><Icon name="text" size={18} /><span className="max-md:sr-only">Version texte</span></button>142        <button type="button" className={btn} onClick={() => setVariant(variant === "site" ? (site === "dark" ? "light" : "dark") : "site")} aria-label={`Thème des diapositives : ${VARIANT_LABEL[variant]}. Changer.`} title={`Thème des diapositives : ${VARIANT_LABEL[variant]}`} data-testid="deck-theme"><Icon name={variant === "site" ? "auto" : variant === "dark" ? "moon" : "sun"} size={18} /></button>143        <button type="button" className={btn} onClick={copy} data-testid="deck-copy"><Icon name="link" size={18} /><span className="max-lg:sr-only">Copier le lien</span><span className="lg:hidden sr-only">Copier le lien de cette diapositive</span></button>144        <button type="button" className={btn} onClick={toggleFull} aria-pressed={full} data-testid="deck-full"><Icon name={full ? "close" : "full"} size={18} /><span className="max-lg:sr-only">{full ? "Quitter" : "Plein écran"}</span><span className="lg:hidden sr-only">{full ? "Quitter le plein écran" : "Plein écran"}</span></button>145        {pdfHref && <a href={pdfHref} className={btn} download data-testid="deck-pdf"><Icon name="download" size={18} /><span className="max-lg:sr-only">PDF</span><span className="lg:hidden sr-only">Télécharger les diapositives en PDF</span></a>}146      </div>147148      <p className="sr-only" role="status" aria-live="polite" data-testid="deck-status">{typed ? `Aller à la diapositive ${typed} : appuyez sur Entrée.` : `Diapositive ${n} sur ${total} : ${slide.title}`}</p>149      {(message || resumed || typed) && (150        <p className="deck-bar flex flex-wrap items-center gap-2 border-t border-line px-3 py-2 text-sm text-muted" data-testid="deck-note">151          {typed ? <>Aller à la diapositive <strong className="text-fg">{typed}</strong> — Entrée pour confirmer, Échap pour annuler.</>152            : message ? message153            : <>Reprise à la diapositive {resumed}, la dernière consultée dans ce navigateur. <button type="button" className="link" onClick={() => { go(1); setResumed(null); }}>Revenir au début</button></>}154        </p>155      )}156157      <div id={`${uid}-grille`} hidden={!overview} className="deck-bar border-t border-line p-3" data-testid="deck-grid">158        {overview && (159          <ol className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">160            {slides.map((s) => (161              <li key={s.n}>162                <button type="button" onClick={() => { go(s.n); setOverview(false); }} aria-current={s.n === n ? "true" : undefined} className="block w-full overflow-hidden rounded-lg border border-line text-left aria-[current=true]:border-blue aria-[current=true]:ring-2 aria-[current=true]:ring-blue">163                  {/* eslint-disable-next-line @next/next/no-img-element */}164                  <img src={theme === "dark" ? s.thumbDark : s.thumbLight} alt="" loading="lazy" decoding="async" className="block w-full" style={{ aspectRatio: String(ratio) }} />165                  <span className="block truncate px-2 py-1 text-xs"><span className="font-mono text-faint">{s.n}</span> {s.title}</span>166                </button>167              </li>168            ))}169          </ol>170        )}171      </div>172173      {/* The text alternative of the slide: always available to assistive technology, shown on demand. */}174      <div id={describedBy} className={textOpen ? "deck-bar border-t border-line p-4" : "sr-only"} data-testid="deck-text">175        <p className="eyebrow">Version texte — diapositive {n}</p>176        <div className="mt-2 max-w-[70ch] whitespace-pre-line text-[0.97rem]">{slide.text || slide.title}</div>177        {slide.figures.map((f) => <p key={f.id} className="mt-3 max-w-[70ch] border-l-2 border-line pl-3 text-[0.95rem] text-muted"><strong className="text-fg">Description de la figure.</strong> {f.alt}</p>)}178      </div>179180      <details className="deck-bar border-t border-line px-3 py-2 text-sm text-muted">181        <summary className="font-medium">Raccourcis clavier</summary>182        <p className="mt-2 leading-relaxed"><kbd>←</kbd> <kbd>→</kbd> diapositive précédente ou suivante · <kbd>Début</kbd> <kbd>Fin</kbd> première ou dernière · un numéro puis <kbd>Entrée</kbd> pour y aller · <kbd>G</kbd> vue d’ensemble · <kbd>F</kbd> plein écran · <kbd>Échap</kbd> pour fermer. Sur un écran tactile, balayez la diapositive vers la gauche ou la droite.</p>183      </details>184    </div>185  );186}187
Files main
Menu

Theme