Code Block

Shows several lines of code, with optional syntax highlighting, a title, and a copy button.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Usage

Code
import { CodeBlock } from '@leverui/components';
Code
<CodeBlock.AdapterProvider>
  <CodeBlock.Root>
    <CodeBlock.Header>
      <CodeBlock.Title />
      <CodeBlock.Control>
        <CodeBlock.CopyTrigger />
        <CodeBlock.CollapseTrigger />
      </CodeBlock.Control>
    </CodeBlock.Header>
    <CodeBlock.Content>
      <CodeBlock.Code>
        <CodeBlock.CodeText />
      </CodeBlock.Code>
    </CodeBlock.Content>
  </CodeBlock.Root>
</CodeBlock.AdapterProvider>

Adapters

Highlights with Shiki or Highlight.js.

These docs use Shiki unless noted.

  • Set up an adapter (Shiki or Highlight.js).
  • Pass it to CodeBlock.AdapterProvider at the top level.
  • Render CodeBlock.Root inside CodeBlock.AdapterProvider.

Shiki

Code
pnpm add shiki

Loads the highlighter on demand, with the languages you list.

Code
import type { HighlighterGeneric } from 'shiki';
import { createShikiAdapter } from '@leverui/components';

const shikiAdapter = createShikiAdapter<HighlighterGeneric<any, any>>({
  async load() {
    const { createHighlighter } = await import('shiki');
    return createHighlighter({
      langs: ['tsx', 'json'],
      themes: ['github-dark', 'github-light'],
    });
  },
  theme: { dark: 'github-dark', light: 'github-light' },
});

<CodeBlock.AdapterProvider value={shikiAdapter}>{/* ... */}</CodeBlock.AdapterProvider>;

Highlight.js

Code
pnpm add highlight.js

Loads the languages you list on demand.

Code
import { createHighlightJsAdapter } from '@leverui/components';
import hljs from 'highlight.js/lib/core';

const highlightJsAdapter = createHighlightJsAdapter<typeof hljs>({
  async load() {
    const languages = {
      tsx: () => import('highlight.js/lib/languages/typescript'),
      html: () => import('highlight.js/lib/languages/xml'),
    };
    await Promise.all(
      Object.entries(languages).map(async ([language, file]) => {
        const { default: languageModule } = await file();
        hljs.registerLanguage(language, languageModule);
      }),
    );
    return hljs;
  },
});

Examples

Sizes

Use the size prop to change the size of the code block component.

(size=sm)
<div class="container">
  <h1>Hello, world!</h1>
</div>
(size=md)
<div class="container">
  <h1>Hello, world!</h1>
</div>
(size=lg)
<div class="container">
  <h1>Hello, world!</h1>
</div>

Title

Render the CodeBlock.Title component within the CodeBlock.Header component to add a title to the code block component.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

Copy button

Use the CodeBlock.CopyTrigger component to add a copy button to the code block component.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

Line numbers

Line numbers make it easier to reference specific lines of code. Pass the meta.showLineNumbers prop to show line numbers in the code block component.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Line highlighting

Pass the meta.highlightLines prop to the CodeBlock.Root component to highlight specific lines of code. The prop accepts an array of line numbers.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Line focus

Pass the meta.focusedLineNumbers prop to the CodeBlock.Root component to focus specific lines of code. The prop accepts an array of line numbers.

const greeting = "Hello, World!"

function sayHello() {
  console.log(greeting);
}

sayHello()

Diff

Diffs are useful for highlighting source code changes. Use the meta.addedLineNumbers and meta.removedLineNumbers props to add line numbers to the code block component. The prop accepts an array of line numbers. The line numbers are 1-based.

const greeting = "Hello, World!"; 
function sayHello() {
  console.log("Hello, World!"); 
  console.log(greeting); 
}
sayHello();

Max lines

Use the meta.maxLines prop to limit the number of lines in the code block component. By default, the code block component will expand to fit the content.

index.tsx

Language switcher

Here's an example that re-creates an API endpoint request component by composing the CodeBlock and Select components.

POST/v1/search
from github import Github

# Create a Github instance using an access token
g = Github("YOUR_ACCESS_TOKEN")

# Get a repository
repo = g.get_repo("octocat/Hello-World")

# Get repository information
print(f"Repository: {repo.name}")
print(f"Description: {repo.description}")
print(f"Stars: {repo.stargazers_count}")

# List issues
issues = repo.get_issues(state='open')
for issue in issues:
    print(f"Issue #{issue.number}: {issue.title}")

Floating copy button

Here's an example that adds a floating copy button to the code block component.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Tabs

Here's an example that composes the CodeBlock component with the Tabs component to create a code block with tabs.

print('Hello, World!')

Tabs sync

Here's an example that automatically syncs all code blocks that share the same storage key. Useful for package manager or framework specific code blocks in a documentation site.

npm install @leverui/components
npm install @leverui/components

Themes

Use the meta.colorScheme prop to add a theme to the code block component. In this example, the colorScheme follows the system color scheme through the useMediaQuery hook.

<div class="container">
  <h1>Hello, world!</h1>
</div>

Wrap overflow

Use the meta.wordWrap prop to wrap the code block component.

index.tsx
const greeting = "Hello, World! I am a long line of text that will wrap to the next line."

function sayHello() {
  console.log(greeting)
}

sayHello()

Line numbers with word wrap

You can combine line numbers with word wrapping by setting both meta.showLineNumbers and meta.wordWrap to true. The line numbers will properly align with wrapped text.

