SPB Git

Repository Public

DiagramBlock.tsx 12.5 KB 205 lines tsx

1"use client";2/**3 * Interactive wrapper of a diagram. The drawing itself is DiagramSvg (pure); this adds, once hydrated:4 * zoom (buttons, pinch, ctrl/⌘ + wheel), pan when zoomed, fit to screen, full screen, and the step player.5 * Before hydration and in print mode it is a static figure: the whole diagram, then every step as text.6 */7import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";8import type { BlockOf, Locale, Source } from "@/schema";9import { LegendList } from "../blocks/basic";10import { useHydrated, useReducedMotion } from "../hooks";11import { Inline } from "../inline";12import { t } from "../i18n";13import { DiagramSvg } from "./DiagramSvg";14import { layoutReadable, printDiagramPlan } from "./layout";1516export interface DiagramBlockProps { block: BlockOf<"diagram">; locale: Locale; mode: "public" | "editor" | "print"; sources?: Source[] }1718interface View { k: number; x: number; y: number }19const FIT: View = { k: 1, x: 0, y: 0 };20const MIN_K = 1, MAX_K = 6;21const SPEEDS = [0.5, 1, 2] as const;22const STEP_MS = 2600;2324const Glyph = ({ d }: { d: string }) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false"><path d={d} /></svg>;25const G = {26  plus: "M12 5v14M5 12h14", minus: "M5 12h14", fit: "M4 9V5h4M20 9V5h-4M4 15v4h4M20 15v4h-4M9 9h6v6H9Z",27  full: "M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5", exit: "M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5",28  prev: "M15 5l-7 7 7 7", next: "M9 5l7 7-7 7", play: "M8 5v14l11-7L8 5Z", pause: "M8 5v14M16 5v14", reset: "M4 12a8 8 0 1 0 2.6-5.9M4 4v5h5",29};3031export function DiagramBlock({ block, locale, mode, sources }: DiagramBlockProps) {32  const hydrated = useHydrated();33  const reduced = useReducedMotion();34  // Screen: the author's direction unless it is unreadable. PDF: the direction and panel that draw it largest.35  const plan = useMemo(() => (mode === "print" ? printDiagramPlan(block) : null), [block, mode]);36  const layout = useMemo(() => plan?.layout ?? layoutReadable(block), [block, plan]);37  const steps = block.animation?.steps ?? [];38  const interactive = hydrated && mode !== "print";3940  const figureRef = useRef<HTMLElement>(null);41  const stageRef = useRef<HTMLDivElement>(null);42  const [view, setView] = useState<View>(FIT);43  const [step, setStep] = useState<number | null>(null);44  const [playing, setPlaying] = useState(false);45  const [speed, setSpeed] = useState<(typeof SPEEDS)[number]>(1);46  const [full, setFull] = useState<"none" | "native" | "overlay">("none");47  const pointers = useRef(new Map<number, { x: number; y: number }>());48  const gesture = useRef<{ dist: number; k: number } | null>(null);4950  const clamp = useCallback((v: View): View => {51    const el = stageRef.current;52    const k = Math.max(MIN_K, Math.min(MAX_K, v.k));53    if (!el || k === 1) return FIT;54    const mx = (el.clientWidth * (k - 1)) / 2, my = (el.clientHeight * (k - 1)) / 2;55    return { k, x: Math.max(-mx, Math.min(mx, v.x)), y: Math.max(-my, Math.min(my, v.y)) };56  }, []);57  const zoomBy = useCallback((factor: number) => setView((v) => clamp({ k: v.k * factor, x: v.x * factor, y: v.y * factor })), [clamp]);5859  // ctrl/⌘ + wheel zooms (trackpad pinch arrives that way); a plain wheel scrolls the page as usual.60  useEffect(() => {61    const el = stageRef.current;62    if (!el || !interactive) return;63    const onWheel = (e: WheelEvent) => {64      if (!e.ctrlKey && !e.metaKey) return;65      e.preventDefault();66      const factor = Math.exp(-e.deltaY * 0.01);67      setView((v) => clamp({ k: v.k * factor, x: v.x * factor, y: v.y * factor }));68    };69    el.addEventListener("wheel", onWheel, { passive: false });70    return () => el.removeEventListener("wheel", onWheel);71  }, [interactive, clamp]);7273  const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {74    pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });75    if (pointers.current.size === 2) {76      const [a, b] = Array.from(pointers.current.values());77      gesture.current = { dist: Math.hypot(a.x - b.x, a.y - b.y) || 1, k: view.k };78    }79    if (view.k > 1 || pointers.current.size === 2) e.currentTarget.setPointerCapture?.(e.pointerId);80  };81  const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {82    const prev = pointers.current.get(e.pointerId);83    if (!prev) return;84    pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });85    if (pointers.current.size === 2 && gesture.current) {86      const [a, b] = Array.from(pointers.current.values());87      const k = gesture.current.k * (Math.hypot(a.x - b.x, a.y - b.y) / gesture.current.dist);88      setView((v) => clamp({ k, x: v.x * (k / v.k), y: v.y * (k / v.k) }));89    } else if (pointers.current.size === 1 && view.k > 1) {90      const dx = e.clientX - prev.x, dy = e.clientY - prev.y;91      setView((v) => clamp({ k: v.k, x: v.x + dx, y: v.y + dy }));92    }93  };94  const onPointerEnd = (e: ReactPointerEvent<HTMLDivElement>) => {95    pointers.current.delete(e.pointerId);96    if (pointers.current.size < 2) gesture.current = null;97  };9899  // Full screen: the Fullscreen API where it exists, a fixed overlay elsewhere (iPhone Safari).100  useEffect(() => {101    if (!interactive) return;102    const onChange = () => { if (!document.fullscreenElement) setFull((f) => (f === "native" ? "none" : f)); setView(FIT); };103    document.addEventListener("fullscreenchange", onChange);104    return () => document.removeEventListener("fullscreenchange", onChange);105  }, [interactive]);106  const toggleFull = () => {107    const el = figureRef.current;108    if (!el) return;109    if (full === "native") { void document.exitFullscreen?.(); setFull("none"); return; }110    if (full === "overlay") { setFull("none"); setView(FIT); return; }111    if (typeof el.requestFullscreen === "function" && document.fullscreenEnabled) {112      el.requestFullscreen().then(() => setFull("native")).catch(() => { setFull("overlay"); setView(FIT); });113    } else { setFull("overlay"); setView(FIT); }114  };115  useEffect(() => {116    if (full !== "overlay") return;117    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { setFull("none"); setView(FIT); } };118    document.addEventListener("keydown", onKey);119    const previous = document.body.style.overflow;120    document.body.style.overflow = "hidden";121    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = previous; };122  }, [full]);123124  // Step player. Never starts by itself; with reduced motion it cannot auto-advance at all.125  const isPlaying = playing && !reduced && steps.length > 0;126  useEffect(() => {127    if (!isPlaying) return;128    const id = window.setInterval(() => {129      setStep((s) => {130        const next = s === null ? 0 : s + 1;131        if (next >= steps.length - 1) setPlaying(false);132        return Math.min(next, steps.length - 1);133      });134    }, STEP_MS / speed);135    return () => window.clearInterval(id);136  }, [isPlaying, speed, steps.length]);137  const go = (delta: number) => { setPlaying(false); setStep((s) => { const n = (s === null ? (delta > 0 ? -1 : steps.length) : s) + delta; return n < 0 ? null : Math.min(n, steps.length - 1); }); };138  const togglePlay = () => {139    if (isPlaying) { setPlaying(false); return; }140    if (step !== null && step >= steps.length - 1) setStep(null);141    setPlaying(true);142  };143144  const current = interactive && step !== null ? steps[step] : undefined;145  const highlight = current ? { nodes: current.nodes, edges: current.edges } : undefined;146  const label = block.alt ?? block.title ?? t(locale, "diagram");147  const svg = <DiagramSvg layout={layout} idPrefix={block.id} title={label} highlight={highlight} />;148  const caption = block.caption ? <figcaption className="sh-caption"><Inline text={block.caption} sources={sources} /></figcaption> : null;149  const title = block.title ? <p className="sh-fig-title"><Inline text={block.title} sources={sources} /></p> : null;150  const legend = block.legend.length ? <LegendList items={block.legend} sources={sources} /> : null;151152  if (!interactive) {153    return (154      <figure className={`sh-diagram sh-diagram--static${plan?.side ? " sh-diagram--side" : ""}`} data-kind={block.kind}>155        {title}156        <div className="sh-diagram-stage"><div className="sh-diagram-canvas" style={{ maxWidth: layout.width, ...(plan ? { ["--dg-w" as string]: `${Math.round(layout.width * plan.scale)}px` } : {}) }}>{svg}</div></div>157        {legend}158        {steps.length ? (159          <ol className="sh-diagram-steps" aria-label={t(locale, "steps")}>160            {steps.map((s, i) => <li key={i}><span className="sh-diagram-step-title"><Inline text={s.title.replace(new RegExp(`^\\s*${i + 1}\\s*[·.:)–—-]\\s*`), "")} sources={sources} /></span>{s.text ? <span className="sh-diagram-step-text"> — <Inline text={s.text} sources={sources} /></span> : null}</li>)}161          </ol>162        ) : null}163        {caption}164      </figure>165    );166  }167168  const zoomed = view.k > 1;169  return (170    <figure ref={figureRef} className={`sh-diagram${full !== "none" ? " sh-diagram--full" : ""}${full === "overlay" ? " sh-diagram--overlay" : ""}`} data-kind={block.kind}>171      {title}172      <div ref={stageRef} className={`sh-diagram-stage${zoomed ? " sh-diagram-stage--zoomed" : ""}`}173        onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerEnd} onPointerCancel={onPointerEnd} onPointerLeave={onPointerEnd}>174        <div className="sh-diagram-canvas" style={{ maxWidth: full === "none" ? layout.width : undefined, transform: zoomed ? `translate(${view.x}px, ${view.y}px) scale(${view.k})` : undefined }}>{svg}</div>175      </div>176      <div className="sh-diagram-bar">177        <div className="sh-diagram-tools" role="group" aria-label="Zoom">178          <button type="button" className="sh-btn" onClick={() => zoomBy(1 / 1.4)} disabled={!zoomed} aria-label={t(locale, "zoomOut")} title={t(locale, "zoomOut")}><Glyph d={G.minus} /></button>179          <button type="button" className="sh-btn" onClick={() => zoomBy(1.4)} disabled={view.k >= MAX_K} aria-label={t(locale, "zoomIn")} title={t(locale, "zoomIn")}><Glyph d={G.plus} /></button>180          <button type="button" className="sh-btn" onClick={() => setView(FIT)} disabled={!zoomed} aria-label={t(locale, "fit")} title={t(locale, "fit")}><Glyph d={G.fit} /></button>181          <button type="button" className="sh-btn" onClick={toggleFull} aria-pressed={full !== "none"} aria-label={t(locale, full !== "none" ? "exitFullscreen" : "fullscreen")} title={t(locale, full !== "none" ? "exitFullscreen" : "fullscreen")}><Glyph d={full !== "none" ? G.exit : G.full} /></button>182        </div>183        {steps.length ? (184          <div className="sh-diagram-player" role="group" aria-label={t(locale, "steps")}>185            <button type="button" className="sh-btn" onClick={() => go(-1)} disabled={step === null} aria-label={t(locale, "previous")} title={t(locale, "previous")}><Glyph d={G.prev} /></button>186            <button type="button" className="sh-btn sh-btn--primary" onClick={togglePlay} disabled={reduced} aria-label={reduced ? t(locale, "reducedMotion") : t(locale, isPlaying ? "pause" : "play")} title={reduced ? t(locale, "reducedMotion") : t(locale, isPlaying ? "pause" : "play")}><Glyph d={isPlaying ? G.pause : G.play} /></button>187            <button type="button" className="sh-btn" onClick={() => go(1)} disabled={step !== null && step >= steps.length - 1} aria-label={t(locale, "next")} title={t(locale, "next")}><Glyph d={G.next} /></button>188            <button type="button" className="sh-btn sh-btn--text" onClick={() => setSpeed((s) => SPEEDS[(SPEEDS.indexOf(s) + 1) % SPEEDS.length])} disabled={reduced} aria-label={`${t(locale, "speed")} ${speed}×`} title={t(locale, "speed")}>{speed}×</button>189            <button type="button" className="sh-btn" onClick={() => { setPlaying(false); setStep(null); }} disabled={step === null} aria-label={t(locale, "reset")} title={t(locale, "reset")}><Glyph d={G.reset} /></button>190          </div>191        ) : null}192      </div>193      {steps.length ? (194        <div className="sh-diagram-step" aria-live="polite" aria-atomic="true">195          <p className="sh-diagram-step-count">{current && step !== null ? `${t(locale, "step")} ${step + 1} / ${steps.length}` : `${t(locale, "overview")} · ${steps.length} ${t(locale, "steps").toLowerCase()}`}</p>196          <p className="sh-diagram-step-title">{current ? <Inline text={current.title} sources={sources} /> : t(locale, "overviewHint")}</p>197          {current?.text ? <p className="sh-diagram-step-text"><Inline text={current.text} sources={sources} /></p> : null}198        </div>199      ) : null}200      {legend}201      {caption}202    </figure>203  );204}205
Files main
Menu

Theme