// SpecDoc → HTML. The body fragment is what the app's spec view shows and // what ///html wraps in a page; the markup follows the // documents sisl.js generates for dasl.ing so spec.css applies unchanged. import { escapeAttr, escapeHtml, featureKind, layout, layoutText, safeHref, type LayoutNode, } from './richtext.ts'; import { IdAllocator, slugify } from './slug.ts'; import { statusLabel } from './status.ts'; import { walkSections } from './fold.ts'; import { SPEC_PAGE_CSS } from './spec-css.ts'; import { BANNER_HEIGHT, BANNER_WIDTH, COLOUR_HEX, specColour, specEmoji } from './banner.ts'; import { highlightCode, knownLanguage } from './highlight.ts'; import { blobCid, normalizeList, type RefView } from './types.ts'; import type { BlockContent, BlockNode, EditorView, Feature, ListBlock, RichText, SectionNode, SpecDoc, } from './types.ts'; export type RenderOptions = { /** Render TeX; must return HTML. Defaults to an escaped fallback. */ math?: (tex: string, display: boolean) => string; /** URL for a blob of the spec's repo. Defaults to the app's /blob redirect. */ blobUrl?: (did: string, cid: string) => string; /** Link target for an account. Defaults to the app's account page. */ accountUrl?: (handleOrDid: string) => string; /** Link target for the spec's own page on the forge. */ specUrl?: (handleOrDid: string, shortname: string) => string; siteName?: string; }; type Ref = { key: string; uri?: string; title?: string }; type Ctx = { opts: Required> & RenderOptions; did: string; dfnIds: IdAllocator; refs: Map; knownDfns: Set; /** The spec's imported catalogue references, by key. */ imports: Map; }; function defaultMath(tex: string, display: boolean): string { return display ? `
${escapeHtml(tex)}
` : `${escapeHtml(tex)}`; } function makeCtx(doc: SpecDoc, options: RenderOptions): Ctx { return { opts: { math: options.math ?? defaultMath, blobUrl: options.blobUrl ?? ((did, cid) => `/blob/${encodeURIComponent(did)}/${encodeURIComponent(cid)}`), accountUrl: options.accountUrl ?? ((h) => `/${encodeURIComponent(h)}`), specUrl: options.specUrl ?? ((h, s) => `/${encodeURIComponent(h)}/${encodeURIComponent(s)}/`), ...options, }, did: doc.did, dfnIds: new IdAllocator(), refs: new Map(), knownDfns: collectDfnIds(doc), imports: new Map((doc.imports ?? []).map((i) => [i.key, i])), }; } /** First pass: every dfn id in the document, so dfn-refs can be validated. */ function collectDfnIds(doc: SpecDoc): Set { const ids = new IdAllocator(); const out = new Set(); const visit = (rt: RichText | undefined) => { if (!rt) return; for (const n of layout(rt)) visitNode(n); }; const visitNode = (n: LayoutNode) => { if (n.kind === 'text') return; if (featureKind(n.feature) === 'dfn') { const explicit = (n.feature as { id?: string }).id; out.add(explicit ? ids.take(explicit) : ids.take(`dfn-${slugify(layoutText(n.children))}`)); } n.children.forEach(visitNode); }; visit(doc.abstract); for (const { section } of walkSections(doc.sections)) { for (const b of section.content) visitBlock(b.content, visit); } return out; } export function visitBlock(c: BlockContent, visit: (rt: RichText | undefined) => void): void { switch (c.$type) { case 'group.standards.block#paragraph': visit(c.text); break; case 'group.standards.block#blob': visit(c.caption); break; case 'group.standards.block#list': visitList(c, visit); break; case 'group.standards.block#definitionList': for (const d of c.items) { visit(d.term); visit(d.description); } break; default: break; } } function visitList(l: ListBlock, visit: (rt: RichText | undefined) => void): void { for (const item of normalizeList(l).items) { visit(item.text); if (item.list) visitList(item.list, visit); } } // --- rich text --------------------------------------------------------------- export function renderRichText(rt: RichText | undefined, ctx: Ctx): string { if (!rt) return ''; return layout(rt).map((n) => renderNode(n, ctx)).join(''); } function renderNode(n: LayoutNode, ctx: Ctx): string { if (n.kind === 'text') return escapeHtml(n.text); const inner = () => n.children.map((c) => renderNode(c, ctx)).join(''); const f: Feature = n.feature; switch (featureKind(f)) { case 'bold': return `${inner()}`; case 'italic': return `${inner()}`; case 'code': return `${inner()}`; case 'sub': return `${inner()}`; case 'sup': return `${inner()}`; case 'link': { const uri = (f as { uri: string }).uri; return `${inner()}`; } case 'math': return `${ctx.opts.math(layoutText(n.children), false)}`; case 'dfn': { const explicit = (f as { id?: string }).id; const id = explicit ? ctx.dfnIds.take(explicit) : ctx.dfnIds.take(`dfn-${slugify(layoutText(n.children))}`); return `${inner()}`; } case 'dfnRef': { const d = f as { id?: string; ref?: string; uri?: string }; if (d.uri) { // a term from an imported reference: link out, and cite the reference if (d.ref) cite(ctx, d.ref); const key = d.ref ? ` data-ref="${escapeAttr(d.ref)}" title="${escapeAttr(`[${d.ref}]`)}"` : ''; return `${inner()}`; } const id = d.id ?? `dfn-${slugify(layoutText(n.children))}`; const cls = ctx.knownDfns.has(id) ? 'dfn-ref' : 'dfn-ref missing'; return `${inner()}`; } case 'ref': { const r = f as { key: string; uri?: string; title?: string }; const key = r.key.trim() || layoutText(n.children).trim(); cite(ctx, key, r); return `[${escapeHtml(key)}]`; } default: return inner(); } } /** Rich text as an HTML fragment on its own (no document context: no dfn ids, no reference list). */ export function richTextHtml(rt: RichText | undefined, options: Pick = {}): string { const ctx: Ctx = { opts: { math: options.math ?? defaultMath, blobUrl: () => '', accountUrl: (h) => `/${encodeURIComponent(h)}`, specUrl: (h, s) => `/${encodeURIComponent(h)}/${encodeURIComponent(s)}/`, }, did: '', dfnIds: new IdAllocator(), refs: new Map(), knownDfns: new Set(), imports: new Map(), }; return renderRichText(rt, ctx); } // --- blocks ------------------------------------------------------------------- function blockAttr(b: BlockNode): string { return ` data-block="${escapeAttr(b.uri)}"`; } export function renderBlock(b: BlockNode, ctx: Ctx): string { const c = b.content; const attr = blockAttr(b); switch (c.$type) { case 'group.standards.block#paragraph': return `${renderRichText(c.text, ctx)}

