Skip to content

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 ​

Highlighted, copyable and foldable

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.

useCart.tsts
import { computed, ref } from 'vue'

// Totals stay in cents so rounding happens once, at display time.
export function useCart(currency = 'USD', locale = 'en-US', taxRate = 0.0825, freeShippingThreshold = 5_000) {
  const items = ref<CartItem[]>([])
  const subtotal = computed(() =>
    items.value.reduce((sum, item) => sum + item.cents * item.quantity, 0),
  )
  const format = new Intl.NumberFormat(locale, { style: 'currency', currency })
  const total = computed(() => format.format((subtotal.value * (1 + taxRate)) / 100))

  return { items, subtotal, total }
}

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.

vue
<GhostCodeBlock :code="code" title="useCart.ts" language="ts" :fold-lines="8">
  <span v-html="highlighted" />
</GhostCodeBlock>
  • code is 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 in code.
  • An empty slot shows the plain code. A slot that renders nothing, or only comments and whitespace (a v-if that is still false), 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-html is your decision. The component never calls v-html. If you render highlighter HTML with v-html, make sure it is safe: highlighters escape the source they tokenize, but never pass HTML from users through v-html unescaped.

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.

HighlighterUse
ShikicodeToHtml(code, { …, structure: 'inline' }) in v-html on a <span>, or codeToTokens / codeToHast rendered as Vue nodes. Not the default codeToHtml output.
PrismPrism.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.jshljs.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.

ts
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:

css
.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 ​

Shell commands

Install commands whose $ prompts render but are left out of the copied text through copyText, with an icon in the copy slot.

Terminalsh
pnpm add @ghostvue/vue @ghostvue/themes
pnpm dev

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 ​

Header actions

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.

useCounter.tsts Open in playground
import { ref } from 'vue'

export function useCounter(start = 0) {
  const count = ref(start)
  const increment = () => {
    count.value += 1
  }
  return { count, increment }
}

Not copied yet

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:expanded with true, 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 ​

Copy an invite link

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.

vue
<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 state and 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 long copied lasts; 0 keeps it until the next copy or reset(). failed lasts 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 ​

TopicBehavior
StructureA 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 buttonA 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.
StatusA 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 copyThe 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 bodyThe <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.
FoldVisual 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 colorsCopy and the fold toggle keep a ButtonText border, and the fade is removed so clipped text ends at a hard edge.

Keyboard and focus ​

KeyTargetBehavior
Tab / Shift+TabWhole blockHeader actions, Copy, the viewport (when it is a tab stop) or links inside the code, then the fold toggle.
Enter / SpaceCopyCopies. Focus stays on the button.
Enter / SpaceFold toggleToggles the fold. Focus stays on the toggle.
Arrow keys, Home/EndViewportNative scrolling.
Ctrl+C / ⌘CAnywhereNative 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.

HookValues
data-partroot, header, title, language, copy, status, viewport, code, fold-toggle
Root data-languageThe language prop, when set.
Root data-foldcollapsed, expanded; absent when the fold is inactive.
Copy and status data-stateidle, copied, failed.
Code and fold toggle data-statecollapsed, expanded; absent on code when the fold is inactive.
Viewport data-overflownone, 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:

css
.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.

PropTypeDefaultDescription
codestringRequiredThe 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.
copiedDurationnumber2000How long the copied state lasts, in ms. 0, a negative number, or a non-finite number keeps it until the next copy.
copyablebooleantrueRenders the copy button. false removes it; the status region stays whenever the header renders.
copyTextstring—Text Copy writes instead of code, for example a shell sample without its $ prompts. The failure fallback also supplies this text.
defaultExpandedbooleanfalseInitial fold state in uncontrolled mode. Read once at setup.
expandedboolean—Controlled fold state (v-model:expanded). Ignored when the fold is not active.
foldLinesnumber—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.
languagestring—Language label in the header (for example ts). Also data-language on the root and the class language-<language> on <code>.
messagesPartial<GhostCodeBlockMessages>"{}"Text overrides, merged over the defaults. Read at render and when a write settles.
titlestring—Header title, usually a file name. Names the copy button and, through the title element, the code region. Replaces the native title attribute.
EventPayloadDescription
copySettledGhostCodeBlockCopySettledEventAfter a write settles, on success and failure, only for the latest request: { text, ok } where text is copyText ?? code at activation time.
SlotSlot propsDescription
actionscopy: () => Promise<boolean>, state: GhostClipboardStateExtra header controls before the copy button. Call copy directly from the event handler, not after an await.
copystate: GhostClipboardStateReplaces 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.

MessageDefault
copy'Copy'
copied'Copied'
failed'Copy failed. The code is now selected; copy it with Ctrl+C, ⌘C, or your device's Copy menu.'
copyLabeltitle ? 'Copy ' + title : 'Copy code'
regionLabellanguage ? language + ' code' : 'Code'
expand'Show all ' + lineCount + ' lines'
collapse'Show fewer lines'

Template ref ​

MemberDescription
elementThe 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.

Headless with consumer CSS Headless

The unstyled GhostCodeBlock from @ghostvue/vue styled only through data-part and data-state hooks.

package.jsonjson
{
  "name": "release-notes",
  "private": true,
  "scripts": {
    "build": "vite build",
    "preview": "vite preview --port 4173 --strictPort --host 127.0.0.1 --open /changelog"
  },
  "dependencies": {
    "@ghostvue/vue": "^0.4.0"
  }
}

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.

MemberDescription
lineCount, foldActive, expandedFold state.
clipboardState, announcementClipboard state and the live region content.
viewportOverflownone or horizontal, measured after mount.
messagesThe defaults merged with the messages option.
copy(), toggle()The Copy action with its fallback, and the fold toggle.
rootRef, titleRef, viewportRef, codeRef, foldToggleRefTemplate refs. The region name uses titleRef to know whether a title renders.
rootProps, headerProps, titleProps, languageProps, copyButtonProps, statusProps, viewportProps, codeProps, foldTogglePropsProp 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 GhostTabs around several blocks for tabs.

See also ​