Code block
53 lines · 1 file · MIT
Highlighted code in its own scroll box, with an optional filename bar and a copy button.
response.json
{
"slug": "launch",
"destination": "https://northwind.example/launch?utm_source=newsletter",
"domain": "go.northwind.example",
"clicks": 1284
}curl https://rdyrct.com/api/links \
-H 'authorization: Bearer rd_live_9f2c'import { useMemo, type ReactNode } from "react";
import { highlight, type LanguageName } from "sugar-high";
import { CopyButton } from "./copy-button";
import { cn } from "./cn";
const copyText = (text: string) => navigator.clipboard.writeText(text);
/**
* Highlighted code with an optional filename bar and a copy button.
* `children` is a literal string you wrote: sugar-high turns it into markup,
* and it is set as HTML, so never pass user input.
*
* `lang` defaults to plaintext for lines sugar-high has no grammar for
* (HTTP request lines, shell). Pass "json" for a JSON body. The code scrolls
* inside its own box, so a long line never widens the page.
*/
export function CodeBlock({
children,
lang = "plaintext",
filename,
onCopy = copyText,
className,
}: {
children: string;
lang?: LanguageName;
/** Shown in a bar above the code, in mono (it is an identifier). */
filename?: ReactNode;
onCopy?: (text: string) => void | Promise<void>;
className?: string;
}) {
const html = useMemo(() => highlight(children, { lang }), [children, lang]);
const copy = <CopyButton text={children} label="Copy code" onCopy={onCopy} />;
return (
<div
className={cn("group relative min-w-0 overflow-hidden rounded-lg bg-surface-2", className)}
>
{filename ? (
<div className="flex h-9 items-center justify-between gap-2 pr-1 pl-4 shadow-[inset_0_-1px_0_var(--border)]">
<span className="min-w-0 truncate font-mono text-xs text-muted">{filename}</span>
{copy}
</div>
) : (
<div className="absolute top-2 right-2 z-10 opacity-0 transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100">
{copy}
</div>
)}
<pre className="overflow-x-auto p-4 font-mono text-xs leading-relaxed">
<code dangerouslySetInnerHTML={{ __html: html }} />
</pre>
</div>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/code-block- Category
- Display
- Files
- code-block.tsx
- Brings in
- sugar-high