MUI Docs Infra

Warning

This is an internal project, and is not intended for public use. No support or stability guarantees are provided.

Code Highlighter

The CodeHighlighter component provides a powerful and flexible way to display interactive code examples with syntax highlighting, multiple variants, and live previews. It supports both static code blocks and interactive demos with component previews.

The component uses the Props Context Layering pattern to work seamlessly across server and client boundaries, allowing progressive enhancement from static code to interactive demos.

Features

  • Syntax highlighting with support for multiple languages using Starry Night
  • Live component previews alongside code
  • Multiple Variant support for showing different implementation styles
  • Automatic Transformations from TypeScript to JavaScript
  • Lazy loading with fallback content
  • Lazy syntax highlighting for performance optimization
  • Customizable content renderers
  • Hybrid rendering support for build, server, or client-time loading, parsing, and transforming
  • Webpack integration for build-time pre-computation

Basic Usage

Let's start with the fundamentals. CodeHighlighter can display simple code blocks with syntax highlighting, perfect for documentation where you just need to show code examples:

Simple Code Block

We can use it to highlight code snippets in various languages, like JavaScript, TypeScript, or even CSS.

hello.js
console.log('Hello, world!');
import * as React from 'react';
import { Code } from './CodeBlock';

export function BasicCode() {
  return <Code fileName="hello.js">{`console.log('Hello, world!');`}</Code>;
}

But CodeHighlighter really shines when you want to combine working React components with their source code. This creates an interactive experience where users can see both the rendered output and the implementation.

Interactive Demo

CheckboxBasic.tsx
import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';

export function CheckboxBasic() {
  return <Checkbox defaultChecked />;
}
import { CheckboxBasic } from './CheckboxBasic';
import { createDemo } from './createDemo';

export const DemoCheckboxBasic = createDemo(import.meta.url, CheckboxBasic);

Demo Factory Pattern

Tip

New to the overall approach? See the broader Built Factories Pattern for why factories use import.meta.url, how variants are derived, and the server vs client split.

Note

Before you can use createDemo() in your demos, you must first create this factory function in your repo (see the abstractCreateDemo docs for details).

To unlock CodeHighlighter's full potential—especially build-time optimization—you'll need to use the factory pattern. This isn't just a convention; it's required for precomputation to work.

The factory pattern uses createDemo() to structure your demos in a way that the webpack loader can process and cache at build time. You implement createDemo within your app using abstractCreateDemo to define the structure and behavior of your demos.

Factory Structure

All demos must use this structure in an index.ts file:

// app/components/checkbox/demos/basic/index.ts
import { createDemo } from '../createDemo';
import { Checkbox } from './Checkbox';

export const DemoCheckboxBasic = createDemo(import.meta.url, Checkbox);

For multiple variants:

// app/components/checkbox/demos/basic/index.ts
import { createDemoWithVariants } from '../createDemo';
import { Checkbox as CssModules } from './css-modules/Checkbox';
import { Checkbox as Tailwind } from './tailwind/Checkbox';

export const DemoCheckboxBasic = createDemoWithVariants(import.meta.url, { CssModules, Tailwind });

Demo File Structure

When using the factory pattern with precomputation, organize your demo files like this:

app/components/checkbox/demos/
  basic/
    index.ts             # Factory file (processed by webpack loader)
    Checkbox.tsx         # Component implementation
    Checkbox.module.css  # Dependencies (auto-loaded)

This follows Next.js' file based routing conventions, similar to how app/components/checkbox/page.tsx is built as a "page", app/components/checkbox/demos/basic/index.ts is built as a "demo".

This also allows demo components to follow internal naming conventions, like CheckboxBasic.tsx that has a named export of CheckboxBasic, while the demo itself can be loaded by importing ./demos/basic (without needing to specify the index file).

It allows imports to remain the same when variants are added, e.g. import { DemoCheckboxBasic } from './demos/basic' will still work even if the demo is split into multiple variants.

app/components/checkbox/demos/
  basic/
    index.ts               # Factory file (processed by webpack loader)
    tailwind/
      index.ts             # Simple re-export of the implementation (optional)
      Checkbox.tsx         # Component implementation
    css-modules/
      index.ts             # Simple re-export of the implementation (optional)
      Checkbox.tsx         # Component implementation
      Checkbox.module.css  # Dependencies (auto-loaded)

Webpack Loader Integration

The precomputation is handled by a webpack loader that processes demo files at build time, enabling caching by the contents of the demo index file and all of its dependencies.

Note

For detailed information about the webpack loader implementation, configuration, and advanced usage, see the Precompute Loader Documentation.

Tip

Client-Side Implementation: For client-side loading, highlighting, and transforms, see the Code Provider Documentation which provides detailed examples of runtime processing.

