Skip to content

OrigamCode ​

<OrigamCode> renders a block of source code with (optional) shiki-powered syntax highlighting, optional line numbers, line highlighting, a copy button and automatic theme integration with the origam design system.

Syntax highlighting requires shiki (optional peer dependency) ​

shiki is an optional peer dependency of origam — it is not pulled in by default (it is heavy: WASM grammars + themes). Install it in your app to enable syntax colouring:

bash
pnpm add shiki

When shiki is present, OrigamCode lazy-loads it on first render and paints dual-theme (--shiki-light / --shiki-dark) tokens. When it is absent (or cannot be loaded — e.g. a purely static bundle with no module resolver), OrigamCode degrades gracefully to plain, un-highlighted rows: line numbers, line-highlighting, the copy button and layout all keep working — only the colours are missing. A one-time console warning points to this section.

Supplying your own highlighter (createOrigam({ code })) ​

An app can replace WHAT useCode() dynamically imports instead of the DS's default import('shiki'), via a code.highlighter loader on createOrigam():

ts
import { createOrigam } from 'origam'

app.use(createOrigam({
    code: {
        highlighter: () => import('./shiki-lite')
    }
}))

The loader must resolve to a module exposing a single createHighlighter method — shiki's own module satisfies this structurally (no cast needed), and so does a lighter alternative such as shiki/core paired with a JS regex engine. A minimal, runnable example — no WASM loader, no oniguruma binary:

ts
// shiki-lite.ts
import { createHighlighterCore } from 'shiki/core'
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'
import githubLightHighContrast from 'shiki/themes/github-light-high-contrast.mjs'
import githubDarkHighContrast from 'shiki/themes/github-dark-high-contrast.mjs'
import typescript from 'shiki/langs/typescript.mjs'
import javascript from 'shiki/langs/javascript.mjs'

const BUNDLED_LANGS: Record<string, unknown> = { ts: typescript, js: javascript }

export function createHighlighter (opts: { themes: readonly string[], langs: readonly string[] }) {
    return createHighlighterCore({
        themes: [githubLightHighContrast, githubDarkHighContrast],
        langs: opts.langs.map((lang) => BUNDLED_LANGS[lang]).filter(Boolean),
        engine: createJavaScriptRegexEngine()
    })
}
  • Absent (default) — <OrigamCode> keeps loading the full shiki package via its own import('shiki'); nothing changes for a consumer who does not set this.
  • Supplied — the DS never imports shiki itself on this path: no bare 'shiki' specifier, no @vite-ignore, no WASM-loader chunk (see the composable's loadHighlighter() doc comment for why that chunk matters to a bundler that doesn't special-case shiki — a lighter module such as shiki/core + a JS regex engine sidesteps it entirely, at a real size trade-off: a curated ts/js-only subset like the one above runs a few tens of KB gzipped against the ~400 KB of the full shiki package).
  • The loader is resolved once, by whichever <OrigamCode> mounts first on the page — useCode()'s highlighter is a page-wide singleton, so every other instance (even one whose own createOrigam() ancestor set a different highlighter, or none) reuses that same highlighter for the rest of the page's life.
  • A highlighter that throws for a language it doesn't embed (e.g. a langs subset narrower than origam's own SUPPORTED_LANGS — the example above only bundles ts / js) degrades that ONE block to plain, un-highlighted text, exactly like the "shiki absent" case above, rather than breaking the page.

Open lang and code.langs ​