`; case 'group.standards.block#code': { const cls = [c.language ? `language-${c.language}` : '', knownLanguage(c.language) ? 'hljs' : ''].filter(Boolean).join(' '); const lang = cls ? ` class="${escapeAttr(cls)}"` : ''; return `${highlightCode(c.code, c.language)}
`; } case 'group.standards.block#math': return `
${ctx.opts.math(c.tex, true)}
`; case 'group.standards.block#blob': { const src = ctx.opts.blobUrl(ctx.did, blobCid(c.blob)); const alt = escapeAttr(c.alt ?? ''); const caption = c.caption && c.caption.text.trim() ? `
${renderRichText(c.caption, ctx)}
` : ''; return `${alt}${caption}`; } case 'group.standards.block#list': return renderList(c, ctx, attr); case 'group.standards.block#definitionList': return `${c.items .map((d) => `
${renderRichText(d.term, ctx)}
${renderRichText(d.description, ctx)}
`) .join('')}`; default: return ''; } } function renderList(l: ListBlock, ctx: Ctx, attr = ''): string { const list = normalizeList(l); const tag = list.ordered ? 'ol' : 'ul'; const items = list.items .map((item) => `
  • ${renderRichText(item.text, ctx)}${item.list ? renderList(item.list, ctx) : ''}
  • `) .join(''); return `<${tag}${attr}>${items}`; } // --- sections ------------------------------------------------------------------ function renderSection(s: SectionNode, ctx: Ctx, depth: number): string { const h = `h${Math.min(depth + 2, 6)}`; const content = s.content.map((b) => renderBlock(b, ctx)).join('\n'); const subs = s.subsections.map((sub) => renderSection(sub, ctx, depth + 1)).join('\n'); return `
    <${h}>${renderRichText(s.title, ctx)} ${content} ${subs}
    `; } /** Add a reference to the References section: from the facet, else from the spec's imports. */ function cite(ctx: Ctx, key: string, given: { uri?: string; title?: string } = {}): void { if (ctx.refs.has(key)) return; const imp = ctx.imports.get(key); const ref: Ref = { key }; const uri = given.uri || imp?.href; const title = given.title || imp?.title; if (uri) ref.uri = uri; if (title) ref.title = title; ctx.refs.set(key, ref); } function renderReferences(ctx: Ctx): string { if (!ctx.refs.size) return ''; const keys = [...ctx.refs.keys()].sort((a, b) => a.localeCompare(b)); const items = keys .map((k) => { const r = ctx.refs.get(k)!; const title = r.title ? `${escapeHtml(r.title)}` : ''; const uri = r.uri ? `${escapeHtml(r.uri)}` : ''; const body = [title, uri].filter(Boolean).join('. ') || escapeHtml(k); return `
    [${escapeHtml(k)}]
    ${body}
    `; }) .join(''); return `

    References

    ${items}
    `; } // --- document ------------------------------------------------------------------ function isoDate(s: string): string { return s.replace(/T.+$/, ''); } /** An editor as avatar + name + handle, linking to their account page. */ export function renderEditor(e: EditorView, ctx: Ctx): string { const who = e.handle ?? e.did; const name = e.displayName || (e.handle ? `@${e.handle}` : e.did); const avatar = e.avatar ? `` : `${escapeHtml(name.replace(/^@/, '').slice(0, 1).toUpperCase())}`; const handle = e.handle && e.displayName ? `@${escapeHtml(e.handle)}` : ''; return `${avatar}${escapeHtml(name)}${handle}`; } /** * The spec body: nav-back, main with header table and sections. The wrapper * carries class "spec" so SPEC_BODY_CSS applies wherever it's inserted. */ export function renderSpecBody(doc: SpecDoc, options: RenderOptions = {}): string { const ctx = makeCtx(doc, options); const who = doc.handle ?? doc.did; const editors = doc.editors.map((e) => `
    ${renderEditor(e, ctx)}
    `).join(''); const sections = doc.sections.map((s) => renderSection(s, ctx, 0)).join('\n'); const refs = renderReferences(ctx); const label = doc.label ? `version${escapeHtml(doc.label)}` : ''; const site = options.siteName ?? 'stan.computer'; return `

    ${renderRichText(doc.title, ctx)}

    ${label}
    date${escapeHtml(isoDate(doc.updatedAt))}
    status${escapeHtml(statusLabel(doc.status))}
    editors${editors}
    abstract
    ${doc.abstract ? `

    ${renderRichText(doc.abstract, ctx)}

    ` : ''}
    ${sections} ${refs}
    `; } export type OgOptions = { url: string; image: string; siteName?: string }; /** The Open Graph / Twitter card tags for a spec, as on dasl.ing. */ export function ogTags(doc: SpecDoc, og: OgOptions): string { const title = doc.title.text; const description = (doc.abstract?.text ?? '').replace(/\s+/g, ' ').trim(); const colour = COLOUR_HEX[specColour(doc)]; return [ ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ].join('\n'); } export function faviconFor(doc: SpecDoc): string { const colour = COLOUR_HEX[specColour(doc)].replace('#', '%23'); return `data:image/svg+xml,`; } /** A complete standalone HTML page for ///html. */ export function renderSpecPage( doc: SpecDoc, options: RenderOptions & { canonical?: string; markdown?: string; katexCss?: string; og?: OgOptions } = {}, ): string { const title = doc.title.text; const alt = options.markdown ? `` : ''; const canonical = options.canonical ? `` : ''; const katex = options.katexCss ? `` : ''; const og = options.og ? ogTags(doc, options.og) : ''; return ` ${escapeHtml(title)} ${canonical} ${alt} ${katex} ${og} ${renderSpecBody(doc, options)} `; }