Code preview
Docs-style panel with a Preview and a Code pane: a live example in the slot, its source in a scrolling pre, and a copy button.
pnpm dlx shadcn@latest add @haze/code-preview---
import { Copy, Check, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Props {
/** Unique on the page. The two panes get `${id}-preview` and `${id}-code`. */
id: string;
/** Source text shown in the Code pane. Rendered in <pre><code>, so line breaks and indentation are kept. */
code: string;
/** Optional heading line above the tabs, for example "Button group". Plain text, not a heading element. */
title?: string;
/** Small language label beside the copy button, for example "astro". */
language?: string;
/** Pane shown first. */
defaultView?: "preview" | "code";
/** Surface behind the live example. dots draws a quiet dot grid in the border color. */
stage?: "default" | "muted" | "dots";
/** Where the example sits inside the stage. */
align?: "center" | "start";
/** Lets the reader drag the corner of the example sideways to test narrower widths. */
resizable?: boolean;
/** Visible hint under a resizable stage. */
resizeHint?: string;
previewLabel?: string;
codeLabel?: string;
/** Accessible name of the Preview / Code tab list. */
viewsLabel?: string;
copyLabel?: string;
/** Text announced after a successful copy. */
copiedLabel?: string;
/** Text announced when the browser refuses the copy. */
failedLabel?: string;
class?: string;
}
const {
id,
code,
title,
language,
defaultView = "preview",
stage = "default",
align = "center",
resizable = false,
resizeHint = "Drag the bottom-right corner to resize the example.",
previewLabel = "Preview",
codeLabel = "Code",
viewsLabel = "Example view",
copyLabel = "Copy code",
copiedLabel = "Copied",
failedLabel = "Copy failed",
class: className,
} = Astro.props;
const codeFirst = defaultView === "code";
const stages = { default: "bg-card", muted: "bg-muted", dots: "bg-card" };
const aligns = { center: "items-center justify-center", start: "items-start justify-start" };
// Without script the tabs are in-page links and :target picks the pane. The script marks the root with
// data-enhanced, which switches every rule below off and takes over with the hidden attribute.
// Tailwind only sees complete class names, so each variant is written out.
const previewPane = codeFirst
? "[[data-haze-code-preview]:not([data-enhanced])_&:not(:target)]:hidden"
: "[[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=code]:target)_&]:hidden";
const codePane = codeFirst
? "[[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=preview]:target)_&]:hidden"
: "[[data-haze-code-preview]:not([data-enhanced])_&:not(:target)]:hidden";
const previewTabState = codeFirst
? "[[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=preview]:target)_&]:bg-background [[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=preview]:target)_&]:text-foreground"
: "[[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=code]:target)_&]:bg-transparent [[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=code]:target)_&]:text-muted-foreground";
const codeTabState = codeFirst
? "[[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=preview]:target)_&]:bg-transparent [[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=preview]:target)_&]:text-muted-foreground"
: "[[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=code]:target)_&]:bg-background [[data-haze-code-preview]:not([data-enhanced]):has([data-cp-panel=code]:target)_&]:text-foreground";
const tabBase =
"inline-flex h-7 min-w-12 shrink-0 cursor-pointer items-center justify-center rounded-md px-2.5 text-[0.8125rem]/5 font-medium whitespace-nowrap text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[active]:bg-background data-[active]:text-foreground";
---
<div
id={id}
data-haze-code-preview
data-copied-label={copiedLabel}
data-failed-label={failedLabel}
class={cn("group min-w-0 overflow-hidden rounded-xl border border-frame bg-card", className)}
>
<div class="flex min-h-11 flex-wrap items-center justify-between gap-x-2 gap-y-1 border-b border-border bg-muted/40 py-1.5 pr-2 pl-2.5">
{title && <p class="basis-full truncate pl-1.5 text-[0.8125rem]/5 font-medium tracking-[-0.01em] text-foreground">{title}</p>}
<nav aria-label={viewsLabel} data-cp-list class="inline-flex items-center gap-1">
<a
href={`#${id}-preview`}
data-cp-tab="preview"
data-active={codeFirst ? undefined : ""}
class={cn(tabBase, previewTabState)}
>{previewLabel}</a>
<a
href={`#${id}-code`}
data-cp-tab="code"
data-active={codeFirst ? "" : undefined}
class={cn(tabBase, codeTabState)}
>{codeLabel}</a>
</nav>
<div class="flex shrink-0 items-center gap-2">
{language && <span class="font-mono text-xs/4 text-muted-foreground">{language}</span>}
<button
type="button"
hidden
data-cp-copy
class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 active:duration-75"
>
<Copy class="size-4 group-data-[copied]:hidden group-data-[failed]:hidden" aria-hidden="true" />
<Check class="hidden size-4 animate-pop text-success group-data-[copied]:block" aria-hidden="true" />
<X class="hidden size-4 animate-pop text-destructive group-data-[failed]:block" aria-hidden="true" />
<span class="sr-only">{copyLabel}</span>
</button>
</div>
</div>
<div id={`${id}-preview`} data-cp-panel="preview" class={cn("min-w-0", previewPane)}>
<div class={cn("relative flex min-h-40 min-w-0 p-4 sm:p-6", stages[stage], aligns[align], resizable && "justify-start")}>
{
stage === "dots" && (
<svg aria-hidden="true" focusable="false" class="pointer-events-none absolute inset-0 size-full">
<defs>
<pattern id={`${id}-dots`} width="16" height="16" patternUnits="userSpaceOnUse">
<circle cx="2" cy="2" r="1" class="fill-border" />
</pattern>
</defs>
<rect width="100%" height="100%" fill={`url(#${id}-dots)`} />
</svg>
)
}
<div
class={cn(
"relative min-w-0 max-w-full",
resizable && "w-full min-w-48 resize-x overflow-auto rounded-lg border border-dashed border-border p-3",
)}
>
<slot />
</div>
</div>
{resizable && <p class="border-t border-border px-4 py-2 text-xs/4 text-muted-foreground">{resizeHint}</p>}
</div>
<div id={`${id}-code`} data-cp-panel="code" class={cn("min-w-0", codePane)}>
<pre
tabindex="0"
class="max-h-72 overflow-auto px-4 py-3.5 font-mono text-[0.8125rem]/6 text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"><code>{code}</code></pre>
</div>
<span role="status" class="sr-only" data-cp-status></span>
</div>
<script>
// Enhancement: ARIA tabs for Preview / Code, plus a copy button. Without script the tabs are in-page links.
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const list = root.querySelector<HTMLElement>("[data-cp-list]");
const tabs = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-cp-tab]"));
const panels = tabs.map((tab) => root.querySelector<HTMLElement>(`[data-cp-panel="${tab.dataset.cpTab}"]`));
if (!list || tabs.length === 0 || panels.some((panel) => !panel)) return;
const select = (index: number, focus = false) => {
tabs.forEach((tab, i) => {
const on = i === index;
tab.setAttribute("aria-selected", String(on));
tab.tabIndex = on ? 0 : -1;
tab.toggleAttribute("data-active", on);
panels[i]!.hidden = !on;
});
if (focus) tabs[index]!.focus();
};
list.setAttribute("role", "tablist");
tabs.forEach((tab, i) => {
const panel = panels[i]!;
tab.setAttribute("role", "tab");
tab.id = `${panel.id}-tab`;
tab.setAttribute("aria-controls", panel.id);
panel.setAttribute("role", "tabpanel");
panel.setAttribute("aria-labelledby", tab.id);
tab.addEventListener("click", (event) => {
event.preventDefault();
select(i);
});
tab.addEventListener("keydown", (event) => {
const next =
event.key === "ArrowRight" ? (i + 1) % tabs.length
: event.key === "ArrowLeft" ? (i - 1 + tabs.length) % tabs.length
: event.key === "Home" ? 0
: event.key === "End" ? tabs.length - 1
: event.key === " " ? i
: -1;
if (next < 0) return;
event.preventDefault();
select(next, true);
});
});
let hash = "";
try {
hash = decodeURIComponent(location.hash.slice(1));
} catch {
hash = "";
}
const fromHash = panels.findIndex((panel) => hash !== "" && panel!.id === hash);
const initial = fromHash >= 0 ? fromHash : tabs.findIndex((tab) => tab.hasAttribute("data-active"));
select(initial >= 0 ? initial : 0);
const button = root.querySelector<HTMLButtonElement>("[data-cp-copy]");
const status = root.querySelector<HTMLElement>("[data-cp-status]");
const pre = root.querySelector("pre");
if (!button || !pre) return;
button.hidden = false;
let timer: number | undefined;
let announceTimer: number | undefined;
button.addEventListener("click", async () => {
let ok = true;
try {
await navigator.clipboard.writeText(pre.textContent ?? "");
} catch {
ok = false;
}
root.removeAttribute("data-copied");
root.removeAttribute("data-failed");
root.setAttribute(ok ? "data-copied" : "data-failed", "");
window.clearTimeout(announceTimer);
if (status) {
// Clear first so a repeat copy is announced again.
status.textContent = "";
const message = (ok ? root.dataset.copiedLabel : root.dataset.failedLabel) ?? "";
announceTimer = window.setTimeout(() => {
status.textContent = message;
}, 60);
}
window.clearTimeout(timer);
timer = window.setTimeout(() => {
root.removeAttribute("data-copied");
root.removeAttribute("data-failed");
if (status) status.textContent = "";
}, 2000);
});
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-code-preview]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-code-preview-listener")) {
document.documentElement.setAttribute("data-haze-code-preview-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- Documenting a component with a live example and the exact source beside it
- Letting readers check an example at narrower widths by dragging the stage edge
- Showing the same snippet either rendered or as text, one pane at a time
When not to use
- Source only, with no rendered example; use code-block
- Install commands in several package managers; use code-tabs
- Showing a page or app inside a device or browser frame; use browser-window
Installation
Add the Haze registry to components.json once, then install Code preview with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/code-previewnpx shadcn@latest add @haze/code-previewyarn dlx shadcn@latest add @haze/code-previewbunx --bun shadcn@latest add @haze/code-previewFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique on the page. The panes get ids `${id}-preview` and `${id}-code`. |
| code* | string | – | Source shown in the Code pane. Kept verbatim in <pre><code>; the pane scrolls inside itself. |
| title | string | – | Optional plain-text line above the tabs. |
| language | string | – | Small language label beside the copy button, for example "astro". |
| defaultView | "preview" | "code" | "preview" | Pane shown first, with and without script. |
| stage | "default" | "muted" | "dots" | "default" | Surface behind the example. dots is an SVG dot pattern filled with the border token. |
| align | "center" | "start" | "center" | Where the example sits in the stage. |
| resizable | boolean | false | Native horizontal resize handle on the example, with a minimum width, to test responsive behavior. |
| resizeHint | string | "Drag the bottom-right corner to resize the example." | Visible hint shown under a resizable stage. |
| previewLabel | string | "Preview" | Text of the first tab. |
| codeLabel | string | "Code" | Text of the second tab and name of the code region. |
| viewsLabel | string | "Example view" | Accessible name of the tab list. |
| copyLabel | string | "Copy code" | Accessible name of the copy button. |
| copiedLabel | string | "Copied" | Text announced after a successful copy. |
| failedLabel | string | "Copy failed" | Text announced when the browser refuses the copy. |
| class | string | – | Extra classes on the outer panel. |
| default slot* | slot | – | The live example shown in the Preview pane. |
Keyboard interactions
- LeftRight
- Switch between the Preview and Code tabs
- HomeEnd
- Select the first or last tab
- Tab
- Move from the selected tab to the copy button, then into the pane
- EnterSpace
- Copy the code when the copy button has focus
Accessibility
- Without script the two tabs are in-page links and :target shows the matching pane; the first pane shows until a link targets the other.
- The script adds tablist, tab and tabpanel roles, aria-selected and a roving tabindex. The static markup never claims them.
- The code region is focusable and named "Code", so keyboard users can scroll long or wide source (WCAG 2.1.1).
- The copy button appears only with script and announces "Copied" or "Copy failed" through a role="status" region.
- The resize handle is a native pointer feature (resize-x): it has no keyboard or touch alternative, so do not hide information that only a narrow width reveals. The example stays reachable at any width because the stage scrolls instead of clipping.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Code preview" with `npx shadcn@latest add @haze/code-preview`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import CodePreview from "@/components/haze/ui/code-preview.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/code-preview.md
Customize with real content
Adapt the Haze code-preview ui for our product. Replace the demo values of these props with our real content: id, code, title, language, defaultView, stage, align, resizable, resizeHint, previewLabel, codeLabel, viewsLabel, copyLabel, copiedLabel, failedLabel, class, default slot. Keep the layout, the heading level rules and these accessibility details: Without script the two tabs are in-page links and :target shows the matching pane; the first pane shows until a link targets the other. The script adds tablist, tab and tabpanel roles, aria-selected and a roving tabindex. The static markup never claims them. The code region is focusable and named "Code", so keyboard users can scroll long or wide source (WCAG 2.1.1). The copy button appears only with script and announces "Copied" or "Copy failed" through a role="status" region. The resize handle is a native pointer feature (resize-x): it has no keyboard or touch alternative, so do not hide information that only a narrow width reveals. The example stays reachable at any width because the stage scrolls instead of clipping. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using code-preview, check it fits: use it when documenting a component with a live example and the exact source beside it; letting readers check an example at narrower widths by dragging the stage edge; showing the same snippet either rendered or as text, one pane at a time. Avoid it when source only, with no rendered example; use code-block; install commands in several package managers; use code-tabs; showing a page or app inside a device or browser frame; use browser-window. Alternatives: @haze/code-tabs, @haze/code-block, @haze/browser-window.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.