core
Link
A link around any content — a word in a sentence, or a whole block made clickable without nesting links
Source
import pb from 'path-browserify';
import Markdoc from '@markdoc/markdoc';
import type { Node as MarkdocNode, RenderableTreeNode, Schema } from '@markdoc/markdoc';
import * as xml from 'fast-xml-parser';
import { unescapeFenceContent } from './fence-escape.js';
import { resolveImageScheme } from './lib/image-schemes.js';
import { headingSlug, renderableText } from './util.js';
import {
readAttribution,
renderAttributedQuote,
splitInsideAttribution,
type Attribution,
} from './lib/attribution.js';
const { dirname, join, isAbsolute } = pb;
const { Tag } = Markdoc;
export interface TargetFile {
_id: string;
content: string;
}
export const heading: Schema = {
children: ['inline'],
attributes: {
level: { type: 'Number', required: true, render: false },
property: { type: String, required: false },
},
transform(node, config) {
const attributes = node.transformAttributes(config);
const children = node.transformChildren(config);
if (!attributes.id || typeof attributes.id !== 'string') {
// Slug the *transformed* children, walking into tags rather than keeping
// only top-level strings (BUG-005). Both halves matter:
//
// - Walking in keeps inline code, which is a Tag by this point. Filtering
// to strings dropped it, so `` ### `fileRoots` — named … `` rendered with
// an id that omitted `fileRoots` entirely.
// - Reading the transformed tree rather than the source node keeps
// variables *resolved*. A heading like `### {% $row.name %}` inside a
// `{% data %}` body is bound per row before this runs; slugging the
// source would give every row the same id.
//
// `headingSlug` itself is shared with `extractHeadings`, so the rules
// cannot drift even though the two read different phases.
attributes.id = headingSlug(renderableText(children));
}
return new Tag(`h${node.attributes['level']}`, attributes, children);
},
};
export const paragraph: Schema = {
children: ['inline'],
attributes: {
property: { type: String, required: false },
},
render: 'p',
};
export const fence: Schema = {
render: 'fence',
attributes: {
content: {
type: String,
render: false,
},
process: { type: Boolean, render: false, default: false },
language: { type: String, render: false, default: 'shell' },
// SPEC-062 / WORK-304 — fence-level annotation contract. All four are
// valid on hand-authored fences via Markdoc annotations (e.g. ```ts {%
// source="theme.ts" lines="74-125" linenumbers=true highlight="80-85" %}).
// Snippet's preprocess stamps `source` / `lines` on fences it
// synthesizes (and propagates author-set `linenumbers` / `highlight`
// from the rune). Consumer runes (codegroup, diff) read these names
// directly from `node.attributes` pre-transform and use them for tab
// labels / diff header / per-side gutter offset.
source: { type: String, render: false },
lines: { type: String, render: false },
linenumbers: { type: Boolean, render: false, default: false },
highlight: { type: String, render: false },
// Per-fence tab label hint consumed by `codegroup` (WORK-304). Inert on
// standalone fences; ignored when the parent rune doesn't read it.
label: { type: String, render: false },
// Set by snippet's preprocess, so a consumer can tell a read-in file
// from a fence the author wrote (preview treats only the latter as source).
snippet: { type: Boolean, render: false },
},
transform(node, config) {
const lang = node.attributes.language || 'shell';
// Forward declared annotation attributes as `data-*` on the rendered
// <pre> and <code>. Both get the same set so the highlight transform
// (which keys off the inner <code data-language>) and the CSS
// line-number / line-status selectors (which key off the outer <pre>)
// each see what they need. Empty / falsy values are dropped so
// unset annotations don't pollute the DOM.
const preAttrs: Record<string, unknown> = { 'data-language': lang };
const codeAttrs: Record<string, unknown> = { 'data-language': lang };
const source = node.attributes.source;
if (typeof source === 'string' && source.length > 0) {
preAttrs['data-source'] = source;
codeAttrs['data-source'] = source;
}
const lines = node.attributes.lines;
if (typeof lines === 'string' && lines.length > 0) {
preAttrs['data-lines'] = lines;
codeAttrs['data-lines'] = lines;
// Seed --rf-start-line so the CSS counter for line numbers begins
// at the file's actual offset rather than 1. Parse the start of the
// range; `--rf-start-line: <start - 1>` so the first increment lands
// on <start>. Silently no-op on malformed values.
const match = /^(\d+)/.exec(lines.trim());
if (match) {
const startLine = Number(match[1]);
if (Number.isFinite(startLine) && startLine > 0) {
const existingStyle = typeof preAttrs.style === 'string' ? `${preAttrs.style}; ` : '';
preAttrs.style = `${existingStyle}--rf-start-line: ${startLine - 1}`;
}
}
}
if (node.attributes.linenumbers === true) {
preAttrs['data-linenumbers'] = 'true';
codeAttrs['data-linenumbers'] = 'true';
}
const highlight = node.attributes.highlight;
if (typeof highlight === 'string' && highlight.length > 0) {
preAttrs['data-highlight-lines'] = highlight;
codeAttrs['data-highlight-lines'] = highlight;
}
// Forward any raw `data-*` attributes from the fence node (e.g. the
// legacy `data-snippet-error` produced by the snippet error-fence
// path). Authored fences with `{% data-foo="bar" %}` style annotations
// already need to declare `data-foo` on the schema for Markdoc to
// accept them — this just lets snippet's error path pass through.
for (const [key, value] of Object.entries(node.attributes)) {
if (key.startsWith('data-')) {
preAttrs[key] = value;
codeAttrs[key] = value;
}
}
const pre = new Tag('pre', preAttrs, [
new Tag('code', codeAttrs, [unescapeFenceContent(node.attributes.content)]),
]);
return new Tag('div', { class: 'rf-codeblock' }, [pre]);
},
};
export const list: Schema = {
children: ['item'],
attributes: {
ordered: { type: Boolean, render: false, required: true },
start: { type: Number },
marker: { type: String, render: false },
},
transform(node, config) {
return new Tag(
node.attributes.ordered ? 'ol' : 'ul',
node.transformAttributes(config),
node.transformChildren(config),
);
},
};
export const item: Schema = {
render: 'li',
children: [
'inline',
'heading',
'paragraph',
'image',
'table',
'tag',
'fence',
'blockquote',
'list',
'hr',
],
attributes: {
property: { type: String, required: false },
typeof: { type: String, required: false },
},
};
export const em: Schema = {
render: 'em',
children: ['strong', 's', 'link', 'code', 'text', 'tag'],
attributes: {
marker: { type: String, render: true },
},
};
export const strong: Schema = {
render: 'strong',
children: ['em', 's', 'link', 'code', 'text', 'tag'],
attributes: {
marker: { type: String, render: true },
},
};
export const text: Schema = {
attributes: {
content: { type: String, required: true },
property: { type: String, required: false },
},
transform(node, config) {
const attr = node.transformAttributes(config);
if (attr.property) {
return new Tag('span', { 'data-field': attr.property }, [node.attributes.content]);
}
return node.attributes.content;
},
};
export const link: Schema = {
children: ['strong', 'em', 's', 'code', 'text', 'tag'],
attributes: {
href: { type: String, required: true },
title: { type: String },
},
render: 'a',
transform(node, config) {
const { urls, path } = config.variables || {};
const dirName = path ? dirname(path) : '/';
let attributes = node.attributes;
const absPath = dirName !== '/' ? join(dirName, node.attributes.href) : node.attributes.href;
if (absPath in (urls || {})) {
const href = urls[absPath];
attributes = { ...attributes, href };
}
return new Tag(this.render, attributes, node.transformChildren(config));
},
};
/**
* `{% link %}` as a tag (SPEC-160 D8, WORK-655). Inline, it is the `link` node:
* a plain `<a>`. Around blocks it makes the whole region a link, and how is
* decided in the identity transform rather than here, because links can be added
* after this transform runs (entity auto-links, resolved refs). So the block
* form emits a marker, `data-link-href`, which the engine turns into a wrapping
* `<a>` or a stretched one (`packages/transform/src/link-regions.ts`). It emits
* no `data-rune`, so a schema property inside it still publishes. An empty
* `href` renders the content unchanged.
*/
export const linkTag: Schema = {
attributes: {
href: { type: String },
title: { type: String },
'aria-label': {
type: String,
description: 'Accessible name for a whole-region link; defaults to the content’s title',
},
},
transform(node, config) {
if (node.inline) {
if (!String(node.attributes.href ?? '')) return node.transformChildren(config);
return link.transform!.call(link, node, config);
}
const { urls, path } = config.variables || {};
const dirName = path ? dirname(path) : '/';
const raw = String(node.attributes.href ?? '');
const absPath = dirName !== '/' && raw ? join(dirName, raw) : raw;
const href = absPath in (urls || {}) ? urls[absPath] : raw;
const children = node.transformChildren(config);
if (!href) return children;
const label = node.attributes['aria-label'];
return new Tag(
'div',
{ 'data-link-href': href, ...(label ? { 'data-link-label': label } : {}) },
children,
);
},
};
export const hardbreak = Markdoc.nodes.hardbreak;
/** SPEC-185 D3 — the quotation role's marker. */
export const QUOTE_ATTR = 'data-quote';
/**
* SPEC-185 D3.2 — a plain `>` that no rune consumes is a quotation: someone
* else's words cited in support of the text. It has no rune to mark it, so the
* node does, and a theme styles the role (`[data-quote="quotation"]`) rather
* than the bare element. A rune that reinterprets `>` (tips, callouts,
* dialogue) produces its own elements, or removes the marker from a
* blockquote it renders: what it makes is not a quotation (D3.3).
*/
export const blockquote: Schema = {
...Markdoc.nodes.blockquote,
transform(node, config) {
// SPEC-185 D6 — an attributed quotation: its last paragraph is
// `— **Name**, Source`, so it is a `<figure>` with its `<figcaption>`.
const split = splitInsideAttribution(node);
if (split) return renderAttributedQuote('quotation', split.quote, split.attribution, config);
return new Tag(
'blockquote',
{ ...node.transformAttributes(config), [QUOTE_ATTR]: 'quotation' },
node.transformChildren(config),
);
},
};
/**
* SPEC-185 D5 — an epigraph at the start of a page: a blockquote that opens the
* page's content, or directly follows its `#` title (a layout may take the
* title from frontmatter, so the content may have none), with an attribution
* paragraph after it. Without the attribution it stays a quotation: epigraphs
* name their source, and requiring one keeps an ordinary opening quote from
* being misread. Returns the index of the blockquote, or -1.
*/
export function pageEpigraphAt(children: readonly MarkdocNode[]): number {
let at = 0;
if (children[at]?.type === 'heading' && children[at].attributes?.level === 1) at++;
return pageEpigraph(children, at) ? at : -1;
}
/** The epigraph at `at`, in either attribution form (D6): the paragraph
* after the quote, or the quote's own last line. */
function pageEpigraph(
children: readonly MarkdocNode[],
at: number,
): { quote: MarkdocNode; attribution: Attribution; span: number } | undefined {
const quote = children[at];
if (quote?.type !== 'blockquote') return undefined;
const after = readAttribution(children[at + 1]);
if (after) return { quote, attribution: after, span: 2 };
const inside = splitInsideAttribution(quote);
return inside ? { ...inside, span: 1 } : undefined;
}
/** The page's `article`, with an opening epigraph recognised (D5). */
export const document: Schema = {
...Markdoc.nodes.document,
transform(node, config) {
const at = pageEpigraphAt(node.children);
if (at === -1) {
return new Tag('article', node.transformAttributes(config), node.transformChildren(config));
}
const epigraph = pageEpigraph(node.children, at)!;
const before = node.children.slice(0, at);
const after = node.children.slice(at + epigraph.span);
const render = (nodes: MarkdocNode[]): RenderableTreeNode[] =>
nodes.flatMap((n) => {
const out = n.transform(config) as RenderableTreeNode | RenderableTreeNode[];
return Array.isArray(out) ? out : [out];
});
return new Tag('article', node.transformAttributes(config), [
...render(before),
renderAttributedQuote('epigraph', epigraph.quote, epigraph.attribution, config),
...render(after),
]);
},
};
/** D3.3 — a rune that renders a `>` it reinterprets takes the quotation marker
* off: its tips, quote or callout are not a quotation. */
export function withoutQuoteRole<T>(tag: T): T {
const attrs = (tag as { attributes?: Record<string, unknown> } | null)?.attributes;
if (attrs && QUOTE_ATTR in attrs) delete attrs[QUOTE_ATTR];
return tag;
}
export const image: Schema = {
render: 'img',
attributes: {
src: { type: String, required: true },
alt: { type: String },
title: { type: String },
property: { type: String },
},
transform(node, config) {
const attr = node.transformAttributes(config);
// SPEC-106 — custom URL-scheme sugar in the image `src`
// (`placeholder:portrait`, `icon:github`). Resolve to an inline renderable
// before any path handling or the `<img>` fallback. Bare paths, absolute
// URLs, and unregistered schemes return null and fall through unchanged.
const resolved = resolveImageScheme(node.attributes.src, {
alt: typeof attr.alt === 'string' ? attr.alt : undefined,
title: typeof attr.title === 'string' ? attr.title : undefined,
property: typeof attr.property === 'string' ? attr.property : undefined,
config,
});
if (resolved) {
if (attr.property) {
resolved.attributes['data-field'] = attr.property;
}
return resolved;
}
const svgFiles: TargetFile[] = config.variables?.svg || [];
let src = node.attributes.src;
if (!isAbsolute(src) && config.variables?.path) {
src = join('/', dirname(config.variables.path), src);
}
const svg = svgFiles.find((file) => file._id === src);
if (svg) {
const parser = new xml.XMLParser({ ignoreAttributes: false });
let jObj = parser.parse(svg.content);
const tag = jObjToTag('svg', jObj.svg);
if (attr.property) {
tag.attributes['data-field'] = attr.property;
}
tag.attributes.xmlns = undefined;
return tag;
}
return new Tag(this.render, attr, node.transformChildren(config));
},
};
export const table: Schema = {
children: ['thead', 'tbody', 'tr'],
attributes: {},
transform(node, config) {
const tableTag = new Tag(
'table',
node.transformAttributes(config),
node.transformChildren(config),
);
return new Tag('div', { class: 'rf-table-wrapper' }, [tableTag]);
},
};
/**
* `td` node — Markdoc's default, extended to forward a `data-value` attribute
* (SPEC-103). A typed-numeric `data` cell carries its normalized number on
* `data-value` (`"$1,200"` → `data-value="1200"`); `chart` reads it via
* `cell.dataset.value` and `datatable`'s sort prefers it over cell text. The
* attribute is absent on hand-authored cells, so existing tables are unchanged
* — `data-value` is a purely additive enhancement channel.
*/
export const td: Schema = {
...Markdoc.nodes.td,
attributes: {
...(Markdoc.nodes.td.attributes ?? {}),
'data-value': { type: String },
},
};
function jObjToTag(tagName: string, content: Record<string, any> | Record<string, any>[]): any {
if (Array.isArray(content)) {
return content.map((c) => jObjToTag(tagName, c));
}
let children: any[] = [];
let attr: Record<string, string | undefined> = {};
for (const [k, v] of Object.entries(content)) {
if (k.startsWith('@_')) {
attr[k.slice(2)] = v;
} else if (k === '#text') {
children.push(v);
} else {
children.push(jObjToTag(k, v));
}
}
return new Tag(tagName, attr, children);
}
{% link %} is a link written as a tag. Inside a line of text it is an ordinary <a>, the same as [text](url), useful when the target is a variable. Around blocks it makes the whole region a link — a figure, a hint, a heading and its paragraph — and works out how to do that without nesting one link inside another.
Inline
In a line of text the tag renders a plain <a>. Its main use is in templates, where the target comes from a variable:
Read {% link href=$item.url %}{% $item.data.title %}{% /link %} next.
Around blocks
{% link href="/runes/card" %}
## Card
A generic content card with an optional whole-card link.
{% /link %}<div data-link-href="/runes/card">
<h2 id="card">Card</h2>
<p>A generic content card with an optional whole-card link.</p>
</div>Card
A generic content card with an optional whole-card link.
<div data-link-href="/runes/card">
<h2 id="card">Card</h2>
<p>A generic content card with an optional whole-card link.</p>
</div>How the region becomes a link depends on what it holds:
- Nothing interactive inside — the region is wrapped in a real
<a data-link="wrap">. - Links or controls inside — an
<a>around them would nest interactive content, which is invalid HTML. A stretched<a data-link="stretch">is laid over the region instead, and the inner links stay clickable above it. This is the same overlay acardwithhrefuses.
{% link href="/runes/figure" %}
{% hint type="note" %}
The whole hint opens the figure page, and [this link](/runes/hint) still opens the hint page.
{% /hint %}
{% /link %}<div data-link-href="/runes/figure">
<section data-rune="hint" data-rune-fields="{"hintType":"note"}">
<div data-name="body">
<p>
The whole hint opens the figure page, and
<a href="/runes/hint">this link</a>
still opens the hint page.
</p>
</div>
</section>
</div>The whole hint opens the figure page, and this link still opens the hint page.
<div data-link-href="/runes/figure">
<section class="rf-hint rf-hint--note" data-hint-type="note" data-elevation="sunken" data-rune="hint" data-density="compact">
<div data-name="header" data-zone="header" data-zone-layout="bar" class="rf-hint__header" data-section="header">
<span data-field="hintType">
<span data-icon-group="hint" data-icon="note"></span>
<span data-meta-value="">note</span>
</span>
</div>
<div data-name="body" class="rf-hint__body">
<p>
The whole hint opens the figure page, and
<a href="/runes/hint">this link</a>
still opens the hint page.
</p>
</div>
</section>
</div>The choice is made when the page is rendered, after the cross-page build has run, so links added late — entity cross-links, resolved xrefs — are taken into account.
Links, buttons, form controls, details, embedded media and interactive runes such as tabs all count as interactive.
Accessible name
The link is a real, focusable link with one tab stop. It is named, in order:
- by
aria-label, when you give one; - else by the content's title — its
title,headlineornameslot, or else its first heading — througharia-labelledby; - else by the content's text, up to 120 characters.
A wrapped link reads its content as its name already; the order above matters for the stretched link, which has no text of its own.
Empty href
An empty href renders the content unchanged, with no link. A template can write {% link href=$item.url %} around a block without first checking that the entry has a URL.
Structured data
link adds no data-rune of its own, so it is not a boundary for the structured data inside it. A character inside a link still publishes as a Person.
Attributes
| Attribute | Type | Required | Description |
|---|---|---|---|
href | string | — | |
title | string | — | |
aria-label | string | — | Accessible name for a whole-region link; defaults to the content’s title |
| Not available | Why |
|---|---|
| bg, elevation, inset, motion (reveal, stagger), spacing, substrate, tint, width | this rune declares no posture for it |
| dropcap, reading | this rune declares no prose body |
| frame | this rune declares neither a `frameTarget` nor a media section |
| prominence | this rune has no page-section header or featured quotation |