Docs

Code Snippet

A lightweight syntax-highlighted code display component with copy functionality and optional file titles.

factorial.py

1def calculate_factorial(n):
2 if n < 0:
3 raise ValueError("Factorial is not defined for negative numbers")
4 if n == 0 or n == 1:
5 return 1
6 return n * calculate_factorial(n - 1)
7
8def main():
9 try:
10 number = int(input("Enter a number: "))
11 result = calculate_factorial(number)
12 print(f"The factorial of {number} is {result}")
13 except ValueError as e:
14 print(f"Error: {e}")
15
16if __name__ == "__main__":
17 main()

Overview

The Code Snippet component provides a clean, lightweight way to display syntax-highlighted code blocks with built-in copy functionality. It uses Prism for syntax highlighting and includes line numbers and hover effects for better code readability.

Installation

pnpm dlx shadcn@latest add https://deltacomponents.dev/r/code-snippet.json

Usage

"use client"
import { CodeSnippet } from "@/registry/media/code-snippet"
export function Component() {
const code = `function hello() {
console.log("Hello, world!");
}`
return (
<CodeSnippet
title="hello.js"
code={code}
language="javascript"
showLineNumbers={true}
/>
)
}

Custom Theme Example

import { PrismTheme } from "prism-react-renderer"
import { CodeSnippet } from "@/registry/media/code-snippet"
const lightTheme: PrismTheme = {
plain: {
color: "#24292e",
backgroundColor: "#FFFFFF",
},
styles: [
{
types: ["comment"],
style: { color: "#6a737d", fontStyle: "italic" },
},
{
types: ["keyword"],
style: { color: "#d73a49" },
},
// ... more styles
],
}
export function CustomThemeExample() {
return (
<CodeSnippet
code="const greeting = 'Hello, world!';"
language="javascript"
theme={lightTheme}
showLineNumbers={false}
/>
)
}

Tabbed Code Snippets

The CodeSnippet component supports tabbed interfaces for displaying multiple related code examples or different approaches to the same task.

"use client"
import { useState } from "react"
import { CodeSnippet } from "@/registry/media/code-snippet"
export function TabbedExample() {
const [activeTab, setActiveTab] = useState("npm")
const installationTabs = {
npm: {
code: "npm install @radix-ui/react-dialog lucide-react",
language: "bash",
},
pnpm: {
code: "pnpm add @radix-ui/react-dialog lucide-react",
language: "bash",
},
yarn: {
code: "yarn add @radix-ui/react-dialog lucide-react",
language: "bash",
},
bun: {
code: "bun add @radix-ui/react-dialog lucide-react",
language: "bash",
},
}
return (
<CodeSnippet
code={installationTabs[activeTab].code}
language="bash"
showLineNumbers={false}
tabs={installationTabs}
activeTab={activeTab}
onTabChange={setActiveTab}
/>
)
}

Adaptive Theme Example

import { PrismTheme } from "prism-react-renderer"
import { CodeSnippet } from "@/registry/media/code-snippet"
const lightTheme: PrismTheme = {
plain: { color: "#24292f", backgroundColor: "#ffffff" },
styles: [
{ types: ["keyword"], style: { color: "#cf222e" } },
{ types: ["string"], style: { color: "#0a3069" } },
// ... more light theme styles
],
}
const darkTheme: PrismTheme = {
plain: { color: "#e6edf3", backgroundColor: "#0d1117" },
styles: [
{ types: ["keyword"], style: { color: "#ff7b72" } },
{ types: ["string"], style: { color: "#a5d6ff" } },
// ... more dark theme styles
],
}
export function AdaptiveThemeExample() {
return (
<CodeSnippet
code="const greeting = 'Hello, world!';"
language="javascript"
adaptiveTheme={{ light: lightTheme, dark: darkTheme }}
showLineNumbers={true}
/>
)
}

API Reference

CodeSnippet

