SPB Git

Repository Public

SheetView.tsx 7.2 KB 130 lines tsx

1/**2 * Sheet renderer. No "use client": SheetView renders in server components (SSR, crawlers, export) and equally3 * inside client components (the editor). Interactive blocks are client components that receive plain data.4 */5import type { ComponentType, CSSProperties, ReactNode } from "react";6import { FORMAT_SIZES, type Block, type BlockOf, type BlockType, type LeafBlock, type Locale, type Sheet } from "@/schema";7import { SimulationBlock } from "@/sim/SimulationBlock";8import type { RenderCtx } from "./context";9import {10  AccordionBlock, CalloutBlock, CardsBlock, ChartBlock, CodeBlock, ComparisonBlock, DividerBlock, EquationBlock, HeadingBlock, ImageBlock,11  LegendBlock, ListBlock, MatrixBlock, ParagraphBlock, ReferencesBlock, StepsBlock, SvgBlock, TableBlock, TimelineBlock, type BlockProps,12} from "./blocks/basic";13import { QuizBlock } from "./blocks/QuizBlock";14import { TabsClient } from "./blocks/TabsClient";15import { DiagramBlock } from "./diagram/DiagramBlock";16import { printDiagramPlan } from "./diagram/layout";17import { FitMath } from "./FitMath";18import { t } from "./i18n";1920export interface SheetViewProps {21  doc: Sheet;22  locale?: Locale;23  mode?: "public" | "editor" | "print";24  assetUrl?: (assetId: string) => string;25  /** Lets the editor wrap each top-level block with selection chrome. */26  wrapBlock?: (block: Block, node: ReactNode) => ReactNode;27}2829// Adapters: client components get serialisable props only (a RenderCtx carries a function).30function DiagramView({ block, ctx }: BlockProps<"diagram">) { return <DiagramBlock block={block} locale={ctx.locale} mode={ctx.mode} sources={ctx.sources} />; }31function QuizView({ block, ctx }: BlockProps<"quiz">) { return <QuizBlock block={block} locale={ctx.locale} mode={ctx.mode} sources={ctx.sources} />; }32function SimulationView({ block, ctx }: BlockProps<"simulation">) {33  return <div className="sh-simulation"><SimulationBlock block={block} locale={ctx.locale} staticOnly={ctx.mode === "print"} /></div>;34}35function TabsView({ block, ctx }: BlockProps<"tabs">) {36  return (37    <TabsClient id={block.id} label={block.alt ?? t(ctx.locale, "tabs")} mode={ctx.mode} tabs={block.tabs.map((tab) => ({ id: tab.id, label: tab.label }))}38      panels={block.tabs.map((tab) => (39        <div key={tab.id} className="sh-tab-blocks">40          {tab.blocks.map((child) => <div key={child.id} id={child.id} className="sh-block" data-block-id={child.id} data-block-type={child.type}><BlockView block={child} ctx={ctx} demoteH1 /></div>)}41        </div>42      ))} />43  );44}4546/** Every block type and its component. A block type without a component is a type error. */47export const REGISTRY: { [T in BlockType]: ComponentType<BlockProps<T>> } = {48  heading: HeadingBlock, paragraph: ParagraphBlock, list: ListBlock, equation: EquationBlock, callout: CalloutBlock, table: TableBlock,49  cards: CardsBlock, steps: StepsBlock, legend: LegendBlock, diagram: DiagramView, timeline: TimelineBlock, matrix: MatrixBlock, code: CodeBlock,50  chart: ChartBlock, svg: SvgBlock, image: ImageBlock, comparison: ComparisonBlock, accordion: AccordionBlock, quiz: QuizView,51  simulation: SimulationView, references: ReferencesBlock, divider: DividerBlock, tabs: TabsView,52};5354function component<T extends BlockType>(type: T): ComponentType<BlockProps<T>> { return REGISTRY[type]; }5556export interface BlockViewProps {57  block: Block | LeafBlock; ctx: RenderCtx;58  /** Render a level-1 heading as an h2 (same look): the page keeps a single h1. */59  demoteH1?: boolean;60}6162/** One block (used by SheetView, by tabs and by the editor). Unknown types render nothing. */63export function BlockView({ block, ctx, demoteH1 }: BlockViewProps) {64  if (!Object.hasOwn(REGISTRY, block.type)) return null;65  const sourceIds = block.type === "references" ? [] : (block.sourceIds ?? []);66  const cited = sourceIds.map((id) => ({ id, n: ctx.sources.findIndex((s) => s.id === id) + 1 })).filter((s) => s.n > 0);67  const body = block.type === "heading"68    ? <HeadingBlock block={block} ctx={ctx} demote={demoteH1} />69    : renderBlock(block, ctx);70  if (cited.length === 0) return body;71  return (72    <>73      {body}74      <p className="sh-sourceline">75        <span>{t(ctx.locale, "sources")}{ctx.locale === "fr" ? " :" : ":"}</span>76        {cited.map((s) => <a key={s.id} href={`#src-${s.id}`} aria-label={`Source ${s.n}`}>{s.n}</a>)}77      </p>78    </>79  );80}8182function renderBlock<T extends BlockType>(block: BlockOf<T>, ctx: RenderCtx): ReactNode {83  const C = component(block.type as T);84  return <C block={block} ctx={ctx} />;85}8687export function buildCtx(doc: Sheet, locale: Locale, mode: RenderCtx["mode"], assetUrl?: (assetId: string) => string): RenderCtx {88  const assets: RenderCtx["assets"] = {};89  for (const a of doc.assets) assets[a.id] = { assetId: a.assetId, alt: a.alt, credit: a.credit, kind: a.kind };90  return { locale, mode, sources: doc.sources, assets, assetUrl: assetUrl ?? ((assetId) => `/media/${encodeURIComponent(assetId)}`) };91}9293export function SheetView({ doc, locale, mode = "public", assetUrl, wrapBlock }: SheetViewProps) {94  const lang = locale ?? doc.metadata.locale;95  const ctx = buildCtx(doc, lang, mode, assetUrl);96  const format = doc.layout.format;97  const size = FORMAT_SIZES[format];98  const fixed = format !== "article";99  const firstH1 = doc.blocks.find((b) => b.type === "heading" && b.level === 1)?.id;100  const frameStyle: CSSProperties = fixed101    ? { width: size.width, minHeight: size.height ?? undefined, padding: size.safeMargin }102    : { maxWidth: doc.layout.maxWidth };103  const cell = (block: Block) => {104    const node = <BlockView block={block} ctx={ctx} demoteH1={block.id !== firstH1} />;105    return (106      <div key={block.id} id={block.id} className={`sh-block sh-span-${block.span}${wide(block) ? " sh-qs-wide" : ""}${full(block) ? " sh-qs-full" : ""}`} data-block-id={block.id} data-block-type={block.type}>107        {wrapBlock ? wrapBlock(block, node) : node}108      </div>109    );110  };111  const paged = mode === "print" && !fixed;112  // Quick sheet: a diagram is wide when that is how it is drawn largest; tables with many columns are wide; the113  // list of references is cut between entries by the imposition and flows from column to column. Simulations fit a column (their pictures scale).114  const wide = (block: Block) => paged && ((block.type === "diagram" && printDiagramPlan(block).wide) || ((block.type === "comparison" || block.type === "table") && block.columns.length >= 4));115  const full = (_block: Block) => false; // kept for panels that must cross the page; references flow column to column instead116  return (117    <article className="sheet" data-theme={doc.theme.preset} data-accent={doc.theme.accent} data-format={format} data-mode={mode} lang={lang}>118      <div className={fixed ? "sh-frame sh-frame--fixed" : "sh-frame"} style={frameStyle}>119        {mode === "print" ? null : <FitMath />}120        {doc.metadata.example ? <p className="sh-example-banner" role="note">{t(lang, "exampleBanner")}</p> : null}121        {paged ? (122          // Paged output of an article = a quick sheet: blocks flow in columns as panels (see "Quick sheet" in sheet.css).123          // Large visuals span all the columns so that they stay readable.124          <div className="sh-grid sh-qs">{doc.blocks.map(cell)}</div>125        ) : <div className="sh-grid">{doc.blocks.map(cell)}</div>}126      </div>127    </article>128  );129}130
Files main
Menu

Theme