Important: Precomputation only works:

  • ✓ In files matching the webpack loader pattern (default: ./app/**/demos/*/index.ts)
  • ✓ Using createDemo()
  • ✓ In both main demos and nested demo examples
  • × Not in direct CodeHighlighter usage
  • × Not in files outside the configured loader pattern

Advanced Features

Once you've mastered the basics, CodeHighlighter offers several powerful features for more sophisticated use cases.

Demo Variants

Sometimes you want to show different approaches to the same problem: CSS Modules versus Tailwind, Hooks or Blocks pattern, or different implementation strategies. CodeHighlighter makes this seamless with variant switching. Your components can even appear differently, but we recommend keeping them as similar as possible to avoid confusion.

import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';

import styles from './CheckboxRed.module.css';

export function CheckboxRed() {
  return <Checkbox defaultChecked className={styles.root} />;
}
import { CheckboxRed as CssModules } from './css-modules/CheckboxRed';
import { CheckboxRed as Tailwind } from './tailwind/CheckboxRed';
import { createDemoWithVariants } from './createDemo';

export const DemoCheckboxRed = createDemoWithVariants(import.meta.url, { CssModules, Tailwind });

Code Transformed

One of CodeHighlighter's most powerful features is automatic code transformation. Write your examples in TypeScript, and users can instantly see the JavaScript equivalent:

example.ts
const x: number = 1;
interface Props { name: string; }
import * as React from 'react';
import { Code } from './Code';

export function BasicCode() {
  return (
    <Code fileName="example.ts">{`const x: number = 1;\ninterface Props { name: string; }`}</Code>
  );
}

Code Highlight Idle

For pages with many code examples, you can defer syntax highlighting until the browser is idle, keeping your initial page loads fast:

hello.js
console.log('Hello, world!');
import * as React from 'react';
import { Code } from './Code';

export function BasicCode() {
  return <Code fileName="hello.js">{`console.log('Hello, world!');`}</Code>;
}

Demo Fallback

Good user experience means showing meaningful feedback during loading. The fallback content is also what search engines and AI bots see in the initial HTML, making it crucial for SEO and content discovery. CodeHighlighter supports custom loading components and skeleton loaders:

import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';
import styles from './CheckboxRed.module.css';

export function CheckboxRed() {
  return <Checkbox className={styles.root} defaultChecked />;
}
import { CheckboxRed } from './CheckboxRed';
import { createDemo } from './createDemo';

export const DemoCheckboxRed = createDemo(import.meta.url, CheckboxRed);

Demo Fallback All Files

When fallbackUsesExtraFiles is enabled, the fallback content receives all extra files from the selected variant. This means search engines and AI bots will see all the component's related files (CSS, utilities, etc.) in the initial HTML, improving content discoverability. Note that the complete list of filenames is always available for navigation, regardless of this setting:

import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';
import styles from './CheckboxRed.module.css';

export function CheckboxRed() {
  return <Checkbox className={styles.root} defaultChecked />;
}
.root {
  background-color: #e5484d !important;
  border-color: #e5484d !important;
}
import { CheckboxRed } from './CheckboxRed';
import { createDemo } from './createDemo';

export const DemoCheckboxRed = createDemo(import.meta.url, CheckboxRed);

Demo Fallback All Variants

When fallbackUsesAllVariants is enabled, the fallback content receives data for all available variants. This ensures that search engines and AI bots can see all implementation approaches (CSS Modules, Tailwind, etc.) in the initial HTML, making your documentation more comprehensive for automated indexing. Note that the complete list of filenames is always available for navigation, regardless of this setting:

import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';

import styles from './CheckboxRed.module.css';

export function CheckboxRed() {
  return <Checkbox defaultChecked className={styles.root} />;
}
.root {
  background-color: #e5484d !important;
  border-color: #e5484d !important;
}
Tailwind
import { CheckboxRed as CssModules } from './css-modules/CheckboxRed';
import { CheckboxRed as Tailwind } from './tailwind/CheckboxRed';
import { createDemoWithVariants } from './createDemo';

export const DemoCheckboxRed = createDemoWithVariants(import.meta.url, { CssModules, Tailwind });
import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';

import styles from './CheckboxRed.module.css';

export function CheckboxRed() {
  return <Checkbox defaultChecked className={styles.root} />;
}
import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';

export function CheckboxRed() {
  return <Checkbox defaultChecked className="bg-red-500" />;
}
import 'server-only';

import {
  createDemoFactory,
  createDemoWithVariantsFactory,
} from '@mui/internal-docs-infra/abstractCreateDemo';

import { DemoContentLoading } from './DemoContentLoading';
import { DemoContent } from './DemoContent';

/**
 * Creates a demo component for displaying code examples with syntax highlighting.
 * @param url Depends on `import.meta.url` to determine the source file location.
 * @param component The component to be rendered in the demo.
 * @param meta Additional meta for the demo.
 */
export const createDemo = createDemoFactory({
  DemoContentLoading,
  DemoContent,
  fallbackUsesAllVariants: true,
});

/**
 * Creates a demo component for displaying code examples with syntax highlighting.
 * A variant is a different implementation style of the same component.
 * @param url Depends on `import.meta.url` to determine the source file location.
 * @param variants The variants of the component to be rendered in the demo.
 * @param meta Additional meta for the demo.
 */
export const createDemoWithVariants = createDemoWithVariantsFactory({
  DemoContentLoading,
  DemoContent,
  fallbackUsesAllVariants: true,
});
.root {
  background-color: #e5484d !important;
  border-color: #e5484d !important;
}
'use client';

import * as React from 'react';
import type { ContentLoadingProps } from '@mui/internal-docs-infra/CodeHighlighter/types';
import { Tabs } from '@/components/Tabs';
import { Select } from '@/components/Select';
import styles from './DemoContent.module.css';
import loadingStyles from './DemoContentLoading.module.css';

import '@wooorm/starry-night/style/light';

const variantNames: Record<string, string | undefined> = {
  CssModules: 'CSS Modules',
};

export function DemoContentLoading(props: ContentLoadingProps<object>) {
  const tabs = React.useMemo(
    () =>
      props.fileNames?.map((name) => ({
        id: name || '',
        name: name || '',
        slug: name,
      })),
    [props.fileNames],
  );
  const variants = React.useMemo(
    () =>
      Object.keys(props.components || {}).map((variant) => ({
        value: variant,
        label: variantNames[variant] || variant,
      })),
    [props.components],
  );

  const onTabSelect = React.useCallback(() => {
    // Handle tab selection
  }, []);

  return (
    <div>
      {Object.keys(props.extraSource || {}).map((slug) => (
        <span key={slug} id={slug} className={styles.fileRefs} />
      ))}
      <div className={styles.container}>
        <div className={styles.demoSection}>{props.component}</div>
        <div className={styles.codeSection}>
          <div className={styles.header}>
            <div className={styles.headerContainer}>
              {tabs && (
                <div className={styles.tabContainer}>
                  <Tabs
                    tabs={tabs}
                    selectedTabId={props.fileNames?.[0]}
                    onTabSelect={onTabSelect}
                    disabled={true}
                  />
                </div>
              )}
              <div className={styles.headerActions}>
                {Object.keys(props.extraVariants || {}).length >= 1 && (
                  <Select items={variants} value={variants[0]?.value} disabled={true} />
                )}
              </div>
            </div>
          </div>
          <div className={styles.code}>
            <pre className={styles.codeBlock}>{props.source}</pre>
          </div>
          <div className={loadingStyles.extraFiles}>
            {Object.keys(props.extraSource || {}).map((slug) => (
              <pre key={slug}>{props.extraSource?.[slug]}</pre>
            ))}
          </div>
          <div className={loadingStyles.extraVariants}>
            {Object.keys(props.extraVariants || {}).map((slug) => (
              <div key={slug} className={loadingStyles.extraVariant}>
                <span>{slug}</span>
                <pre>
                  {Object.keys(props.extraVariants?.[slug].extraSource || {}).map((key) => (
                    <div key={key}>
                      <strong>{key}:</strong> {props.extraVariants?.[slug]?.extraSource?.[key]}
                    </div>
                  ))}
                </pre>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
'use client';

import * as React from 'react';
import type { ContentProps } from '@mui/internal-docs-infra/CodeHighlighter/types';
import { useDemo } from '@mui/internal-docs-infra/useDemo';
import { LabeledSwitch } from '@/components/LabeledSwitch';
import { Tabs } from '@/components/Tabs';
import { CopyButton } from '@/components/CopyButton';
import { Select } from '@/components/Select';
import styles from './DemoContent.module.css';

import '@wooorm/starry-night/style/light';

const variantNames: Record<string, string | undefined> = {
  CssModules: 'CSS Modules',
};

export function DemoContent(props: ContentProps<object>) {
  const demo = useDemo(props, { preClassName: styles.codeBlock });

  const hasJsTransform = demo.availableTransforms.includes('js');
  const isJsSelected = demo.selectedTransform === 'js';

  const labels = { false: 'TS', true: 'JS' };
  const toggleJs = React.useCallback(
    (checked: boolean) => {
      demo.selectTransform(checked ? 'js' : null);
    },
    [demo],
  );

  const tabs = React.useMemo(
    () => demo.files.map(({ name, slug }) => ({ id: name, name, slug })),
    [demo.files],
  );
  const variants = React.useMemo(
    () =>
      demo.variants.map((variant) => ({ value: variant, label: variantNames[variant] || variant })),
    [demo.variants],
  );

  return (
    <div>
      {demo.allFilesSlugs.map(({ slug }) => (
        <span key={slug} id={slug} className={styles.fileRefs} />
      ))}
      <div className={styles.container}>
        <div className={styles.demoSection}>{demo.component}</div>
        <div className={styles.codeSection}>
          <div className={styles.header}>
            <div className={styles.headerContainer}>
              <div className={styles.tabContainer}>
                <Tabs
                  tabs={tabs}
                  selectedTabId={demo.selectedFileName}
                  onTabSelect={demo.selectFileName}
                />
              </div>
              <div className={styles.headerActions}>
                <CopyButton copy={demo.copy} />
                {demo.variants.length > 1 && (
                  <Select
                    items={variants}
                    value={demo.selectedVariant}
                    onValueChange={demo.selectVariant}
                  />
                )}
                {hasJsTransform && (
                  <div className={styles.switchContainer}>
                    <LabeledSwitch
                      checked={isJsSelected}
                      onCheckedChange={toggleJs}
                      labels={labels}
                    />
                  </div>
                )}
              </div>
            </div>
          </div>
          <div className={styles.code}>{demo.selectedFile}</div>
        </div>
      </div>
    </div>
  );
}
.container {
  border: 1px solid #d0cdd7;
  border-radius: 8px;
}

.demoSection {
  padding: 24px;
  border-radius: 7px 7px 0 0;
}

.codeSection {
  border-top: 1px solid #d0cdd7;
}

.header {
  border-bottom: 1px solid #d0cdd7;
  height: 48px;
  position: relative;
}

.headerContainer {
  position: absolute;
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.headerContainer::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 1px;
  margin: -1px;
  background-color: #d0cdd7;
}

.headerActions {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-right: 8px;
  height: 48px;
}

.tabContainer {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: -1px;
  padding-bottom: 2px;
  overflow-x: auto;
}

.switchContainer {
  display: flex;
}

.switchContainerHidden {
  display: none;
}

.code {
  padding: 10px 6px;
}

.codeBlock {
  margin: 0;
  padding: 6px;
  overflow-x: auto;
}

.codeBlock :global(.frame[data-lined]) {
  display: block;
  white-space: normal;
}

.codeBlock :global(.frame[data-lined] .line) {
  display: block;
  white-space: pre;
}

.codeBlock :global(.line[data-hl]) {
  background: #ebe4ff;
  margin: 0 -6px;
  padding: 0 6px;
}

.codeBlock :global(:not(.line)[data-hl]) {
  background: #e1d9ff;
  border-radius: 4px;
}

.codeBlock :global(.line[data-hl='strong']) {
  background: #e1d9ff;
  margin: 0 -6px;
  padding: 0 6px;
}

.codeBlock :global(.line[data-hl='strong'][data-hl-position='end']) {
  position: relative;
}

.codeBlock :global(.line[data-hl-position='single']) {
  border-radius: 8px;
}

.codeBlock :global(.line[data-hl-position='start']) {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.codeBlock :global(.line[data-hl-position='end']) {
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.codeBlock :global(.line[data-hl]:has(+ .line[data-hl='strong'][data-hl-position='start'])) {
  margin-bottom: -8px;
  padding-bottom: 8px;
}

.codeBlock :global(.line[data-hl='strong'][data-hl-position='end']) + :global(.line[data-hl]) {
  margin-top: -8px;
  padding-top: 8px;
}

.codeBlock :global(.line[data-hl-description])::after {
  content: attr(data-hl-description);
  float: right;
  background: #8145b5;
  border-radius: 8px;
  color: white;
  padding: 2px 4px;
  margin-right: -6px;
}
.extraFiles {
  display: none;
}

.extraVariants {
  display: none;
}

Demo Server Loaded

For more dynamic use cases, you can load code content from external sources or APIs at runtime:

Note

This example uses React Server Components (RSC) to load and parse files at request time instead of relying on the webpack loader for build-time precomputation. This approach is recommended when rendering based on dynamic routes (like app/components/[component].tsx) where the content isn't known at build time. In these scenarios, you'd typically use the <CodeHighlighter> component directly rather than the factory pattern with createDemo().

CheckboxBasic.tsx
import * as React from 'react';
import { Checkbox } from '@/components/Checkbox';

export function CheckboxBasic() {
  return <Checkbox defaultChecked />;
}
import { createDemo } from './createDemo';
import { CheckboxBasic } from './CheckboxBasic';

export const DemoCheckboxBasic = createDemo(import.meta.url, CheckboxBasic, {
  skipPrecompute: true,
});

Client-Side Rendering

CodeHighlighter can also be used on the client side, allowing you to load and parse code dynamically without server-side rendering. This is useful for applications that fetch code from APIs or databases.

You can do so by using the CodeProvider component, which provides the necessary context for CodeHighlighter to function correctly on the client.

Controlled Code Scenarios

CodeHighlighter also supports controlled scenarios where you need to manage code state externally. This is useful for interactive demos where code changes affect other parts of your application or when you need to synchronize code across multiple components.

You can use the CodeControllerContext for this purpose, which provides a controlled environment for managing code state in interactive scenarios.

Authoring Recommendations

Component Name

Demos are exported as Demo${componentName}${demoName} e.g. DemoCheckboxBasic This makes it easy to import a demo by simply typing <DemoCheckbox, and your IDE should display a list of existing demos to auto-import.

Demo Titles

We recommend exporting a Title component attached within your createDemo() factory. This allows us to use an automatically generated title and slug from the URL of the demo index. This ensures that the link for the title is consistent with links to files within the demo itself.

e.g. ./app/components/checkbox/demos/advanced-keyboard/index.ts would generate a title of Advanced Keyboard and a slug of advanced-keyboard. The URL for this demo would be /components/checkbox#advanced-keyboard and a file within it could be /components/checkbox#advanced-keyboard:file.ts.

Also, when MDX is rendered in GitHub, <DemoCheckboxAdvancedKeyboard.Title /> will be visible on the page because it contains the dot. The import is also visible, so readers on GitHub will see this in the place of a demo:

import { DemoCheckboxAdvancedKeyboard } from './demos/advanced-keyboard';

<DemoCheckboxAdvancedKeyboard.Title />

Description of the demo.

If this convention isn't followed, URLs might deviate e.g. /components/checkbox#advanced-keyboard might not link to the correct demo.

// This is not recommended
import { DemoCheckboxAdvancedKeyboard } from './demos/advanced-keyboard'

### An Advanced Keyboard Demo

Description of the demo.

<DemoCheckboxAdvancedKeyboard />

This would result in the URL becoming /components/checkbox#an-advanced-keyboard-demo, and the file URL being /components/checkbox#advanced-keyboard:file.ts, which is not expected.

Descriptions

The description should be a short, concise explanation of what the demo does or why it shows a useful case. It is located directly in the component's docs because it can have rich contents like links, images, or other components. Try to avoid referring directly to the demo itself as when viewing the raw markdown, users won't see the code or renderings from the demo. Ideally, the reader can picture the demo in their mind without needing to see it.

Include a "See Demo" link after each demo component to allow users to navigate directly to the demo's source directory. This is especially useful when viewing the documentation in markdown editors or GitHub, where users can click the link to browse the demo files.

The link should point to the demo's directory using a relative path:

<DemoCheckboxBasic />

[See Demo](./demos/basic/)

This pattern makes it easy for developers to explore the demo's implementation, understand the file structure, and reference the source code when building their own components.

Separators

Use horizontal rules (---) to separate different sections of the demo. This allows the description of the previous demo to be visually distinct from the next demo.

import { DemoCheckboxBasic } from './demos/basic';

<DemoCheckboxBasic.Title />

Description of the basic demo.

<DemoCheckboxBasic />

[See Demo](./demos/basic/)

---

import { DemoCheckboxAdvanced } from './demos/second-demo';

<DemoCheckboxAdvanced.Title />

Description of the second demo.

<DemoCheckboxAdvanced />

[See Demo](./demos/second-demo/)

Within GitHub, it will display like this without rendering the demo and with See Demo underlined:

import { DemoCheckboxBasic } from './demos/basic';

<DemoCheckboxBasic.Title />

Description of the basic demo.

See Demo

---

import { DemoCheckboxAdvanced } from './demos/advanced';

<DemoCheckboxAdvanced.Title />

Description of the advanced demo.

See Demo

Tip

For Documentation Tooling: If you're building tooling to render these demos in a web interface, you can use a remark plugin to automatically remove the "See Demo" links and horizontal rule separators (---) from the rendered output, since the interactive demos provide their own navigation. See the transformMarkdownMetaLinks plugin documentation for implementation details.

Benchmarking

For performance benchmarks of the CodeHighlighter component, see the Benchmarking Code Highlighter page.

Build-Time vs Server Rendering vs Client Rendering

Note

The CodeControllerContext works with all three rendering methods.

When rendering a code block, the user should consider the following options based on their use case:

Use the factory pattern optimal performance:

Advantages:

  • ✓ Faster initial load times
  • ✓ Isomorphic rendering support
  • ✓ Automatic caching based on dependencies for each demo

Requirements:

  • Must use createDemo() in index.ts files
  • Must be in a demo directory structure

Server Rendering

Use direct CodeHighlighter for dynamic content:

Advantages:

  • ✓ Works with dynamic content
  • ✓ Flexible component structure
  • ✓ Can still benefit from the page level cache

Trade-offs:

  • × Slower initial rendering
  • × No per-demo build-time cache
  • × Can only be used within a Server Component

Client Rendering

Use CodeHighlighter on the client with CodeProvider:

Advantages:

  • ✓ Works with dynamic content fetched on the client
  • ✓ Doesn't require an API or server-side rendering
  • ✓ Can be used anywhere in the app
  • ✓ Flexible component structure

Trade-offs:

  • × Slower initial rendering
  • × Requires loading and highlighting functions to be bundled
  • x No automatic caching

Best Practices

  1. Use precompute for static content - Enables a per-demo cache for faster builds
  2. Implement proper loading states - Provide ContentLoading for quicker hydration
  3. Handle errors gracefully - Use ErrorHandler to display meaningful error messages
  4. Optimize highlight timing - Use highlightAfter: 'idle' for non-critical code blocks
  5. Group related variants - Keep related code variations together

Troubleshooting

Common Issues

Code not highlighting:

  • Ensure sourceParser is provided
  • Check that the code variant exists
  • Verify highlightAfter timing is appropriate

Loading states not showing:

  • Provide ContentLoading component
  • Use highlightAfter: 'stream' for loading states
  • Check fallbackUsesExtraFiles settings

Performance issues:

  • Use demo factory pattern for build-time optimization
  • Consider highlightAfter: 'idle' for non-critical code
  • Implement proper error boundaries
  • Remember: precomputation only works with createDemo() in index.ts files

Precomputation not working:

  • Ensure you're using createDemo() in an index.ts file
  • Verify the file is in the correct path pattern: './app/**/demos/*/index.ts'
  • Make sure the webpack loader is configured correctly

Variants not switching:

  • Verify variant names match between components and variants
  • Check that source transformers are configured correctly
  • Ensure controlled mode is set up properly if needed

Shape

CodeHighlighter

PropTypeDescription
name
string | undefined

Display name for the code example, used for identification and titles

Content
React.ComponentType<ContentProps<{}>>

Component to render the code content and preview

ContentLoading
| React.ComponentType<ContentLoadingProps<{}>>
| undefined

Component to show while code is being loaded or processed

code
Code | undefined

Static code content with variants and metadata

components
Components | undefined

React components for live preview alongside code

contentProps
{} | undefined

Additional props passed to the Content component

controlled
boolean | undefined

Enable controlled mode for external code state management

defaultVariant
string | undefined

Fallback variant when the requested variant is not available

deferParsing
'none' | 'json' | 'gzip' | undefined

Defer parsing and populating the AST into memory until the code is enhanced Applies only in production when RSC loading

enhanceAfter
| 'init'
| 'stream'
| 'hydration'
| 'idle'
| undefined

When to enhance the code display with interactivity

fallbackUsesAllVariants
boolean | undefined

Whether fallback content should include all variants

fallbackUsesExtraFiles
boolean | undefined

Whether fallback content should include extra files

fileName
string | undefined

Currently selected file name

forceClient
boolean | undefined

Force client-side rendering even when server rendering is available

globalsCode
(string | Code)[] | undefined

Global static code snippets to inject, typically for styling or tooling

highlightAfter
| 'init'
| 'stream'
| 'hydration'
| 'idle'
| undefined

When to perform syntax highlighting and code processing

initialVariant
string | undefined

Default variant to show on first load

language
string | undefined

Language for syntax highlighting (e.g., ‘tsx’, ‘css’). When provided, fileName is not required for parsing.

loadCodeMeta
LoadCodeMeta | undefined

Function to load code metadata from a URL

loadSource
LoadSource | undefined

Function to load raw source code and dependencies

loadVariantMeta
LoadVariantMeta | undefined

Function to load specific variant metadata

precompute
Code | undefined

Pre-computed code data from build-time optimization

slug
string | undefined

URL-friendly identifier for deep linking and navigation

sourceEnhancers
SourceEnhancers | undefined

Array of source enhancers that run after parsing to enhance the HAST tree

sourceParser
Promise<ParseSource> | undefined

Promise resolving to a source parser for syntax highlighting

sourceTransformers
SourceTransformers | undefined

Array of source transformers for code processing (e.g., TypeScript to JavaScript)

url
string | undefined

Source URL where the code content originates from

variant
string | undefined

Currently selected variant name

variantType
string | undefined

What type of variants are available (e.g., a type packageManager when variants npm and yarn are available)

variants
string[] | undefined

Static variant names that should be fetched at runtime

children
string | undefined

Raw code string for simple use cases

CodeHighlighter Types

These types are available by importing from @mui/internal-docs-infra/CodeHighlighter/types.

BaseContentLoadingProps
type BaseContentLoadingProps = {
  fileNames?: string[];
  source?: React.ReactNode;
  extraSource?: { [fileName: string]: React.ReactNode };
  /** Display name for the code example, used for identification and titles */
  name?: string;
  /** URL-friendly identifier for deep linking and navigation */
  slug?: string;
  /** Source URL where the code content originates from */
  url?: string;
  extraVariants?: Record<string, ContentLoadingVariant>;
}
Code
type Code = { [key: string]: string | VariantCode | undefined }
CodeClientRenderingProps

Client-specific rendering props

type CodeClientRenderingProps = {
  /** The CodeContent component that renders the code display and syntax highlighting */
  children: React.ReactNode;
  /** Loading placeholder shown while code is being processed */
  fallback?: React.ReactNode;
  /** Skip showing fallback content entirely */
  skipFallback?: boolean;
}
CodeContentProps

Core code content and variant management props

type CodeContentProps = {
  /** Static code content with variants and metadata */
  code?: Code;
  /** React components for live preview alongside code */
  components?: Components;
  /** What type of variants are available (e.g., a type `packageManager` when variants `npm` and `yarn` are available) */
  variantType?: string;
  /** Static variant names that should be fetched at runtime */
  variants?: string[];
  /** Currently selected variant name */
  variant?: string;
  /** Currently selected file name */
  fileName?: string;
  /** Language for syntax highlighting (e.g., 'tsx', 'css'). When provided, fileName is not required for parsing. */
  language?: string;
  /** Default variant to show on first load */
  initialVariant?: string;
  /** Fallback variant when the requested variant is not available */
  defaultVariant?: string;
  /** Global static code snippets to inject, typically for styling or tooling */
  globalsCode?: (string | Code)[];
}
CodeFunctionProps

Function props for loading and transforming code

type CodeFunctionProps = {
  /** Function to load code metadata from a URL */
  loadCodeMeta?: LoadCodeMeta;
  /** Function to load specific variant metadata */
  loadVariantMeta?: LoadVariantMeta;
  /** Function to load raw source code and dependencies */
  loadSource?: LoadSource;
  /** Array of source transformers for code processing (e.g., TypeScript to JavaScript) */
  sourceTransformers?: SourceTransformers;
  /** Promise resolving to a source parser for syntax highlighting */
  sourceParser?: Promise<ParseSource>;
  /** Array of source enhancers that run after parsing to enhance the HAST tree */
  sourceEnhancers?: SourceEnhancers;
}
CodeHighlighterBaseProps

Base props containing essential properties shared across CodeHighlighter components and helper functions. This serves as the foundation for other CodeHighlighter-related interfaces.

type CodeHighlighterBaseProps<T extends {}> = {
  /** Display name for the code example, used for identification and titles */
  name?: string;
  /** URL-friendly identifier for deep linking and navigation */
  slug?: string;
  /** Source URL where the code content originates from */
  url?: string;
  /** Static code content with variants and metadata */
  code?: Code;
  /** React components for live preview alongside code */
  components?: Components;
  /** What type of variants are available (e.g., a type `packageManager` when variants `npm` and `yarn` are available) */
  variantType?: string;
  /** Static variant names that should be fetched at runtime */
  variants?: string[];
  /** Currently selected variant name */
  variant?: string;
  /** Currently selected file name */
  fileName?: string;
  /** Language for syntax highlighting (e.g., 'tsx', 'css'). When provided, fileName is not required for parsing. */
  language?: string;
  /** Default variant to show on first load */
  initialVariant?: string;
  /** Fallback variant when the requested variant is not available */
  defaultVariant?: string;
  /** Global static code snippets to inject, typically for styling or tooling */
  globalsCode?: (string | Code)[];
  /** Pre-computed code data from build-time optimization */
  precompute?: Code;
  /** Whether fallback content should include extra files */
  fallbackUsesExtraFiles?: boolean;
  /** Whether fallback content should include all variants */
  fallbackUsesAllVariants?: boolean;
  /** Enable controlled mode for external code state management */
  controlled?: boolean;
  /** Raw code string for simple use cases */
  children?: string;
  /**
   * When to perform syntax highlighting and code processing
   * @default 'idle'
   */
  highlightAfter?: 'init' | 'stream' | 'hydration' | 'idle';
  /**
   * When to enhance the code display with interactivity
   * @default 'idle'
   */
  enhanceAfter?: 'init' | 'stream' | 'hydration' | 'idle';
  /** Force client-side rendering even when server rendering is available */
  forceClient?: boolean;
  /**
   * Defer parsing and populating the AST into memory until the code is enhanced
   * Applies only in production when RSC loading
   * @default 'gzip'
   */
  deferParsing?: 'none' | 'json' | 'gzip';
  /** Function to load code metadata from a URL */
  loadCodeMeta?: LoadCodeMeta;
  /** Function to load specific variant metadata */
  loadVariantMeta?: LoadVariantMeta;
  /** Function to load raw source code and dependencies */
  loadSource?: LoadSource;
  /** Array of source transformers for code processing (e.g., TypeScript to JavaScript) */
  sourceTransformers?: SourceTransformers;
  /** Promise resolving to a source parser for syntax highlighting */
  sourceParser?: Promise<ParseSource>;
  /** Array of source enhancers that run after parsing to enhance the HAST tree */
  sourceEnhancers?: SourceEnhancers;
  /** Component to render the code content and preview */
  Content: React.ComponentType<ContentProps<T>>;
  /** Additional props passed to the Content component */
  contentProps?: T;
}
CodeHighlighterClientProps

Props for the client-side CodeHighlighter component. Used when rendering happens in the browser with lazy loading and interactive features.

type CodeHighlighterClientProps = {
  /**
   * When to perform syntax highlighting for performance optimization
   * @default 'hydration'
   */
  highlightAfter?: 'init' | 'hydration' | 'idle';
  enhanceAfter?: 'init' | 'hydration' | 'idle';
  /** Display name for the code example, used for identification and titles */
  name?: string;
  /** URL-friendly identifier for deep linking and navigation */
  slug?: string;
  /** Source URL where the code content originates from */
  url?: string;
  /** Static code content with variants and metadata */
  code?: Code;
  /** React components for live preview alongside code */
  components?: Components;
  /** What type of variants are available (e.g., a type `packageManager` when variants `npm` and `yarn` are available) */
  variantType?: string;
  /** Static variant names that should be fetched at runtime */
  variants?: string[];
  /** Currently selected variant name */
  variant?: string;
  /** Currently selected file name */
  fileName?: string;
  /** Language for syntax highlighting (e.g., 'tsx', 'css'). When provided, fileName is not required for parsing. */
  language?: string;
  /** Default variant to show on first load */
  initialVariant?: string;
  /** Fallback variant when the requested variant is not available */
  defaultVariant?: string;
  /** Global static code snippets to inject, typically for styling or tooling */
  globalsCode?: (string | Code)[];
  /** Whether fallback content should include extra files */
  fallbackUsesExtraFiles?: boolean;
  /** Whether fallback content should include all variants */
  fallbackUsesAllVariants?: boolean;
  /** Pre-computed code data from build-time optimization */
  precompute?: Code;
  /** Enable controlled mode for external code state management */
  controlled?: boolean;
  /** Force client-side rendering even when server rendering is available */
  forceClient?: boolean;
  /**
   * Defer parsing and populating the AST into memory until the code is enhanced
   * Applies only in production when RSC loading
   * @default 'gzip'
   */
  deferParsing?: 'none' | 'json' | 'gzip';
  /** The CodeContent component that renders the code display and syntax highlighting */
  children: React.ReactNode;
  /** Loading placeholder shown while code is being processed */
  fallback?: React.ReactNode;
  /** Skip showing fallback content entirely */
  skipFallback?: boolean;
}
CodeHighlighterProps

Main props for the CodeHighlighter component. Supports both build-time precomputation and runtime code loading with extensive customization options. Generic type T allows for custom props to be passed to Content and ContentLoading components.

type CodeHighlighterProps<T extends {}> = {
  /** Component to show while code is being loaded or processed */
  ContentLoading?: React.ComponentType<ContentLoadingProps<T>>;
  /** Display name for the code example, used for identification and titles */
  name?: string;
  /** URL-friendly identifier for deep linking and navigation */
  slug?: string;
  /** Source URL where the code content originates from */
  url?: string;
  /** Static code content with variants and metadata */
  code?: Code;
  /** React components for live preview alongside code */
  components?: Components;
  /** What type of variants are available (e.g., a type `packageManager` when variants `npm` and `yarn` are available) */
  variantType?: string;
  /** Static variant names that should be fetched at runtime */
  variants?: string[];
  /** Currently selected variant name */
  variant?: string;
  /** Currently selected file name */
  fileName?: string;
  /** Language for syntax highlighting (e.g., 'tsx', 'css'). When provided, fileName is not required for parsing. */
  language?: string;
  /** Default variant to show on first load */
  initialVariant?: string;
  /** Fallback variant when the requested variant is not available */
  defaultVariant?: string;
  /** Global static code snippets to inject, typically for styling or tooling */
  globalsCode?: (string | Code)[];
  /** Pre-computed code data from build-time optimization */
  precompute?: Code;
  /** Whether fallback content should include extra files */
  fallbackUsesExtraFiles?: boolean;
  /** Whether fallback content should include all variants */
  fallbackUsesAllVariants?: boolean;
  /** Enable controlled mode for external code state management */
  controlled?: boolean;
  /** Raw code string for simple use cases */
  children?: string;
  /**
   * When to perform syntax highlighting and code processing
   * @default 'idle'
   */
  highlightAfter?: 'init' | 'stream' | 'hydration' | 'idle';
  /**
   * When to enhance the code display with interactivity
   * @default 'idle'
   */
  enhanceAfter?: 'init' | 'stream' | 'hydration' | 'idle';
  /** Force client-side rendering even when server rendering is available */
  forceClient?: boolean;
  /**
   * Defer parsing and populating the AST into memory until the code is enhanced
   * Applies only in production when RSC loading
   * @default 'gzip'
   */
  deferParsing?: 'none' | 'json' | 'gzip';
  /** Function to load code metadata from a URL */
  loadCodeMeta?: LoadCodeMeta;
  /** Function to load specific variant metadata */
  loadVariantMeta?: LoadVariantMeta;
  /** Function to load raw source code and dependencies */
  loadSource?: LoadSource;
  /** Array of source transformers for code processing (e.g., TypeScript to JavaScript) */
  sourceTransformers?: SourceTransformers;
  /** Promise resolving to a source parser for syntax highlighting */
  sourceParser?: Promise<ParseSource>;
  /** Array of source enhancers that run after parsing to enhance the HAST tree */
  sourceEnhancers?: SourceEnhancers;
  /** Component to render the code content and preview */
  Content: React.ComponentType<ContentProps<T>>;
  /** Additional props passed to the Content component */
  contentProps?: T;
}
CodeIdentityProps

Basic identification and metadata props for code examples

type CodeIdentityProps = {
  /** Display name for the code example, used for identification and titles */
  name?: string;
  /** URL-friendly identifier for deep linking and navigation */
  slug?: string;
  /** Source URL where the code content originates from */
  url?: string;
}
CodeLoadingProps

Loading and processing configuration props

type CodeLoadingProps = {
  /** Pre-computed code data from build-time optimization */
  precompute?: Code;
  /** Whether fallback content should include extra files */
  fallbackUsesExtraFiles?: boolean;
  /** Whether fallback content should include all variants */
  fallbackUsesAllVariants?: boolean;
  /** Enable controlled mode for external code state management */
  controlled?: boolean;
  /** Raw code string for simple use cases */
  children?: string;
  /**
   * When to perform syntax highlighting and code processing
   * @default 'idle'
   */
  highlightAfter?: 'init' | 'stream' | 'hydration' | 'idle';
  /**
   * When to enhance the code display with interactivity
   * @default 'idle'
   */
  enhanceAfter?: 'init' | 'stream' | 'hydration' | 'idle';
  /** Force client-side rendering even when server rendering is available */
  forceClient?: boolean;
  /**
   * Defer parsing and populating the AST into memory until the code is enhanced
   * Applies only in production when RSC loading
   * @default 'gzip'
   */
  deferParsing?: 'none' | 'json' | 'gzip';
}
CodeRenderingProps

Component and rendering props

type CodeRenderingProps<T extends {}> = {
  /** Component to render the code content and preview */
  Content: React.ComponentType<ContentProps<T>>;
  /** Additional props passed to the Content component */
  contentProps?: T;
}
Components
type Components = { [key: string]: React.ReactNode }
ContentLoadingProps
type ContentLoadingProps<T extends {}> = ContentLoadingVariant &
  CodeIdentityProps & { extraVariants?: Record<string, ContentLoadingVariant> } & T & {
    component: React.ReactNode;
    components?: Record<string, React.ReactNode>;
    initialFilename?: string;
  }
ContentLoadingVariant
type ContentLoadingVariant = {
  fileNames?: string[];
  source?: React.ReactNode;
  extraSource?: { [fileName: string]: React.ReactNode };
}
ContentProps
type ContentProps<T extends {}> = CodeIdentityProps &
  Pick<CodeContentProps, 'code' | 'components' | 'variantType'> &
  T
ControlledCode
type ControlledCode = { [key: string]: ControlledVariantCode | null | undefined }
ControlledVariantCode
type ControlledVariantCode = {
  /** Name of the file (e.g., 'Button.tsx') */
  fileName?: string;
  /** Language for syntax highlighting (e.g., 'tsx', 'css'). When provided, fileName is not required. */
  language?: string;
  /** Flattened path for the file */
  path?: string;
  url?: string;
  source?: string | null;
  extraFiles?: ControlledVariantExtraFiles;
  filesOrder?: string[];
}
ControlledVariantExtraFiles
type ControlledVariantExtraFiles = { [fileName: string]: { source: string | null } }
ExternalImportItem
type ExternalImportItem = {
  name: string;
  type: 'named' | 'default' | 'namespace';
  isType?: boolean;
}
Externals
type Externals = { [key: string]: ExternalImportItem[] }
HastRoot
type HastRoot = { data?: RootData & { totalLines?: number } }
LoadFallbackCodeOptions

Options for loading fallback code with various configuration flags

type LoadFallbackCodeOptions = {
  /** Flag to indicate if syntax highlighting should be performed */
  shouldHighlight?: boolean;
  /** Specific filename to initially display */
  initialFilename?: string;
  /** Array of global code to include (overrides LoadFileOptions.globalsCode with different type) */
  globalsCode?: (string | Code)[];
  /** Disable applying source transformers */
  disableTransforms?: boolean;
  /** Disable parsing source strings to AST */
  disableParsing?: boolean;
  /** Maximum recursion depth for loading nested extra files */
  maxDepth?: number;
  /** Set of already loaded file URLs to prevent circular dependencies */
  loadedFiles?: Set<string>;
  /**
   * Output format for the loaded file
   * @default 'hast'
   */
  output?: 'hast' | 'hastJson' | 'hastGzip';
  /** Function to load code metadata from a URL */
  loadCodeMeta?: LoadCodeMeta;
  /** Function to load specific variant metadata */
  loadVariantMeta?: LoadVariantMeta;
  /** Function to load raw source code and dependencies */
  loadSource?: LoadSource;
  /** Array of source transformers for code processing (e.g., TypeScript to JavaScript) */
  sourceTransformers?: SourceTransformers;
  /** Promise resolving to a source parser for syntax highlighting */
  sourceParser?: Promise<ParseSource>;
  /** Array of source enhancers that run after parsing to enhance the HAST tree */
  sourceEnhancers?: SourceEnhancers;
  /** Static variant names that should be fetched at runtime */
  variants?: string[];
  /** Whether fallback content should include extra files */
  fallbackUsesExtraFiles?: boolean;
  /** Whether fallback content should include all variants */
  fallbackUsesAllVariants?: boolean;
}
LoadFileOptions

Options for controlling file loading behavior

type LoadFileOptions = {
  /** Disable applying source transformers */
  disableTransforms?: boolean;
  /** Disable parsing source strings to AST */
  disableParsing?: boolean;
  /** Maximum recursion depth for loading nested extra files */
  maxDepth?: number;
  /** Set of already loaded file URLs to prevent circular dependencies */
  loadedFiles?: Set<string>;
  /** Side effects code to inject into extraFiles */
  globalsCode?: (string | VariantCode)[];
  /**
   * Output format for the loaded file
   * @default 'hast'
   */
  output?: 'hast' | 'hastJson' | 'hastGzip';
}
LoadVariantOptions

Options for the loadCodeVariant function, extending LoadFileOptions with required function dependencies

type LoadVariantOptions = {
  /** Disable applying source transformers */
  disableTransforms?: boolean;
  /** Disable parsing source strings to AST */
  disableParsing?: boolean;
  /** Maximum recursion depth for loading nested extra files */
  maxDepth?: number;
  /** Set of already loaded file URLs to prevent circular dependencies */
  loadedFiles?: Set<string>;
  /** Side effects code to inject into extraFiles */
  globalsCode?: (string | VariantCode)[];
  /**
   * Output format for the loaded file
   * @default 'hast'
   */
  output?: 'hast' | 'hastJson' | 'hastGzip';
  /** Promise resolving to a source parser for syntax highlighting */
  sourceParser?: Promise<ParseSource>;
  /** Function to load raw source code and dependencies */
  loadSource?: LoadSource;
  /** Function to load specific variant metadata */
  loadVariantMeta?: LoadVariantMeta;
  /** Array of source transformers for code processing (e.g., TypeScript to JavaScript) */
  sourceTransformers?: SourceTransformers;
  /** Array of source enhancers that run after parsing to enhance the HAST tree */
  sourceEnhancers?: SourceEnhancers;
}
SourceComments

Comments extracted from source code, keyed by line number. Each line number maps to an array of comment strings found on that line.

type SourceComments = { [key: number]: string[] }
SourceEnhancers

Array of source enhancer functions that run in order after parsing.

SourceTransformer
type SourceTransformer = { extensions: string[]; transformer: TransformSource }
SourceTransformers
Transforms
type Transforms = { [key: string]: { delta: Delta; fileName?: string } }
VariantCode

Complete code variant definition with source, metadata, and configuration. Extends CodeMeta with all the information needed to display and process a code example.

type VariantCode = {
  /** Name of the file (e.g., 'Button.tsx') */
  fileName?: string;
  /** Language for syntax highlighting (e.g., 'tsx', 'css'). When provided, fileName is not required. */
  language?: string;
  /** Flattened path for the file */
  path?: string;
  /** Source URL where this variant originates */
  url?: string;
  /** Main source content for this variant */
  source?: VariantSource;
  /** Additional files associated with this variant */
  extraFiles?: VariantExtraFiles;
  /** Prefix for metadata keys, e.g. /src */
  metadataPrefix?: string;
  /** External module dependencies */
  externals?: string[];
  /** The name of the export for this variant's entrypoint */
  namedExport?: string;
  /** Order in which files should be displayed */
  filesOrder?: string[];
  /** Transformations that can be applied to the source */
  transforms?: Transforms;
  /** Whether all files in the variant are explicitly listed */
  allFilesListed?: boolean;
  /** Skip generating source transformers for this variant */
  skipTransforms?: boolean;
  /** Comments extracted from source, stored when parsing is disabled for later use */
  comments?: SourceComments;
}
VariantExtraFiles

Additional files associated with a code variant. Can be either simple string content or objects with source and transformation options.

type VariantExtraFiles = {
  [fileName: string]:
    | string
    | {
        source?: VariantSource;
        language?: string;
        transforms?: Transforms;
        skipTransforms?: boolean;
        metadata?: boolean;
        path?: string;
        comments?: SourceComments;
      };
}
VariantSource
type VariantSource = string | HastRoot | { hastJson: string } | { hastGzip: string }