GhostCodeBlock
GhostCodeBlock renders a code sample with a header, a Copy button, a body that scrolls sideways for long lines, and an optional fold for long samples. GhostVue does not bundle a syntax highlighter: your highlighter (Shiki, Prism, highlight.js, or none) produces the markup, you put it in the default slot, and you pass the raw text as code. Copy always writes code (or copyText), so line numbers, prompts and diff markers your markup renders never end up on the clipboard. Import it from @ghostvue/themes for the default styling; the behavior comes from the headless component in @ghostvue/vue. The same page documents the clipboard helper for copy buttons that are not code blocks. To style the block yourself, see Advanced: headless composition.
Show a highlighted file
A TypeScript file rendered from consumer-highlighted tokens with a file name header, Copy, horizontal scroll for a long line, and a fold after eight lines.
The sample renders tokens in the default slot and passes the same text as code. title names the file, language adds the label and the language-ts class on <code>, and fold-lines clips the sample after eight lines until the reader expands it. Narrow the preview to see the long line scroll inside the block while the page stays put.
<GhostCodeBlock :code="code" title="useCart.ts" language="ts" :fold-lines="8">
<span v-html="highlighted" />
</GhostCodeBlock>codeis the source of truth. Copy writes it, the line count for the fold comes from it, and it renders as escaped text whenever the default slot is empty. Render the same lines in the slot that you pass incode.- An empty slot shows the plain code. A slot that renders nothing, or only comments and whitespace (a
v-ifthat is stillfalse), counts as empty. An app that highlights asynchronously keeps the slot empty until the highlighter resolves, so the plain text shows first and nothing moves except token colors. v-htmlis your decision. The component never callsv-html. If you render highlighter HTML withv-html, make sure it is safe: highlighters escape the source they tokenize, but never pass HTML from users throughv-htmlunescaped.
Highlighter recipes
The default slot is phrasing content inside the component's own <pre><code>. It must not contain a <pre> or <code> of its own; in development a nested <pre> logs GHOST035.
| Highlighter | Use |
|---|---|
| Shiki | codeToHtml(code, { …, structure: 'inline' }) in v-html on a <span>, or codeToTokens / codeToHast rendered as Vue nodes. Not the default codeToHtml output. |
| Prism | Prism.highlight(code, grammar, language) in v-html on a <span>. Prism theme selectors such as code[class*='language-'] match, because <code> has the class. |
| highlight.js | hljs.highlight(code, { language }).value in v-html on a <span>. Token classes (.hljs-keyword) work anywhere; the recipe paints the container instead of .hljs. |
Shiki's default codeToHtml output wraps the tokens in its own <pre class="shiki"><code>, which would nest a second scroll container inside the block. structure: 'inline' returns only the token spans, with <br> between lines.
import { codeToHtml } from 'shiki'
const highlighted = await codeToHtml(code, {
lang: 'ts',
themes: { light: 'github-light', dark: 'github-dark' },
defaultColor: false,
structure: 'inline',
})With defaultColor: false, Shiki writes both colors as --shiki-light and --shiki-dark custom properties on each token. Pick one from the color mode GhostVue already follows:
.ghost-code-block [data-part='code'] span {
color: var(--shiki-light);
}
@media (prefers-color-scheme: dark) {
:root:not([data-ghost-mode='light'])
.ghost-code-block
[data-part='code']
span {
color: var(--shiki-dark);
}
}
[data-ghost-mode='dark'] .ghost-code-block [data-part='code'] span {
color: var(--shiki-dark);
}This is one way to set it up, not a contract: token colors are your highlighter's. The themed recipe paints only the surface, border, header and default text color.
Copy shell commands
Install commands whose $ prompts render but are left out of the copied text through copyText, with an icon in the copy slot.
copyText replaces what Copy writes, so a terminal sample can show $ prompts and copy only the commands. Make the prompts user-select: none too, so a manual selection skips them. The copy slot replaces the button's visible content, here with an icon before the word. The button keeps its accessible name, "Copy Terminal" (from messages.copyLabel(title)), in every state.
Header actions and a custom Copy
An Open in playground link and an icon-only custom Copy button in the actions slot, with the built-in button removed and copySettled recording the last result.
The actions slot renders before the Copy button. It receives copy and the clipboard state, so a custom copy control gets the same announcement and failure fallback. With :copyable="false" the built-in button goes away and the status region stays, so the custom control is still announced. Name your own controls; start a copy control's name with "Copy" so voice control users can say "click Copy".
Call copy directly from the event handler. Browsers, Safari in particular, reject clipboard writes that start after an await, once the user gesture has ended.
copySettled fires with { text, ok } after the latest write settles, on success and failure. Use it for your own feedback, such as analytics or a toast; the block already announces the result. The event is not called copy, so @copy on the component still means the native DOM copy event.
Fold long samples
fold-lines turns the fold on when the sample has more lines than that number (a trailing line break does not count). A sample that fits renders no toggle. Bind v-model:expanded to control the fold, or set default-expanded to start open.
- The fold clips visually only. Every line stays in the page, so screen readers read the whole sample and the toggle has no
aria-expanded. Its text says what it does: "Show all 42 lines" or "Show fewer lines". - When focus enters a clipped line (a link in your markup), the block expands so focus never lands on hidden content. In controlled mode it emits
update:expandedwithtrue, and you apply it. - After collapsing, the toggle is scrolled back into view if it moved off screen.
- Find in page counts matches on clipped lines but cannot show them until the reader expands the sample.
The themed recipe sets a numeric line height, so a collapsed block shows exactly fold-lines lines, with a fade over the last one. The fade is removed when the user asks for reduced transparency and in forced colors. A headless block with line-height: normal, or lines with taller glyphs (emoji, CJK), can show part of a line.
Clipboard helper
useGhostClipboard on an ordinary button outside a code block, announcing the result in GhostVisuallyHidden and showing the failure next to the field.
useGhostClipboard is the copy logic behind the block, for any other copy control: an invite link, an API token, a commit SHA. It returns a state (idle, copied, failed), an announcement for a live region, and copy(text), which resolves true or false and never rejects.
<script setup lang="ts">
import { GhostVisuallyHidden, useGhostClipboard } from '@ghostvue/vue'
const { state, announcement, liveRegionProps, copy } = useGhostClipboard({
messages: { copied: 'Invite link copied' },
})
</script>
<template>
<button type="button" @click="copy(link)">Copy invite link</button>
<GhostVisuallyHidden v-bind="liveRegionProps">
<span :key="announcement.key">{{ announcement.text }}</span>
</GhostVisuallyHidden>
</template>- Render the live region from the start, empty, and put the text in a child keyed by
announcement.key. The key changes on every announcement, so copying twice announces "Copied" twice. - Keep the button's name constant. Show success through
stateand the announcement, not by renaming the button. - Only the latest copy counts. A permission prompt can hold one write back; an older write that settles late resolves its own boolean but changes nothing.
reset()retires pending writes the same way. - Failure is yours to finish. The helper does not select text or show anything. The example selects the link and shows the message next to it.
copiedDuration(default 2000 ms) sets how longcopiedlasts;0keeps it until the next copy orreset().failedlasts until the next copy.- It works in any effect scope and touches no browser API until
copy()runs, so it is safe during server rendering.
writeClipboardText(text) is the stateless write underneath, for code outside a Vue scope (a directive, a markdown enhancer). It calls navigator.clipboard.writeText synchronously, before any await, and resolves false instead of throwing during server rendering, on insecure origins where the Clipboard API is missing, and when the write is rejected (denied permission, an unfocused document, a cross-origin frame without allow="clipboard-write").
GhostVue has no document.execCommand('copy') fallback: it is deprecated, steals focus, and fails in the same embedded contexts.
Accessibility
| Topic | Behavior |
|---|---|
| Structure | A div with no role: a code sample is content, not a landmark. The header has the title, the language label (always exposed, since a title such as "Terminal" does not name the language), your actions and Copy. |
| Copy button | A native button. Its visible text is "Copy" in every state and its name is Copy <title> ("Copy code" without a title), so the name contains the visible word. Success shows as data-state="copied" (a check in the theme) and a polite announcement. |
| Status | A role="status" region in the server markup, visually hidden until a copy fails. The failure text then shows under the header in headless and themed use. |
| Failed copy | The code is selected and focus stays on Copy. Ctrl+C, ⌘C or the device's Copy menu then copies copyText ?? code, even on insecure origins, because the block supplies the text to the native copy event while the selection still covers the code. |
| Scrolling body | The <pre> is left to right on every page. While a line overflows and the code holds no links or buttons, it is a tab stop and a region named by the title (or "ts code", "Code" without a title or language), so keyboard users can scroll it with the arrow keys. |
| Fold | Visual clip only; the toggle is a plain button with no disclosure state. Focus entering a clipped line expands the fold. |
| Translation | <code> has translate="no", so page translation leaves identifiers alone. |
| Forced colors | Copy and the fold toggle keep a ButtonText border, and the fade is removed so clipped text ends at a hard edge. |
Keyboard and focus
| Key | Target | Behavior |
|---|---|---|
Tab / Shift+Tab | Whole block | Header actions, Copy, the viewport (when it is a tab stop) or links inside the code, then the fold toggle. |
Enter / Space | Copy | Copies. Focus stays on the button. |
Enter / Space | Fold toggle | Toggles the fold. Focus stays on the toggle. |
Arrow keys, Home/End | Viewport | Native scrolling. |
Ctrl+C / ⌘C | Anywhere | Native copy of the selection, which is how the failure fallback completes. |
Styling hooks
The themed recipe uses the --ghost-type-family-mono token for code, the small control size for Copy and the fold toggle (so coarse pointers get 44px targets), and inset tokens for spacing, so data-ghost-density tightens or loosens the block. Override the code font on the palette host: --ghost-type-family-mono: 'JetBrains Mono', monospace.
| Hook | Values |
|---|---|
data-part | root, header, title, language, copy, status, viewport, code, fold-toggle |
Root data-language | The language prop, when set. |
Root data-fold | collapsed, expanded; absent when the fold is inactive. |
Copy and status data-state | idle, copied, failed. |
Code and fold toggle data-state | collapsed, expanded; absent on code when the fold is inactive. |
Viewport data-overflow | none, horizontal. |
Code class language-<language> | When language is set. |
--ghost-code-block-fold-lines (custom property on code) | The fold-lines value while the fold is active. |
Other class names and wrapper nesting are not part of the contract. Line numbers, highlighted lines and diff markers depend on your highlighter's per-line markup; add them with CSS on those hooks. For Shiki's .line spans:
.numbered [data-part='code'] {
counter-reset: line;
}
.numbered [data-part='code'] .line::before {
color: var(--ghost-text-muted);
content: counter(line);
counter-increment: line;
display: inline-block;
inline-size: 3ch;
margin-inline-end: 1ch;
text-align: end;
user-select: none;
}API
@ghostvue/themes adds no props, events, or slots to the headless GhostCodeBlock API, which it forwards.
| Prop | Type | Default | Description |
|---|---|---|---|
code | string | Required | The raw source text. Copy writes it (unless copyText is set), the line count is taken from it, and it renders as escaped text when the default slot is empty. The slot must render the same lines. |
copiedDuration | number | 2000 | How long the copied state lasts, in ms. 0, a negative number, or a non-finite number keeps it until the next copy. |
copyable | boolean | true | Renders the copy button. false removes it; the status region stays whenever the header renders. |
copyText | string | — | Text Copy writes instead of code, for example a shell sample without its $ prompts. The failure fallback also supplies this text. |
defaultExpanded | boolean | false | Initial fold state in uncontrolled mode. Read once at setup. |
expanded | boolean | — | Controlled fold state (v-model:expanded). Ignored when the fold is not active. |
foldLines | number | — | Enables the fold when the sample has more lines than this. Must be a positive integer; any other value warns in development and disables the fold. |
language | string | — | Language label in the header (for example ts). Also data-language on the root and the class language-<language> on <code>. |
messages | Partial<GhostCodeBlockMessages> | "{}" | Text overrides, merged over the defaults. Read at render and when a write settles. |
title | string | — | Header title, usually a file name. Names the copy button and, through the title element, the code region. Replaces the native title attribute. |
| Event | Payload | Description |
|---|---|---|
copySettled | GhostCodeBlockCopySettledEvent | After a write settles, on success and failure, only for the latest request: { text, ok } where text is copyText ?? code at activation time. |
| Slot | Slot props | Description |
|---|---|---|
actions | copy: () => Promise<boolean>, state: GhostClipboardState | Extra header controls before the copy button. Call copy directly from the event handler, not after an await. |
copy | state: GhostClipboardState | Replaces the copy button's visible content, for example an icon. The button keeps its aria-label. |
default | — | Highlighted markup, rendered inside <code data-part="code">. Phrasing content only: no <pre> or <code> of its own. When empty (absent, or only comments and whitespace), code renders as escaped text. |
title | — | Replaces the title text. The region is named by this element; the copy button name still comes from the title prop, so pass both. |
Messages
messages is merged over these defaults. It is read at render and when a write settles, so a reactive object updates later output.
| Message | Default |
|---|---|
copy | 'Copy' |
copied | 'Copied' |
failed | 'Copy failed. The code is now selected; copy it with Ctrl+C, ⌘C, or your device's Copy menu.' |
copyLabel | title ? 'Copy ' + title : 'Copy code' |
regionLabel | language ? language + ' code' : 'Code' |
expand | 'Show all ' + lineCount + ' lines' |
collapse | 'Show fewer lines' |
Template ref
| Member | Description |
|---|---|
element | The root element; null before mount and after unmount. |
copy() | Runs the same copy as the button, including the failure fallback. |
Advanced: headless composition
For teams that bring their own design system: the headless GhostCodeBlock from @ghostvue/vue renders the same markup. Without a theme it already scrolls the viewport sideways, clips the fold and shows the failure text; your CSS targets the hooks above.
The unstyled GhostCodeBlock from @ghostvue/vue styled only through data-part and data-state hooks.
The parts render inside the component, so a <style scoped> block reaches them through :deep() from the root, which carries your scope attribute.
Custom markup
useGhostCodeBlock(options) takes the component props as refs or getters, plus onUpdateExpanded and onCopySettled, and returns everything the component renders. Bind the template refs and spread the prop bags on your own elements to keep identical behavior.
| Member | Description |
|---|---|
lineCount, foldActive, expanded | Fold state. |
clipboardState, announcement | Clipboard state and the live region content. |
viewportOverflow | none or horizontal, measured after mount. |
messages | The defaults merged with the messages option. |
copy(), toggle() | The Copy action with its fallback, and the fold toggle. |
rootRef, titleRef, viewportRef, codeRef, foldToggleRef | Template refs. The region name uses titleRef to know whether a title renders. |
rootProps, headerProps, titleProps, languageProps, copyButtonProps, statusProps, viewportProps, codeProps, foldToggleProps | Prop bags with ids, ARIA attributes, data-* hooks, inline styles and listeners. |
With your own elements, the accessibility contract above is yours: render the status region from the start with its text in a child keyed by announcement.key, keep Copy a native button, and keep the fold toggle after the viewport.
Known limitations
- Find in page cannot reveal matches on clipped lines until the sample is expanded.
- How an embedded webview shows the fallback selection (handles, Copy menu) varies; it is part of the manual checks recorded before the component leaves
experimental. - No line numbers, line highlighting, diff markers, word wrap or file tabs. Compose
GhostTabsaround several blocks for tabs.
See also
GhostScrollArea: the same tab-stop rule for other scrolling regions.GhostVisuallyHidden: for the clipboard helper's live region.- Specification