Components · Content
note:Copy source: not an npm package.
CopyableCodeBlock
A code block with a filename or language header, optional line numbers and a copy button that handles failure honestly.
- clipboard
- code
- live region
- Dependencies
- None beyond React
- Source
- src/components/collection/copyable-code-block/copyable-code-block.tsx
Preview & code
export async function refreshSession(signal?: AbortSignal) { // The HttpOnly cookie is attached by the browser; JS never sees it. const res = await fetch("/auth/refresh", { method: "POST", credentials: "include", signal }); if (res.status === 401) return null; // rotated or expired: sign in again return (await res.json()) as { accessToken: string };}"use client";/** * CopyableCodeBlock — a code block with a language/filename header, optional * line numbers, and a copy button with accessible success/failure feedback. * * - Copies the exact `code` string (line numbers are never copied). * - If the Clipboard API is unavailable or denied, it selects the code so the * visitor can press Ctrl/Cmd+C, and says so in a live region. * - Long lines scroll horizontally; `maxHeight` makes tall blocks scroll too. * The scroll area is focusable so keyboard users can scroll it. * - Highlighting is optional and external: pass pre-computed `tokens`. * * Styling uses Tailwind utilities backed by CSS variables (--code-bg, --border, * --text-muted, --accent and --code-* token colours, with fallbacks). Adjust to * your design system. * * Source: Sayed Risat's portfolio component collection. Copy freely. */import { useEffect, useRef, useState, useSyncExternalStore } from "react";const subscribeToNothing = () => () => {};const clientReady = () => true;const serverReady = () => false;export type HighlightToken = { text: string; type?: "keyword" | "string" | "comment" | "number" | "type";};export type CopyableCodeBlockProps = { /** The exact text that is displayed and copied. */ code: string; /** Shown in the header, e.g. "tsx" or "bash". */ language?: string; /** Shown in the header instead of the language when present. */ filename?: string; /** Render non-copyable line numbers. */ showLineNumbers?: boolean; /** Optional pre-highlighted lines; their text must join back to `code`. */ tokens?: HighlightToken[][]; /** CSS length; content scrolls vertically beyond it. */ maxHeight?: string; /** Override the clipboard write (custom transports, tests). Defaults to navigator.clipboard. */ writeText?: (text: string) => Promise<void>; /** Called after each copy attempt. */ onCopy?: (result: "success" | "error") => void; className?: string;};type CopyState = "idle" | "copied" | "error";const tokenClass: Record<NonNullable<HighlightToken["type"]>, string> = { keyword: "text-[var(--code-keyword,#7c3aed)]", string: "text-[var(--code-string,#0b6b63)]", comment: "text-[var(--code-comment,#5c696d)] italic", number: "text-[var(--code-number,#a14c06)]", type: "text-[var(--code-type,#1d4ed8)]",};export function CopyableCodeBlock({ code, language, filename, showLineNumbers = false, tokens, maxHeight, writeText, onCopy, className,}: CopyableCodeBlockProps) { const hydrated = useSyncExternalStore(subscribeToNothing, clientReady, serverReady); const [state, setState] = useState<CopyState>("idle"); const preRef = useRef<HTMLPreElement>(null); const resetTimer = useRef<number | undefined>(undefined); useEffect(() => () => window.clearTimeout(resetTimer.current), []); const source = code.replace(/\n$/, ""); const lines: HighlightToken[][] = tokens ?? source.split("\n").map((text) => [{ text }]); const label = filename ?? language ?? "Code"; async function copy() { let result: CopyState; try { if (writeText) await writeText(source); else await navigator.clipboard.writeText(source); result = "copied"; } catch { result = "error"; // Fallback: select the code so a keyboard shortcut finishes the job. const pre = preRef.current; const selection = window.getSelection(); if (pre && selection) { const range = document.createRange(); range.selectNodeContents(pre.querySelector("code") ?? pre); selection.removeAllRanges(); selection.addRange(range); } } setState(result); onCopy?.(result === "copied" ? "success" : "error"); window.clearTimeout(resetTimer.current); resetTimer.current = window.setTimeout(() => setState("idle"), result === "copied" ? 2000 : 5000); } return ( <figure className={[ "min-w-0 overflow-hidden rounded-[var(--rad-md,10px)] border border-[var(--border,#dce3df)] bg-[var(--code-bg,#f1f4f2)]", className, ] .filter(Boolean) .join(" ")} > <figcaption className="flex min-h-11 items-center justify-between gap-3 border-b border-[var(--border,#dce3df)] py-1.5 pr-1.5 pl-4"> <span className="min-w-0 truncate font-mono text-[0.78125rem] text-[var(--text-muted,#59666a)]">{label}</span> <span className="flex shrink-0 items-center gap-2"> {filename && language && ( <span className="font-mono text-[0.75rem] text-[var(--text-muted,#59666a)] uppercase max-sm:hidden">{language}</span> )} <button type="button" disabled={!hydrated} onClick={copy} className="inline-flex h-8 items-center gap-1.5 rounded-[var(--rad-sm,6px)] px-2.5 font-mono text-[0.78125rem] text-[var(--text,#1b2428)] transition-colors hover:bg-[var(--surface-raised,#fff)] focus-visible:outline-2 focus-visible:outline-[var(--focus,#0b8177)]" > <CopyIcon state={state} /> <span>{state === "copied" ? "Copied" : state === "error" ? "Selected, press ⌘/Ctrl+C" : "Copy"}</span> <span className="sr-only"> {label}</span> </button> </span> </figcaption> <pre ref={preRef} tabIndex={0} aria-label={`${label} code`} style={maxHeight ? { maxHeight } : undefined} className="overflow-auto py-4 font-mono text-[0.875rem] leading-6 text-[var(--text,#1b2428)] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[var(--focus,#0b8177)]" > <code className="grid min-w-max"> {lines.map((line, i) => ( <span key={i} className="flex px-4"> {showLineNumbers && ( <span aria-hidden="true" className="mr-4 inline-block w-[2ch] shrink-0 text-right text-[var(--text-muted,#59666a)] select-none" > {i + 1} </span> )} <span className="whitespace-pre"> {line.length === 0 ? "" : line.map((token, j) => token.type ? ( <span key={j} className={tokenClass[token.type]}> {token.text} </span> ) : ( token.text ), )} </span> </span> ))} </code> </pre> <span role="status" aria-live="polite" className="sr-only"> {state === "copied" ? "Code copied to clipboard." : state === "error" ? "Copy failed. The code is selected; press Control+C or Command+C to copy it." : ""} </span> </figure> );}function CopyIcon({ state }: { state: CopyState }) { return ( <svg aria-hidden="true" viewBox="0 0 24 24" className="size-3.5" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"> {state === "copied" ? ( <path d="M20 6 9 17l-5-5" /> ) : state === "error" ? ( <> <circle cx="12" cy="12" r="9" /> <path d="M12 8v4M12 16h.01" /> </> ) : ( <> <rect x="9" y="9" width="12" height="12" rx="2" /> <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" /> </> )} </svg> );}When to use it
Technical writing and docs need code people can copy in one action, with feedback they can trust: including when the Clipboard API is blocked, which plain copy buttons usually ignore.
Usage
- Copy
src/components/collection/copyable-code-block/copyable-code-block.tsxinto your project (from the Code tab above). - Import it from where you placed it. In this repo that’s
@/components/collection/copyable-code-block/copyable-code-block.
import { CopyableCodeBlock } from "@/components/collection/copyable-code-block/copyable-code-block";export function InstallStep() { return ( <CopyableCodeBlock language="bash" filename="terminal" code={"npm run build\nnpm run start"} showLineNumbers /> );}API
| Prop | Type | Default | Description |
|---|---|---|---|
| code* (required) | string | — | The exact text displayed and copied. A trailing newline is trimmed. |
| language | string | — | Shown in the header (and next to the filename on wider screens). |
| filename | string | — | Shown in the header instead of the language. |
| showLineNumbers | boolean | false | Renders line numbers that are never selected or copied. |
| tokens | HighlightToken[][] | — | Optional pre-highlighted lines. Their text must join back to code. |
| maxHeight | string | — | CSS length. Taller code scrolls inside a focusable region. |
| writeText | (text: string) => Promise<void> | Clipboard API | Override the clipboard write (defaults to navigator.clipboard.writeText), for custom transports or tests. Client components only. |
| onCopy | (result: "success" | "error") => void | — | Called after every copy attempt, e.g. for analytics. Client components only. |
| className | string | — | Extra classes on the outer figure. |
* required
Accessibility
- Tab
- Moves to the copy button, then into the code area.
- Enter / Space
- Copies the code (on the button).
- Arrow keys
- Scroll long code once the code area has focus.
- Copy results are announced through a polite live region, not only shown visually.
- If copying fails, the code is selected and the announcement explains the keyboard shortcut.
- The button's accessible name includes the filename or language, so several blocks on a page stay distinguishable.
- Line numbers are aria-hidden and unselectable; token colours meet WCAG AA contrast in both themes.
Limits & tests
Limitations
- Highlighting is external: pass
tokensfrom your own highlighter, or none for plain text. - No line wrapping option; long lines scroll horizontally by design.
- Function props (
writeText,onCopy) can only be passed from client components.
Tests
tests/e2e/components.spec.ts
- Copies the exact source text to the clipboard and announces success
- Falls back to selecting the code and explaining the shortcut when the clipboard is denied
- Line numbers toggle without affecting the copied text