Components
Code Block
Displays code, terminal output and diffs with a header, line numbers, syntax highlighting and a copy button.
Credits
Shout out to Shadcn Vue for the original CodeBlock. This version adds a code + language shortcut, themes, line highlight props, automatic diffs, a built-in show more, download and wrap buttons, more languages, and success / warning variants.
Source code
Click to see the source code for this component on GitHub. Feel free to copy it and adjust it for your own use.
Installation
This installs Shiki and two helpers next to the component: useHighlightedCode (a composable) and code-highlighter.ts (a util). CodeBlock uses the scroll-fade utility, so add it if you have not yet: Scroll Fade.
About
UiCodeBlock displays code, terminal output, logs and diffs. It has a header with a title and actions, line numbers, wrapping, diff and highlighted lines, and a small size for tool output in a Trace.
Syntax highlighting is lazy. Shiki and each language load the first time they are used, so a block that only shows plain output stays small.
import { streamText } from "ai"
export default defineEventHandler(async (event) => { const { messages } = await readBody(event)
const result = streamText({ model: "anthropic/claude-sonnet-4.5", system: "You are a helpful assistant. Answer in one short paragraph.", messages, })
return result.toUIMessageStreamResponse()})Usage
Set code, language and filename on the root. The title, content, copy and download parts read them, so you do not repeat them on each part.
import { streamText } from "ai";
export default defineEventHandler(async (event) => { const { messages } = await readBody(event);
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages, });
return result.toUIMessageStreamResponse();});Or put plain text in UiCodeBlockContent and pass value to the copy button yourself:
<template>
<UiCodeBlock>
<UiCodeBlockHeader>
<UiCodeBlockTitle>Terminal</UiCodeBlockTitle>
<UiCodeBlockActions>
<UiCodeBlockCopyButton :value="output" />
</UiCodeBlockActions>
</UiCodeBlockHeader>
<UiCodeBlockContent>{{ output }}</UiCodeBlockContent>
</UiCodeBlock>
</template>
<script lang="ts" setup>
const output = `$ pnpm add ai @ai-sdk/vue zod
Done in 2.8s using pnpm v10.18.0`;
</script>
Composition
UiCodeBlock
├── UiCodeBlockHeader
│ ├── UiCodeBlockTitle
│ └── UiCodeBlockActions
│ ├── UiCodeBlockWrapButton
│ ├── UiCodeBlockDownloadButton
│ └── UiCodeBlockCopyButton
├── UiCodeBlockActions (floating, when there is no header)
├── UiCodeBlockContent
│ └── UiCodeBlockLine
│ └── UiCodeBlockToken
└── UiCodeBlockFooter
└── UiCodeBlockExpandButton
UiCodeBlockContent highlights code for you, or takes plain text, or a list of UiCodeBlockLine. Use lines when you want full control over each line and token.
Features
- It streams cheaply. Plain text in the slot renders as one text node, and the highlighter tokenizes only the new lines as code arrives.
- It copies cleanly. Line numbers and diff markers are left out of a selection, and blank lines survive the copy.
- It reads left to right. The content is always
dir="ltr". The header follows the page direction. - It highlights without WASM. Shiki's JavaScript engine, 30+ languages loaded on first use, ANSI colors for terminal output, and 11 themes. Add more with
registerCodeLanguageandregisterCodeTheme. - It does the common things for you.
highlight-lines, automaticdiff,max-lineswith an expand button, a wrap toggle, a download button. - It fits where code shows up. Use it in a message, a Markdown fence, a Trace line, Tabs, a Dialog or a
typesetcontainer. - It scrolls by keyboard. The content is focusable, and floating actions show on focus as well as on hover.
- Four tones.
default,destructive,successandwarning.
Basic
Put plain text in UiCodeBlockContent. It renders as one text node, so it stays cheap while output streams.
$ pnpm build
> nuxt build
✔ Client built in 4215ms
✔ Server built in 1803ms
Route Size Gzip
┌ ○ / 1.9 kB 0.9 kB
├ ○ /about 993 B 0.5 kB
└ ƒ /api/chat 141 B 0.1 kBHeader
UiCodeBlockHeader holds a UiCodeBlockTitle and UiCodeBlockActions. UiCodeBlockCopyButton copies its value.
$ pnpm add ai @ai-sdk/vue zod
Packages: +14
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0A long title truncates. Give the title an icon and text, or put your own markup in its slot. To link the title to a file, wrap UiCodeBlockTitle in an anchor.
<template>
<UiCodeBlockHeader>
<a href="/files/chat.post.ts">
<UiCodeBlockTitle icon="lucide:file-code" text="server/api/chat.post.ts" />
</a>
</UiCodeBlockHeader>
</template>
Actions
UiCodeBlockActions holds any number of buttons. Drop in UiCodeBlockCopyButton, UiCodeBlockDownloadButton, UiCodeBlockWrapButton, or your own.
$ pnpm lint
app/components/MessageList.vue
18:22 error 'messages' is possibly 'undefined'. Add a guard before calling map ts/no-unsafe-call
42:7 warning 'scrollToBottom' is assigned a value but never used unused-imports/no-unused-vars
✖ 2 problems (1 error, 1 warning)Wrap, download and copy buttons
The buttons read what they need from the surrounding UiCodeBlock. Bind v-model:wrap on the root and the wrap button toggles it. The download button saves code as filename, and the copy button copies code.
$ pnpm add ai @ai-sdk/vue zod @ai-sdk/anthropic @ai-sdk/openai @ai-sdk/googlePackages: +42Progress: resolved 128, reused 120, downloaded 8, added 42, doneDone in 2.8s using pnpm v10.18.0Floating Actions
Without a header, put UiCodeBlockActions directly inside UiCodeBlock. The actions float at the top end and stay hidden until the block is hovered or focused. They always show on touch screens.
$ pnpm add ai @ai-sdk/vue zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
dependencies:
+ @ai-sdk/vue 3.0.12
+ ai 6.0.12
+ zod 4.1.12
Done in 2.8s using pnpm v10.18.0Line Numbers
Add line-numbers to UiCodeBlockContent. Plain text in the slot is split into lines, and the numbers are not copied with a selection.
{ "name": "chat", "private": true, "scripts": { "dev": "nuxt dev", "build": "nuxt build" }}Start Line
Set start-line to number lines from a given line, for a snippet from the middle of a file. The gutter grows to fit the widest number.
if (!session) { throw createError({ statusCode: 401 }) }
const projects = await db.project.findMany({ where: { ownerId: session.user.id }, orderBy: { updatedAt: "desc" }, })
return projects})Wrap
Long lines scroll by default. Add wrap to wrap them, which suits tool output and error messages. To let the reader toggle it, see the wrap button.
Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.Highlighted Lines
Pass highlight-lines to UiCodeBlockContent with numbers or ranges such as "17-18". The numbers are the ones shown in the gutter, so they follow start-line.
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages: convertToModelMessages(messages), tools: { weather: tool({ description: "Get the weather in a location", inputSchema: z.object({ location: z.string() }), execute: async ({ location }) => getWeather(location), }), },});To control each line yourself, render every line as a UiCodeBlockLine and set variant="highlighted" on the lines to call out.
export default defineNuxtConfig({ experimental: { viewTransition: true, typedPages: true, }, image: { domains: ["avatars.githubusercontent.com"], },})Diff
With language="diff" (or :diff="true" for any language) lines that start with + are marked as added and lines that start with - as removed. The + and - stay in the text, so a copied selection is still a valid diff.
"dependencies": {- "ai": "^4.3.0",+ "ai": "^5.0.0",+ "@ai-sdk/vue": "^2.0.0", "zod": "^4.0.0" }To build the diff yourself, set variant="added" or variant="removed" on a UiCodeBlockLine. Each one adds a + or − marker.
<template> <p>Hello, {{ name }}</p> <p class="text-sm text-muted-foreground"> Hello, {{ name }}! </p></template>Height
Cap the height with a max-h-* class on UiCodeBlockContent. The content scrolls inside the block.
[01] GET /api/chat 200 in 12ms
[02] GET /api/chat 200 in 19ms
[03] GET /api/chat 200 in 26ms
[04] GET /api/chat 200 in 33ms
[05] GET /api/chat 200 in 40ms
[06] GET /api/chat 200 in 47ms
[07] GET /api/chat 200 in 14ms
[08] GET /api/chat 200 in 21ms
[09] GET /api/chat 200 in 28ms
[10] GET /api/chat 200 in 35ms
[11] GET /api/chat 200 in 42ms
[12] GET /api/chat 200 in 49ms
[13] GET /api/chat 200 in 16ms
[14] GET /api/chat 200 in 23ms
[15] GET /api/chat 200 in 30ms
[16] GET /api/chat 200 in 37ms
[17] GET /api/chat 200 in 44ms
[18] GET /api/chat 200 in 51ms
[19] GET /api/chat 200 in 18ms
[20] GET /api/chat 200 in 25ms
[21] GET /api/chat 200 in 32ms
[22] GET /api/chat 200 in 39ms
[23] GET /api/chat 200 in 46ms
[24] GET /api/chat 200 in 13ms
[25] GET /api/chat 200 in 20ms
[26] GET /api/chat 200 in 27ms
[27] GET /api/chat 200 in 34ms
[28] GET /api/chat 200 in 41ms
[29] GET /api/chat 200 in 48ms
[30] GET /api/chat 200 in 15ms
[31] GET /api/chat 200 in 22ms
[32] GET /api/chat 200 in 29ms
[33] GET /api/chat 200 in 36ms
[34] GET /api/chat 200 in 43ms
[35] GET /api/chat 200 in 50ms
[36] GET /api/chat 200 in 17ms
[37] GET /api/chat 200 in 24ms
[38] GET /api/chat 200 in 31ms
[39] GET /api/chat 200 in 38ms
[40] GET /api/chat 200 in 45msUiCodeBlockContent fades its edges with scroll-fade as it scrolls: left and right by default, top and bottom when it wraps. Add scroll-fade-y to a capped block that does not wrap.
Show More
Set max-lines on the root to show only that many lines until the block is expanded. UiCodeBlockExpandButton toggles v-model:expanded and only renders when there is something to expand.
<template> <div class="flex flex-col gap-4"> <div v-for="message in chat.messages" :key="message.id"> <template v-for="(part, index) in message.parts" :key="index"> <p v-if="part.type === 'text'"> {{ part.text }} </p> </template> </div> <form @submit.prevent="onSubmit"> <UiInput v-model="input" /> <UiButton :disabled="chat.status !== 'ready'">Send</UiButton> </form> </div></template>
<script lang="ts" setup>import { Chat } from "@ai-sdk/vue";
const input = ref("");const chat = new Chat({});
function onSubmit() { chat.sendMessage({ text: input.value }); input.value = "";}</script>Build it yourself
UiCodeBlockFooter is a slot below the content. To control it yourself, cap the content while it is collapsed and put a ghost xs button in the footer.
<script setup lang="ts">import { Chat } from "@ai-sdk/vue"
const input = ref("")const chat = new Chat({})
function onSubmit() { chat.sendMessage({ text: input.value }) input.value = ""}</script>
<template> <div class="flex flex-col gap-4"> <div v-for="message in chat.messages" :key="message.id"> <template v-for="(part, index) in message.parts" :key="index"> <p v-if="part.type === 'text'"> {{ part.text }} </p> </template> </div> <form @submit.prevent="onSubmit"> <UiInput v-model="input" /> <UiButton :disabled="chat.status !== 'ready'"> Send </UiButton> </form> </div></template>Max Height
To keep a long block from taking over the page, raise the cap instead of removing it. The expanded content scrolls, and the edges fade as you scroll.
<script setup lang="ts">import { Chat } from "@ai-sdk/vue"
const input = ref("")const chat = new Chat({})
function onSubmit() { chat.sendMessage({ text: input.value }) input.value = ""}</script>
<template> <div class="flex flex-col gap-4"> <div v-for="message in chat.messages" :key="message.id"> <template v-for="(part, index) in message.parts" :key="index"> <p v-if="part.type === 'text'"> {{ part.text }} </p> </template> </div> <form @submit.prevent="onSubmit"> <UiInput v-model="input" /> <UiButton :disabled="chat.status !== 'ready'"> Send </UiButton> </form> </div></template>Size
Use size="sm" for tool and Trace output. It has tighter padding and text-xs text.
$ pnpm add ai @ai-sdk/vue zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0$ pnpm add ai @ai-sdk/vue zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0Variants
variant sets the tone of the block: default, destructive, success and warning. Use destructive for errors and failed output.
Done in 2.8sTests 42 passed (42)2 warnings: unused variable `props`ERR_PNPM_OUTDATED_LOCKFILE Cannot install with frozen-lockfileTypeError: Cannot read properties of undefined (reading 'map')
at setup (components/MessageList.vue:18:22)
at callWithErrorHandling (runtime-core.esm-bundler.js:199:19)Trace
Put a UiCodeBlock with size="sm" in UiTraceCollapsibleContent for tool and terminal output. Add wrap and a max-h-64 class to UiCodeBlockContent so long output wraps and scrolls inside the trace. The block sets its own text color, so UiTraceCollapsibleContent does not mute it.
$ node --version
v24.18.0$ pnpm dev
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1908:16)Tabs
Show several files with Tabs, one UiCodeBlock in each UiTabsContent.
import { streamText } from "ai"
export default defineEventHandler(async (event) => { const { messages } = await readBody(event) const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()})Message
Put a UiCodeBlock between paragraphs inside a Message.
Typeset
A UiCodeBlock inside a typeset container keeps its own styles and gets the same space above as a paragraph.
Stream a response
Create a server route that calls streamText and returns the stream to the client.
import { streamText } from "ai"
export default defineEventHandler(async (event) => { const { messages } = await readBody(event) const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()}) The Chat class from @ai-sdk/vue reads the stream on the client and renders the answer while it is written.
RTL
Code always reads left to right. The header follows the page direction.
ثبّت الحزم، ثم شغّل خادم التطوير.
pnpm add ai @ai-sdk/vue zodpnpm devSyntax Highlighting
Set language and code and the content highlights itself. For full control, useHighlightedCode highlights with Shiki and returns a computed list of lines. Each line is a list of tokens, which you render with UiCodeBlockToken inside a UiCodeBlockLine.
{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}<template>
<UiCodeBlock>
<UiCodeBlockContent>
<UiCodeBlockLine v-for="(line, index) in lines" :key="index">
<UiCodeBlockToken v-for="(token, i) in line" :key="i" :token="token" />
</UiCodeBlockLine>
</UiCodeBlockContent>
</UiCodeBlock>
</template>
<script lang="ts" setup>
const lines = useHighlightedCode(code, "json");
</script>
Both arguments accept a plain value, a ref or a getter, so the lines update when the code or the language changes. The optional third argument takes the themes:
const props = defineProps<{ code: string; language: string }>();
const lines = useHighlightedCode(
() => props.code,
() => props.language
);
Shiki uses its JavaScript regex engine, so there is no WASM to load.
Languages
Each language loads the first time it is used. A language that is not registered renders as plain text.
@import "tailwindcss";
:root { --radius: 0.625rem;}def greet(name: str) -> str: return f"Hello, {name}!"A language that is not in the list renders as plain text.The list ships with astro, bash, c, cpp, csharp, css, dart, diff, docker, go, graphql, html, ini, java, javascript, json, jsonc, jsx, kotlin, lua, markdown, php, powershell, prisma, python, ruby, rust, scss, sql, svelte, swift, toml, tsx, typescript, vue, xml and yaml, plus aliases such as ts, js, sh, yml, py and rs.
To add another language, register a Shiki language module once, for example in a plugin:
registerCodeLanguage("zig", () => import("shiki/langs/zig.mjs"));
Themes
Pass themes on the root (or on the content) with a light and a dark Shiki theme. The default is github-light and github-dark. Bundled: catppuccin-latte, catppuccin-mocha, dracula, github-dark, github-light, min-dark, min-light, one-dark-pro, tokyo-night, vitesse-dark and vitesse-light.
export function useDebounce<T>(value: Ref<T>, delay = 300) { const debounced = shallowRef(value.value);
watch(value, (next, _, onCleanup) => { const timeout = setTimeout(() => (debounced.value = next), delay); onCleanup(() => clearTimeout(timeout)); });
return debounced;}export function useDebounce<T>(value: Ref<T>, delay = 300) { const debounced = shallowRef(value.value);
watch(value, (next, _, onCleanup) => { const timeout = setTimeout(() => (debounced.value = next), delay); onCleanup(() => clearTimeout(timeout)); });
return debounced;}Register another theme with registerCodeTheme("nord", () => import("shiki/themes/nord.mjs")) and use its name in themes.
Terminal Output
Pass "ansi" as the language to render the colors in terminal output. Without it, escape codes show as text.
$ pnpm test[32m✓[39m src/format.test.ts [2m(4 tests)[22m[32m✓[39m src/parse.test.ts [2m(7 tests)[22m[31m✗[39m src/stream.test.ts [2m(3 tests | 1 failed)[22m
[31mAssertionError: expected 'hello' to be 'hello world'[39m
Tests [31m1 failed[39m | [32m13 passed[39m (14)ANSI colors do not carry from one line to the next.
Server Rendering
highlightCode is async and returns the tokens of each line, or null for a language that is not registered. Call it from a server route or with useAsyncData so the tokens are part of the server-rendered HTML.
<template>
<UiCodeBlock>
<UiCodeBlockContent line-numbers>
<UiCodeBlockLine v-for="(line, index) in lines" :key="index">
<UiCodeBlockToken v-for="(token, i) in line" :key="i" :token="token" />
</UiCodeBlockLine>
</UiCodeBlockContent>
</UiCodeBlock>
</template>
<script lang="ts" setup>
const props = defineProps<{ code: string }>();
const { data: lines } = await useAsyncData(
`code-${props.code}`,
async () =>
(await highlightCode(props.code, "ts")) ??
props.code.split("\n").map((line) => (line ? [{ content: line }] : []))
);
</script>
To highlight many snippets in a row, loadHighlighter loads a language once and returns a highlighter with a synchronous highlight(code) method. It returns null for a language that is not registered.
const highlighter = await loadHighlighter("ts");
const { lines } = highlighter?.highlight(code) ?? { lines: [] };
Streaming
While the code streams, the composable tokenizes only the new lines, starting where the last line left off. Lines that did not change keep the same tokens, so Vue skips them.
export function useDebounce<T>(value: Ref<T>, delay = 300) { const debounced = shallowRef(value.value)
watch(value, (next, _, onCleanup) => { const timeout = setTimeout(() => (debounced.value = next), delay) onCleanup(() => clearTimeout(timeout)) })
return debounced}bunx ui-thing@latest add code-block<script setup lang="ts">const query = ref("")const results = useSearch(query)const debounced = useDebounce(query, 300)const results = useSearch(debounced)</script>
<template> <SearchResults :results="results" /></template>import { streamText } from "ai"
export default defineEventHandler(async (event) => { const { messages } = await readBody(event)
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages, })
return result.toUIMessageStreamResponse()})AI_GATEWAY_API_KEY=your-api-keyMarkdown
Fenced code in a Markdown message renders well as a UiCodeBlock. Split the text into blocks, render the fences with a UiCodeBlock and the rest with your Markdown renderer. While the message streams, the last fence may not be closed yet, so disable the copy button on it.
Accessibility
UiCodeBlockContentis aprewith acodeelement and always setsdir="ltr", so code reads left to right on an RTL page.UiCodeBlockContenthastabindex="0", so keyboard users can focus it and scroll it. Passtabindex="-1"to remove the tab stop.- Floating actions show when focus is inside the block, not only on hover, so keyboard users can reach them.
- Line numbers are hidden from screen readers.
- Diff lines carry a
+or−marker as well as a tint, so the change does not rely on color. UiCodeBlockCopyButtonis labelled "Copy", and a polite live region announces "Copied" after a successful copy.UiCodeBlockWrapButtonsetsaria-pressedandUiCodeBlockExpandButtonsetsaria-expanded, so their state is announced.- Every button takes a
label(orexpand-text/collapse-text) so you can translate the accessible names.
API Reference
The layout parts (block, header, title, actions, footer) are built on a Reka Primitive, so as and as-child work on them. The buttons accept as. Every part accepts class.
UiCodeBlock
The surface that holds the header, the content and the footer. It also shares its code, language, filename, themes, wrap and expanded state with the parts inside it.
| Prop / Model | Type | Default | Description |
|---|---|---|---|
variant | "default" | "destructive" | "success" | "warning" | "default" | The tone of the block. |
size | "default" | "sm" | "default" | "sm" has tighter padding and text-xs code, for tool output. |
code | string | - | The code. The content, copy and download parts fall back to it. |
language | string | - | The language of code. |
filename | string | - | The name used by the download button. |
themes | { light: string; dark: string } | GitHub | The Shiki themes for light and dark mode. |
max-lines | number | - | Show only this many lines until expanded. |
v-model:wrap | boolean | false | Wrap long lines. Shared with the wrap button and the content. |
v-model:expanded | boolean | false | Whether the block is expanded. Shared with the expand button. |
as | string | Component | "div" | The element to render. |
class | string | - | Additional classes to apply to the block. |
UiCodeBlockHeader
A row above the content for a title and actions.
| Prop | Type | Default | Description |
|---|---|---|---|
class | string | - | Additional classes to apply to the header. |
UiCodeBlockTitle
A filename or a label, with an optional icon. It truncates.
| Prop | Type | Default | Description |
|---|---|---|---|
text | string | filename | The title. Used when the default slot is empty. Falls back to the filename of UiCodeBlock. |
icon | string | - | An Iconify icon shown before the text. |
class | string | - | Additional classes to apply to the title. |
UiCodeBlockActions
Holds buttons at the end of the header. As a direct child of UiCodeBlock, it floats.
| Prop | Type | Default | Description |
|---|---|---|---|
class | string | - | Additional classes to apply to the actions. |
UiCodeBlockCopyButton
A ghost icon button that copies value to the clipboard. It accepts the props of UiButton.
| Prop / Event | Type | Default | Description |
|---|---|---|---|
value | string | code | The text to copy. Falls back to the code of UiCodeBlock. |
variant | string | "ghost" | The variant of the button. |
size | string | "icon-xs" | The size of the button. |
timeout | number | 2000 | How long, in milliseconds, the copied state lasts. |
label | string | "Copy" | The accessible name. |
copied-label | string | "Copied" | The accessible name and announcement after copying. |
copy | (text: string) => void | - | Emitted after the text was copied. |
class | string | - | Additional classes to apply to the button. |
The default slot receives { copied } to replace the icon.
UiCodeBlockDownloadButton
Saves text as a file. It accepts the props of UiButton.
| Prop / Event | Type | Default | Description |
|---|---|---|---|
value | string | code | The text to save. Falls back to the code of UiCodeBlock. |
filename | string | filename | The file name. Falls back to the filename of UiCodeBlock. |
variant | string | "ghost" | The variant of the button. |
size | string | "icon-xs" | The size of the button. |
label | string | "Download" | The accessible name. |
download | (filename: string) => void | - | Emitted after the download was started. |
UiCodeBlockWrapButton
A toggle for the wrap state of the surrounding UiCodeBlock. It sets aria-pressed.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | string | "ghost" | The variant of the button. |
size | string | "icon-xs" | The size of the button. |
label | string | "Toggle line wrapping" | The accessible name. |
The default slot receives { wrap }.
UiCodeBlockExpandButton
Toggles the expanded state of the surrounding UiCodeBlock. It only renders when the code has more lines than max-lines.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | string | "ghost" | The variant of the button. |
size | string | "xs" | The size of the button. |
expand-text | string | "Show more" | The text while collapsed. |
collapse-text | string | "Show less" | The text while expanded. |
The default slot receives { expanded }.
UiCodeBlockContent
The pre that scrolls or wraps.
| Prop | Type | Default | Description |
|---|---|---|---|
| default slot | - | - | Plain text, or a list of UiCodeBlockLine. Used when there is no code. |
code | string | root code | The code to render and highlight. |
language | string | root language | The language of the code. |
themes | { light: string; dark: string } | root themes | The Shiki themes. |
wrap | boolean | root wrap | Wrap long lines instead of scrolling. |
line-numbers | boolean | false | Number each line. Plain text in the slot is split into lines. |
start-line | number | 1 | The number of the first line. |
highlight-lines | (number | string)[] | - | Lines to highlight: numbers or ranges such as "3-5", using the displayed line numbers. |
diff | boolean | language === "diff" | Mark lines that start with + as added and - as removed. |
max-lines | number | root max-lines | Show only this many lines until expanded. |
tabindex | number | 0 | Makes the content focusable so it can be scrolled by keyboard. |
class | string | - | Additional classes to apply to the content, such as max-h-72. |
UiCodeBlockLine
One line of code.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "default" | "added" | "removed" | "highlighted" | "default" | The state of the line. |
marker | boolean | true | Show the + / − gutter marker on added and removed lines. Turn it off when the text already starts with + or -. |
class | string | - | Additional classes to apply to the line. |
UiCodeBlockToken
One highlighted token from useHighlightedCode or highlightCode. It renders a span with the light and dark theme colors.
| Prop | Type | Default | Description |
|---|---|---|---|
token | HighlightedToken | - | Required. The token. |
UiCodeBlockFooter
A row below the content, such as for a Show More button.
| Prop | Type | Default | Description |
|---|---|---|---|
class | string | - | Additional classes to apply to the footer. |
useHighlightedCode
const lines = useHighlightedCode(code, language, themes);
Returns a ComputedRef<HighlightedToken[][]>, one list of tokens per line. It returns plain lines until the first pass finishes, on the server, and for a language that is not registered.
| Argument | Type | Description |
|---|---|---|
code | MaybeRefOrGetter<string> | The code to highlight. A trailing newline is ignored. |
language | MaybeRefOrGetter<string | undefined> | A language or alias, or "ansi". |
themes | MaybeRefOrGetter<CodeBlockThemes | undefined> | Optional. The light and dark theme names. |
highlightCode
const lines = await highlightCode(code, language, themes);
Returns Promise<HighlightedToken[][] | null>, one list of tokens per line, or null for a language that is not registered.
loadHighlighter
const highlighter = await loadHighlighter(language, themes);
Loads a language and its themes, and returns a highlighter for it, or null for a language that is not registered. highlighter.highlight(code, state?) returns { lines, state }. Pass state back to continue tokenizing where the code left off.
registerCodeLanguage / registerCodeTheme
registerCodeLanguage("zig", () => import("shiki/langs/zig.mjs"), "zg");
registerCodeTheme("nord", () => import("shiki/themes/nord.mjs"));
Make a language (with optional aliases) or a theme available to every block.
HighlightedToken
interface HighlightedToken {
content: string;
htmlStyle?: Record<string, string>;
}