a code block with syntax highlighting by shiki on the server: marks, diffs, copy
npx shadcn add @ag/codeAlready installed? Preview an update
npx shadcn add @ag/code --dry-runYour installed source stays unchanged until you update it. How updates work
- Changed: a line longer than 20 000 characters (
TOKENIZED_LINE_LENGTH, VS Code's own limit) is drawn whole in the theme's foreground instead of read by the grammar, inCode,codeHtmlandcodeColours. The grammar's cost grows with the line and blocks the thread: a file holding a long payload (a base64 module, a minified bundle) took tens of seconds to render on the server, enough to fail a static build's per-page limit for every page rendered beside it.
also called syntax highlighting
shelf text & code
used by markdown, markdown-prepare, walkthrough, walkthrough-session, terminal-editor, terminal-editor-screen, ide, cells-code
Run pnpm build from your project directory.
npx shadcn add @ag/codeimport { Scrims } from "@/components/ui/scrims"
export default function Page() {
return (
<div className="px-6">
{/* fixed to the viewport, so it lives outside the flow */}
<Scrims top={false} />
<article>…</article>
</div>
)
}import { Scrims } from "@/components/ui/scrims"
export default function Page() {
return (
<div className="px-6">
{/* fixed to the viewport, so it lives outside the flow */}
<Scrims top={false} />
<article>…</article>
</div>
)
}A line is marked with a [!code highlight] comment on the line before it. The mark runs the full width and keeps a bar in the gutter, which is the part that survives scrolling a long line sideways.
const b = panBounds(view, fitted, band)
return { x: clamp(view.x, -b.x, b.x), y: clamp(view.y, -b.y, b.y), s: view.s }A diff is [!code ++] and [!code --]. The sign is a real character in the gutter, not just a colour: colour alone is invisible to a reader who cannot separate red from green.
const b = panBounds(ctx.pose, ctx.fitted, ctx.band)
const dx = boundTick(wheelPx(input.deltaX, input.deltaMode, ctx.band.h))
w = { ...w, x: w.x - dx, y: w.y - dy }
const x = clamp(w.raw0.x + w.x - dx, -b.x, b.x)
const y = clamp(w.raw0.y + w.y - dy, -b.y, b.y)
w = { ...w, x: x - w.raw0.x, y: y - w.raw0.y }
effects.push({
kind: "pose",
pose: { ...ctx.pose, x: overshoot(w.raw0.x + w.x, b.x) },
pose: { ...ctx.pose, x, y },
})[!code focus] steps the rest of the block back. Hover to bring it all forward: a reader who wants the surrounding lines should not have to leave the page for them.
function swipeSlides(travel, slideW) {
assert(slideW > 0, "a slide has no width")
return Math.floor(Math.abs(travel) / slideW + 1 - SWIPE_COMMIT + 1e-9)
}[!code word:momentum] marks a word wherever it appears on the lines below.
// The momentum is the platform's; only the momentum knows when fingers left.For source you do not own, and so cannot write a comment into, highlight="2,5-6" takes the lines from outside. This page uses it: an item page renders its demo file verbatim and must not edit it to document it.
import { Scrims } from "@/components/ui/scrims"
export default function Page() {
return (
<div className="px-6">
{/* fixed to the viewport, so it lives outside the flow */}
<Scrims top={false} />
<article>…</article>
</div>
)
}A shell block, with no filename: the tab falls back to the language.
npx shadcn add @ag/code
# the copy control comes with itNo lang: the filename's extension picks it, cells-code's engine colours it.
---
import accounts from "./accounts.cells"
---
what: text,amount: EUR>0,to: accounts.account,on: date
rent,950.00,expenses:home,2026-07-01
coffee,3.20,expenses:food,2026-07-02registerLanguage tells code a grammar and the names files and fences call it by.
2026-07-01 rent
expenses:home 950.00 EUR
assets:bank -950.00 EUR ; julythe demo above, verbatim
import { Sample } from "@/app/samples"
import { registerLanguage } from "@/registry/base-nova/lib/code-tokens"
import { Code } from "@/registry/base-nova/ui/code"
import { InlineCode } from "@/registry/base-nova/ui/code-inline"
// #region money
const MONEY = `---
import accounts from "./accounts.cells"
---
what: text,amount: EUR>0,to: accounts.account,on: date
rent,950.00,expenses:home,2026-07-01
coffee,3.20,expenses:food,2026-07-02`
// #endregion
// #region ledger
// A language Shiki does not bundle, told to code once, here at the top of a module
// the page imports: every `.journal` file and every `ledger` fence is coloured by it.
registerLanguage("ledger", {
aliases: ["journal", "hledger"],
grammar: async () => ({
name: "ledger",
scopeName: "source.ledger",
patterns: [
{ match: "^\\d{4}-\\d{2}-\\d{2}", name: "constant.numeric.date.ledger" },
{ match: ";.*$", name: "comment.line.semicolon.ledger" },
{
match: "^\\s+([a-z][\\w:]*)",
captures: { "1": { name: "entity.name.type.ledger" } },
},
{
match: "-?\\d+(?:\\.\\d+)?\\s+[A-Z]{3}",
name: "constant.numeric.ledger",
},
],
repository: {},
}),
})
const JOURNAL = `2026-07-01 rent
expenses:home 950.00 EUR
assets:bank -950.00 EUR ; july`
// #endregion
const PLAIN = `import { Scrims } from "@/components/ui/scrims"
export default function Page() {
return (
<div className="px-6">
{/* fixed to the viewport, so it lives outside the flow */}
<Scrims top={false} />
<article>…</article>
</div>
)
}`
// The notations live in the source, so they move with the line they mark when the
// code is edited. Shiki strips them from the render; the clipboard keeps the source.
const MARKED = `const b = panBounds(view, fitted, band)
// [!code highlight]
return { x: clamp(view.x, -b.x, b.x), y: clamp(view.y, -b.y, b.y), s: view.s }`
// The real commit: the wheel pan stopped rubbering and started clamping.
const DIFF = `const b = panBounds(ctx.pose, ctx.fitted, ctx.band)
const dx = boundTick(wheelPx(input.deltaX, input.deltaMode, ctx.band.h))
w = { ...w, x: w.x - dx, y: w.y - dy } // [!code --]
const x = clamp(w.raw0.x + w.x - dx, -b.x, b.x) // [!code ++]
const y = clamp(w.raw0.y + w.y - dy, -b.y, b.y) // [!code ++]
w = { ...w, x: x - w.raw0.x, y: y - w.raw0.y } // [!code ++]
effects.push({
kind: "pose",
pose: { ...ctx.pose, x: overshoot(w.raw0.x + w.x, b.x) }, // [!code --]
pose: { ...ctx.pose, x, y }, // [!code ++]
})`
const FOCUS = `function swipeSlides(travel, slideW) {
assert(slideW > 0, "a slide has no width")
return Math.floor(Math.abs(travel) / slideW + 1 - SWIPE_COMMIT + 1e-9) // [!code focus]
}`
const WORDS = `// [!code word:momentum]
// The momentum is the platform's; only the momentum knows when fingers left.`
const SH = `npx shadcn add @ag/code
# the copy control comes with it`
const Note = ({ children }: { children: React.ReactNode }) => (
<p className="max-w-prose text-[0.9375rem] leading-relaxed text-foreground/70">
{children}
</p>
)
export default function Demo() {
return (
<div className="space-y-12">
<Sample name="inline" glance title="inline code, copyable commands">
<div className="space-y-4">
<p className="text-sm text-foreground/80">
Run <InlineCode>pnpm build</InlineCode> from your project directory.
</p>
<Code compact lang="sh">
npx shadcn add @ag/code
</Code>
</div>
</Sample>
<Code lang="tsx" filename="app/page.tsx">
{PLAIN}
</Code>
<Sample name="glass" title="in glass">
<div className="rounded-xl bg-[url(/lightbox/shore.jpg)] bg-cover bg-center p-6">
<Code lang="tsx" filename="app/page.tsx" material="glass">
{PLAIN}
</Code>
</div>
</Sample>
<div className="space-y-3">
<Note>
A line is marked with a{" "}
<code className="font-mono text-xs">[!code highlight]</code> comment
on the line before it. The mark runs the full width and keeps a bar in
the gutter, which is the part that survives scrolling a long line
sideways.
</Note>
<Code lang="ts" filename="clampPan.ts">
{MARKED}
</Code>
</div>
<div className="space-y-3">
<Note>
A diff is <code className="font-mono text-xs">[!code ++]</code> and{" "}
<code className="font-mono text-xs">[!code --]</code>. The sign is a
real character in the gutter, not just a colour: colour alone is
invisible to a reader who cannot separate red from green.
</Note>
<Code lang="ts" filename="lightbox-wheel.ts">
{DIFF}
</Code>
</div>
<div className="space-y-3">
<Note>
<code className="font-mono text-xs">[!code focus]</code> steps the
rest of the block back. Hover to bring it all forward: a reader who
wants the surrounding lines should not have to leave the page for
them.
</Note>
<Code lang="js" filename="swipe.js">
{FOCUS}
</Code>
</div>
<div className="space-y-3">
<Note>
<code className="font-mono text-xs">[!code word:momentum]</code> marks
a word wherever it appears on the lines below.
</Note>
<Code lang="ts">{WORDS}</Code>
</div>
<div className="space-y-3">
<Note>
For source you do not own, and so cannot write a comment into,{" "}
<code className="font-mono text-xs">highlight="2,5-6"</code> takes the
lines from outside. This page uses it: an item page renders its demo
file verbatim and must not edit it to document it.
</Note>
<Code lang="tsx" filename="app/page.tsx" highlight="2,5-6" lines>
{PLAIN}
</Code>
</div>
<div className="space-y-3">
<Note>
A shell block, with no filename: the tab falls back to the language.
</Note>
<Code lang="bash">{SH}</Code>
</div>
<Sample
name="cells"
title="a .cells file, by its name"
description="No lang: the filename's extension picks it, cells-code's engine colours it."
with="money"
>
<Code filename="money.cells">{MONEY}</Code>
</Sample>
<Sample
name="register"
title="a language of your own"
description="registerLanguage tells code a grammar and the names files and fences call it by."
with="ledger"
>
<Code filename="2026.journal">{JOURNAL}</Code>
</Sample>
</div>
)
}the source, every file an install writes
// A code block, highlighted on the SERVER. Shiki is the highlighter VS Code uses, so
// the grammars and themes are the ones the reader already knows, and running it at
// build time means the page ships the markup and none of the highlighter: only the
// copy control is client code.
//
// Two themes are baked into one render (`--shiki-light` / `--shiki-dark` on every
// token) and code.css picks with the theme, so switching does not re-highlight and
// cannot flash.
//
// Two parts anyone can use alone: the markup is lib/code-highlight's `codeHtml`, the
// frame is code-frame's `CodeFrame`, which markdown draws its blocks with too, so a
// block in a page of markdown and one written here are the same block.
import "server-only"
import {
type CodeLang,
codeHtml,
} from "@/registry/base-nova/lib/code-highlight"
import { langOf } from "@/registry/base-nova/lib/code-tokens"
import { CodeFrame } from "@/registry/base-nova/ui/code-frame"
export interface CodeProps {
/** The source. Common leading indentation is removed, so a snippet can be written
* indented inside the code that renders it and still read flush. */
children: string
/** A highlighted command row without a filename bar. Copy stays on the right;
* a command too long for the row scrolls on one line, its hidden side fading. */
compact?: boolean
/** A Shiki language id, or a registered one (lib/code-tokens `registerLanguage`:
* `cells` once cells-code is imported). `text` when it is not code,
* which skips the grammar. Absent: the `filename`'s extension's, else `tsx`. */
lang?: CodeLang
/** A path or a name for the tab. Without one the bar names the language. */
filename?: string
/** Hide the copy control, for a snippet nobody would want in their clipboard. */
copy?: boolean
/** Lines to mark, `"2"` or `"1,4-6"`, counted from 1. For source you do NOT own:
* a file rendered verbatim cannot carry `[!code highlight]` comments without them
* becoming part of the file. Where you do own it, prefer the comments, which move
* with the lines when the code is edited. */
highlight?: string
/** Number the lines. Off by default: most snippets are short enough that numbers
* are furniture, and they are only worth their width when something refers to one. */
lines?: boolean
/** Read `[!code ...]` comments. ON, except where the source is being shown AS
* ITSELF: a file that writes those comments inside a string would have them eaten
* out of its own listing, and a block promising verbatim would be quietly lying. */
notations?: boolean
/** Its face: `plain`, the page's frame (default), or `glass`, the one glass
* material (`material-glass`), its own border and ground dropped for it. Set
* here rather than read from a provider: the block renders on the server. */
material?: "plain" | "glass"
/** No frame, no bar and no copy of its own: for a frame that holds it (a
* tab of a `Card` with an example's code, its copy in the card's head), so a
* block in a frame is never a frame in a frame. `material` is then the
* holder's. */
bare?: boolean
className?: string
}
/** Strip the shortest indentation any non-blank line has, and the blank first and
* last lines a template literal always brings. */
function dedent(src: string): string {
const lines = src.replace(/\t/g, " ").split("\n")
while (lines.length && !lines[0]?.trim()) lines.shift()
while (lines.length && !lines[lines.length - 1]?.trim()) lines.pop()
const pad = Math.min(
...lines
.filter((l) => l.trim())
.map((l) => l.length - l.trimStart().length),
)
return lines.map((l) => l.slice(pad)).join("\n")
}
export async function Code({
children,
lang: given,
highlight,
notations = true,
...frame
}: CodeProps) {
const named = frame.filename ? langOf(frame.filename) : "text"
const lang = given ?? (named === "text" ? "tsx" : named)
const source = dedent(children)
const html = await codeHtml(source, { lang, highlight, notations })
return <CodeFrame source={source} html={html} lang={lang} {...frame} />
}import type { ComponentPropsWithRef } from "react"
import { cn } from "@/lib/utils"
/** Plain inline code for names and short expressions within prose.
* Use Code with compact and lang for syntax-highlighted command rows. */
export function InlineCode({
children,
className,
...props
}: ComponentPropsWithRef<"code">) {
return (
<code
{...props}
data-slot="code-inline"
className={cn(
"rounded-md bg-fill-rest px-1.5 py-0.5 font-mono text-[0.875em] text-foreground/85",
className,
)}
>
{children}
</code>
)
}/* The frame around highlighted code. Shiki writes both themes onto every token as
custom properties; this picks one, so a theme switch is a repaint and never a
re-highlight, and there is no flash of the wrong palette on first paint. */
@layer components {
.ag-code {
overflow: hidden;
}
/* The plain face's frame. The glass face is the glass's own (material-glass),
its edge and body; a border or ground here would be a second frame. A
selector on state, which a utility merged with the glass's could not keep
apart. */
.ag-code[data-material="plain"] {
border: 1px solid var(--border);
border-radius: 0.75rem;
background: var(--sidebar);
}
/* The bar is the block's head strip, a band of the fill ladder: a step above the
code it heads, in either scheme and on either face, so the name and the copy read
as the frame's and the code as what it holds. */
.ag-code-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.375rem 0.5rem 0.375rem 0.875rem;
border-bottom: 1px solid var(--border);
background: var(--color-fill-band);
}
.ag-code-name {
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 0.75rem;
color: var(--muted-foreground);
user-select: none;
}
/* The scroller, not the <pre>: the frame keeps its corners while long lines run.
A block is a column, its bar and then the scroller, which takes the rest of the
frame's height: given less height than the code needs (`h-96`, a pane's
`min-h-0 flex-1`), the code scrolls inside the frame, the frame staying whole. */
.ag-code:not([data-compact]) {
display: flex;
flex-direction: column;
}
.ag-code:not([data-compact]) > .ag-code-scroll {
flex: 1 1 auto;
min-height: 0;
}
/* Compact commands keep the same Shiki output and theme, with the copy control
outside the horizontal scroller so long commands never hide the action. */
.ag-code[data-compact] {
display: flex;
width: fit-content;
max-width: 100%;
align-items: center;
gap: 0.5rem;
}
/* Basis auto, not 0: the row's own width is fit-content, and a zero basis
would tell it the command has no length, so it would wrap even with room. */
.ag-code[data-compact] > .ag-code-scroll {
flex: 1 1 auto;
min-width: 0;
}
/* Shiki with `defaultColor: false` writes its palette as custom properties and sets
no colour of its own, so the frame keeps its own surface with nothing to override. */
/* As wide as its longest line, never less than the frame: a pre the scroller's width
would let a long line run past it and end on the frame's edge, its right padding
left behind where the scroll began. */
.ag-code pre {
width: fit-content;
min-width: 100%;
margin: 0;
padding: 1rem 0.875rem;
background: transparent;
font-size: 0.8125rem;
line-height: 1.65;
tab-size: 2;
}
.ag-code[data-compact] pre {
padding-block: 0.75rem;
}
/* Code never breaks its lines. A line too long for the block scrolls sideways
with the scrims' edge fade (`ag-edge-fade`, set on its scroller in code.tsx): no
scrollbar drawn over it, the hidden side fading. */
.ag-code code {
display: block;
width: fit-content;
min-width: 100%;
font-family: var(--font-mono, ui-monospace, monospace);
}
/* Shiki with `defaultColor: false` writes --shiki-light and --shiki-dark and no
colour of its own, so the theme chooses here. */
.ag-code span {
color: var(--shiki-light);
}
.dark .ag-code span {
color: var(--shiki-dark);
}
/* ---- marked lines.
A marked line is marked EDGE TO EDGE, which is why `.line` is a block that runs the
full scroll width: a tint that stops at the end of the text draws a ragged shape
down the block and reads as damage rather than emphasis. The gutter bar is what
survives being scrolled sideways, when the tint under a long line is off screen. */
.ag-code .line {
display: inline-block;
width: 100%;
padding-inline: 0.875rem;
margin-inline: -0.875rem;
border-left: 2px solid transparent;
}
.ag-code .line.highlighted {
background: color-mix(
in oklab,
var(--brand, var(--foreground)) 10%,
transparent
);
border-left-color: color-mix(
in oklab,
var(--brand, var(--foreground)) 55%,
transparent
);
}
/* An error or a warning is a highlight that has something to say, so it keeps the
shape and changes only the hue. */
.ag-code .line.highlighted.error {
background: color-mix(in oklab, var(--tone-bad) 12%, transparent);
border-left-color: var(--tone-bad);
}
.ag-code .line.highlighted.warning {
background: color-mix(in oklab, var(--tone-warn) 12%, transparent);
border-left-color: var(--tone-warn);
}
/* ---- a diff.
The sign is a real character in the gutter, not a colour: colour alone is invisible
to a reader who cannot separate red from green, and it does not survive a
screenshot pasted into a grey chat. */
.ag-code .line.diff {
position: relative;
}
.ag-code .line.diff::before {
position: absolute;
left: 0.25rem;
opacity: 0.7;
}
.ag-code .line.diff.add {
background: color-mix(in oklab, var(--tone-ok) 14%, transparent);
border-left-color: var(--tone-ok);
}
.ag-code .line.diff.add::before {
content: "+";
color: var(--tone-ok);
}
.ag-code .line.diff.remove {
background: color-mix(in oklab, var(--tone-bad) 12%, transparent);
border-left-color: var(--tone-bad);
}
/* Removed code is still readable, just plainly on its way out. */
.ag-code .line.diff.remove {
opacity: 0.65;
}
.ag-code .line.diff.remove::before {
content: "-";
color: var(--tone-bad);
}
/* ---- focus: everything else steps back, and comes back on hover, because a reader
who wants the surrounding lines should not have to leave the page to see them. */
.ag-code:has(.focused) .line:not(.focused) {
filter: blur(2px);
opacity: 0.5;
transition:
filter 200ms ease,
opacity 200ms ease;
}
.ag-code:has(.focused):hover .line:not(.focused) {
filter: none;
opacity: 1;
}
/* ---- a word, marked inside the line. */
.ag-code .highlighted-word {
border-radius: 0.25rem;
padding: 0.1em 0.25em;
background: color-mix(
in oklab,
var(--brand, var(--foreground)) 14%,
transparent
);
box-shadow: 0 0 0 1px
color-mix(in oklab, var(--brand, var(--foreground)) 30%, transparent);
}
/* ---- line numbers, opt-in. A counter, so nothing is added to the copied text. */
.ag-code-numbered code {
counter-reset: ag-line;
}
.ag-code-numbered .line {
counter-increment: ag-line;
padding-left: 3rem;
}
.ag-code-numbered .line::after {
content: counter(ag-line);
position: absolute;
left: 0;
width: 2.25rem;
text-align: right;
color: var(--muted-foreground);
opacity: 0.5;
user-select: none;
}
.ag-code-numbered .line {
position: relative;
}
.ag-code-numbered .line.diff::before {
left: 2.5rem;
}
@media (prefers-reduced-motion: reduce) {
.ag-code:has(.focused) .line:not(.focused) {
transition: none;
}
}
}// Code's colours, character by character: the same highlighter `code` renders with
// (Shiki, VS Code's own grammars), read as one style per character instead of as
// markup, for a view that draws text which is not all there yet (an editor whose
// file is being typed: each character keeps the colour it has in the finished file,
// so a half-typed attribute already reads as one). A language Shiki does not bundle
// is registered here, read by a TextMate grammar or by a reader of its own (an engine
// that knows what every part is), its spans resolved against the same themes by the
// themes' own rules: one source of colour for every view. Framework-free; Shiki loads
// on the first call, so the page ships none of it until something asks, and then only
// its core, the JavaScript regex engine and the one grammar and two themes asked for.
/** The two themes every code view here wears, light and dark, picked by the scheme
* it stands in. `code` and `markdown` render with them. */
export const CODE_THEMES = {
light: "github-light",
dark: "github-dark",
} as const
/** VS Code's default themes' token colours, which `ide` wears: Dark Modern and
* Light Modern are built on Dark+ and Light+. */
export const VSCODE_THEMES = {
light: "light-plus",
dark: "dark-plus",
} as const
/** The longest line the grammar reads, in characters; a longer one is drawn whole in
* the theme's foreground. VS Code's own limit (`editor.maxTokenizationLineLength`):
* the tokenizer's cost grows with the line (some 60 µs a character inside a string)
* and blocks its thread, and a line past this is data, not code: cells-wasm.ts's one
* line of 885 000 characters of base64 takes 30 s read and half a second drawn
* whole, and a prerender worker blocked that long fails every page beside it. Both
* ways of colouring here (`codeHtml`, `codeColours`) pass it to Shiki. */
export const TOKENIZED_LINE_LENGTH = 20_000
/** Lines to mark, as every code view here spells them: `"2"` or `"1,4-6"`, counted
* from 1. Screams at anything else. */
export function linesOf(spec: string): Set<number> {
const out = new Set<number>()
for (const part of spec.split(",")) {
const range = part.trim()
if (!range) continue
const [a, b = a] = range.split("-").map((n) => Number(n.trim()))
if (!Number.isInteger(a) || !Number.isInteger(b) || a === undefined)
throw new Error(`code: "${range}" is not a line or a range of lines`)
for (let n = a; n <= (b as number); n++) out.add(n)
}
return out
}
/** A pair of Shiki theme ids, light and dark. */
export interface CodeThemes {
light: string
dark: string
}
/** One style a character can wear, in both themes. */
export interface CodeInk {
light: string
dark: string
italic: boolean
bold: boolean
}
/** A text's colours: `inks` the distinct styles, `of[i]` the one character `i` of
* the text wears (an index into `inks`). */
export interface CodeColours {
inks: CodeInk[]
of: Uint16Array
}
/** A stretch of a text as a language's own reader reads it (`from` to `to`, a string's
* indices), coloured by what it is: a TextMate scope, resolved against each code theme
* by the theme's own rules, so it wears what that theme gives the scope; an ink of the
* language's own, where no theme has a colour for what it means (a Cells column); or
* the language it is written in (a script inside a file), coloured as that language. */
export type CodeSpan = {
from: number
to: number
bold?: boolean
} & (
| { scope: string }
| { ink: { light: string; dark: string } }
| { lang: string }
)
/** A language Shiki does not bundle, told to code, read one of two ways: by a TextMate
* `grammar` Shiki runs (Shiki's `LanguageInput`: one registration whose `name` is the
* language's id, or a list, the languages it embeds first), or by a `read`er of its
* own that knows what every part of the text is (a language whose engine runs where
* code does). Either is loaded the first time the language is asked for. */
export type CodeLanguage = {
/** Other names a file's extension or a fence may call it by (`yml` for `yaml`); none
* where the extension is the id (`.cells`). */
aliases?: readonly string[]
} & (
| {
grammar: () => Promise<
| import("shiki").LanguageRegistration
| import("shiki").LanguageRegistration[]
>
/** What the grammar's own scopes wear in every theme, over its colours. Each a
* TextMate scope selector, which a theme's rule for a deeper scope still wins
* over. */
styles?: readonly { scope: string; bold?: boolean; italic?: boolean }[]
}
| { read: () => Promise<(text: string) => CodeSpan[]> }
)
/** The languages code colours beyond Shiki's bundle, by id, and every alias to its
* id, filled by `registerLanguage`. Code holds none of its own: an item that brings a
* language registers it (`cells-code`, Cells read by its engine). */
const LANGUAGES = new Map<string, CodeLanguage>()
const ALIASES = new Map<string, string>()
/** Tells code a language Shiki does not bundle, so every view that picks a language
* from a file's name or a fence (`code`, `markdown`, `walkthrough`, `ide`,
* `terminal-editor`) colours it. Call it at the top of a module the pages that draw
* it import, once in each place code runs (the server for `Code`, the browser for an
* editor): a language registered in neither is drawn plain. Registering an id again
* replaces its grammar (a module evaluated again in development); an alias another
* language holds, or one that is a registered id, throws. */
export function registerLanguage(id: string, language: CodeLanguage): void {
const lower = id.toLowerCase()
if (lower !== id)
throw new Error(`code-tokens: a language id is lowercase, not ${id}`)
if (ALIASES.has(id))
throw new Error(
`code-tokens: ${id} is already an alias of ${ALIASES.get(id)}`,
)
for (const alias of language.aliases ?? []) {
const held = ALIASES.get(alias)
if (
(held !== undefined && held !== id) ||
(alias !== id && LANGUAGES.has(alias))
)
throw new Error(
`code-tokens: the alias ${alias} of ${id} already names ${held ?? alias}`,
)
}
for (const [alias, of] of ALIASES) if (of === id) ALIASES.delete(alias)
LANGUAGES.set(id, language)
for (const alias of language.aliases ?? []) ALIASES.set(alias, id)
readers.delete(id)
if ("styles" in language && language.styles?.length) styled++
}
/** Bumped whenever a language brings styles: a theme loaded before is loaded again,
* wearing them. */
let styled = 0
/** Every registered language's styles, as a theme's rules. */
const styleRules = () =>
[...LANGUAGES.values()].flatMap((l) =>
("styles" in l ? (l.styles ?? []) : []).map((s) => ({
scope: s.scope,
settings: {
fontStyle: [s.bold && "bold", s.italic && "italic"]
.filter(Boolean)
.join(" "),
},
})),
)
/** Each reader language's reader, loaded once. */
const readers = new Map<string, Promise<(text: string) => CodeSpan[]>>()
/** The reader `lang` (an id or an alias) is read by; undefined for a language read by
* a grammar, or none. */
export function readerOf(
lang: string,
): Promise<(text: string) => CodeSpan[]> | undefined {
const id = languageOf(lang)
const language = LANGUAGES.get(id)
if (!language || !("read" in language)) return undefined
let r = readers.get(id)
if (!r) {
r = language.read()
readers.set(id, r)
}
return r
}
/** The id a language name stands for: a registered language's alias resolved, any
* other name as it is (Shiki reads its own aliases). */
export const languageOf = (name: string): string => {
const lower = name.toLowerCase()
return ALIASES.get(lower) ?? lower
}
/** The language a path is written in: its extension (`html`, `ts`, `md`, `cells`)
* read through `languageOf`, which Shiki reads as a language or one of its aliases;
* `text` with none. */
export function langOf(path: string): string {
const ext = /\.([a-z0-9]+)$/i.exec(path)?.[1]
return ext ? languageOf(ext) : "text"
}
/** Whether `lang` (an id or an alias) is a registered language. */
export const registeredLanguage = (lang: string) =>
LANGUAGES.has(languageOf(lang))
/** The grammar loaded for `id`, which must name its language `id`: a grammar called
* anything else would load and never be found. */
async function grammarOf(
id: string,
language: Extract<CodeLanguage, { grammar: unknown }>,
) {
const g = await language.grammar()
const list = Array.isArray(g) ? g : [g]
if (!list.some((r) => r.name === id))
throw new Error(
`code-tokens: the grammar registered as ${id} names itself ${list.map((r) => r.name).join(", ")}`,
)
return list
}
/** A registered grammar language's grammar (an id or an alias), loaded and checked;
* undefined for any other. */
export const ownGrammar = (lang: string) => {
const id = languageOf(lang)
const language = LANGUAGES.get(id)
return language && "grammar" in language ? grammarOf(id, language) : undefined
}
type Core = import("shiki/core").HighlighterCore
/** One highlighter for the page, made on the first call: Shiki's core with its
* JavaScript regex engine, never the WebAssembly one (Oniguruma, 600 KB a browser
* would download to colour a few lines), each language and theme loaded the first
* time it is asked for, alone. */
let core: Promise<Core> | undefined
/** The page's highlighter with `lang`'s grammar (none for a reader language, or
* `text`) and both `themes` loaded, each theme wearing the languages' styles: what
* every code view colours with, as markup (`codeHtml`) or per character. */
export async function codeHighlighter(
lang: string,
themes: CodeThemes,
): Promise<Core> {
core ??= (async () => {
const [{ createHighlighterCore }, { createJavaScriptRegexEngine }] =
await Promise.all([
import("shiki/core"),
import("shiki/engine/javascript"),
])
return createHighlighterCore({
engine: createJavaScriptRegexEngine(),
themes: [],
langs: [],
})
})()
const h = await core
const [{ bundledLanguages }, { bundledThemes }] = await Promise.all([
import("shiki/langs"),
import("shiki/themes"),
])
const loading: Promise<void>[] = []
if (lang !== "text" && !h.getLoadedLanguages().includes(lang)) {
const bundled = bundledLanguages[lang as keyof typeof bundledLanguages]
const own = ownGrammar(lang)
if (bundled) loading.push(h.loadLanguage(bundled))
else if (own) loading.push(own.then((g) => h.loadLanguage(...g)))
}
for (const name of [themes.light, themes.dark]) {
let worn = wearing.get(name)
if (worn?.styled !== styled) {
const theme = bundledThemes[name as keyof typeof bundledThemes]
if (!theme) throw new Error(`code-tokens: no Shiki theme ${name}`)
worn = {
styled,
loaded: theme().then(({ default: t }) =>
h.loadTheme({
...t,
tokenColors: [
...(t.tokenColors ?? t.settings ?? []),
...styleRules(),
],
}),
),
}
wearing.set(name, worn)
}
// A call made while the theme loads waits for the same load.
loading.push(worn.loaded)
}
await Promise.all(loading)
return h
}
/** Each theme's load, and the languages' styles it wears (`styled` when it began). */
const wearing = new Map<string, { styled: number; loaded: Promise<void> }>()
/** Every character of `text` coloured by `lang`'s grammar in both `themes`. A
* language Shiki does not know is `text`: one ink, the theme's foreground. Runs
* where it is called: on the server for a still (passed to a view as its
* `colours`), or in the browser for text that changes. */
export async function codeColours(
text: string,
name: string,
themes: CodeThemes = CODE_THEMES,
): Promise<CodeColours> {
const lang = languageOf(name)
const read = readerOf(lang)
if (read) return readColours(text, await read, themes)
const h = await codeHighlighter(lang, themes)
const lines = h.codeToTokensWithThemes(text, {
lang: h.getLoadedLanguages().includes(lang) ? lang : "text",
themes: { light: themes.light, dark: themes.dark },
tokenizeMaxLineLength: TOKENIZED_LINE_LENGTH,
})
const inks: CodeInk[] = []
const known = new Map<string, number>()
const of = new Uint16Array(text.length)
for (const line of lines)
for (const token of line) {
const light = token.variants.light
const dark = token.variants.dark
if (!light || !dark)
throw new Error("code-tokens: a token without both themes' colours")
// Shiki's FontStyle flags: 1 italic, 2 bold.
const style = light.fontStyle ?? 0
const ink: CodeInk = {
light: light.color ?? "inherit",
dark: dark.color ?? "inherit",
italic: (style & 1) !== 0,
bold: (style & 2) !== 0,
}
const key = `${ink.light} ${ink.dark} ${style}`
let n = known.get(key)
if (n === undefined) {
n = inks.length
inks.push(ink)
known.set(key, n)
}
of.fill(n, token.offset, token.offset + token.content.length)
}
return { inks, of }
}
/** What a loaded theme gives a TextMate scope, by the theme's own rules (VS Code's
* matcher, Shiki's): its foreground and font style, the theme's foreground where no
* rule colours it. One per theme load, each scope resolved once. */
interface ScopeInks {
fg: string
of(scope: string): { color: string; italic: boolean; bold: boolean }
}
const scopeInks = new Map<string, Promise<ScopeInks>>()
function scopeInksOf(h: Core, name: string): Promise<ScopeInks> {
const key = `${name} ${styled}`
let ready = scopeInks.get(key)
if (!ready) {
ready = import("shiki/textmate").then(({ Theme }) => {
const theme = h.getTheme(name)
const tm = Theme.createFromRawTheme({
name: theme.name,
settings: theme.settings,
})
const colours = tm.getColorMap()
const fg = theme.fg
const known = new Map<string, ReturnType<ScopeInks["of"]>>()
return {
fg,
of(scope) {
let ink = known.get(scope)
if (!ink) {
// The scope inside the file's root, as a tokenizer would stand it: the
// matcher reads a path's names and parents alone.
const path = {
parent: { parent: null, scopeName: "source" },
scopeName: scope,
}
const style = tm.match(path as never)
const font = style?.fontStyle ?? -1
ink = {
color:
style && style.foregroundId > 0
? (colours[style.foregroundId] ?? fg)
: fg,
italic: font > 0 && (font & 1) !== 0,
bold: font > 0 && (font & 2) !== 0,
}
known.set(scope, ink)
}
return ink
},
}
})
scopeInks.set(key, ready)
}
return ready
}
/** A reader language's text in both themes: each span as what it is (a scope by each
* theme's rules, an ink of its own, or another language coloured as itself), what no
* span covers in each theme's foreground. A span outside the text throws. */
async function readColours(
text: string,
read: (text: string) => CodeSpan[],
themes: CodeThemes,
): Promise<CodeColours> {
const h = await codeHighlighter("text", themes)
const [light, dark] = await Promise.all([
scopeInksOf(h, themes.light),
scopeInksOf(h, themes.dark),
])
const inks: CodeInk[] = []
const known = new Map<string, number>()
const index = (ink: CodeInk) => {
const key = `${ink.light} ${ink.dark} ${ink.italic} ${ink.bold}`
let n = known.get(key)
if (n === undefined) {
n = inks.length
inks.push(ink)
known.set(key, n)
}
return n
}
const of = new Uint16Array(text.length).fill(
index({ light: light.fg, dark: dark.fg, italic: false, bold: false }),
)
for (const span of read(text)) {
if (span.from < 0 || span.to > text.length || span.to < span.from)
throw new Error(
`code-tokens: a span ${span.from}..${span.to} outside a text of ${text.length}`,
)
if ("lang" in span) {
const inner = await codeColours(
text.slice(span.from, span.to),
span.lang,
themes,
)
for (let i = 0; i < inner.of.length; i++)
of[span.from + i] = index(inner.inks[inner.of[i] as number] as CodeInk)
continue
}
let ink: CodeInk
if ("ink" in span) ink = { ...span.ink, italic: false, bold: !!span.bold }
else {
const l = light.of(span.scope)
const d = dark.of(span.scope)
ink = {
light: l.color,
dark: d.color,
italic: l.italic,
bold: !!span.bold || l.bold,
}
}
of.fill(index(ink), span.from, span.to)
}
return { inks, of }
}
/** A stretch of a line in one ink (null: the view's own foreground, before the
* colours have loaded). */
export interface CodeRun {
text: string
ink: CodeInk | null
}
/** A run with what lies over it: the marks of every range it falls in. */
export interface CodePaint<M> extends CodeRun {
marks: M[]
}
/** A line's runs cut again where `ranges` begin and end (offsets of the whole text;
* the line begins at `start`), each piece carrying the marks of the ranges over it:
* a diagnostic's squiggle, a selection, a flash. */
export function paintRuns<M>(
runs: readonly CodeRun[],
start: number,
ranges: readonly { from: number; to: number; mark: M }[],
): CodePaint<M>[] {
const end = start + runs.reduce((n, r) => n + r.text.length, 0)
const here = ranges.filter((r) => r.from < end && r.to > start)
if (!here.length) return runs.map((r) => ({ ...r, marks: [] }))
const cuts = new Set<number>()
for (const r of here) {
cuts.add(Math.max(start, r.from))
cuts.add(Math.min(end, r.to))
}
const out: CodePaint<M>[] = []
let at = start
for (const run of runs) {
const runEnd = at + run.text.length
const points = [
at,
...[...cuts].filter((c) => c > at && c < runEnd).sort((a, b) => a - b),
runEnd,
]
for (let i = 0; i + 1 < points.length; i++) {
const a = points[i] as number
const b = points[i + 1] as number
out.push({
text: run.text.slice(a - at, b - at),
ink: run.ink,
marks: here.filter((r) => r.from <= a && b <= r.to).map((r) => r.mark),
})
}
at = runEnd
}
return out
}
/** `text` cut into lines of runs, each character inked by `colours` at its offset
* in the text they were read from: `origin[i]` for character `i` (a file being
* typed, coloured as it will be), or `i` itself without one. */
export function runsOf(
text: string,
colours: CodeColours | null,
origin?: readonly number[],
): CodeRun[][] {
const lines: CodeRun[][] = [[]]
let line = lines[0] as CodeRun[]
let run: CodeRun | null = null
for (let i = 0; i < text.length; i++) {
const ch = text[i] as string
if (ch === "\n") {
line = []
lines.push(line)
run = null
continue
}
const at = origin ? (origin[i] as number) : i
const ink = colours
? (colours.inks[colours.of[at] as number] ?? null)
: null
if (run && run.ink === ink) run.text += ch
else {
run = { text: ch, ink }
line.push(run)
}
}
return lines
}// Code as `code` draws it, as markup: Shiki with the two themes every code view here
// wears (CODE_THEMES, both in one render, `--shiki-light` and `--shiki-dark` on each
// token), the `[!code …]` notations read where asked, lines marked, and every token
// in the block's own colours unwrapped. One function, so a block on the server
// (`Code`), one prepared at build (markdown-prepare) and one coloured in the browser
// (markdown-code) are the same markup. Framework-free; Shiki loads on the first call.
import type { BundledLanguage, ShikiTransformer } from "shiki"
import {
CODE_THEMES,
codeColours,
codeHighlighter,
languageOf,
linesOf,
readerOf,
registeredLanguage,
runsOf,
TOKENIZED_LINE_LENGTH,
} from "@/registry/base-nova/lib/code-tokens"
/** A language as code is told it: a Shiki id or alias, a registered language's id or
* alias (lib/code-tokens `registerLanguage`: `cells` once `cells-code` is imported), or
* `text`. */
export type CodeLang = BundledLanguage | "text" | (string & {})
export type CodeHtmlOptions = {
/** `text` when it is not code, which skips the grammar. One neither Shiki nor
* `registerLanguage` knows throws (`knownLanguage` asks first). */
lang: CodeLang
/** Lines to mark, `"2"` or `"1,4-6"`. */
highlight?: string
/** Read `[!code …]` comments: off where the source is shown as itself. */
notations?: boolean
}
/** One of the two inks a Shiki style names (`--shiki-light`, `--shiki-dark`). */
const inkOf = (style: string, name: string) =>
new RegExp(`(?:^|;)${name}:([^;]+)`).exec(style)?.[1]?.toLowerCase()
/** A token in the block's own colours says nothing its line does not: the line wears
* them already (the `<pre>`'s `--shiki-light` and `--shiki-dark`, inherited, which
* code.css colours every span with), so its span is markup alone, two in five of a
* page's tokens. It goes, its text left in the line. Run last, once every notation
* has read the spans: a word highlight counts characters through them. */
const unwrapPlainTokens: ShikiTransformer = {
name: "ag:unwrap-plain-tokens",
root(root) {
const pre = root.children.find(
(n) => n.type === "element" && n.tagName === "pre",
)
if (pre?.type !== "element") throw new Error("code: Shiki drew no <pre>")
const own = String(pre.properties.style ?? "")
const light = inkOf(own, "--shiki-light")
const dark = inkOf(own, "--shiki-dark")
if (!light || !dark)
throw new Error(`code: the <pre> names no inks of its own (${own})`)
const plain = `--shiki-light:${light};--shiki-dark:${dark}`
const code = pre.children.find(
(n) => n.type === "element" && n.tagName === "code",
)
if (code?.type !== "element") throw new Error("code: Shiki drew no <code>")
for (const line of code.children) {
if (line.type !== "element") continue
line.children = line.children.flatMap((token) =>
token.type === "element" &&
token.tagName === "span" &&
Object.keys(token.properties).length === 1 &&
String(token.properties.style).toLowerCase() === plain &&
token.children.every((c) => c.type === "text")
? token.children
: [token],
)
}
},
}
/** Whether code knows `name` (Shiki's, a registered one, or `text`): a block in any
* other is drawn plain. */
export async function knownLanguage(name: string): Promise<boolean> {
const lang = languageOf(name)
if (lang === "text" || registeredLanguage(lang)) return true
const { bundledLanguages } = await import("shiki")
return lang in bundledLanguages
}
/** A reader language's colours as Shiki's tokens, a line each, so its markup is Shiki's
* own and every transformer reads it as any other's. */
function readTokens(
source: string,
colours: import("@/registry/base-nova/lib/code-tokens").CodeColours,
): ShikiTransformer {
return {
name: "ag:reader-tokens",
tokens() {
let offset = 0
return runsOf(source, colours).map((line) => {
const tokens = line.map((run) => {
const ink = run.ink as NonNullable<typeof run.ink>
const token = {
content: run.text,
offset,
htmlStyle: {
"--shiki-light": ink.light,
"--shiki-dark": ink.dark,
...(ink.bold ? { "font-weight": "bold" } : {}),
...(ink.italic ? { "font-style": "italic" } : {}),
},
}
offset += run.text.length
return token
})
offset += 1
return tokens
})
},
}
}
/** `source` as Shiki's markup, in code's two themes, from the one highlighter every
* code view colours with (lib/code-tokens): a grammar language by Shiki, a reader
* language by its reader, the same markup either way. */
export async function codeHtml(
source: string,
{ lang: name, highlight, notations = false }: CodeHtmlOptions,
): Promise<string> {
const lang = languageOf(name)
const read = readerOf(lang)
const h = await codeHighlighter(read ? "text" : lang, CODE_THEMES)
const reader = read
? [readTokens(source, await codeColours(source, lang, CODE_THEMES))]
: []
const marked = highlight ? linesOf(highlight) : null
const notes = notations
? await import("@shikijs/transformers").then((t) => [
t.transformerNotationDiff({ matchAlgorithm: "v3" }),
t.transformerNotationHighlight({ matchAlgorithm: "v3" }),
t.transformerNotationWordHighlight({ matchAlgorithm: "v3" }),
t.transformerNotationFocus({ matchAlgorithm: "v3" }),
t.transformerNotationErrorLevel({ matchAlgorithm: "v3" }),
])
: []
return h.codeToHtml(source, {
lang: read ? "text" : lang,
themes: CODE_THEMES,
defaultColor: false,
tokenizeMaxLineLength: TOKENIZED_LINE_LENGTH,
transformers: [
...reader,
// The notations travel INSIDE the source, so they survive an edit that moves a
// line; Shiki strips the comment from the markup, the clipboard keeps it.
...notes,
// ...and `highlight` for source nobody may write into.
{
name: "ag:highlight-prop",
line(node, line) {
if (marked?.has(line)) this.addClassToHast(node, "highlighted")
},
},
unwrapPlainTokens,
],
})
}// A code block's frame, given its markup: the bar (its name, the copy), the scroller
// with its fading edges, the material's face. What `Code` draws on the server and
// markdown draws anywhere (a prepared block, or one coloured in the browser), so a
// block reads the same wherever it is. No highlighter here: `html` is Shiki's markup
// (lib/code-highlight), or null for the plain text until it is.
import { Copy } from "@/registry/base-nova/ui/copy"
import { Glass } from "@/registry/base-nova/ui/material-glass"
import "./code.css"
import "./edge-fade"
export interface CodeFrameProps {
/** The source, as the clipboard gets it. */
source: string
/** Shiki's markup of it (lib/code-highlight `codeHtml`); null draws it plain. */
html: string | null
/** The language, the bar's name when there is no filename. */
lang: string
/** A path or a name for the bar. */
filename?: string
/** A highlighted command row without a bar; copy stays on the right. */
compact?: boolean
/** The copy control. */
copy?: boolean
/** Number the lines. */
lines?: boolean
/** Its face: the page's frame, or the one glass material. */
material?: "plain" | "glass"
/** No frame, bar or copy of its own: for a frame that holds it. */
bare?: boolean
/** Lines drawn by the caller in place of `html` (a `<pre><code>` of `.line`s, as
* Shiki's): a view whose lines move (walkthrough). */
children?: React.ReactNode
/** The scroller, for a view that keeps lines in sight itself. */
scroller?: React.Ref<HTMLDivElement>
className?: string
}
export function CodeFrame({
source,
html,
lang,
filename,
compact = false,
copy = true,
lines = false,
material = "plain",
bare = false,
children,
scroller,
className,
}: CodeFrameProps) {
// Shiki's own <pre><code>, styled by code.css. A long line scrolls sideways, and a
// block given less height than it needs scrolls down, inside the frame, with the
// scrims' edge fade: never a scrollbar drawn over the code, never a hard cut.
const scroll = children ? (
<div ref={scroller} className="ag-code-scroll ag-edge-fade-xy">
{children}
</div>
) : html ? (
<div
ref={scroller}
className="ag-code-scroll ag-edge-fade-xy"
// biome-ignore lint/security/noDangerouslySetInnerHtml: Shiki's own escaped markup of the source (lib/code-highlight)
dangerouslySetInnerHTML={{ __html: html }}
/>
) : (
<div ref={scroller} className="ag-code-scroll ag-edge-fade-xy">
<pre>
<code>{source}</code>
</pre>
</div>
)
const frame = `ag-code${lines ? " ag-code-numbered" : ""}${className ? ` ${className}` : ""}`
if (bare)
return (
<div data-slot="code" data-bare className={frame}>
{scroll}
</div>
)
const body = (
<>
{!compact && (
<div className="ag-code-bar">
<span className="ag-code-name">{filename ?? lang}</span>
{copy && <Copy value={source} label />}
</div>
)}
{scroll}
{compact && copy && <Copy value={source} className="mr-2" />}
</>
)
if (material === "glass")
return (
<Glass
shape="surface"
data-slot="code"
data-compact={compact || undefined}
className={`${frame} [--glass-radius:0.75rem]`}
>
{body}
</Glass>
)
return (
<div
data-slot="code"
data-material="plain"
data-compact={compact || undefined}
className={frame}
>
{body}
</div>
)
}"use client"
import * as React from "react"
import {
CODE_THEMES,
type CodeColours,
type CodeThemes,
codeColours,
} from "@/registry/base-nova/lib/code-tokens"
/** `text`'s colours in `lang` (lib/code-tokens), read in the browser once it
* renders: null until Shiki has loaded, so a view draws the text plain at once and
* coloured a moment later, never blank. `given`, colours already read (on the
* server, for a still), are used as they are, and the browser loads no Shiki. */
export function useCodeColours(
text: string,
lang: string,
themes: CodeThemes = CODE_THEMES,
given?: CodeColours,
): CodeColours | null {
const [colours, setColours] = React.useState<{
key: string
colours: CodeColours
} | null>(null)
const { light, dark } = themes
const key = `${light} ${dark} ${lang}\n${text}`
React.useEffect(() => {
if (given) return
let live = true
void codeColours(text, lang, { light, dark }).then((c) => {
if (live) setColours({ key, colours: c })
})
return () => {
live = false
}
}, [given, key, text, lang, light, dark])
if (given) return given
return colours?.key === key ? colours.colours : null
}
const NONE: readonly (CodeColours | null)[] = []
/** Many texts' colours at once (every state an edit passes through), read once in
* the browser, so a view moving from one to the next never waits for one: none
* until all have loaded, then each at its index. `texts` keeps its identity while
* it holds the same texts. */
export function useCodeColoursOf(
texts: readonly { text: string; lang: string }[],
themes: CodeThemes = CODE_THEMES,
): readonly (CodeColours | null)[] {
const [read, setRead] = React.useState<{
texts: readonly { text: string; lang: string }[]
colours: CodeColours[]
} | null>(null)
const { light, dark } = themes
React.useEffect(() => {
let live = true
void Promise.all(
texts.map((t) => codeColours(t.text, t.lang, { light, dark })),
).then((colours) => {
if (live) setRead({ texts, colours })
})
return () => {
live = false
}
}, [texts, light, dark])
return read?.texts === texts ? read.colours : NONE
}