NameTypeDefaultDescription
titlestring-Optional title displayed in the header
codestring-The code content to display
languagestring"typescript"Programming language for syntax highlighting
classNamestring-Additional CSS classes
borderbooleantrueWhether to show the border around the component
themePrismTheme-Custom theme object for syntax highlighting
showLineNumbersbooleantrueWhether to display line numbers
adaptiveTheme{ light: PrismTheme, dark: PrismTheme }-Themes that automatically adapt to dark/light mode
tabs{ [key: string]: { code: string; language?: string } }-Tab data for multi-code display
activeTabstring-Currently active tab key
onTabChange(tab: string) => void-Callback fired when tab is changed

Theme Schema

The theme prop accepts a PrismTheme object that defines colors and styles for syntax highlighting. The theme object follows this schema:

{
"plain": {
"color": "#24292e",
"backgroundColor": "#FFFFFF"
},
"styles": [
{
"types": ["comment"],
"style": {
"color": "#6a737d",
"fontStyle": "italic"
}
},
{
"types": ["keyword", "property", "property-access", "attr-name"],
"style": {
"color": "#d73a49"
}
},
{
"types": ["tag"],
"style": {
"color": "#22863a"
}
},
{
"types": ["punctuation", "symbol", "dom"],
"style": {
"color": "#24292e"
}
},
{
"types": ["definition", "function"],
"style": {
"color": "#6f42c1"
}
},
{
"types": ["string", "char", "attr-value"],
"style": {
"color": "#032f62"
}
},
{
"types": ["static", "number"],
"style": {
"color": "#005cc5"
}
}
]
}

Theme Properties

  • plain: Base styles applied to all code content
    • color: Default text color
    • backgroundColor: Background color for the code area and header
  • styles: Array of style rules for different token types
    • types: Array of token types to target (e.g., "comment", "keyword", "string")
    • style: CSS properties to apply (color, fontStyle, fontWeight, etc.)

Common Token Types

  • comment - Code comments
  • keyword - Language keywords (if, function, const, etc.)
  • string - String literals
  • number - Numeric values
  • function - Function names
  • property - Object properties
  • punctuation - Brackets, semicolons, etc.
  • tag - HTML/JSX tags
  • attr-name - HTML/JSX attribute names
  • attr-value - HTML/JSX attribute values

Examples

Basic Code Snippet

Simple code display with syntax highlighting and copy functionality.

factorial.py

1def calculate_factorial(n):
2 if n < 0:
3 raise ValueError("Factorial is not defined for negative numbers")
4 if n == 0 or n == 1:
5 return 1
6 return n * calculate_factorial(n - 1)
7
8def main():
9 try:
10 number = int(input("Enter a number: "))
11 result = calculate_factorial(number)
12 print(f"The factorial of {number} is {result}")
13 except ValueError as e:
14 print(f"Error: {e}")
15
16if __name__ == "__main__":
17 main()

Theme Customization

Switch between dark and light themes for different visual preferences.

advanced-patterns.js

1// Advanced JavaScript patterns and concepts
2class EventEmitter {
3 constructor() {
4 this.events = new Map();
5 }
6
7 on(event, callback) {
8 if (!this.events.has(event)) {
9 this.events.set(event, []);
10 }
11 this.events.get(event).push(callback);
12 return () => this.off(event, callback);
13 }
14
15 off(event, callback) {
16 const callbacks = this.events.get(event);
17 if (callbacks) {
18 const index = callbacks.indexOf(callback);
19 if (index > -1) {
20 callbacks.splice(index, 1);
21 }
22 }
23 }
24
25 emit(event, ...args) {
26 const callbacks = this.events.get(event);
27 if (callbacks) {
28 callbacks.forEach(callback => {
29 try {
30 callback(...args);
31 } catch (error) {
32 console.error(`Error in event handler for ${event}:`, error);
33 }
34 });
35 }
36 }
37}
38
39// Usage with modern async/await patterns
40const api = {
41 async fetchUser(id) {
42 const response = await fetch(`/api/users/${id}`);
43 if (!response.ok) {
44 throw new Error(`Failed to fetch user: ${response.statusText}`);
45 }
46 return response.json();
47 },
48
49 async updateUser(id, data) {
50 const response = await fetch(`/api/users/${id}`, {
51 method: 'PATCH',
52 headers: {
53 'Content-Type': 'application/json',
54 },
55 body: JSON.stringify(data),
56 });
57 return response.json();
58 }
59};
60
61// Functional programming with higher-order functions
62const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
63const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
64
65const addTax = (rate) => (price) => price * (1 + rate);
66const applyDiscount = (discount) => (price) => price * (1 - discount);
67const formatCurrency = (price) => `$${price.toFixed(2)}`;
68
69const calculatePrice = pipe(
70 addTax(0.08),
71 applyDiscount(0.1),
72 formatCurrency
73);
74
75console.log(calculatePrice(100)); // $97.20

