CodeBlock

The CodeBlock component provides syntax highlighting, line numbers, and copy to clipboard functionality for code blocks.

Installation

pnpm dlx shadcn-svelte@latest add https://svelte-ai-elements.vercel.app/r/code.json

If you prefer using jsrepo, please install via the command below:

pnpm dlx jsrepo add @ai/elements/ai-elements/code

Usage

Usage with AI SDK

Build a simple code generation tool using the streamObject function from the AI SDK.

Add the following component to your frontend:

+page.svelte

Add the following route to your backend:

api/codegen/+server.ts

Features

  • Syntax highlighting with Shiki
  • Line numbers (optional)
  • Copy to clipboard functionality
  • Automatic light/dark theme switching
  • Customizable styles
  • Accessible design

Props

Code

PropTypeDefaultDescription
codestring-The code string to syntax highlight and display (required)
langSupportedLanguage'typescript'Programming language for syntax highlighting
variant'default' | 'ghost''default'Visual style variant of the code block
hideLinesbooleanfalseWhether to hide line numbers
highlight(number | [number, number])[][]Array of line numbers or ranges to highlight (e.g., [1, [3, 5], 7])
classstring-Additional CSS classes to apply to the code container
childrenSnippet-Child components (typically CodeCopyButton or CodeOverflow)
refHTMLDivElement-Bindable reference to the code container element
...restPropsHTMLAttributes<HTMLDivElement>-All other div props are supported

CodeCopyButton

PropTypeDefaultDescription
variantButtonProps['variant']'ghost'Button variant style
sizeButtonProps['size']'icon'Button size
classstring-Additional CSS classes to apply to the copy button
refHTMLButtonElement-Bindable reference to the button element
...restPropsCopyButtonProps-All other CopyButton component props are supported

CodeOverflow

PropTypeDefaultDescription
collapsedbooleantrueWhether the code block is collapsed (bindable)
classstring-Additional CSS classes to apply to the overflow container
childrenSnippet-Code content to render with overflow control
...restPropsHTMLAttributes<HTMLDivElement>-All other div props are supported