Rune authoring›Patterns & Best Practices

Patterns & Best Practices

This page documents the canonical patterns used across the rune library. Follow these when writing new runes or reviewing existing ones.

Heading-based splitting

Many runes use headings as structural boundaries — each heading starts a new step, tab, accordion item, etc. Heading level is determined automatically, not by the content author.

Auto-detect

Runes that split on headings auto-detect the level from the first heading in the content. Use a sections content model with sectionHeading: 'heading':

contentModel: {
  type: 'sections',
  sectionHeading: 'heading',  // auto-detect level from first heading
  emitTag: 'my-item',
  emitAttributes: { name: '$heading' },
},

This works because content authors typically use a consistent heading level within a rune. It also handles AI-generated content seamlessly.

Fixed level

Some runes hardcode a specific heading level as part of their design contract — for example, Bento always splits at h2, and Symbol uses h3 for groups and h4 for members:

const converted = headingsToList({ level: 2 })(nodes);

Header + body group split

The standard pattern for runes with a title area uses a delimited content model with header fields before the body:

contentModel: {
  type: 'sequence',
  fields: [
    { name: 'header', match: 'heading|paragraph', optional: true, greedy: true },
    { name: 'body', match: 'any', optional: true, greedy: true },
  ],
},

Use pageSectionProperties(header) for consistent extraction of eyebrow, headline, image, and blurb:

transform(resolved, attrs, config) {
  const header = renderNodes(resolved.header, config);

  return createComponentRenderable({
    rune: 'my-rune',
    tag: 'section',
    refs: {
      ...pageSectionProperties(header),
      // adds: eyebrow, headline, image, blurb
    },
    children: [...],
  });
},

This pattern gives you:

  • Eyebrow — a short paragraph directly before the main heading (small label above it); a heading is never read as an eyebrow
  • Headline — the main heading
  • Image — first image in the header area
  • Blurb — the paragraph directly after the main heading

Child item runes

When a rune has repeating items (Steps, Accordion, Tabs), create a separate schema for the child:

// Child — separate schema
export const accordionItem = createContentModelSchema({
  attributes: {
    name: { type: String, required: true },
  },
  contentModel: {
    type: 'sequence',
    fields: [{ name: 'body', match: 'any', optional: true, greedy: true }],
  },
  transform(resolved, attrs, config) {
    return createComponentRenderable({
      rune: 'accordion-item',
      tag: 'details',
      // ...
    });
  },
});

// Parent — uses sections content model to emit child tags
export const accordion = createContentModelSchema({
  attributes: {},
  contentModel: () => ({
    type: 'sections',
    sectionHeading: 'heading',
    emitTag: 'accordion-item',
    emitAttributes: { name: '$heading' },
    // ...
  }),
  transform(resolved, attrs, config) { /* ... */ },
});

Don't inline item logic in the parent's transform(). Separate item schemas:

  • Get their own data-rune marker (and matching typeName config entry)
  • Can have their own attributes and groups
  • Are reusable as explicit child tags: {% accordion-item name="..." %}
  • Can be registered independently in the rune catalog via defineRune

Choosing the interactivity path

PathWhen to useExamples
Identity transform + CSSLayout, styling, structural decorationGrid, Hint, Recipe, Feature, Hero
Behaviors libraryProgressive enhancement of native HTMLAccordion, Tabs, DataTable, Form, Reveal
postTransform hooksData rendering, custom elementsChart, Map, Diagram, Comparison, Sandbox

Default to CSS. About 75% of runes need nothing beyond the identity transform and CSS. If you can achieve the interaction with :target, :checked, sibling selectors, or scroll-driven effects, you don't need JavaScript.

Use behaviors for progressive enhancement. The behaviors library adds ARIA attributes, keyboard navigation, and event listeners to existing HTML. The rune still works without JavaScript — it just gets enhanced.

Use postTransform hooks when you need to generate complex HTML structure from metadata, produce custom element tags for client-side initialization, or integrate with external libraries. These hooks run during the identity transform and keep rendering framework-agnostic.


Modifier naming

Use camelCase for modifier names in code. The engine auto-converts to kebab-case for data attributes:

// In the rune:
properties: { hintType }

// Engine outputs:
// class="rf-hint--warning"
// data-hint-type="warning"

Use semantic names that describe the variant's purpose, not its visual treatment:

// Good
difficulty: 'medium'
hintType: 'warning'
align: 'center'

// Bad
color: 'yellow'
style: 'bordered'
size: 'large'

type vs sentiment vs variant