terminal-output.txt
total 121M
  drwxr-xr-x   3 root root 4.0K Sep 11  2022  ..
  -rw-r--r--   1 ali  ali   220 Sep 11  2022  .bash_logout
  drwxr-xr-x   2 ali  ali  4.0K Sep 11  2022  Templates
  drwxr-xr-x   2 ali  ali  4.0K Sep 11  2022  Public
  -rw-r--r--   1 ali  ali     0 Sep 11  2022  .sudo_as_admin_successful
  drwx------   3 ali  ali  4.0K Sep 11  2022  .pki
  drwx------   3 ali  ali  4.0K Sep 11  2022  .gnome
  -rw-r--r--   1 ali  ali    10 Sep 13  2022  .shell.pre-oh-my-zsh
  drwxrwxr-x   3 ali  ali  4.0K Sep 26  2022  v2ray
  -rw-r--r--   1 root root  12K Sep 26  2022  .profile.swp
  drwxrwxrwx   4 ali  ali  4.0K Sep 28  2022  .sonarlint
  drwxrwxr-x   3 ali  ali  4.0K Sep 28  2022  .eclipse
  drwxrwxr-x   8 ali  ali  4.0K Oct  4  2022  zsh-syntax-highlighting
  drwxrwxr-x   2 ali  ali  4.0K Oct  5  2022  .dart
  drwxrwxr-x   4 ali  ali  4.0K Oct  5  2022  .dartServer
  drwxrwxrwx   2 ali  ali  4.0K Oct  7  2022  .quicktype-vscode
  -rw-rw-r--   1 ali  ali   38K Oct 31  2022  .zcompdump-ali-laptop-5.8.1.ali-laptop.5060
  drwxrwxr-x   3 ali  ali  4.0K Nov 16  2022  .swt
  drwx------   3 ali  ali  4.0K Nov 17  2022  .nv
  drwxrwxr-x  15 ali  ali  4.0K Nov 18  2022  .gvm
  drwxrwxr-x   2 ali  ali  4.0K Nov 27  2022  .docker-esopmoc
  drwxrwxr-x   3 ali  ali  4.0K Dec  5  2022  .ipython
  drwx------   7 ali  ali  4.0K Dec  5  2022  .local
  drwxrwxr-x   2 ali  ali  4.0K Dec  5  2022  .jupyter
  drwxrwxr-x   2 ali  ali  4.0K Dec 11  2022  .anydesk
  drwxrwxr-x   3 ali  ali  4.0K Feb 18  2023  .dotnet
  drwxrwxr-x   3 ali  ali  4.0K Feb 19  2023  .degit
  drwxrwxr-x   3 ali  ali  4.0K Feb 26  2023  .cargo
  -rw-rw-r--   1 ali  ali    21 Feb 26  2023  .zshenv
  drwxrwxr-x   6 ali  ali  4.0K Feb 26  2023  .rustup
  drwxrwxr-x   2 ali  ali  4.0K Apr  8  2023  .ipynb_checkpoints
  drwxr-xr-x   8 ali  ali  4.0K Apr 20  2023  my_folder
  drwx------   3 ali  ali  4.0K May  5  2023  .vmware
  drwxrwxr-x  15 ali  ali  4.0K May  7  2023  .openshot
  drwxrwxr-x   3 ali  ali  4.0K May 10  2023  .parallel
  drwxrwxr-x   2 ali  ali  4.0K May 16  2023  .simplelocalize
  -rw-rw-r--   1 ali  ali   5.7K May 21  2023  .v8flags.9.4.146.26-node.26.86318e52f5ed4801abe1d13d509443de.json
  drwxrwxr-x 105 ali  ali  4.0K Sep  5 10:27

Highlight.js

Here's an example that uses highlight.js to highlight the code block.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

Plain text

The code block falls back to a plain text by default. To create a plain text code block, remove the use of CodeBlock.AdapterProvider.

$npm install @leverui/components

Props

PropDefaultTypeDescription
coderequiredstringSource code to show.
language—stringLanguage name passed to the adapter.
meta—CodeBlockHighlightMetaLine numbers, highlighted and focused lines, diffs, color scheme.
colorPalettegraystringColor palette. Built-in or your own.
sizemd'sm' | 'md' | 'lg'Code block size. Responsive.
asdivNative HTML tagHTML tag to render.
asChild—Solid render functionRender your own element with the code block's props.

All props are reactive. To switch language or tab, change code and language on the same root.

Shared defaults

CodeBlock.PropsProvider sets default props for every code block inside it. A prop on a root wins.

Code
<CodeBlock.PropsProvider value={{ size: 'lg' }}>
  <CodeBlock.Root code="const ready = true">...</CodeBlock.Root>
  <CodeBlock.Root size="sm" code="const done = true">
    ...
  </CodeBlock.Root>
</CodeBlock.PropsProvider>

ref and asChild go on each root, not on the provider.

Customize with CSS

Classes: .leverui-code-block__root, plus __header, __title, __control, __content, __code, __codeText, __overlay, and __footer.

Set variables on :root, a theme wrapper, or one code block.

VariableSets
--leverui-code-block-bgBackground.
--leverui-code-block-fgText color.
--leverui-code-block-radiusCorner radius.
--leverui-code-block-paddingInner spacing.
--leverui-code-block-max-heightHeight before the code scrolls.
--leverui-code-block-code-font-sizeCode text size.
--leverui-code-block-header-heightHeader and footer height.
--leverui-code-block-highlight-bgBackground of a highlighted line.
Code
.api-sample {
  --leverui-code-block-radius: 12px;
  --leverui-code-block-max-height: 480px;
}

State attributes:

  • Root: data-size.
  • Content: data-expanded.
  • Code text: data-has-line-numbers, data-word-wrap, data-has-focused.
  • Each line: data-line, plus data-highlight, data-focused, or data-diff.

unstyled on the root turns off the Lever UI styles.