Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394// SpecDoc → HTML. The body fragment is what the app's spec view shows and// what /<handle>/<shortname>/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 <code> 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<Pick<RenderOptions, 'math' | 'blobUrl' | 'accountUrl' | 'specUrl'>> & RenderOptions; did: string; dfnIds: IdAllocator; refs: Map<string, Ref>; knownDfns: Set<string>; /** The spec's imported catalogue references, by key. */ imports: Map<string, RefView>;};
function defaultMath(tex: string, display: boolean): string { return display ? `<pre class="math-src"><code>${escapeHtml(tex)}</code></pre>` : `<code class="math-src">${escapeHtml(tex)}</code>`;}
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<string> { const ids = new IdAllocator(); const out = new Set<string>(); 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 `<strong>${inner()}</strong>`; case 'italic': return `<em>${inner()}</em>`; case 'code': return `<code>${inner()}</code>`; case 'sub': return `<sub>${inner()}</sub>`; case 'sup': return `<sup>${inner()}</sup>`; case 'link': { const uri = (f as { uri: string }).uri; return `<a href="${escapeAttr(safeHref(uri))}">${inner()}</a>`; } case 'math': return `<span class="math">${ctx.opts.math(layoutText(n.children), false)}</span>`; 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 `<dfn id="${escapeAttr(id)}">${inner()}</dfn>`; } 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 `<a class="dfn-ref external" href="${escapeAttr(safeHref(d.uri))}"${key}>${inner()}</a>`; } const id = d.id ?? `dfn-${slugify(layoutText(n.children))}`; const cls = ctx.knownDfns.has(id) ? 'dfn-ref' : 'dfn-ref missing'; return `<a class="${cls}" href="#${escapeAttr(id)}">${inner()}</a>`; } 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 `[<a href="#ref-${escapeAttr(slugify(key))}" class="ref">${escapeHtml(key)}</a>]`; } 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<RenderOptions, 'math'> = {}): 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 `<p${attr}>${renderRichText(c.text, ctx)}</p>`; 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 `<pre${attr}><code${lang}>${highlightCode(c.code, c.language)}</code></pre>`; } case 'group.standards.block#math': return `<div class="math-block"${attr}>${ctx.opts.math(c.tex, true)}</div>`; 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() ? `<figcaption>${renderRichText(c.caption, ctx)}</figcaption>` : ''; return `<figure${attr}><img src="${escapeAttr(src)}" alt="${alt}">${caption}</figure>`; } case 'group.standards.block#list': return renderList(c, ctx, attr); case 'group.standards.block#definitionList': return `<dl${attr}>${c.items .map((d) => `<dt>${renderRichText(d.term, ctx)}</dt><dd>${renderRichText(d.description, ctx)}</dd>`) .join('')}</dl>`; 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) => `<li>${renderRichText(item.text, ctx)}${item.list ? renderList(item.list, ctx) : ''}</li>`) .join(''); return `<${tag}${attr}>${items}</${tag}>`;}
// --- 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 `<section id="${escapeAttr(s.id)}" data-section="${escapeAttr(s.uri)}"><${h}>${renderRichText(s.title, ctx)}</${h}>${content}${subs}</section>`;}
/** 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 ? `<cite>${escapeHtml(r.title)}</cite>` : ''; const uri = r.uri ? `<a href="${escapeAttr(safeHref(r.uri))}">${escapeHtml(r.uri)}</a>` : ''; const body = [title, uri].filter(Boolean).join('. ') || escapeHtml(k); return `<dt id="ref-${escapeAttr(slugify(k))}">[${escapeHtml(k)}]</dt><dd>${body}</dd>`; }) .join(''); return `<section id="references"><h2>References</h2><dl>${items}</dl></section>`;}
// --- 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 ? `<img class="avatar" src="${escapeAttr(e.avatar)}" alt="">` : `<span class="avatar initial">${escapeHtml(name.replace(/^@/, '').slice(0, 1).toUpperCase())}</span>`; const handle = e.handle && e.displayName ? `<span class="handle">@${escapeHtml(e.handle)}</span>` : ''; return `<a class="editor" href="${escapeAttr(ctx.opts.accountUrl(who))}">${avatar}<span class="name">${escapeHtml(name)}</span>${handle}</a>`;}
/** * 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) => `<div class="editor-row">${renderEditor(e, ctx)}</div>`).join(''); const sections = doc.sections.map((s) => renderSection(s, ctx, 0)).join('\n'); const refs = renderReferences(ctx); const label = doc.label ? `<tr><th>version</th><td>${escapeHtml(doc.label)}</td></tr>` : ''; const site = options.siteName ?? 'stan.computer'; return `<div class="spec"><div class="nav-back"><a href="/">${escapeHtml(site)}</a> / <a href="${escapeAttr(ctx.opts.accountUrl(who))}">${escapeHtml(who)}</a> / <a href="${escapeAttr(ctx.opts.specUrl(who, doc.shortname))}">${escapeHtml(doc.shortname)}</a></div><main><header><h1>${renderRichText(doc.title, ctx)}</h1><table><tr><th>date</th><td>${escapeHtml(isoDate(doc.updatedAt))}</td></tr><tr><th>status</th><td><span class="maturity ${escapeAttr(doc.status)}">${escapeHtml(statusLabel(doc.status))}</span></td></tr><tr><th>editors</th><td>${editors}</td></tr>${label}<tr><th>abstract</th><td><div id="abstract">${doc.abstract ? `<p>${renderRichText(doc.abstract, ctx)}</p>` : ''}</div></td></tr></table></header>${sections}${refs}</main></div>`;}
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 [ `<meta name="twitter:card" content="summary_large_image">`, `<meta name="twitter:title" property="og:title" content="${escapeAttr(title)}">`, `<meta name="twitter:description" property="og:description" content="${escapeAttr(description)}">`, `<meta name="twitter:image" property="og:image" content="${escapeAttr(og.image)}">`, `<meta property="og:image:width" content="${BANNER_WIDTH}">`, `<meta property="og:image:height" content="${BANNER_HEIGHT}">`, `<meta name="twitter:image:alt" content="${escapeAttr(`${specEmoji(doc)} on ${specColour(doc)}`)}">`, `<meta name="twitter:url" property="og:url" content="${escapeAttr(og.url)}">`, `<meta property="og:type" content="article">`, `<meta property="og:site_name" content="${escapeAttr(og.siteName ?? 'stan.computer')}">`, `<meta property="og:locale" content="en">`, `<meta name="theme-color" content="${colour}">`, ].join('\n');}
export function faviconFor(doc: SpecDoc): string { const colour = COLOUR_HEX[specColour(doc)].replace('#', '%23'); return `data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><rect x=%220%22 y=%220%22 width=%22100%22 height=%22100%22 fill=%22${colour}%22></rect></svg>`;}
/** A complete standalone HTML page for /<handle>/<shortname>/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 ? `<link rel="alternate" type="text/markdown" href="${escapeAttr(options.markdown)}">` : ''; const canonical = options.canonical ? `<link rel="canonical" href="${escapeAttr(options.canonical)}">` : ''; const katex = options.katexCss ? `<link rel="stylesheet" href="${escapeAttr(options.katexCss)}">` : ''; const og = options.og ? ogTags(doc, options.og) : ''; return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title><link rel="icon" href="${faviconFor(doc)}">${canonical}${alt}${katex}${og}<style>${SPEC_PAGE_CSS}</style></head><body>${renderSpecBody(doc, options)}</body></html>`;}