These three recur across runes and name different axes — pick the one that matches what the attribute actually is, rather than defaulting to variant:

  • type — a semantic kind that carries meaning beyond color: an icon, an implied label, sometimes behavior. Color is a side effect. Examples: hint type="warning" (admonition kind), api method="POST", diff type.
  • sentiment — a pure tone cue, nothing but a color signal: positive / caution / negative / neutral, backed by the shared sentiment tokens (--rf-color-success / -warning / -danger / -muted, see dimensions/metadata.css). Examples: badge sentiment, progress sentiment.
  • variant — an enumerated visual style that is not about tone: feature variant=…. (A variant naming a look belongs to the theme, not the rune.)

If the values are positive/caution/negative, it's a sentiment, not a variant.


Canonical layout vocabulary

Many runes expose an arrangement axis through a layout string attribute. The attribute name is universal — every rune that arranges its children uses layout, never a synonym — but the values are governed by a two-tier vocabulary so a shared value means the same thing everywhere.

  • Canonical tokens carry a shared DOM/behavior contract: the same value implies the same emitted structure and behavior wherever it appears. The pool is grid, list, and carousel. Import them from the shared const so the spelling cannot drift and importing a token implies its contract:

    import { LAYOUT, layoutMatches } from '@refrakt-md/runes';
    
    // canonical picks + any rune-local literals
    layout: { type: String, matches: layoutMatches([LAYOUT.grid, LAYOUT.list, LAYOUT.carousel], 'masonry') }
    
  • Local tokens are arrangements unique to one rune with no shared machinery — masonry (variable-height media only), table (columnar data only). They stay declared inline because they don't generalise. Local values are sanctioned, not a smell.

No rune must support every canonical token — pick the subset that makes sense and append local values.