lang is not limited to the 14 bundled grammars (#1180).

  • Custom code.highlighter — lang is no longer filtered: it is handed to your highlighter untouched. If the highlighter cannot tokenise it (no such grammar), that one block falls back to plaintext and a dev-only console warning names the language. Production stays silent.
  • code.langs — the list passed to createHighlighter({ langs }). Default: the 14 SUPPORTED_LANGS. It replaces the default (keep plaintext in it if you use it). With the built-in highlighter, a lang listed here is accepted instead of being folded onto plaintext. Like highlighter, it is read once by the first <OrigamCode> to mount.
ts
import { createOrigam } from 'origam'

app.use(createOrigam({
  code: {
    // optional: your own shiki-compatible module (see above)
    highlighter: () => import('./shiki-lite'),
    // grammars loaded up front — `dockerfile` becomes a valid `lang`
    langs: ['plaintext', 'ts', 'dockerfile']
  }
}))
vue
<origam-code lang="dockerfile" code="FROM node:22" />

Without langs and without a highlighter that embeds dockerfile, that block renders as plain text (with a one-shot warning when the built-in highlighter is used, a dev-only one when a custom highlighter is used).

Quick start ​

Via the code prop ​

vue
<template>
    <OrigamCode lang="ts" :code="snippet" line-numbers/>
</template>

<script setup lang="ts">
    const snippet = `const x = 42`
</script>

Via the default slot (multi-line snippets read better here) ​

vue
<template>
    <OrigamCode lang="vue" filename="App.vue" line-numbers>
&lt;template&gt;
  &lt;h1&gt;Hello&lt;/h1&gt;
&lt;/template&gt;
    </OrigamCode>
</template>

The prop wins when both are provided. The slot path strips leading / trailing blank lines so authors don't have to worry about indentation.

Props ​

PropTypeDefaultDescription
codestringundefinedSource code. Falls back to the default slot when omitted.
langTCodeLang | (string & {})'plaintext'Grammar to apply. Autocompletes the 14 bundled values but accepts any string. Without a custom code.highlighter, a value outside the bundled set and outside code.langs falls back to plaintext with a one-shot console warning. With a custom code.highlighter it is passed through as-is (see Open lang).
lineNumbersbooleanfalseShow a left gutter with line numbers (pure CSS counter). A blank source line keeps the height of a full row, and a trailing newline gets no number.
highlightLinesnumber[] | string | nullnullLines to highlight. Accepts an array ([2, 5]) or a range string ('2,5-7').
copyablebooleantrueShow the copy-to-clipboard button. In non-compact mode it always renders a header bar so the button sits next to the filename (or the language badge when no filename is set) — never floating over the code.
maxHeightnumber | string | nullnullCap the rendered height and enable vertical scroll past it.
formatbooleanfalseStub in v2.x. Currently normalises whitespace only. Prettier is intentionally not bundled at runtime (size cost).
wrapbooleanfalseWrap long lines instead of scrolling horizontally.
filenamestringundefinedDisplay the filename on the left of the header bar. Without a filename the header still renders (showing the language badge) as long as copyable is on, so the chrome stays consistent with or without a filename.
compactbooleanfalseRender a single-line pill instead of a multi-line surface — ideal for an install command. Suppresses header / filename / line-numbers, shrinks vertical padding to one line, and collapses the copy control to a small inline icon button at the end of the row. <figure><pre><code> semantics are preserved.
promptstringundefinedDecorative prompt prefix rendered before the code (e.g. '$'). Purely visual — it is NOT part of the highlighted code and is NEVER included in the clipboard copy. Most useful with compact.
hideHeaderbooleanfalseDo not render the header bar (filename / language badge / copy button), whatever filename, copyable or the header slot say. For a block embedded in a surface that already shows that information, such as a tab of <OrigamCodeGroup>.
flatbooleanfalseFlatten the block into its host: no border, no radius, no elevation, no outer margin.
scrollerAriaLabelstringundefinedAccessible name of the scrollable region. Left out, it is derived from filename, then lang. Set it when several blocks of the same language share a page, so each region has a distinct name.
fontFamilyTFontFamilyundefinedFont family token (sans · mono · serif). Overrides the theme font-family on the code surface. When unset the theme value stays in control.
fontSizeTFontSizeundefinedFont size token (xs · sm · md · lg · xl · 2xl · 3xl · 4xl · 5xl). Overrides the theme font-size.
lineHeightTLineHeightundefinedLine-height token (none · tight · snug · normal · relaxed · loose). Overrides the theme line-height.

Events ​

EventPayloadDescription
copycode: stringEmitted after a successful clipboard write.

Slots ​

SlotSlot propsDescription
default—Alternative to the code prop for multi-line snippets.
header{ filename, langName, copy, copied }Override the entire header bar (filename + copy button).
footer—Add a custom footer under the code surface.

Supported languages ​

Valueshiki grammar
plaintexttext
vueVue SFC
ts / tsxTypeScript (+ JSX)
js / jsxJavaScript (+ JSX)
scss / cssSCSS / CSS
jsonJSON
bashBash / sh
html / xmlHTML / XML
yamlYAML
mdMarkdown

To serve another language, list it in createOrigam({ code: { langs } }) (and make sure your code.highlighter, if any, embeds the grammar) — see Open lang.

Compact mode (install pill) ​

compact turns the block into a single-line pill — the canonical use case is a copyable install command:

vue
<template>
    <OrigamCode compact prompt="$" lang="bash" :code="'npm install origam'"/>
</template>

In compact mode:

  • the header, filename and line-numbers are suppressed (one row only);
  • vertical padding shrinks to a single line and the surface stays themed by the --origam-code---* tokens;
  • the copy control collapses to a small icon button anchored inline at the end of the row (it swaps to a check mark during the copied feedback window so the pill never reflows);
  • prompt renders a decorative prefix ($) that is aria-hidden and is never part of the clipboard copy — only code is copied.

The <figure><pre><code> semantics are preserved, so the snippet stays screen-reader-readable and W3C-valid.

Theme integration ​

The component's own surface (background, border, header, line gutter, prompt, line-highlight, scrollbar) follows <html data-theme="…"> via the regular --origam-code---* / --origam-code__*---* design tokens, same as any other origam component.

Syntax colouring is a separate, DELIBERATELY NON-tokenised mechanism. There is no --origam-code__syntax---* token family (removed in #661/C2 — see below for why), and no theme prop.

useCode calls shiki with two real themes and defaultColor: false:

ts
codeToHtml(code, {
    themes: { light: 'github-light-high-contrast', dark: 'github-dark-high-contrast' },
    defaultColor: false
})

⛔ #535 — the themes were github-light / github-dark until this fix. Several of their fixed per-token colours fail WCAG AA (4.5:1) against every --origam-code---background-color this DS or its marketing brand themes can produce — the "parameter/property" hue (#e36209) tops out at 3.49:1 even against pure white, so no background choice could have fixed it. shiki's own github-*-high-contrast themes are the same GitHub palette re-tuned for accessibility, bundled at no extra cost (same theme count, just different names). Paired with --origam-code---background-color now resolving to --origam-color__surface---raised (the lightest surface every theme already defines) instead of --origam-color__surface---sunken, every one of the 8 token categories clears AA with margin — measured worst case 4.77:1 (light) / 5.79:1 (dark) across the 7 marketing brand themes, Playwright-verified against the built Histoire OrigamCode story. See the PR for the full before/after table.

In this mode shiki writes BOTH computed colours directly onto every token <span> it emits, e.g. style="--shiki-light:#0e1116;--shiki-dark:#f0f3f6". The component's scoped <style> block then just picks whichever custom property the current data-theme / data-mode calls for:

scss
.origam-code .shiki { color: var(--shiki-light); }
html[data-mode="dark"] .origam-code .shiki,
html:not([data-mode])[data-theme="dark"] .origam-code .shiki {
    color: var(--shiki-dark);
}

Switching <html data-theme="dark"> re-resolves var(--shiki-dark) for every span already in the DOM — no JavaScript re-render, no re-tokenising.

Why there is no per-token-type design token (#661/C2) ​

Earlier versions of shiki (and of this doc) used a css-variables BUILT-IN THEME that emitted one named, stable CSS variable per token TYPE (--shiki-token-keyword, --shiki-token-string, …), which the origam token sheets then mapped to --origam-code__syntax---keyword / ---string / etc. — a real, themeable design-token surface.

shiki v4.3.1 no longer ships that css-variables theme. The dual-theme mode above is the maintained replacement, and it writes --shiki-light / --shiki-dark per span, carrying each theme's own literal colour for that specific token — there is no longer a stable, named variable per token TYPE to hang a design token on. The 12 --origam-code__syntax---* tokens were declared in light.css / dark.css but read by nothing (0 occurrences in OrigamCode.vue — confirmed by grep, and by the token-var-channels guard's dormant list), because the mapping they were meant to feed no longer exists. They were removed, not renamed: recreating them under a different name would still not connect to anything shiki emits today.

Consequences:

  • Syntax colours are not overridable per token type today. Overriding --shiki-light / --shiki-dark on an ancestor changes the DEFAULT colour applied before a span's own inline value takes over — since every highlighted span sets its own inline --shiki-light/--shiki-dark, an ancestor override has no visible effect on highlighted code, only on plain-text fallback (format-less content with no spans).
  • The theme switch stays free of JS re-render — this property survives the removal intact, since it comes from the dual-theme span markup, not from the removed tokens.
  • A brand wanting its own syntax palette picks its own shiki theme, not a token override: pass different theme names to useCode/codeToHtml (a bundled shiki theme, or a custom Textmate-grammar-compatible theme JSON). That is a build-time/composable-level choice, not a CSS one.

Performance ​

  • Lazy highlighter: shiki is dynamic-imported on the first mount, not at app boot. The first <OrigamCode> pays a ~200 ms cold load; subsequent ones reuse the singleton.
  • LRU cache: highlighted HTML is cached by (code, lang) up to 64 entries. Re-renders, hover effects and re-mounts never re-tokenise. Theme switches are free — the CSS cascade handles colour changes with no JS involved.
  • Tarball impact: shiki sits in dependencies and adds ~3 MB to the installed node_modules (curated to 14 langs + 2 built-in themes, github-light-high-contrast + github-dark-high-contrast — far below the ~30 MB of the full default bundle). The actual JS shipped to the browser is split per chunk via dynamic import.

Accessibility ​

  • Syntax colours meet WCAG AA (4.5:1) — #535. Both shiki themes are the github-*-high-contrast variants (see "Syntax colouring" above), and the component background resolves to --origam-color__surface---raised, not ---sunken. Together they clear 4.5:1 on every one of the 8 token categories (keyword, punctuation, string, comment, number/variable, function, parameter, tag), in both modes, across every marketing brand theme — measured, not assumed (see the linked PR for the full table).

  • The scroll wrapper (.origam-code__scroller) is a <section> carrying tabindex="0" so a code block wider than its column stays readable without a mouse, plus an aria-label that names it. Since #781 there is no explicit role="region": a named <section> already maps to that role (HTML-AAM), and the label is never empty, so the attribute only restated the tag. The tabindex stays — a scroll container no keyboard can reach fails WCAG 2.1.1 (axe rule scrollable-region-focusable). The label resolves in this order: filename when one is passed, else lang when it is anything other than plaintext, else the generic "Code block, scrollable region". Keys: origam.code.scroller_aria_label_filename, origam.code.scroller_aria_label_lang, origam.code.scroller_aria_label. Pass a filename (or at least a lang) whenever a page shows several blocks — otherwise every one of them lands in the screen-reader landmark list under the same name.

  • The copy button is a real <button> with an aria-label describing the action, and an aria-live="polite" region for the "Copied!" feedback.

  • Line numbers are emitted via a CSS ::before counter with user-select: none; they do not appear in clipboard copies of the code text.

  • The code content remains screen-reader-readable in its natural sequence (shiki only adds inline <span> styling, never reorders tokens).