Code Block
import { CodeBlock } from '@hanzo/ui'
Default
A filename, a language badge, line numbers, and a copy button that confirms itself for two seconds.
fibonacci.js
javascript1function fibonacci(n) {
2 if (n <= 1) {
3 return n
4 }
5 return fibonacci(n - 1) + fibonacci(n - 2)
6}
7
8const result = fibonacci(10)
9console.log(result) // 55
export function Default() {return (<CodeBlock code={FIBONACCI} language="javascript" filename="fibonacci.js" highlightLines={[5]} />)}
Diff
Added and removed lines each carry their own sign and left-edge color, independent of the highlighted range.
calculator.js
javascript1function calculateTotal(items) {
2 let total = 0
3- for (const item of items) {
4 total += item.price
5+ }
6+ if (total > 100) {
7 total *= 0.9 // 10% discount
8 }
9 return total
10}
export function Diff() {return (<CodeBlock code={CALCULATOR} language="javascript" filename="calculator.js" theme="github-dark" diff={{ added: [5, 6], removed: [3] }} />)}
Themes
Eight named syntax palettes, each a fixed color quartet independent of the surrounding page's own theme.
javascript
const greeting = "Hello, World!"
console.log(greeting)
javascript
const greeting = "Hello, World!"
console.log(greeting)
javascript
const greeting = "Hello, World!"
console.log(greeting)
export function Themes() {const sample = `const greeting = "Hello, World!"\nconsole.log(greeting)`return (<YStack gap="$4"><CodeBlock code={sample} language="javascript" theme="light" showLineNumbers={false} /><CodeBlock code={sample} language="javascript" theme="dracula" showLineNumbers={false} /><CodeBlock code={sample} language="javascript" theme="nord" showLineNumbers={false} /></YStack>)}
Bare
No filename, no language and no copy button, so the header is dropped and only the numbered code remains.
1function fibonacci(n) {
2 if (n <= 1) {
3 return n
4 }
5 return fibonacci(n - 1) + fibonacci(n - 2)
6}
7
8const result = fibonacci(10)
9console.log(result) // 55
export function Bare() {return (<CodeBlock code={FIBONACCI} language="" showCopyButton={false} size="sm" maxHeight={160} />)}
Types
export type CodeBlockTheme =| 'dark'| 'light'| 'github'| 'github-dark'| 'vs-dark'| 'monokai'| 'dracula'| 'nord'
export type CodeBlockSize = 'sm' | 'default' | 'lg'
export interface CodeBlockDiff {added?: number[]removed?: number[]}
export interface CodeBlockProps extends Omit<ComponentProps<'div'>, 'children'> {code: stringlanguage?: stringfilename?: stringtheme?: CodeBlockTheme | nullsize?: CodeBlockSize | nullshowLineNumbers?: booleanhighlightLines?: number[]showCopyButton?: boolean/** The body's ceiling, in px or any CSS length; past it the body scrolls. */maxHeight?: number | stringdiff?: CodeBlockDiff}
Exports
CodeBlocktype CodeBlockDifftype CodeBlockPropstype CodeBlockSizetype CodeBlockTheme