Skip to main content

Demo

A live component above its source: the preview on the page ground, with the variants in a Select in its corner, and the code beneath with the file tabs, the actions and, for long code, a window.

import { DemoContent } from '@fairgarden/design/content/demo'

Demo is the @fairgarden/docs DemoContent component: the demo factories render it for every demo. It calls the engine's useDemo(props) and renders the result: the selected variant's component, and beneath it the same code section as a Code Block, joined to the preview by a 1 px rule. The engine owns the precomputed files, the variants and their live components, the TS | JS transform, the swap, the hash deep links, the stored preferences and copy. @fairgarden/docs is an optional peer dependency; install it to use Demo. Every demo on this site is one.

Setup

createDemo and createDemoWithVariants from @fairgarden/design/utils/docs are the engine's factories pre-wired with Demo: DemoLazy (DemoContent in its own chunk) and DemoLoading until it loads, and the demo heading. A demo is a folder with the component and an index.ts:

demos/basic/index.ts
import { createDemo } from '@fairgarden/design/utils/docs'
import { JoinCrew } from './JoinCrew'

export const DemoBasic = createDemo(import.meta.url, JoinCrew, { name: 'Basic', slug: 'basic' })

DemoLoading renders the live component at once and the engine's precomputed fallback in the code section, in the loaded demo's frame, so the server HTML carries the component and its code, the height holds at the swap, and the #slug targets are there before the demo loads. It calls nothing from useDemo, so it stays small; its controls are disabled until the swap.

Basic

Basic