carousel is a layout mode, not a wrapper rune: the same homogeneous items, arranged on a scroll-snap track with a progressive-enhancement behavior layer (the same shape as tabs/accordion). A rune opts in by accepting LAYOUT.carousel in its matches and emitting the shared DOM contract:

  • the host carries data-layout="carousel" (the engine's output for the layout modifier);
  • a track container marked data-name="items";
  • the slides are the track's direct element children — a rune keeps its own item marker (gallery's data-name="item" figures, feature's definition items, …), so adoption needs no renaming.

A single block-agnostic behavior binds on [data-layout="carousel"] (not on any rune name) and adds prev/next nav buttons and keyboard scrolling; the CSS scroll-snap track is the baseline. Emit that shape and the behavior works with zero per-rune behavior code — adoption is config + contract + CSS. Keep the track's direct children to just the slides (no stray non-slide elements inside data-name="items").

Graduation rule: a value enters the canonical pool when a second rune needs the same concept with the same contract. Until then it stays local. This guards both premature abstraction (a pool full of one-offs) and no abstraction (three runes reinventing the same concept). A private spelling of a canonical concept (e.g. compare's side-by-side/stacked) is a defect to migrate — with deprecations — when that rune is next touched; a genuinely unique arrangement is a legitimate local value.


Don't hardcode structure in transform

Rune schemas should produce semantic output — meta tags with values and content in named containers. The engine config should inject visual structure.

1// Hardcoding visual structure in the rune2transform() {3 const icon = new Tag('span', { class: 'icon' });4 const title = new Tag('span', {}, [this.type]);5 const header = new Tag('div', {}, [icon, title]);6 return new Tag('section', {}, [header, body]);7}
1// Semantic output, visual structure in engine config2transform(resolved, attrs, config) {3 const hintType = new Tag('meta', { content: attrs.type });4 return createComponentRenderable({5 rune: 'hint',6 tag: 'section',7 properties: { hintType },8 refs: { body: children.tag('div') },9 children: [hintType, children.next()],10 });11}

The engine config then handles the visual structure declaratively:

structure: {
  header: { tag: 'div', before: true, children: [
    { tag: 'span', ref: 'icon', icon: { group: 'hint', variant: 'hintType' } },
    { tag: 'span', ref: 'title', metaText: 'hintType' },
  ]},
}

This separation means:

  • Rune output is framework-agnostic (works with any renderer)
  • Themes can override structure without forking the rune
  • Icons, badges, and meta displays are configurable per-theme

Field ordering

Sequence fields consume nodes in declaration order. Each field matches the next eligible node from where the previous field stopped.

contentModel: {
  type: 'sequence',
  fields: [
    { name: 'header', match: 'heading|paragraph', greedy: true },  // headings + paragraphs first
    { name: 'ingredients', match: 'list' },                         // then lists
    { name: 'body', match: 'any', optional: true, greedy: true },   // remaining content
  ],
},

Design field match patterns to be mutually exclusive when possible. If two fields can match the same node type, the first one wins.

Use delimited content models (HR delimiter) when content has explicit visual breaks:

contentModel: {
  type: 'delimited',
  delimiter: 'hr',
  zones: [
    { name: 'main', type: 'sequence', fields: [...] },     // before first ---
    { name: 'showcase', type: 'sequence', fields: [...] },  // after first ---
  ],
},

Content boundaries

A rune's content model should include exactly what it reinterprets — content that gains new semantic meaning by being inside the rune. Content that would render identically whether inside or outside the rune belongs on the page, not in the rune.

Three tests

  1. Does the rune give this content new meaning? A list inside {% recipe %} becomes ingredients — with data-name="ingredient", schema.org markup, and dedicated styling. That's reinterpretation. A paragraph that's just a paragraph is pass-through.
  2. Does it map to a structured data field? If schema.org/Recipe has no story field, a narrative paragraph doesn't belong inside the recipe rune.
  3. Is the rune still portable without it? A recipe card should work on an index page, a blog post, or a sidebar. Narrative content couples it to a single page context.

What goes where

RuneInside (reinterpreted)Outside (page content)
RecipeIngredients, steps, tips, metadata, headline, blurb, mediaStory, editorial, famous quotes. A story may sit inside a rune that declares a narrative field, wrapped in an editorial rune (below)
PlaylistTracks, cover art, name, descriptionAlbum review, discovery story
CharacterStats, abilities, portrait, nameChapter featuring the character
EventDate, venue, schedule, locationBlog post about why to attend

Page composition

A recipe blog post demonstrates the pattern — the rune is a semantic island within surrounding page content:

# My Summer in Tuscany

That long story about grandma's kitchen
goes here, as regular page content...

{% recipe prepTime="PT15M" cookTime="PT30M" servings=4 difficulty="easy" %}
# Classic Pasta Carbonara

A rich and creamy Italian pasta dish.

- 400g spaghetti
- 200g pancetta
- 4 egg yolks

1. Cook pasta in salted boiling water
2. Fry pancetta until crispy
3. Whisk egg yolks with grated cheese

> Never add eggs directly to a hot pan.
{% /recipe %}

More thoughts on the trip, or a second
recipe rune, or any other page content.

Everything inside the {% recipe %} tags is reinterpreted: the heading becomes the recipe name, the list becomes ingredients, the ordered list becomes steps, the blockquote becomes a chef's tip. Everything outside is regular Markdown rendered as-is.

The narrative field

A food blog lays a recipe out differently. The recipe's name, image and times come first, then the story, then a card with the ingredients and method. The story sits between the rune's parts, so it cannot simply go before or after the rune.

A rune may declare one narrative field for this. Its match names the editorial runes textblock and mediatext, and nothing else:

story: { match: "tag:textblock|tag:mediatext", optional: true, greedy: true }

The author wraps the story in an editorial rune, in the place the content model reads it, and the template places it between the rune's parts:

{% dish prepTime="PT15M" %}
# Classic Pasta Carbonara

A rich and creamy Italian pasta dish.

{% textblock %}
The summer we spent in Tuscany, grandma made this every Sunday...
{% /textblock %}

- 400g spaghetti
- 200g pancetta

1. Cook the pasta
2. Fry the pancetta
{% /dish %}

Two rules hold. Both are checked when the definition loads:

  • One narrative field per rune. A field is the narrative field because its match names only editorial runes, so nothing extra is declared. A definition with two is rejected (narrative-field-twice).
  • It is never structured data. The rune's schema row describes the rune, not the editorial around it. A schema table that maps the narrative field is rejected (narrative-field-mapped).

The three tests above still apply to everything else. Loose prose inside the rune is still outside its content model: only a story wrapped in {% textblock %} or {% mediatext %}, in the narrative field's place, is read. A field that mixes editorial runes with other matches (tag:textblock|paragraph) is not a narrative field and is not checked as one. The default stays a semantic island; a narrative field is opt-in per rune, and a site's own composed rune can declare one today.


Testing

Every rune should have a test file at packages/runes/test/{name}.test.ts.

Test helpers

import { describe, it, expect } from 'vitest';
import { parse, findTag, findAllTags } from './helpers.js';
  • parse(markdown) — runs the full Markdoc parse + transform pipeline
  • findTag(node, predicate) — finds the first matching Tag in a tree
  • findAllTags(node, predicate) — finds all matching Tags

What to test

Basic output structure:

it('should produce the expected structure', () => {
  const result = parse(`{% hint type="warning" %}
Be careful.
{% /hint %}`);

  const hint = findTag(result as any, t => t.attributes['data-rune'] === 'hint');
  expect(hint).toBeDefined();
  expect(hint!.name).toBe('section');
});

Auto-detection behavior (headings are automatically detected):

it('should auto-detect h2 heading level', () => {
  const result = parse(`{% steps %}
## Step One
Content.

## Step Two
Content.
{% /steps %}`);

  const steps = findTag(result as any, t => t.attributes['data-rune'] === 'steps');
  const items = findAllTags(steps!, t => t.attributes['data-rune'] === 'step');
  expect(items.length).toBe(2);
});

Child tags still work (for runes that support both heading syntax and explicit child tags):

it('should support explicit child tags', () => {
  const result = parse(`{% accordion %}
{% accordion-item name="Item One" %}
Content.
{% /accordion-item %}
{% /accordion %}`);

  const items = findAllTags(acc!, t => t.attributes['data-rune'] === 'accordion-item');
  expect(items.length).toBe(1);
});

Run tests

# All tests
npm test

# Single file
npx vitest run packages/runes/test/mystep.test.ts

# Watch mode
npm run test:watch

Neutral primitives for cross-cutting behaviour

A few data-* attributes act as neutral conventions that any rune can opt into. They aren't tied to a specific rune; the cross-cutting machinery that consumes them just looks for the attribute and reacts. Adopt them when your rune wants the corresponding behaviour without re-implementing it.

data-outline-scope — sub-outline boundary

Set data-outline-scope="{value}" on a rune's wrapper to mark the subtree as a sub-outline boundary. Two generic walkers honor the attribute:

  1. Heading-ID walker — heading IDs inside the subtree are prefixed with {value}-- (e.g. SPEC-023--acceptance-criteria). The host page can collide on id="acceptance-criteria" without clashing.
  2. TOC walker — {% toc %} skips list entries that point at headings inside the scoped subtree, so the host's TOC stays focused on host-only structure.

Both walkers run automatically in the core postProcess pass. Set the attribute once and you get both behaviours. expand is the first consumer (the embed is a quoted document, not part of the host outline); future runes like aside, sidenote, or quote can adopt the same convention with no walker changes needed.

The walker rules:

  • Nearest enclosing data-outline-scope wins for nested scopes — data-outline-scope="A" containing data-outline-scope="B" containing <h2 id="foo"> produces id="B--foo".
  • Already-prefixed IDs are skipped (idempotent), so a re-run of the pass doesn't double-prefix.
  • A rune that doesn't set the attribute behaves exactly as today.

data-target-type — addressable-by-xref

Set data-target-type="{rune-name}" on resolved xref anchors so the behaviours layer can identify "this link points at a drawer / popover / modal / future-thing" and intercept the click. The xref resolver propagates this from the registered entity's type automatically — runes that register entities don't need to set the attribute themselves; they just need to be registered in the EntityRegistry.

Drawer ({% drawer %}) is the canonical consumer: its behaviours layer queries a[data-target-type="drawer"] and turns matching clicks into dialog.showModal() calls.

Background:

Canonical layout vocabulary

ADR-018accepted

Canonical layout vocabulary

layoutrunesvocabularyarchitecturecarousel

Context

Many runes expose an arrangement axis through a layout string attribute, and the name is already universal — every rune that arranges its children uses layout, never a synonym:

Runelayout values
gallerygrid · carousel · masonry
compareside-by-side · stacked
castgrid · list
bloglist · grid · compact
collectionlist · grid · table
relationshipslist · grid
comparisontable

The attribute name is consistent; the values are a zoo. The same concept wears different spellings across runes (compare's side-by-side is a grid; its stacked is a single-column list), while genuinely rune-specific arrangements (masonry, table) sit in the same flat enum as the cross-cutting ones with no signal that they don't generalise. Each rune mints its own value set in isolation.

This becomes a concrete problem the moment a value is meant to be shared. carousel exists today only in gallery, implemented as a gallery-coupled behavior ([data-rune="gallery"], rf-gallery__nav chrome). We want it to become a layout mode for several runes (feature, then testimonial, pricing, cast, …). For that to be a config-and-CSS change per rune rather than a behavior rewrite, carousel has to mean the same thing and be spelled the same way everywhere, and it has to carry a shared DOM/behavior contract — not just a shared label. Without a governing policy, three runes would each reinvent it with drifting spellings.

There is an opposing failure mode too: a single flat enum that every rune must draw from would force genuinely unique arrangements (masonry, table) to either join a club they don't belong to or be banned. Neither is right.

Options Considered

  1. One flat canonical enum; every rune subsets from it; no local values. Rejected. Forces the genuinely rune-specific arrangements (masonry, table) into the shared set, where they carry no shared contract and confuse the meaning of "canonical." Either they pollute the pool or they're disallowed.

  2. Leave it as-is — each rune owns its layout values. Rejected. This is the status quo that makes carousel non-portable: every adopting rune would reimplement it, spellings would drift, and the shared behavior could never bind block-agnostically.

  3. Two-tier vocabulary: a curated canonical pool + sanctioned per-rune local values, governed by a graduation rule. Chosen. A rune's accepted layout values are the union of its picks from the canonical pool plus its own local values. Canonical tokens carry a shared contract; local tokens are rune-private with no shared machinery.

Decision

  1. Two tiers, distinguished by contract — not popularity.

    • Canonical tokens carry a shared DOM/behavior contract, not merely a shared word. grid, list, carousel are canonical: the same value implies the same emitted structure (e.g. data-layout="carousel" + the track/item contract) and the same behavior wherever it appears.
    • Local tokens are arrangements unique to one rune, with no shared machinery — masonry (variable-height media only), table (columnar data only). They live in the rune, not the shared set, because they don't generalise. Local values are sanctioned, not a smell.
  2. A rune's matches set is the union of its canonical picks + its local values. A rune supports whatever subset of the canonical pool makes sense for it, and may append local values inline. No rune is required to support every canonical token.

  3. Graduation rule. A value enters the canonical pool when a second rune needs the same concept with the same contract. Until then it stays local. This guards both failure modes: premature abstraction (a pool full of one-offs) and no abstraction (three runes reinventing the same concept). carousel graduates now — it already has 3+ identified consumers (SPEC-100).

  4. Canonical tokens are a single shared const. Runes import the canonical tokens from one place (e.g. LAYOUT.grid, LAYOUT.carousel) rather than re-typing the string, so spelling cannot drift and importing a token implies its contract. The seed set is grid, list, carousel. Each rune's matches: array is built from these picks plus any local string literals.

  5. No forced migration. Existing runes are not eagerly rewritten to the canonical spellings. compare's side-by-side/stacked, blog's compact, etc. stay as-is until something else touches that rune — lazy graduation, consistent with rule 3. When a rune is next worked on, private spellings of a canonical concept should be migrated (with deprecations) to the canonical token; genuinely local values are left alone.

Rationale

  • Portability is the whole point. A canonical token that implies a contract is what lets carousel move from gallery to feature to testimonial as a config-and-CSS change with zero new behavior code each time. The shared const makes the spelling un-driftable; the contract makes the behavior bindable block-agnostically.
  • The two-tier split respects reality. Some arrangements genuinely generalise and some genuinely don't. Forcing masonry/table into a shared pool, or banning them, would both be wrong; sanctioning local values keeps the pool meaningful (everything in it carries a contract) without amputating the outliers.
  • The graduation rule is the load-bearing guardrail. It is the same "fixed vocabulary, earn your place" discipline ADR-015 applies to scale ramps, one level up: the pool only grows when a concept has proven it generalises by acquiring a second consumer.
  • Lazy migration avoids a big-bang spec. The existing outliers carry no urgency; rewriting them all at once would be churn for its own sake. Migrating opportunistically as runes are touched keeps the change cost proportional to the work actually happening.

Consequences

  • Enabling work:
    • Add a canonical-token const (the seed set grid, list, carousel) in a shared location the rune schemas can import (packages/runes).
    • Document the two-tier model + graduation rule in the rune-authoring guide so new runes pick from the pool rather than minting private values.
  • carousel carries a contract, defined by SPEC-100. The shared track/item DOM contract + the generalised, contract-bound behavior are specified there; this ADR only establishes that a canonical token has such a contract.
  • SPEC-099 is the first consumer of the pool. feature draws grid and list from the const (no bespoke values), proving the subset model before carousel lands.
  • Existing runes keep working unchanged. No selector or value changes ship until a rune is independently revisited; CSS-coverage and structure contracts are unaffected by this decision on its own.
  • Tooling: refrakt inspect and the structure contracts continue to derive data-layout variants per rune from that rune's declared matches; the canonical const changes where the strings come from, not how many a given rune declares.
  • Authoring guidance (new invariant): a private spelling of a canonical concept is a defect to be fixed when next touched; a genuinely unique arrangement is a legitimate local value. The graduation rule is the test for which is which.