Code Block
Shows code from a reply, a canvas, a workflow step, or a file. It colors every language Shiki knows, over 240, picks the language from the file name, and copies the exact source with one button.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/code-block.jsonCopies Code Block and the components it uses (Button) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/code-block. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @hugeicons/core-free-icons @hugeicons/react shikiAdd Sprout base once per app: the
cn()helper and the design tokens.lib/sprout/classes.ts- Design tokens, for your global CSS
Add the components it uses: Button.
Copy and paste the following code into your project.
'use client'; import { Fragment, useEffect, useMemo, useRef, useState, type HTMLAttributes } from 'react'; import { CheckIcon } from '@/lib/sprout/icons/check-icon'; import { CopyIcon } from '@/lib/sprout/icons/copy-icon'; import { cn } from '@/lib/sprout/classes'; import { codeLanguageIds, codeLanguageNames, type CodeLanguage } from '@/lib/sprout/languages'; import { tokenClass, useCodeTokens } from '@/lib/sprout/code-tokens'; import { languageForFilename, loadCodeLanguage, resolveCodeLanguage } from '@/lib/sprout/syntax'; import { Button } from '@/components/ui/button'; export type { CodeLanguage }; export { languageForFilename }; export const codeBlockVariantNames = ['inline', 'file', 'preview'] as const; export type CodeBlockVariant = (typeof codeBlockVariantNames)[number]; export const codeBlockLanguages = codeLanguageIds; export type CodeBlockCopyState = 'idle' | 'copying' | 'copied' | 'error'; export interface CodeBlockProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> { code: string; language?: string | undefined; filename?: string | undefined; lineNumbers?: boolean | undefined; wrap?: boolean | undefined; variant?: CodeBlockVariant | undefined; } const copiedResetMs = 2000; export function isHighlightedLanguage(language: string) { return resolveCodeLanguage(language) !== null; } export function codeLanguageName(language: string) { const resolved = resolveCodeLanguage(language); return resolved ? codeLanguageNames[resolved] : 'Plain text'; } export async function preloadCodeLanguages(...languages: string[]) { await Promise.all( languages.flatMap(language => { const resolved = resolveCodeLanguage(language); return resolved ? [loadCodeLanguage(resolved)] : []; }), ); } export function CodeBlock({ code, language, filename, lineNumbers = true, wrap = false, variant = 'inline', className, ...props }: CodeBlockProps) { const [copyState, setCopyState] = useState<CodeBlockCopyState>('idle'); const timer = useRef<ReturnType<typeof setTimeout>>(undefined); useEffect(() => () => clearTimeout(timer.current), []); const resolved = resolveCodeLanguage(language, filename); const tokens = useCodeTokens(code, resolved); const lineCount = useMemo(() => code.split('\n').length, [code]); const copy = async () => { clearTimeout(timer.current); setCopyState('copying'); try { await navigator.clipboard.writeText(code); setCopyState('copied'); timer.current = setTimeout(() => setCopyState('idle'), copiedResetMs); } catch { setCopyState('error'); } }; const languageLabel = resolved ? codeLanguageNames[resolved] : 'Plain text'; const label = filename ?? languageLabel; const copied = copyState === 'copied'; const preview = variant === 'preview'; return ( <div data-slot="code-block" data-variant={variant} data-language={resolved ?? 'text'} data-highlighted={tokens ? '' : undefined} data-wrap={wrap ? '' : undefined} data-copy-state={copyState} {...props} className={cn('sprout-code-block', className)} > {!preview && ( <div className="sprout-code-block-header"> <span className="sprout-code-block-label">{label}</span> <Button variant="ghost" size="sm" focusableWhenDisabled disabled={copyState === 'copying'} onClick={() => void copy()} aria-label={`Copy ${filename ?? 'code'}`} className="sprout-code-block-copy" > <span className="sprout-code-block-icon" aria-hidden="true"> {copied ? <CheckIcon size="sm" /> : <CopyIcon size="sm" />} </span> {copied ? 'Copied' : 'Copy'} </Button> </div> )} <div className="sprout-code-block-viewport" {...(preview ? {} : { tabIndex: 0, role: 'region', 'aria-label': filename ?? `${languageLabel} code`, })} > {lineNumbers && !wrap && ( <pre aria-hidden="true" className="sprout-code-block-gutter"> {Array.from({ length: lineCount }, (_, index) => index + 1).join('\n')} </pre> )} <pre className="sprout-code-block-pre"> {tokens ? ( <code className="sprout-code-block-syntax"> {tokens.map((line, row) => ( <Fragment key={row}> {row > 0 && '\n'} {line.map((token, index) => ( <span key={index} className={tokenClass(token)}> {token.content} </span> ))} </Fragment> ))} </code> ) : ( <code>{code}</code> )} </pre> </div> {copyState === 'error' && ( <p role="alert" className="sprout-code-block-error"> Clipboard unavailable. Select the code to copy it, or try Copy again. </p> )} {!preview && ( <span className="sprout-code-block-sr-only" role="status"> {copied ? 'Code copied to clipboard.' : ''} </span> )} </div> ); }And the files it imports:
lib/sprout/icons/check-icon.tsxlib/sprout/icons/copy-icon.tsxlib/sprout/icons/create-icon.tsxlib/sprout/code-tokens.tslib/sprout/languages.tslib/sprout/syntax.ts
Add the styles to your global CSS, after
@import "tailwindcss".@layer components { .sprout-code-block { box-sizing: border-box; min-width: 0; max-width: 100%; color: var(--sprout-text); font-family: var(--sprout-font); font-size: var(--sprout-text-sm); flex-direction: column; display: flex; overflow: hidden; } .sprout-code-block[data-variant="inline"] { border: 1px solid var(--sprout-line); border-radius: var(--sprout-radius-panel); background: color-mix(in oklab, var(--sprout-hover) 40%, var(--sprout-surface)); } .sprout-code-block[data-variant="file"] { height: 100%; min-height: 0; } .sprout-code-block[data-variant="preview"] { max-height: 100%; font-size: var(--sprout-text-xs); mask-image: linear-gradient(oklch(0% 0 0) 75%, #0000); } .sprout-code-block[data-variant="preview"] .sprout-code-block-viewport { font-size: var(--sprout-text-xs); padding: 12px; line-height: 1.125rem; overflow: hidden; } .sprout-code-block-header { box-sizing: border-box; border-bottom: 1px solid var(--sprout-line); flex-shrink: 0; justify-content: space-between; align-items: center; gap: 12px; min-height: 40px; padding: 4px 6px 4px 12px; display: flex; } .sprout-code-block-label { min-width: 0; color: var(--sprout-muted); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: var(--sprout-text-xs); white-space: nowrap; text-overflow: ellipsis; line-height: 1rem; overflow: hidden; } .sprout-code-block-icon { display: inline-flex; } .sprout-code-block-copy:disabled { cursor: progress; } .sprout-code-block-viewport { box-sizing: border-box; min-width: 0; font-size: var(--sprout-text-sm); padding: 16px; line-height: 1.25rem; display: flex; overflow: auto; } .sprout-code-block[data-variant="inline"] .sprout-code-block-viewport { max-height: 24rem; } .sprout-code-block[data-variant="file"] .sprout-code-block-viewport { flex: 1; min-height: 0; } .sprout-code-block-viewport:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: -1px; } .sprout-code-block-gutter, .sprout-code-block-pre { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: inherit; line-height: inherit; tab-size: 2; margin: 0; } .sprout-code-block-gutter { border-right: 1px solid var(--sprout-line); color: var(--sprout-muted); text-align: right; user-select: none; flex-shrink: 0; margin-right: 16px; padding-right: 12px; } .sprout-code-block-pre { background: none; flex: 1; min-width: 0; } .sprout-code-block-pre code { font: inherit; } .sprout-code-block[data-wrap] .sprout-code-block-pre { white-space: pre-wrap; overflow-wrap: anywhere; } .sprout-syntax-keyword { color: var(--sprout-syntax-keyword, var(--sprout-info)); } .sprout-syntax-string, .sprout-syntax-string-expression { color: var(--sprout-syntax-string, var(--sprout-success)); } .sprout-syntax-constant { color: var(--sprout-syntax-constant, var(--sprout-warning)); } .sprout-syntax-function { color: var(--sprout-syntax-function, color-mix(in oklab, var(--sprout-info) 55%, var(--sprout-danger))); } .sprout-syntax-parameter { color: var(--sprout-syntax-parameter, color-mix(in oklab, var(--sprout-danger) 65%, var(--sprout-warning))); } .sprout-syntax-comment { color: var(--sprout-syntax-comment, var(--sprout-muted)); } .sprout-syntax-punctuation { color: var(--sprout-syntax-punctuation, color-mix(in oklab, var(--sprout-text) 70%, var(--sprout-muted))); } .sprout-syntax-link { color: var(--sprout-syntax-link, var(--sprout-info)); } .sprout-syntax-heading { color: var(--sprout-syntax-heading, var(--sprout-info)); } .sprout-syntax-inserted { color: var(--sprout-syntax-inserted, var(--sprout-success)); } .sprout-syntax-deleted { color: var(--sprout-syntax-deleted, var(--sprout-danger)); } .sprout-syntax-italic { font-style: italic; } .sprout-syntax-bold { font-weight: 600; } .sprout-syntax-underline { text-underline-offset: 2px; text-decoration: underline; } .sprout-code-block-error { border-top: 1px solid var(--sprout-line); color: var(--sprout-danger); font-size: var(--sprout-text-sm); flex-shrink: 0; margin: 0; padding: 8px 12px; line-height: 1.25rem; } .sprout-code-block-sr-only { clip-path: inset(50%); white-space: nowrap; border: 0; width: 1px; height: 1px; margin: -1px; padding: 0; position: absolute; overflow: hidden; } @media (pointer: coarse) { .sprout-code-block-copy { min-height: 44px; } } @media (prefers-reduced-motion: no-preference) { .sprout-code-block-error { animation: sprout-code-block-in var(--sprout-motion-normal) var(--sprout-motion-ease); } } @keyframes sprout-code-block-in { from { opacity: 0; } } }Import it from
@/components/ui/code-block. Update the paths if your@/alias points elsewhere.
pnpm add @tulipfarm/sprout@import "tailwindcss";
@import "@tulipfarm/sprout/styles.css";The package keeps the source and ships fixes with each release. Import from @tulipfarm/sprout/code-block.
Usage
import { CodeBlock } from "@tulipfarm/sprout/code-block";
<CodeBlock
code={step.source}
language="python"
filename="score_lead.py"
/>language takes a name, an alias, or an extension, such astypescript, ts, or py, so a Markdown fence name can go straight in. Leave it out and the language comes from filename: main.rs,Dockerfile, and .env.local all work.text, txt, and unknown names show plain text. The header shows filename, or the language’s name.lineNumbers is on by default. wrap wraps long lines for prose such as notes, and hides line numbers.
Syntax colors
Shiki tokenizes the code with its JavaScript regex engine, so there is no WebAssembly and no inline styles. Each grammar loads the first time a block needs it, and the block shows plain text until then. Markdown also loads the languages of its fences. Code over 200,000 characters stays plain so a huge file can’t freeze the page.
[data-theme="sunset"] {
--sprout-syntax-keyword: #c2410c;
--sprout-syntax-string: #15803d;
--sprout-syntax-comment: #78716c;
}Tokens get the classes sprout-syntax-keyword,-string, -constant, -function,-parameter, -comment, -punctuation,-link, and, for Markdown and diffs, -heading,-inserted, and -deleted. Each reads a matching--sprout-syntax-* variable and falls back to the theme’s info, success, warning, danger, and muted colors, so every theme works without setup.
import { preloadCodeLanguages } from "@tulipfarm/sprout/code-block";
await preloadCodeLanguages("tsx", "python");Await preloadCodeLanguages before server rendering to send colored HTML. languageForFilename,codeLanguageName, and isHighlightedLanguageexpose the same lookup the block uses.
Variants
inline is a bordered card that scrolls after 24rem.file has no frame and fills its parent, so give the parent a height.preview drops the header and copy button and fades out at its parent’s height, for hover cards and thumbnails.
In a chat reply
Render fenced code from Markdown with the fence language and no filename. A fence without a language shows as text.
pre({ node, children }) {
const code = node?.children[0];
if (code?.type !== "element" || code.tagName !== "code") return <pre>{children}</pre>;
const language = languageClass(code)?.slice("language-".length) ?? "text";
return <CodeBlock code={textOf(code).replace(/\n$/, "")} language={language} />;
}Canvas and workflow steps
Step 1: run JavaScript code with the trigger input
calculate.jsStep 2: run Python code with Lead from Step 1
score_lead.py
File pane
<div className="flex h-full min-h-0 flex-col">
<CodeBlock
key={`${file.revision}:${file.path}`}
code={file.content}
filename={file.path}
variant="file"
/>
{file.content === "" && <p>This file is empty.</p>}
</div>A new key per file and revision resets the copy state and scroll position. Long paths truncate in the header; the region and the copy button still use the full path.
Shell examples
Turn off line numbers for shell commands so a copied command runs as is.
POST https://hooks.tulipfarm.app/w/wf_8k2m4qz7/run
Set TULIPFARM_WEBHOOK_KEY to your key before you run the example. The example never contains the key.
Accessibility
The code scrolls in a focusable region named after the file, or “Language code”, such as “TypeScript code”. The preview variant is not focusable. Line numbers are hidden from screen readers. The copy button is named “Copy filename” or “Copy code”, stays focusable while it copies, shows Copied for 2 seconds, and announces “Code copied to clipboard.” When the clipboard is blocked an alert says to select the code instead, and Copy tries again. On touch screens the button is 44px tall. The error fades in over 180ms, or appears at once with reduced motion.