The preview sits on the page ground, inset 32 px, in a wrapping row with a 16 px gap. The code of a one-file demo shows its actions inline: the TS | JS switch (the engine's JavaScript transform of a TypeScript demo), then copy and copy link, quiet until you point at them. The switch can arrive after the page hydrates; it takes its room from the file name, which truncates, so the header never grows. Every file's #slug has a hidden scroll target before the frame, so a copied link lands on the demo.

JoinCrew.tsx
import { Button } from '@fairgarden/design/actions/button'

/** Signs a volunteer up for the next work day. */
export function JoinCrew() {
  return <Button variant="solid">Join the Crew</Button>
}

Variants

Variants

Two or more variants show as a compact Select in the preview's top-start corner. The Select changes at once; the preview and the code swap 350 ms later while the changed lines grow or shrink, and the page holds still around the Select. Under reduced motion the swap is instant. The engine stores the choice, keyed by the variant names, and applies it to every demo with the same variants. A demo with two or more files shows them as folder tabs, with the actions in the "More actions" menu, as a Code Block does.

0 planted
'use client'

import * as React from 'react'
import { Button } from '@fairgarden/design/actions/button'
import styles from './seedling-counter.module.css'

/** Counts the seedlings planted on a work day. */
export function SeedlingCounter() {
  const [planted, setPlanted] = React.useState(0)

  return (
    <div className={styles.row}>
      <Button variant="solid" onClick={() => setPlanted((n) => n + 1)}>
        Plant a Seedling
      </Button>
      <output className={styles.count}>{planted} planted</output>
    </div>
  )
}

Collapsible code

Collapsible code

Pass collapse to a demo and its code shows only the window its source marks (// @focus-start and // @focus-end, or a highlighted run) until the reader expands it with "Show all n lines", as a collapsible Code Block does.

North: 0South: 0Orchard: 0
'use client'

import * as React from 'react'
import { Button } from '@fairgarden/design/actions/button'
import { Tag } from '@fairgarden/design/feedback/tag'
import styles from './plot-tally.module.css'

const plots = ['North', 'South', 'Orchard']

function nextPlot(current: number) {
  return (current + 1) % plots.length
}

/** Tallies seedlings by plot on a work day. */
export function PlotTally() {
  const [plot, setPlot] = React.useState(0)
  const [tally, setTally] = React.useState<number[]>(() => plots.map(() => 0))

  const plant = () => {
    setTally((current) => current.map((count, index) => (index === plot ? count + 1 : count)))
  }

  return (
    <div className={styles.row}>
      <Button variant="solid" onClick={plant}>
        Plant in {plots[plot]}
      </Button>
      <Button onClick={() => setPlot(nextPlot)}>Next Plot</Button>
      {plots.map((name, index) => (
        <Tag key={name}>
          {name}: {tally[index]}
        </Tag>
      ))}
    </div>
  )
}

Runtime error

Runtime error

A runtime error is an alert laid across the preview's top edge, so showing it never moves the preview or the code. It takes the danger edge at 2 px and the danger text on the face, with no shadow. The message is the engine's error for the selected variant, reported through its CodeControllerContext the way a live runner reports one; this demo's ClientProvider reports it, and the button clears it.

'use client'

import * as React from 'react'
import { Button } from '@fairgarden/design/actions/button'
import { ReportContext } from './ReportedError'

/** Toggles the reported error, so the banner comes and goes. */
export function PlotLabel() {
  const { failing, setFailing } = React.useContext(ReportContext)
  return (
    <Button onClick={() => setFailing(!failing)}>{failing ? 'Pass a Plot' : 'Drop the Plot'}</Button>
  )
}

Custom preview

Custom preview

renderPreview wraps or replaces what renders in the surface; it's called with the selected variant's component. A rendered preview that runs edge to edge cancels the surface's inset with margin: calc(-1 * var(--demo-inset)). This site's page-frame demos work this way: with frame, the preview is an iframe of the demo's preview route, a page outside the docs layout that renders the component alone, so viewport media resolve against the frame. "Full page" opens that route at the window's width. renderPreview is a function, so pass it from a client component that wraps DemoLazy, and give DemoLoading a stand-in the frame's size, so the frame mounts once, after the swap.

import { Button } from '@fairgarden/design/actions/button'
import { Tag } from '@fairgarden/design/feedback/tag'
import styles from './crew-banner.module.css'

/** A banner for the next work day, laid out by the viewport it runs in. */
export function CrewBanner() {
  return (
    <div className={styles.banner}>
      <Tag>Saturday</Tag>
      <span>Twelve volunteers are planting the orchard.</span>
      <Button variant="solid">Join the Crew</Button>
    </div>
  )
}

Print

The preview prints as rendered, never split across pages; components inside it carry their own print fallbacks. The variant bar prints the selected variant's name, a runtime error prints in flow above the preview, and the code prints in full with the window open, black on white.

API Reference

DemoContent

A demo: the live component on the page ground, with a Select of the variants in its top-start corner (two or more), above the embedded code with the file tabs, the actions (copy, copy link, view source, TS | JS) and, with collapse, the window. Every file’s #slug has a hidden scroll target before the frame.

PropTypeDescription
collapse
boolean | 'true' | undefined

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.

primary
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| undefined

Primary scale: frame, labels, syntax inks, focus ring. Never defaulted [D133].

renderPreview
| ((component: React.ReactNode) => React.ReactNode)
| undefined

Wraps or replaces what renders in the preview surface, such as a docs site’s iframe of the demo’s own page. Called with useDemo’s component. Default: the component as is. A rendered preview that runs edge to edge cancels the surface’s inset with margin: calc(-1 * var(--demo-inset)). A function, so pass it from a client component that wraps DemoContent.

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'
| undefined

Secondary scale: keywords, highlight accent, the selected file tab. Never defaulted.

className
string | undefined

DemoLoading

The loading state of a demo: the component above its precomputed code, with the controls disabled until the content loads.

PropTypeDescription
collapse
boolean | 'true' | undefined

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.

primary
| 'olive'
| 'sage'
| 'slate'
| 'sand'
| 'gray'
| 'mauve'
| 'brown'
| 'bronze'
| 'gold'
| 'red'
| 'ruby'
| 'crimson'
| 'tomato'
| 'pink'
| 'plum'
| 'indigo'
| 'iris'
| 'violet'
| 'purple'
| undefined
renderPreview
| ((component: React.ReactNode) => React.ReactNode)
| undefined

As DemoContent’s renderPreview, called with the fallback’s component. Pass the loaded demo’s, or a stand-in the same size: a preview that must mount only once (an iframe) renders its stand-in here, since the swap replaces the loading tree.

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'
| undefined
className
string | undefined

Additional types

demo

Demo’s CVA function.

type demo = demo
DemoContentProps

Props for DemoContent: the content props the demo factories hand over, plus the preview hook and scales.

type DemoContentProps = CodeIdentityProps &
  Pick<CodeContentProps, 'code' | 'components' | 'variantType'> &
  __type &
  CodeBlockOptions & {
    renderPreview?: (component: React.ReactNode) => React.ReactNode;
    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;
  }
DemoLoadingProps

Props for DemoLoading: what the demo factories hand DemoContentLoading, plus the preview hook and scales.

type DemoLoadingProps = ContentLoadingVariant &
  CodeIdentityProps &
  __type &
  CodeBlockOptions & {
    renderPreview?: (component: React.ReactNode) => React.ReactNode;
    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;
  }
DemoOptions

Demo’s own content props: JSON, so a demo’s props (<DemoX collapse />) can carry them.

type DemoOptions = {
  /**
   * 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';
}