Repository Public
1/**2 * Static block components (no hooks, no "use client"): they render the same in server components, in the editor3 * and in static export. Styles: src/renderer/sheet.css (classes prefixed sh-).4 */5import type { CSSProperties, ReactNode } from "react";6import type { BlockOf, BlockType, Tone } from "@/schema";7import type { RenderCtx } from "../context";8import { ChartSvg } from "../chart/ChartSvg";9import { tokenizeLines } from "../code-highlight";10import { IconGlyph } from "../icons";11import { Inline, safeHref } from "../inline";12import { formatNumber, t, type StringKey } from "../i18n";13import { MathView } from "../math";14import { Mark, type MarkName } from "../marks";15import { toneClass } from "../tone";16import { MatrixSvg, matrixSize } from "./MatrixSvg";17import { SvgTree, svgNaturalSize } from "./SvgTree";1819export interface BlockProps<T extends BlockType> { block: BlockOf<T>; ctx: RenderCtx }2021const Txt = ({ text, ctx }: { text: string; ctx: RenderCtx }) => <Inline text={text} sources={ctx.sources} />;2223/** Title above and caption below a figure. */24export function FigTitle({ text, ctx }: { text?: string; ctx: RenderCtx }) { return text ? <p className="sh-fig-title"><Txt text={text} ctx={ctx} /></p> : null; }25export function FigCaption({ text, ctx, children }: { text?: string; ctx: RenderCtx; children?: ReactNode }) {26 return text || children ? <figcaption className="sh-caption">{text ? <Txt text={text} ctx={ctx} /> : null}{children}</figcaption> : null;27}2829// ── Text ────────────────────────────────────────────────────────────────────────────────────────────3031/** `demote`: a second level-1 heading (or one inside a tab) keeps its look but is an h2, so the page has one h1. */32export function HeadingBlock({ block, ctx, demote }: BlockProps<"heading"> & { demote?: boolean }) {33 const Tag = block.level === 1 ? (demote ? "h2" : "h1") : block.level === 2 ? "h2" : "h3";34 return (35 <div className={`sh-heading sh-heading--${block.level}`}>36 {block.eyebrow ? <p className="sh-eyebrow">{block.eyebrow}</p> : null}37 <Tag className={`sh-h sh-h${block.level}`}><Txt text={block.text} ctx={ctx} /></Tag>38 </div>39 );40}4142export function ParagraphBlock({ block, ctx }: BlockProps<"paragraph">) {43 const parts = block.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);44 return <>{parts.map((p, i) => <p key={i} className={block.lead ? "sh-p sh-p--lead" : "sh-p"}><Txt text={p} ctx={ctx} /></p>)}</>;45}4647export function ListBlock({ block, ctx }: BlockProps<"list">) {48 const items = block.items.map((item, i) => (49 <li key={i}>50 {block.style === "check" ? <span className="sh-list-mark sh-list-check"><Mark name="check" size={20} /></span> : block.style === "bullet" ? <span className="sh-list-mark"><Mark name="bullet" size={13} /></span> : null}51 <span className="sh-list-text"><Txt text={item} ctx={ctx} /></span>52 </li>53 ));54 return block.style === "number" ? <ol className="sh-list sh-list--number">{items}</ol> : <ul className={`sh-list sh-list--${block.style}`}>{items}</ul>;55}5657const CALLOUT: Record<BlockOf<"callout">["tone"], { tone: Tone; mark: MarkName; label: StringKey }> = {58 note: { tone: "blue", mark: "note", label: "note" },59 tip: { tone: "green", mark: "tip", label: "tip" },60 warning: { tone: "amber", mark: "warn", label: "warning" },61 definition: { tone: "violet", mark: "definition", label: "definition" },62 theorem: { tone: "teal", mark: "theorem", label: "theorem" },63 example: { tone: "neutral", mark: "example", label: "example" },64 assumption: { tone: "pink", mark: "assumption", label: "assumption" },65};6667export function CalloutBlock({ block, ctx }: BlockProps<"callout">) {68 const c = CALLOUT[block.tone];69 const parts = block.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);70 return (71 <aside className={`sh-callout sh-callout--${block.tone} ${toneClass(c.tone)}`} role="note">72 <p className="sh-callout-label"><span className="sh-callout-emblem"><Mark name={c.mark} size={20} /></span><span>{t(ctx.locale, c.label)}</span></p>73 {block.title ? <p className="sh-callout-title"><Txt text={block.title} ctx={ctx} /></p> : null}74 {parts.map((p, i) => <p key={i} className="sh-callout-text"><Txt text={p} ctx={ctx} /></p>)}75 </aside>76 );77}7879export function DividerBlock(_: BlockProps<"divider">) { return <hr className="sh-divider" />; }8081// ── Equation ────────────────────────────────────────────────────────────────────────────────────────8283export function EquationBlock({ block, ctx }: BlockProps<"equation">) {84 const flagged = block.derivation !== "standard";85 return (86 <figure className={`sh-equation${flagged ? ` sh-equation--${block.derivation}` : ""}`}>87 {block.label ? <figcaption className="sh-equation-label">{block.label}</figcaption> : null}88 <div className="sh-equation-row">89 <div className="sh-equation-math sh-scroll" tabIndex={0} role="group" aria-label={block.label ?? block.alt ?? "Equation"}><MathView latex={block.latex} display /></div>90 </div>91 {flagged ? (92 <p className={`sh-flag sh-flag--${block.derivation}`}>93 {block.derivation === "unverified" ? <Mark name="warn" size={16} /> : <IconGlyph name="function" size={16} />}94 <span>{t(ctx.locale, block.derivation === "unverified" ? "unverified" : "derived")}</span>95 </p>96 ) : null}97 {block.explanation ? <p className="sh-equation-explanation"><Txt text={block.explanation} ctx={ctx} /></p> : null}98 {block.variables?.length ? (99 <table className="sh-vars">100 <caption className="sh-visually-hidden">{t(ctx.locale, "variables")}</caption>101 <thead className="sh-visually-hidden"><tr><th scope="col">{t(ctx.locale, "symbol")}</th><th scope="col">{t(ctx.locale, "meaning")}</th><th scope="col">{t(ctx.locale, "unit")}</th></tr></thead>102 <tbody>103 {block.variables.map((v, i) => (104 <tr key={i}>105 <th scope="row" className="sh-vars-symbol"><span className="sh-vars-chip"><MathView latex={v.symbol} /></span></th>106 <td className="sh-vars-meaning"><Txt text={v.meaning} ctx={ctx} /></td>107 <td className="sh-vars-unit">{v.unit ? <Txt text={v.unit} ctx={ctx} /> : null}</td>108 </tr>109 ))}110 </tbody>111 </table>112 ) : null}113 </figure>114 );115}116117// ── Table, comparison ───────────────────────────────────────────────────────────────────────────────118119export function TableBlock({ block, ctx }: BlockProps<"table">) {120 return (121 <figure className="sh-table-fig">122 <div className="sh-scroll sh-table-scroll" tabIndex={0} role="region" aria-label={block.caption ? undefined : t(ctx.locale, "table")} aria-labelledby={block.caption ? `${block.id}-cap` : undefined}>123 <table className="sh-table">124 {block.caption ? <caption id={`${block.id}-cap`}><Txt text={block.caption} ctx={ctx} /></caption> : null}125 <thead><tr>{block.columns.map((c, j) => <th key={j} scope="col" className={`sh-al-${c.align}`}><Txt text={c.label} ctx={ctx} /></th>)}</tr></thead>126 <tbody>127 {block.rows.map((row, i) => (128 <tr key={i}>129 {row.map((cell, j) => block.headerColumn && j === 0130 ? <th key={j} scope="row" className={`sh-al-${block.columns[j]?.align ?? "left"}`}><Txt text={cell} ctx={ctx} /></th>131 : <td key={j} className={`sh-al-${block.columns[j]?.align ?? "left"}`}><Txt text={cell} ctx={ctx} /></td>)}132 </tr>133 ))}134 </tbody>135 </table>136 </div>137 </figure>138 );139}140141export function ComparisonBlock({ block, ctx }: BlockProps<"comparison">) {142 return (143 <figure className="sh-comparison">144 {/* Wide screens and print: a table. */}145 <div className="sh-comparison-wide">146 <table className="sh-comparison-table">147 {block.caption ? <caption><Txt text={block.caption} ctx={ctx} /></caption> : null}148 <thead>149 <tr>150 <th scope="col"><span className="sh-visually-hidden">{t(ctx.locale, "criterion")}</span></th>151 {block.columns.map((c, j) => (152 <th key={j} scope="col" className={`sh-comparison-col ${toneClass(c.tone)}`}>153 <span className="sh-comparison-title"><Txt text={c.title} ctx={ctx} /></span>154 {c.badge ? <span className="sh-badge">{c.badge}</span> : null}155 </th>156 ))}157 </tr>158 </thead>159 <tbody>160 {block.rows.map((r, i) => (161 <tr key={i}><th scope="row"><Txt text={r.label} ctx={ctx} /></th>{r.cells.map((cell, j) => <td key={j}><Txt text={cell} ctx={ctx} /></td>)}</tr>162 ))}163 </tbody>164 </table>165 </div>166 {/* Phones: one card per column, in the same order. */}167 <div className="sh-comparison-stack">168 {block.caption ? <p className="sh-caption"><Txt text={block.caption} ctx={ctx} /></p> : null}169 {block.columns.map((c, j) => (170 <section key={j} className={`sh-comparison-card ${toneClass(c.tone)}`}>171 <p className="sh-comparison-card-head"><span className="sh-comparison-title"><Txt text={c.title} ctx={ctx} /></span>{c.badge ? <span className="sh-badge">{c.badge}</span> : null}</p>172 <dl>{block.rows.map((r, i) => <div key={i}><dt><Txt text={r.label} ctx={ctx} /></dt><dd><Txt text={r.cells[j] ?? ""} ctx={ctx} /></dd></div>)}</dl>173 </section>174 ))}175 </div>176 {block.verdict ? <p className="sh-verdict"><span className="sh-verdict-label">{t(ctx.locale, "verdict")}</span><span><Txt text={block.verdict} ctx={ctx} /></span></p> : null}177 </figure>178 );179}180181// ── Cards, steps, legend ────────────────────────────────────────────────────────────────────────────182183export function CardsBlock({ block, ctx }: BlockProps<"cards">) {184 return (185 <ul className="sh-cards" style={{ "--sh-cols": block.columns } as CSSProperties}>186 {block.items.map((item, i) => (187 <li key={i} className={`sh-card ${toneClass(item.tone)}`}>188 {item.icon || item.badge ? (189 <div className="sh-card-top">190 {item.icon ? <span className="sh-card-icon"><IconGlyph name={item.icon} size={22} /></span> : <span />}191 {item.badge ? <span className="sh-badge">{item.badge}</span> : null}192 </div>193 ) : null}194 <p className="sh-card-title"><Txt text={item.title} ctx={ctx} /></p>195 {item.text ? <p className="sh-card-text"><Txt text={item.text} ctx={ctx} /></p> : null}196 </li>197 ))}198 </ul>199 );200}201202export function StepsBlock({ block, ctx }: BlockProps<"steps">) {203 return (204 <ol className="sh-steps">205 {block.items.map((item, i) => (206 <li key={i} className="sh-step">207 <span className="sh-step-marker" aria-hidden="true">{item.icon ? <IconGlyph name={item.icon} size={18} /> : i + 1}</span>208 <div className="sh-step-body">209 <p className="sh-step-title"><Txt text={item.title} ctx={ctx} /></p>210 {item.text ? <p className="sh-step-text"><Txt text={item.text} ctx={ctx} /></p> : null}211 </div>212 </li>213 ))}214 </ol>215 );216}217218type LegendItem = BlockOf<"legend">["items"][number];219export function LegendSwatch({ shape }: { shape: LegendItem["shape"] }) {220 return (221 <svg className="sh-swatch" width="28" height="14" viewBox="0 0 28 14" aria-hidden="true" focusable="false">222 {shape === "square" ? <rect x="7" y="1" width="14" height="12" rx="3" fill="var(--tone-soft)" stroke="var(--tone)" strokeWidth="1.5" /> : null}223 {shape === "circle" ? <circle cx="14" cy="7" r="5.5" fill="var(--tone-soft)" stroke="var(--tone)" strokeWidth="1.5" /> : null}224 {shape === "line" ? <path d="M2 7h24" stroke="var(--tone)" strokeWidth="2" strokeLinecap="round" /> : null}225 {shape === "dashed" ? <path d="M2 7h24" stroke="var(--tone)" strokeWidth="2" strokeLinecap="round" strokeDasharray="5 4" /> : null}226 {shape === "arrow" ? <path d="M2 7h21M19 3l5 4-5 4" fill="none" stroke="var(--tone)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> : null}227 </svg>228 );229}230export function LegendList({ items, title, sources }: { items: LegendItem[]; title?: string; sources?: RenderCtx["sources"] }) {231 return (232 <div className="sh-legend">233 {title ? <p className="sh-legend-title"><Inline text={title} sources={sources} /></p> : null}234 <ul className="sh-legend-items">235 {items.map((item, i) => <li key={i} className={toneClass(item.tone)}><LegendSwatch shape={item.shape} /><span><Inline text={item.label} sources={sources} /></span></li>)}236 </ul>237 </div>238 );239}240export function LegendBlock({ block, ctx }: BlockProps<"legend">) { return <LegendList items={block.items} title={block.title} sources={ctx.sources} />; }241242// ── Timeline (HTML: readable, reflowable; the vector version for export is blocks/TimelineSvg.tsx) ──243244export function TimelineBlock({ block, ctx }: BlockProps<"timeline">) {245 return (246 <ol className={`sh-timeline sh-timeline--${block.orientation}`}>247 {block.items.map((item, i) => (248 <li key={i} className={`sh-timeline-item ${toneClass(item.tone)}`}>249 <span className="sh-timeline-when">{item.when}</span>250 <span className="sh-timeline-dot" aria-hidden="true" />251 <div className="sh-timeline-body">252 <p className="sh-timeline-title"><Txt text={item.title} ctx={ctx} /></p>253 {item.text ? <p className="sh-timeline-text"><Txt text={item.text} ctx={ctx} /></p> : null}254 </div>255 </li>256 ))}257 </ol>258 );259}260261// ── Code ────────────────────────────────────────────────────────────────────────────────────────────262263export function CodeBlock({ block, ctx }: BlockProps<"code">) {264 const lines = tokenizeLines(block.code, block.language);265 return (266 <figure className="sh-code">267 <div className="sh-code-head"><span className="sh-code-lang">{block.language === "pseudo" ? "pseudo-code" : block.language}</span></div>268 <pre className="sh-code-pre sh-scroll" tabIndex={0} aria-label={`${t(ctx.locale, "code")} ${block.language}`}>269 <code>270 {lines.map((line, i) => (271 <span key={i} className="sh-code-line">272 {line.map((tok, k) => (tok.kind === "plain" ? tok.text : <span key={k} className={`sh-tok-${tok.kind}`}>{tok.text}</span>))}273 {"\n"}274 </span>275 ))}276 </code>277 </pre>278 <FigCaption text={block.caption} ctx={ctx} />279 </figure>280 );281}282283// ── Chart, matrix ───────────────────────────────────────────────────────────────────────────────────284285export function ChartBlock({ block, ctx }: BlockProps<"chart">) {286 const label = block.alt ?? block.title ?? t(ctx.locale, "chart");287 const category = block.x.type === "category";288 const hasInterval = block.series.some((s) => s.points.some((p) => p.lo !== undefined || p.hi !== undefined));289 const cell = (v: number | string | undefined) => (v === undefined ? "" : typeof v === "number" ? formatNumber(v, ctx.locale) : v);290 const unit = (a: { label: string; unit?: string }) => (a.unit ? `${a.label} (${a.unit})` : a.label);291 return (292 <figure className="sh-chart">293 <FigTitle text={block.title} ctx={ctx} />294 {/* Two drawings of the same points: one laid out for wide columns, one for phones. CSS shows exactly one. */}295 <div className="sh-chart-wide"><ChartSvg chart={block} locale={ctx.locale} width={720} height={400} idPrefix={`${block.id}-w`} label={label} /></div>296 <div className="sh-chart-compact"><ChartSvg chart={block} locale={ctx.locale} width={340} height={290} idPrefix={`${block.id}-c`} label={label} /></div>297 <FigCaption text={block.caption} ctx={ctx} />298 <details className="sh-data">299 <summary>{t(ctx.locale, "seeData")}</summary>300 <div className="sh-scroll" tabIndex={0} role="region" aria-label={t(ctx.locale, "seeData")}>301 <table className="sh-table sh-table--data">302 <caption className="sh-visually-hidden">{label} — {t(ctx.locale, block.dataKind)}</caption>303 <thead><tr><th scope="col">{t(ctx.locale, "series")}</th><th scope="col" className={category ? "sh-al-left" : "sh-al-right"}>{unit(block.x)}</th><th scope="col" className="sh-al-right">{unit(block.y)}</th>{hasInterval ? <th scope="col" className="sh-al-right">{t(ctx.locale, "interval")}</th> : null}</tr></thead>304 <tbody>305 {block.series.flatMap((s, si) => s.points.map((p, i) => (306 <tr key={`${si}-${i}`}>307 <th scope="row">{s.name}</th>308 <td className={category ? "sh-al-left" : "sh-al-right"}>{cell(p.x)}</td>309 <td className="sh-al-right">{cell(p.y)}</td>310 {hasInterval ? <td className="sh-al-right">{p.lo !== undefined && p.hi !== undefined ? `${cell(p.lo)} – ${cell(p.hi)}` : ""}</td> : null}311 </tr>312 )))}313 </tbody>314 </table>315 </div>316 </details>317 </figure>318 );319}320321export function MatrixBlock({ block, ctx }: BlockProps<"matrix">) {322 const size = matrixSize(block, ctx.locale);323 return (324 <figure className="sh-matrix">325 <FigTitle text={block.title} ctx={ctx} />326 <div className="sh-scroll" tabIndex={0} role="region" aria-label={block.alt ?? block.title ?? t(ctx.locale, "matrix")}>327 <div style={{ width: "100%", minWidth: Math.min(size.width, block.colLabels.length * 40 + size.rowW), maxWidth: size.width * 1.25 }}>328 <MatrixSvg matrix={block} locale={ctx.locale} label={block.alt ?? block.title} />329 </div>330 </div>331 <FigCaption text={block.caption} ctx={ctx} />332 </figure>333 );334}335336// ── Illustration, image ─────────────────────────────────────────────────────────────────────────────337338export function SvgBlock({ block, ctx }: BlockProps<"svg">) {339 const size = svgNaturalSize(block.tree);340 return (341 <figure className="sh-svg" style={{ maxWidth: block.maxWidth ?? Math.max(size.width, 320) }}>342 <SvgTree tree={block.tree} idPrefix={block.id} title={block.alt ?? t(ctx.locale, "illustration")} />343 <FigCaption text={block.caption} ctx={ctx} />344 </figure>345 );346}347348export function ImageBlock({ block, ctx }: BlockProps<"image">) {349 const asset = ctx.assets[block.assetRef];350 const alt = block.alt ?? asset?.alt ?? "";351 return (352 <figure className="sh-image" style={block.maxWidth ? { maxWidth: block.maxWidth } : undefined}>353 {asset && asset.kind === "image"354 ? <img src={ctx.assetUrl(asset.assetId)} alt={alt} loading={ctx.mode === "print" ? "eager" : "lazy"} decoding="async" />355 : <div className="sh-image-missing" role="img" aria-label={alt || t(ctx.locale, "missingImage")}><IconGlyph name="eye" size={22} /><span>{t(ctx.locale, "missingImage")}</span></div>}356 <FigCaption text={block.caption} ctx={ctx}>357 {asset?.credit ? <span className="sh-credit">{block.caption ? " · " : ""}{t(ctx.locale, "credit")} : {asset.credit}</span> : null}358 </FigCaption>359 </figure>360 );361}362363// ── Accordion, references ───────────────────────────────────────────────────────────────────────────364365export function AccordionBlock({ block, ctx }: BlockProps<"accordion">) {366 return (367 <div className="sh-accordion">368 {block.items.map((item, i) => (369 <details key={i} className="sh-accordion-item" open={ctx.mode === "print" ? true : undefined}>370 <summary><span><Txt text={item.title} ctx={ctx} /></span></summary>371 <div className="sh-accordion-body">372 {item.text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean).map((p, k) => <p key={k} className="sh-p"><Txt text={p} ctx={ctx} /></p>)}373 </div>374 </details>375 ))}376 </div>377 );378}379380export function ReferencesBlock({ block, ctx }: BlockProps<"references">) {381 return (382 <section className="sh-references" aria-label={block.title ?? t(ctx.locale, "references")}>383 <p className="sh-references-title">{block.title ? <Txt text={block.title} ctx={ctx} /> : t(ctx.locale, "references")}</p>384 {ctx.sources.length === 0 ? <p className="sh-references-empty">{t(ctx.locale, "noReferences")}</p> : (385 <ol className="sh-references-list">386 {ctx.sources.map((s) => { const url = s.url ? safeHref(s.url) : null; return (387 <li key={s.id} id={`src-${s.id}`}>388 {s.authors.length ? <span className="sh-ref-authors">{s.authors.join(", ")}</span> : null}389 {s.year !== undefined ? <span className="sh-ref-year"> ({s.year})</span> : null}390 {s.authors.length || s.year !== undefined ? ". " : null}391 <cite className="sh-ref-title">{s.title}</cite>392 {s.container ? <span className="sh-ref-container">. {s.container}</span> : null}393 {"."}394 {s.doi ? <> <a className="sh-link sh-ref-link" href={`https://doi.org/${encodeURI(s.doi)}`} target="_blank" rel="noopener noreferrer">doi:{s.doi}</a></> : null}395 {url && !(s.doi && url.toLowerCase().includes(s.doi.toLowerCase())) ? <> <a className="sh-link sh-ref-link" href={url} target="_blank" rel="noopener noreferrer">{displayUrl(url)}</a></> : null}396 {s.license ? <span className="sh-ref-note"> · {s.license}</span> : null}397 {s.status === "unverified" || s.status === "unreachable"398 ? <> <span className={`sh-ref-status sh-ref-status--${s.status}`}>{t(ctx.locale, s.status === "unverified" ? "unverifiedSource" : "unreachableSource")}</span></>399 : null}400 {s.note ? <span className="sh-ref-note-line">{s.note}</span> : null}401 </li>402 ); })}403 </ol>404 )}405 </section>406 );407}408409function displayUrl(url: string): string {410 try { const u = new URL(url); if (u.protocol === "mailto:") return u.pathname; const path = u.pathname === "/" ? "" : u.pathname; const s = u.host + path; return s.length > 60 ? s.slice(0, 57) + "…" : s; }411 catch { return url; }412}413