Code blocks
I draw every code sample on the site with one CodeBlock component. The blog renders it in full and the assistant renders it light, with different settings on the same component.
How a sample is built
Sanity block → normalizeCodeBlockConfig → buildAnnotatedModel → Shiki (server) → <CodeBlock>
Assistant fence → normalizeCodeBlockConfig → buildPlainModel (no Shiki) → <CodeBlock>- Shiki is the only tokenizer and runs only on the server.
highlightCodeBlocksinsrc/lib/blog/highlight.tsturns each code block into a model: the source, a language, and one entry per line with its token markup and an optional mark. No highlighter ships to the browser. CodeBlockdraws from props. It takes a model and a validated config and runs no highlighter, so it renders on the server and in the browser alike. The assistant builds a model without token markup, which is why its blocks have no syntax colors.- The client part is small.
CodeFrame(frame, header, wrap and expand controls) andCopyButtonare the only client components. The listing inside stays server-rendered markup.
Authoring in the Studio
The Studio’s code block has a language, the code, an optional filename and clickable line numbers.
| To get | Do this |
|---|---|
| A filename in the header | Fill in the filename field. |
| Highlighted lines | Click the line numbers in the editor. The plugin stores them as highlightedLines. |
| A highlighted line, inline | End the line with a comment containing [!code highlight]. |
| An added line in a diff | End the line with a comment containing [!code ++]. |
| A removed line in a diff | End the line with a comment containing [!code --]. |
| A terminal frame | Set the language to bash, sh, shell, zsh, console or shellscript. |
let total = 0; // [!code --]
const total = items.reduce((sum, item) => sum + item.price, 0); // [!code ++]The note is a trailing comment in the language’s own style: //, #, --, /* */ or <!-- -->. The reader sees and copies the code without the note, and the Markdown alternate leaves it out too. A note only counts at the end of a line, after a comment opener that starts the line or follows whitespace, so i-- [!code ++] and a string containing the text are left as written. A diff note wins over a highlight on the same line. Lines keep their numbers, because a note never removes a line.
The Studio’s code type has fixed fields, so a block cannot store a variant, line numbers, wrapping or a collapse count. Those are read from the block when present (an API write sets them) but the Studio does not offer them. Offering them would mean wrapping code in a new type, which is a content migration.
Settings and defaults
normalizeCodeBlockConfig(raw, preset) in src/lib/code-block/config.ts validates settings. A value of the wrong type or outside its range is dropped and the preset’s value is used. It never throws. Precedence, lowest to highest: the preset, then what the block sets, then the reader’s own choices (wrap and expand).
| Setting | Blog | Chat | Limits |
|---|---|---|---|
variant | editor, or terminal for a shell | plain | editor, terminal, plain |
filename, title | shown in the header | ignored | trimmed, 120 characters |
lineNumbers | off | off | lineNumberStart 1 to 99999 |
wrap | off | off | |
copy | on | on | |
collapseAfter | 30 | never | 3 to 1000; 0 or false turns it off |
wrapToggle | on, when a line is over 72 characters | off |
The header shows the filename, else the title, else the language (not for text). It is omitted when it would be empty.
Limits
These bound the work one block can cause.
- Highlighting is skipped, and the block renders as plain text, above 100,000 characters or 2,000 lines (
MAX_HIGHLIGHT_SOURCE_LENGTH,MAX_HIGHLIGHT_LINES). Notes are still applied. - At most 500
highlightedLinesentries are read, and anything that is not a line of the code is dropped. - A line over 10,000 characters is not scanned for notes.
- A language the highlighter does not know falls back to
text. The lookup uses own keys only, so names such asconstructorcannot reach Shiki.
Security rules I hold the renderer to
- A stored
htmlorcodeBlockfield is always discarded. The dataset is untrusted: an API write can add any field to a block, and the query spreads them all. - Token markup is injected only from a sealed model.
highlightCodeBlocksregisters the models it builds in aWeakSet(sealModel).CodeBlockchecksisSealedModelbefore it uses a line’shtml. A model that came from stored JSON, a client prop or a spread copy is never in the set, so it renders as escaped text. - Everything else is a text node. Source, filename, title, language and marks are rendered through React. A mark outside
highlight,addedandremovedis ignored. - The assistant never interprets notes. A reply can be steered by a visitor, so its fences render as literal text with no notes, filename or token markup. Images, links and raw HTML stay out of an answer.
- Display-only settings stay out of the source. The copy button writes the model’s source, so line numbers, diff glyphs and notes are never copied.
Accessibility
- The listing is a labelled
regionwithtabindex="0", so a keyboard can scroll it. Tab visits the wrap toggle, the copy button, the region and the expand button, then leaves. - Copy and its failure are announced through a polite live region. Wrap and expand are real buttons with
aria-pressedandaria-expanded. - Line numbers and diff glyphs are generated content with empty alternative text, so a screen reader does not read them and a selection does not include them. An added line is an
<ins>and a removed line a<del>, so the change does not depend on color. - Collapsing clips the block visually. Every line stays in the page.
- Hover, focus and the copy confirmation respect
prefers-reduced-motion.
Styling
CodeBlock.css.ts owns the look. Colors are theme tokens (themeColors, mix), the radius is borderRadius.control, focus rings come from focusRing, and the copy confirmation time is copyConfirmMs.
- Token colors. The highlighter’s theme emits
var(--shiki-*)custom properties.FrameStylemaps them to theme tokens, so both themes work with no color literals. - Marked lines. The diff and highlight tints use the accent and the ink color, because the palette has no green or red token.
- Layout variables.
padX(horizontal padding, which a marked line reaches back over) andcollapseLines(set inline from the config) are vanilla-extract variables.
Extending it
- A new surface. Add a preset to
PRESETSinsrc/lib/code-block/config.tsand pass its name tonormalizeCodeBlockConfig. - A language that gets the terminal frame. Add it to
SHELL_LANGUAGESin the same file. - A new kind of line mark. Add it to
LineMarkintypes.ts,MARKSinannotations.ts,LINE_TAGinCodeBlock.tsxand adata-markrule inCodeBlock.css.ts. - A new surface that needs colors. Highlight on the server with
highlightCodeBlocksand pass the sealed model through. The browser cannot add token markup of its own.
What I have not built
- Tabs for several files in one example.
- Type hovers (Twoslash) and runnable examples. Each is a separate piece of work.
- Studio fields for variant, line numbers, wrapping and collapse, which need a wrapper type around
code. - Syntax colors in assistant answers. They would need a server round trip after the reply settles.