Display Options

Toggle various display options including title, border, and line numbers.

fibonacci.js

1function fibonacci(n) {
2 if (n <= 1) return n;
3 return fibonacci(n - 1) + fibonacci(n - 2);
4}
5
6// Calculate the 10th Fibonacci number
7const result = fibonacci(10);
8console.log(`Fibonacci(10) = ${result}`);
9
10// More efficient iterative approach
11function fibonacciIterative(n) {
12 let a = 0, b = 1, temp;
13 for (let i = 2; i <= n; i++) {
14 temp = a + b;
15 a = b;
16 b = temp;
17 }
18 return n === 0 ? a : b;
19}

C++20 with Custom Theme

Modern C++20 features showcased with a custom purple-blue theme optimized for C++ syntax.

modern_cpp20.cpp

1#include <iostream>
2#include <vector>
3#include <ranges>
4#include <concepts>
5#include <coroutine>
6#include <format>
7
8// C++20 Concepts
9template<typename T>
10concept Numeric = std::integral<T> || std::floating_point<T>;
11
12template<Numeric T>
13auto multiply(T a, T b) -> T {
14 return a * b;
15}
16
17// C++20 Coroutines
18struct Generator {
19 struct promise_type {
20 int current_value;
21
22 Generator get_return_object() {
23 return Generator{handle_type::from_promise(*this)};
24 }
25
26 std::suspend_always initial_suspend() { return {}; }
27 std::suspend_always final_suspend() noexcept { return {}; }
28 void unhandled_exception() {}
29
30 std::suspend_always yield_value(int value) {
31 current_value = value;
32 return {};
33 }
34 };
35
36 using handle_type = std::coroutine_handle<promise_type>;
37 handle_type coro;
38
39 Generator(handle_type h) : coro(h) {}
40 ~Generator() { if (coro) coro.destroy(); }
41};
42
43Generator fibonacci() {
44 int a = 0, b = 1;
45 while (true) {
46 co_yield a;
47 auto next = a + b;
48 a = b;
49 b = next;
50 }
51}
52
53int main() {
54 // C++20 Ranges and Views
55 std::vector<int> numbers{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
56
57 auto even_squares = numbers
58 | std::views::filter([](int n) { return n % 2 == 0; })
59 | std::views::transform([](int n) { return n * n; });
60
61 // C++20 Format library
62 std::cout << std::format("Even squares: ");
63 for (auto value : even_squares) {
64 std::cout << std::format("{} ", value);
65 }
66 std::cout << std::endl;
67
68 // Using concepts
69 auto result = multiply(3.14, 2.71);
70 std::cout << std::format("Result: {:.2f}\n", result);
71
72 return 0;
73}

Adaptive Dark/Light Mode

Automatically adapts to your system's dark/light mode preference using the adaptiveTheme prop.

The code snippet automatically follows your theme preference. This demo shows custom light and dark themes that switch automatically.

TodoApp.tsx

1import React, { useState, useEffect } from 'react'
2import { motion, AnimatePresence } from 'motion/react'
3
4interface TodoItem {
5 id: string
6 text: string
7 completed: boolean
8 createdAt: Date
9}
10
11const TodoApp: React.FC = () => {
12 const [todos, setTodos] = useState<TodoItem[]>([])
13 const [inputValue, setInputValue] = useState('')
14 const [filter, setFilter] = useState<'all' | 'active' | 'completed'>('all')
15
16 useEffect(() => {
17 const savedTodos = localStorage.getItem('todos')
18 if (savedTodos) {
19 setTodos(JSON.parse(savedTodos))
20 }
21 }, [])
22
23 useEffect(() => {
24 localStorage.setItem('todos', JSON.stringify(todos))
25 }, [todos])
26
27 const addTodo = (e: React.FormEvent) => {
28 e.preventDefault()
29 if (inputValue.trim()) {
30 const newTodo: TodoItem = {
31 id: crypto.randomUUID(),
32 text: inputValue.trim(),
33 completed: false,
34 createdAt: new Date()
35 }
36 setTodos(prev => [...prev, newTodo])
37 setInputValue('')
38 }
39 }
40
41 const toggleTodo = (id: string) => {
42 setTodos(prev =>
43 prev.map(todo =>
44 todo.id === id ? { ...todo, completed: !todo.completed } : todo
45 )
46 )
47 }
48
49 const deleteTodo = (id: string) => {
50 setTodos(prev => prev.filter(todo => todo.id !== id))
51 }
52
53 const filteredTodos = todos.filter(todo => {
54 if (filter === 'active') return !todo.completed
55 if (filter === 'completed') return todo.completed
56 return true
57 })
58
59 return (
60 <div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-lg">
61 <h1 className="text-2xl font-bold text-gray-800 mb-6">
62 Todo App
63 </h1>
64
65 <form onSubmit={addTodo} className="mb-6">
66 <div className="flex gap-2">
67 <input
68 type="text"
69 value={inputValue}
70 onChange={(e) => setInputValue(e.target.value)}
71 placeholder="Add a new todo..."
72 className="flex-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
73 />
74 <button
75 type="submit"
76 className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
77 >
78 Add
79 </button>
80 </div>
81 </form>
82
83 <div className="flex gap-2 mb-4">
84 {(['all', 'active', 'completed'] as const).map(filterType => (
85 <button
86 key={filterType}
87 onClick={() => setFilter(filterType)}
88 className={`px-3 py-1 rounded-md text-sm transition-colors ${
89 filter === filterType
90 ? 'bg-blue-500 text-white'
91 : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
92 }`}
93 >
94 {filterType.charAt(0).toUpperCase() + filterType.slice(1)}
95 </button>
96 ))}
97 </div>
98
99 <AnimatePresence>
100 {filteredTodos.map(todo => (
101 <motion.div
102 key={todo.id}
103 initial={{ opacity: 0, y: -10 }}
104 animate={{ opacity: 1, y: 0 }}
105 exit={{ opacity: 0, y: -10 }}
106 className="flex items-center gap-3 p-3 bg-gray-50 rounded-md mb-2"
107 >
108 <input
109 type="checkbox"
110 checked={todo.completed}
111 onChange={() => toggleTodo(todo.id)}
112 className="rounded"
113 />
114 <span
115 className={`flex-1 ${
116 todo.completed ? 'line-through text-gray-500' : 'text-gray-800'
117 }`}
118 >
119 {todo.text}
120 </span>
121 <button
122 onClick={() => deleteTodo(todo.id)}
123 className="text-red-500 hover:text-red-700 transition-colors"
124 >
125 Delete
126 </button>
127 </motion.div>
128 ))}
129 </AnimatePresence>
130
131 {todos.length === 0 && (
132 <p className="text-gray-500 text-center py-8">
133 No todos yet. Add one above!
134 </p>
135 )}
136 </div>
137 )
138}
139
140export default TodoApp

Tabbed Code Snippets

Display multiple related code examples with tab navigation, perfect for showing installation commands across different package managers.

Package Installation

npm install @radix-ui/react-dialog lucide-react

Features

Syntax Highlighting

  • Powered by Prism React Renderer
  • Supports multiple programming languages
  • Dark theme optimized for readability

Copy Functionality

  • One-click copy to clipboard
  • Visual feedback with check icon
  • Positioned contextually based on content

Line Numbers

  • Automatic line numbering
  • Hover effects for better interaction
  • Proper spacing and alignment

Tabbed Interface

  • Support for multiple code examples in tabs
  • Seamless tab switching with state management
  • Compact tab design with underlined active states
  • Perfect for package manager commands or code alternatives

Responsive Design

  • Horizontal scrolling for long lines
  • Vertical scrolling for tall code blocks
  • Maximum height constraints for better layout