Docs Utilities
Factories for a documentation site built on @fairgarden/docs: demos, API tables and the MDX component map, pre-wired with the design system's Code Block, Demo and Types Table.
import {
createDemo,
createDemoWithVariants,
createTypes,
createMultipleTypes,
createMdxComponents,
} from '@fairgarden/design/utils/docs'
Each is a thin wrapper over the engine's own factory with the design system's components plugged in, and every option passes through, so an app can replace any of them. They're server-safe and hold no framework code: pass your router's link in. @fairgarden/docs is an optional peer dependency; install it to use these. Each factory also has its own path (@fairgarden/design/utils/docs/createDemo, …/createTypes, …/createMdxComponents, …/serverSourceEnhancers, …/toSidebarItems), so an app imports only what it uses. This site is built with them.
createDemo
createDemo and createDemoWithVariants are the engine's demo factories with DemoLazy as the demo content (the Demo in its own chunk), DemoLoading until it loads, DemoTitle for <DemoX.Title />, and the source links withDeploymentConfig sets up (SOURCE_CODE_ROOT_DIR, SOURCE_CODE_ROOT_URL). Code highlights at the engine's default, 'idle': the server HTML carries the plain code, which highlights once the browser is idle. highlightAfter still passes through, but keep 'init' for a demo that shows server-side highlighting, since it costs server work and page weight. createDemoWithVariants also passes fallbackUsesAllVariants, so the loading state has every variant: it draws the variant Select, and every variant's files have their #slug targets. The page loads the Demo's chunk only after the loading state has painted.
import { createDemoWithVariants } from '@fairgarden/design/utils/docs'
import { SeedlingCounter as CssModules } from './css-modules/SeedlingCounter'
import { SeedlingCounter as Tag } from './tag/SeedlingCounter'
export const DemoVariants = createDemoWithVariants(import.meta.url, { CssModules, Tag }, { name: 'Variants' })To change a default, build your own pair with createDemoFactory(options) and createDemoWithVariantsFactory(options). This site passes its own content and loading state, which wrap the Demo's with its page-frame preview:
import { createDemoFactory, createDemoWithVariantsFactory } from '@fairgarden/design/utils/docs/createDemo'
import { DemoContent } from '@/components/DemoContent'
import { DemoLoading } from '@/components/DemoLoading'
const options = { DemoContent, DemoContentLoading: DemoLoading }
export const createDemo = createDemoFactory(options)
export const createDemoWithVariants = createDemoWithVariantsFactory(options)createTypes
createTypes and createMultipleTypes are the engine's types factories with the Types Table and TypePre. They extract an export's API from TypeScript at build time. Pass your MDX map as components, so the descriptions render in the same components as your pages; without it they render as plain elements.
import { createMultipleTypesFactory, createTypesFactory } from '@fairgarden/design/utils/docs/createTypes'
import { mdxComponents } from '@/mdx-components'
export const createTypes = createTypesFactory({ components: mdxComponents })
export const createMultipleTypes = createMultipleTypesFactory({ components: mdxComponents })import { createTypes } from '@/functions/createTypes'
import { Button } from '@fairgarden/design/actions/button'
export const TypesButton = createTypes(import.meta.url, Button)createMdxComponents
createMdxComponents(options) returns the MDX component map. pre renders every fenced code block as a Code Block through CodeHighlighter, code-split, with CodeBlockLoading until its chunk loads. code sets inline code in the Code Block's syntax tiers. h1 to h4 take the type roles, and the headings with ids (rehype-slug gives each one) link to themselves. a is the design system's Link, with the external mark on absolute URLs. p, the lists, table, blockquote and hr follow the design system's prose.
The options:
Link: renders links to internal paths (/…), such as next/link, as the Link's element. Default: a plaina.Image: rendersimg, such as next/image. Default: the plain element.Content,ContentLoadingandhighlightAfter: the fenced blocks'CodeHighlighterslots. Defaults:CodeBlockLazy,CodeBlockLoadingand the engine's own ('idle').sourceEnhancers: the enhancers the server runs on the blocks' code. Default:serverSourceEnhancers, so each block's emphasis window is in the server HTML. Pass[]to run none.components: more components, or replacements for any in the map, merged last.
import NextLink from 'next/link'
import { createMdxComponents } from '@fairgarden/design/utils/docs/createMdxComponents'
import { PagesIndex } from './components/PagesIndex'
export const mdxComponents = createMdxComponents({ Link: NextLink, components: { PagesIndex } })
export function useMDXComponents(components) {
return { ...components, ...mdxComponents }
}The map's pre is also exported alone as Pre, and the demo heading as DemoTitle.
serverSourceEnhancers
serverSourceEnhancers is the list of source enhancers CodeHighlighter runs on the server: the engine's emphasis enhancer, enhanceCodeEmphasis, with its default options. Pre and createMdxComponents pass it by default; pass it yourself wherever a page renders CodeHighlighter directly with code the build didn't precompute, such as inline code or a string child, as the Code Block examples do.
It's the default because it keeps the layout still. On the server the enhancer draws the emphasis frames and the collapsed window, so the server HTML has the block's final height, and the loading state and the loaded block paint the same lines. It records its name on the code, so CodeProviderLazy's own emphasis pass, which has the same name, skips the block. Without it, that pass would window the code after hydration, and the block would shrink in front of the reader. Highlighting still waits for the engine's default, 'idle': only the colors arrive late.
Its options are the ones demos get from the build, the enhancer's defaults, which withFairGardenDocs uses when it has no demoEmphasisOptions, so inline code and demos window alike. If you set demoEmphasisOptions, pass [createEnhanceCodeEmphasis(sameOptions)] instead, to createMdxComponents and your own CodeHighlighters.
import { CodeHighlighter } from '@fairgarden/docs/CodeHighlighter'
import { createParseSource } from '@fairgarden/docs/pipeline/parseSource'
import { CodeBlock } from '@fairgarden/design/content/code-block'
import { serverSourceEnhancers } from '@fairgarden/design/utils/docs/serverSourceEnhancers'
const sourceParser = createParseSource()
export function SeedPacketCode({ source }: { source: string }) {
return (
<CodeHighlighter
fileName="SeedPacket.tsx"
Content={CodeBlock}
sourceParser={sourceParser}
sourceEnhancers={serverSourceEnhancers}
>
{source}
</CodeHighlighter>
)
}toSidebarItems
toSidebarItems(sitemap) turns the engine's sitemap, the object that also feeds search, into the Sidebar Nav's page tree for the Docs Layout: each section's title over its pages, in the section index's order, the heading linking to the section's index page. It returns plain data, so build it on the server where the sitemap is imported and hand it to the client SidebarNav, as this site's layout does. sitemapHref(prefix, path) is the route it gives each page (/actions/button for ./button/page.mdx under /actions/); pass toHref to build routes another way, or groupLinks: false for plain group headings. A toTableOfContents(page) beside it is planned, for the contents column, once the engine records each heading's rendered id and level (see the Docs Layout's wiring plan).
import { toSidebarItems } from '@fairgarden/design/utils/docs/toSidebarItems'
import { sitemap } from '../sitemap'
const sidebarItems = toSidebarItems(sitemap)The engine's client side
Code Block and Demo highlight from the engine's precomputed output. Code the browser produces, such as an edited demo, needs the engine's client parser: put CodeProviderLazy from @fairgarden/docs/CodeProvider in the root layout, as this site does. It loads the parser, the grammars and the transform tools only when a block needs them.
The prose prints black on white: headings stay with what follows, tables and callouts never split, and a callout drops its fill and keeps its edge.
API Reference
createDemoFactory
The engine’s createDemoFactory with the design system’s defaults
(DemoContent: DemoLazy, DemoContentLoading: DemoLoading, DemoTitle,
projectDir / projectUrl from SOURCE_CODE_ROOT_DIR /
SOURCE_CODE_ROOT_URL); options override any. highlightAfter is left
to the engine’s default ('idle'); pass 'init' only where a demo shows
server-side highlighting.
| Parameter | Type | Description |
|---|---|---|
options | |
__typecreateDemoWithVariantsFactory
As createDemoFactory, over the engine’s createDemoWithVariantsFactory,
with fallbackUsesAllVariants: true: the loading state gets every
variant, so it draws the variant Select (nothing shifts at the swap) and
every variant’s #slug targets.
| Parameter | Type | Description |
|---|---|---|
options | |
__typecreateTypesFactory
The engine’s createTypesFactory with TypesTable and TypePre; options override either.
| Parameter | Type | Description |
|---|---|---|
options | |
__typecreateMultipleTypesFactory
As createTypesFactory, over the engine’s createMultipleTypesFactory.
| Parameter | Type | Description |
|---|---|---|
options | |
__typecreateMdxComponents
The MDX component map: pre (the Code Block, through CodeHighlighter),
code (inline code in the syntax tiers), h1–h4 (h2–h4 link to
themselves), p, a (the design system’s Link), ul, ol, table,
blockquote, hr, and img when an Image is given. Use it as the
return of your useMDXComponents, and as the types factories’
components.
| Property | Type | Description |
|---|---|---|
Link | | Renders links to internal paths ( |
Image | | Renders |
Content | | Fenced blocks’ CodeHighlighter |
ContentLoading | | Fenced blocks’ CodeHighlighter |
highlightAfter | | When fenced blocks highlight. Default: the engine’s own ( |
sourceEnhancers | | The source enhancers the server runs on fenced blocks’ code. Default
|
components | | More components, or replacements for any of the map’s, merged last. |
MdxComponentsDemoTitle
The heading the demo factories render for <DemoX.Title />: an H3 in
type-subhead that links to itself, so a demo can be linked by its slug.
| Prop | Type | Description |
|---|---|---|
slug | | |
children | |
Pre
The MDX pre override, as fg-docs’ own Pre: the docs pipeline
(transformHtmlCodeBlock) replaces every fenced code block with
<pre data-precompute=…>, which only CodeHighlighter can render. Each
renders as a Code Block, code-split, with its loading state until the
chunk loads, and its emphasis window in the server HTML. A fence’s flags
(```tsx collapse) arrive in data-content-props.
| Prop | Type | Description |
|---|---|---|
Content | | CodeHighlighter’s |
ContentLoading | | CodeHighlighter’s |
data-content-props | | |
data-name | | |
data-precompute | | |
data-slug | | |
highlightAfter | | When the code highlights. Default: the engine’s own ( |
sourceEnhancers | | The source enhancers the server runs on code it parses. Default
|
toSidebarItems and sitemapHref
The sitemap’s sections, in sitemap order, as SidebarNav groups: each section’s title over its pages, in the section index’s order, the heading linking to the section’s index page. Pages without a title use their slug.
| Parameter | Type | Description |
|---|---|---|
sitemap | | |
options | |
SidebarNavItem[]A sitemap page’s route: its path (./button/page.mdx) under its
section’s prefix (/actions/), without page.mdx or a trailing slash
(/actions/button); the section itself with no path (/actions).
| Parameter | Type | Description |
|---|---|---|
prefix | | |
path | Default: "" |
stringAdditional types
createDemo
Creates a demo: the component rendered above its highlighted source.
type createDemo = createDemoCreateDemo
What createDemoFactory returns: createDemo(url, component, meta?).
type CreateDemo = ReturnTypecreateDemoWithVariants
As createDemo, with switchable variants of the same demo.
type createDemoWithVariants = createDemoWithVariantsCreateDemoWithVariants
What createDemoWithVariantsFactory returns: createDemoWithVariants(url, variants, meta?).
type CreateDemoWithVariants = ReturnTypeCreateMdxComponentsOptions
Options for createMdxComponents. Every one is optional.
type CreateMdxComponentsOptions = {
/**
* Renders links to internal paths (`/…`), such as next/link, as the
* design system's Link's element. Default: a plain `a`.
*/
Link?: MdxLinkComponent;
/** Renders `img`, such as next/image. Default: the plain element. */
Image?: React.ElementType<
ElementProps<'img'>,
| 'symbol'
| 'object'
| 'a'
| 'abbr'
| 'address'
| 'area'
| 'article'
| 'aside'
| 'audio'
| 'b'
| 'base'
| 'bdi'
| 'bdo'
| 'big'
| 'blockquote'
| 'body'
| 'br'
| 'button'
| 'canvas'
| 'caption'
| 'center'
| 'cite'
| 'code'
| 'col'
| 'colgroup'
| 'data'
| 'datalist'
| 'dd'
| 'del'
| 'details'
| 'dfn'
| 'dialog'
| 'div'
| 'dl'
| 'dt'
| 'em'
| 'embed'
| 'fieldset'
| 'figcaption'
| 'figure'
| 'footer'
| 'form'
| 'h1'
| 'h2'
| 'h3'
| 'h4'
| 'h5'
| 'h6'
| 'head'
| 'header'
| 'hgroup'
| 'hr'
| 'html'
| 'i'
| 'iframe'
| 'img'
| 'input'
| 'ins'
| 'kbd'
| 'keygen'
| 'label'
| 'legend'
| 'li'
| 'link'
| 'main'
| 'map'
| 'mark'
| 'menu'
| 'menuitem'
| 'meta'
| 'meter'
| 'nav'
| 'noindex'
| 'noscript'
| 'ol'
| 'optgroup'
| 'option'
| 'output'
| 'p'
| 'param'
| 'picture'
| 'pre'
| 'progress'
| 'q'
| 'rp'
| 'rt'
| 'ruby'
| 's'
| 'samp'
| 'search'
| 'slot'
| 'script'
| 'section'
| 'select'
| 'small'
| 'source'
| 'span'
| 'strong'
| 'style'
| 'sub'
| 'summary'
| 'sup'
| 'table'
| 'template'
| 'tbody'
| 'td'
| 'textarea'
| 'tfoot'
| 'th'
| 'thead'
| 'time'
| 'title'
| 'tr'
| 'track'
| 'u'
| 'ul'
| 'var'
| 'video'
| 'wbr'
| 'webview'
| 'svg'
| 'animate'
| 'animateMotion'
| 'animateTransform'
| 'circle'
| 'clipPath'
| 'defs'
| 'desc'
| 'ellipse'
| 'feBlend'
| 'feColorMatrix'
| 'feComponentTransfer'
| 'feComposite'
| 'feConvolveMatrix'
| 'feDiffuseLighting'
| 'feDisplacementMap'
| 'feDistantLight'
| 'feDropShadow'
| 'feFlood'
| 'feFuncA'
| 'feFuncB'
| 'feFuncG'
| 'feFuncR'
| 'feGaussianBlur'
| 'feImage'
| 'feMerge'
| 'feMergeNode'
| 'feMorphology'
| 'feOffset'
| 'fePointLight'
| 'feSpecularLighting'
| 'feSpotLight'
| 'feTile'
| 'feTurbulence'
| 'filter'
| 'foreignObject'
| 'g'
| 'image'
| 'line'
| 'linearGradient'
| 'marker'
| 'mask'
| 'metadata'
| 'mpath'
| 'path'
| 'pattern'
| 'polygon'
| 'polyline'
| 'radialGradient'
| 'rect'
| 'set'
| 'stop'
| 'switch'
| 'text'
| 'textPath'
| 'tspan'
| 'use'
| 'view'
>;
/** Fenced blocks' CodeHighlighter `Content`. Default: `CodeBlockLazy`. */
Content?: React.ComponentType<ContentProps<{}>>;
/** Fenced blocks' CodeHighlighter `ContentLoading`. Default: `CodeBlockLoading`. */
ContentLoading?: React.ComponentType<ContentLoadingProps<{}>>;
/**
* When fenced blocks highlight. Default: the engine's own (`'idle'`). Pass
* `'init'` only to show server-side highlighting, which costs server work
* and page weight.
*/
highlightAfter?: 'init' | 'stream' | 'hydration' | 'idle';
/**
* The source enhancers the server runs on fenced blocks' code. Default
* `serverSourceEnhancers`: the engine's emphasis enhancer with the options
* demos get, so every block's emphasis window is in the first paint and
* nothing changes size after hydration [D201]. Pass the enhancers your
* `demoEmphasisOptions` make, if you set them, or `[]` to run none.
*/
sourceEnhancers?: SourceEnhancer[];
/** More components, or replacements for any of the map's, merged last. */
components?: Record<string, React.ElementType>;
}createMultipleTypes
API tables for several related exports, rendered as <TypesX.Part />.
type createMultipleTypes = createMultipleTypesCreateMultipleTypes
What createMultipleTypesFactory returns: createMultipleTypes(url, components, meta?).
type CreateMultipleTypes = ReturnTypecreateTypes
The API table for one export, extracted from TypeScript at build time.
type createTypes = createTypesCreateTypes
What createTypesFactory returns: createTypes(url, component, meta?).
type CreateTypes = ReturnTypeDemoFactoryOptions
The engine’s demo factory options (createDemoFactory from @fairgarden/docs/abstractCreateDemo).
type DemoFactoryOptions<T extends {} = CodeBlockOptions> = AbstractCreateDemoOptions<T>DemoTitleProps
Props the demo factories hand their DemoTitle.
type DemoTitleProps = { slug?: string; children?: string }MdxComponents
The map createMdxComponents returns.
type MdxComponents = { [key: string]: React.ElementType }MdxLinkComponent
A link component for internal hrefs, such as next/link.
type MdxLinkComponent = React.ComponentType<{
href: string;
children?: React.ReactNode;
className?: string;
}>PreProps
What the docs pipeline puts on a fenced block’s pre, plus the slots.
type PreProps = {
'data-name'?: string;
'data-slug'?: string;
'data-precompute'?: string;
'data-content-props'?: string;
/** CodeHighlighter's `Content`. Default: `CodeBlockLazy`. */
Content?: React.ComponentType<ContentProps<{}>>;
/** CodeHighlighter's `ContentLoading`. Default: `CodeBlockLoading`. */
ContentLoading?: React.ComponentType<ContentLoadingProps<{}>>;
/**
* When the code highlights. Default: the engine's own (`'idle'`: the server
* HTML carries the plain code, highlighted once the browser is idle). Pass
* `'init'` only to show server-side highlighting: the HTML then arrives
* highlighted, at the cost of server work and page weight.
*/
highlightAfter?: 'init' | 'stream' | 'hydration' | 'idle';
/**
* The source enhancers the server runs on code it parses. Default
* `serverSourceEnhancers` (the engine's emphasis enhancer, with the
* options demos get), so the emphasis window is in the server HTML and
* nothing changes size after hydration [D201]. A fence the build
* precomputed already carries its window; this covers any code the server
* still parses. Pass `[]` to run none.
*/
sourceEnhancers?: SourceEnhancer[];
}serverSourceEnhancers
The source enhancers CodeHighlighter runs on the server: the engine’s
emphasis enhancer (enhanceCodeEmphasis) with its default options. Pass
it as CodeHighlighter’s sourceEnhancers wherever a page renders code
the build didn’t precompute, such as inline code or a string child;
Pre and createMdxComponents default to it.
On the server it frames the code and records its name on the tree, so
the HTML arrives with the emphasis frames and the collapsed window, the
loading state paints the same lines as the loaded block, and
CodeProviderLazy’s own emphasis enhancer, which has the same name,
skips the tree instead of windowing it after hydration. Nothing changes
size once the page is interactive, and hydration never depends on which
side has loaded the lazy enhancer. Highlighting stays at the engine’s
default highlightAfter.
The options are the ones demos get from the build and
CodeProviderLazy loads: the enhancer’s defaults, which
withFairGardenDocs uses when it has no demoEmphasisOptions. An app
that sets demoEmphasisOptions passes
[createEnhanceCodeEmphasis(sameOptions)] instead, so inline code and
demos window alike.
type serverSourceEnhancers = SourceEnhancer[]ToSidebarItemsOptions
TypesFactoryOptions
The engine’s types factory options (@fairgarden/docs/abstractCreateTypes).
type TypesFactoryOptions = AbstractCreateTypesOptions