Code Block
Highlighted source in a frame: the file tabs, the actions, the selected file's code and, for long code, a window with a toggle to show every line.
import { CodeBlock } from '@fairgarden/design/content/code-block'
Code Block is a @fairgarden/docs Content component: pass it as CodeHighlighter's Content. It calls the engine's useCode(props) and renders the result. The engine owns the highlighting, the file, variant and TS | JS state, the swap between them, the hash deep links, the stored preferences and copy; Code Block draws them in the design system's frame. Its header is File Tabs, with the actions as its controls and the busy label as its status. @fairgarden/docs is an optional peer dependency; install it to use Code Block. Every fenced code block on this site is a Code Block.
Code sets in mono at the caption size. Every syntax color is a role of the block's scales, so a block follows its ground and the page mode, and prints black on white. Code and file names always read left to right; on a right-to-left page the header's layout mirrors around them.
Setup
Three pieces wire a site. The MDX pre override hands every fenced block to CodeHighlighter; createMdxComponents from @fairgarden/design/utils/docs builds it for you, code-split, with CodeBlockLoading until the block's chunk loads. CodeProviderLazy in the root layout gives the engine its client side, which highlights the code in the browser. And for code written in a component, CodeHighlighter takes Code Block directly, with sourceEnhancers={serverSourceEnhancers} from @fairgarden/design/utils/docs, as every example below passes. Keep the engine's default highlightAfter ('idle') everywhere: the server HTML carries the plain code, which highlights once the browser is idle. highlightAfter="init" is an opt-in for showing server-side highlighting, as one example below does, not a site-wide setting.
What sets a block's size is always in the server HTML, so nothing moves when the page hydrates, the block's chunk swaps in or the code highlights; only the colors arrive later. The emphasis frames and the collapsed window come from the server: the build frames fenced blocks and demos, and serverSourceEnhancers, the engine's emphasis enhancer with the options demos get, frames any code the server parses. createMdxComponents passes it by default. The enhancer records its name on the code, so CodeProviderLazy's own emphasis pass skips the block rather than windowing it after hydration.
import NextLink from 'next/link'
import { createMdxComponents } from '@fairgarden/design/utils/docs'
export const mdxComponents = createMdxComponents({ Link: NextLink })
export function useMDXComponents(components) {
return { ...components, ...mdxComponents }
}import { CodeProviderLazy } from '@fairgarden/docs/CodeProvider'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<CodeProviderLazy>{children}</CodeProviderLazy>
</body>
</html>
)
}The loaded block, CodeBlock, is also exported code-split as CodeBlockLazy, the pair to CodeBlockLoading: the loading state renders the engine's precomputed fallback in the same frame, with its window and the loaded block's controls, disabled, in their places, so the server HTML carries the code, the height holds at the swap, and every file's #slug target is there for a deep link before the block loads. It calls nothing from useCode, so it stays small.
One file
One file
One file shows its name in the header and its actions as a row of quiet icon-only buttons, each named by a tooltip: copy the source, copy the file's deep link (the page URL with its #slug; every slug has a hidden scroll target, so the link lands on the block) and, for a file with a hosted URL, view the source. The buttons are a glyph with no edge until you point at one or focus it, like the ⋮. The header is one fixed row: a long name truncates with an ellipsis rather than wrap.
A fence without a file name has no header at all, so a one-line snippet stays one line tall. Where copying is its only action, as for the import line at the top of this page, a copy button hangs just outside the frame's top-end corner: one click copies the code and a toast says "Code copied". It sits where the ⋮ would, the same size, and outlines at once when you point at it or focus it. With more actions (view source, variants, the TS | JS switch) the ⋮ menu hangs there instead, and if an action arrives after the page loads, the button turns into the ⋮ in place: only the glyph changes.
Every copy (the source, the link, or all files as Markdown) confirms with a Toast in the page's toast bar: "VolunteerShift.tsx copied", "Link copied" or "Markdown copied", or a danger toast if the browser refuses the clipboard. The header and the buttons never change to say so. The toasts need the design system's ToastProvider in the app shell, as this site mounts it; without one, copying still works, silently.
import { Button } from '@fairgarden/design/actions/button'
export function JoinCrew() {
return <Button variant="solid">Join the Crew</Button>
}Files
Files
Two or more files become folder tabs, and the actions move into the "More actions" menu: copy, copy link, view source, copy all files as Markdown, and the TS | JS option and variants when there are any. Tabs are links to each file's #slug: a plain click switches the file, a modifier click opens the link and leaves the selection. The tabs take the header's whole width and scroll when they overflow, passing under the frame's side edges.
The menu's trigger, a vertical ⋮, always hangs just outside the frame's end edge, never inside it. Opening the menu grows the ⋮'s ear (or, from the keyboard, its ring) into the menu's frame, the Menu's outline morph; --fgd-outline-morph: none on the block turns it off. Leave --fgd-size-file-tabs-control (24 px) free past every code block's end, with nothing clipping it sideways: this site's column keeps that gutter at every width (44 px from the medium breakpoint, so the whole hit area fits), and a demo's preview keeps it inside its inset. The same block in the page column:
import styles from './volunteer-shift.module.css'
export function VolunteerShift({ day, crew }: { day: string; crew: number }) {
return (
<article className={styles.shift}>
<h3 className={styles.day}>{day}</h3>
<p>{crew} volunteers signed up</p>
</article>
)
}import styles from './volunteer-shift.module.css'
export function VolunteerShift({ day, crew }: { day: string; crew: number }) {
return (
<article className={styles.shift}>
<h3 className={styles.day}>{day}</h3>
<p>{crew} volunteers signed up</p>
</article>
)
}Variants and TS | JS
Variants and TS | JS
With one file, the variants show as a Select and the engine's JavaScript transform as a TS | JS segmented switch; with several files both move into the menu. When the engine works the transform out in the browser, the switch arrives after the page hydrates: it joins at the start of the row, taking its room from the file name, so nothing below moves and the buttons already there stay put. The control changes at once; the code swaps 350 ms later while the changed lines grow or shrink, and the page holds still around the control. Under reduced motion the swap is instant. The engine stores the choice and applies it to every block on the page.
type Shift = { day: string; crew: number }
export function crewLabel({ day, crew }: Shift): string {
return `${day}: ${crew} volunteers`
}Highlighted on the server
Highlighted on the server
With highlightAfter="init" the server parses every file, the extra files of inline code included, so the HTML arrives highlighted before any script runs. It costs server work and page weight, so it's for demonstrating the capability; every other block here keeps the engine's default.
import styles from './seed-packet.module.css'
export function SeedPacket({ name, sown }: { name: string; sown: string }) {
return (
<p className={styles.packet}>
{name}, sown {sown}
</p>
)
}Highlighted lines
Comments in the source mark emphasis, and the pipeline removes them from the rendered code: // @highlight on a line, // @highlight-start and // @highlight-end around a run, a quoted description after either, and // @highlight-text "…" for a phrase. A highlighted frame or line takes the step-3 fill and a 2 px start bar in the accent, so it still reads in print and forced colors; a phrase takes a fill and an underline.
'use client'
import * as React from 'react'
import { Button } from '@fairgarden/design/actions/button'
export function SeedlingCounter() {
const [planted, setPlanted] = React.useState(0)
return (
<Button variant="solid" onClick={() => setPlanted((n) => n + 1)}>
Plant a Seedling ({planted})
</Button>
)
}Collapsible window
With collapse (a fence flag, a content prop or a demo prop), code that has a window shows only that window until the reader expands it with "Show all n lines". // @focus-start and // @focus-end set the window, @padding n its context lines, which sit in the muted ink until expanded, and a highlighted run is a window on its own. The toggle is a hidden checkbox and a label with the disclosure glyph, so it works before hydration; once loaded, the engine's useCodeWindow keeps the page still while the window opens or closes. A window that cuts a highlighted run ends on a 2 px rule. Frames reveal with a clip, never a fade, and print expanded.
// Totals for the season's work days.
type Plot = 'north' | 'south' | 'orchard'
const plots: readonly Plot[] = ['north', 'south', 'orchard']
const goals: Record<Plot, number> = {
north: 40,
south: 45,
orchard: 35,
}
export function seasonReport(planted: Partial<Record<Plot, number>>) {
let total = 0
for (const plot of plots) {
total += planted[plot] ?? 0
}
const goal = plots.reduce((sum, plot) => sum + goals[plot], 0)
return {
total,
goal,
plots: plots.length,
done: total >= goal,
}
}On grounds
On grounds
The frame's face is always the scope's step 1, where only three steps are text-safe on every scope, so color sorts tokens into three tiers and weight and slant tell the rest apart. Keywords take the secondary step 12 at weight 700 and constants the same step at 400; strings are the ink, oblique; functions and entity names the ink at 700; comments the primary step 11, oblique; punctuation that step, upright. Every token holds 4.5:1 on each page ground, in both modes; in print they are all black, and weight and slant remain.
// Totals for the season's work days.
const plots = ['north', 'south', 'orchard'] as const
export function seasonReport(planted: Record<string, number>) {
let total = 0
for (const plot of plots) total += planted[plot] ?? 0
return { total, plots: plots.length, done: total >= 120 }
}// Totals for the season's work days.
const plots = ['north', 'south', 'orchard'] as const
export function seasonReport(planted: Record<string, number>) {
let total = 0
for (const plot of plots) total += planted[plot] ?? 0
return { total, plots: plots.length, done: total >= 120 }
}Busy
When a TS | JS swap waits on slower blocks elsewhere on the page past the engine's grace window, the block the reader touched shows "Switching to JS…" over its header's end, from the engine's pendingTransform. The label is muted text inside a live region, laid over the header so it never moves or narrows the tabs, and the block takes aria-busy. There is no spinner.
A block never splits across pages. It prints every line, wrapped, with the window open and no controls, black on white: fills drop, and the start bars and underlines carry the emphasis.
API Reference
CodeBlock
A code block: the file tabs (or the one file’s name), the busy label and
the actions in the header, the selected file’s highlighted source, and,
with collapse, the window’s toggle under a long block. Tabs are links
to each file’s #slug; a modifier click opens the link instead of
switching. Copy writes the selected file; “Copy link” its deep link. Each
copy confirms with a toast (a danger toast if the clipboard refuses)
through the design system’s ToastProvider, where one is mounted above;
without one, copying is silent. A nameless snippet has no header row.
With several files, or none named, the “More actions” ⋮ hangs outside
the frame’s inline-end edge: leave --fgd-size-file-tabs-control
(24 px) free past the block, unclipped.
| Prop | Type | Description |
|---|---|---|
collapse | | Collapses the code to its window ( |
primary | | Primary scale: frame, labels, syntax inks, highlight fills, focus ring. Never defaulted [D133]. |
secondary | | Secondary scale: highlight accent bar ( |
className | |
CodeBlockLoading
The loading state of a code block: the precomputed fallback in the
loaded block’s frame, with its tabs and actions disabled until the
content loads. Pass it as CodeHighlighter’s ContentLoading.
| Prop | Type | Description |
|---|---|---|
collapse | | Collapses the code to its window ( |
primary | | |
secondary | | |
className | |
Additional types
CodeBlockLoadingProps
Props for CodeBlockLoading: what CodeHighlighter hands its ContentLoading, plus the block’s scales.
type CodeBlockLoadingProps = ContentLoadingVariant &
CodeIdentityProps &
__type &
CodeBlockOptions & {
primary?:
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple';
secondary?:
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| 'amber'
| 'blue'
| 'cyan'
| 'grass'
| 'green'
| 'jade'
| 'lime'
| 'mint'
| 'orange'
| 'sky'
| 'teal'
| 'yellow';
className?: string;
}CodeBlockOptions
Code Block’s own content props: JSON, so a fence’s data-content-props or a demo’s props can carry them.
type CodeBlockOptions = {
/**
* Collapses the code to its window (`@focus`, emphasis) with the "Show all {n} lines" toggle,
* where the code has one. A fence flag (` ```tsx collapse `) arrives as the string `'true'`,
* which counts. Not `collapsible`: the engine hands a ContentLoading its own `collapsible`
* (whether a file has a window), which would shadow it. Default `false`.
*/
collapse?: boolean | 'true';
}CodeBlockProps
Props for CodeBlock: the content props CodeHighlighter hands its Content, plus the block’s scales.
type CodeBlockProps = CodeIdentityProps &
Pick<CodeContentProps, 'code' | 'components' | 'variantType'> &
__type &
CodeBlockOptions & {
primary?:
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple';
secondary?:
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| 'amber'
| 'blue'
| 'cyan'
| 'grass'
| 'green'
| 'jade'
| 'lime'
| 'mint'
| 'orange'
| 'sky'
| 'teal'
| 'yellow';
className?: string;
}