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 16 return n * calculate_factorial(n - 1)78def 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}")1516if __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 (<CodeSnippettitle="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 (<CodeSnippetcode="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 (<CodeSnippetcode={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 (<CodeSnippetcode="const greeting = 'Hello, world!';"language="javascript"adaptiveTheme={{ light: lightTheme, dark: darkTheme }}showLineNumbers={true}/>)}
API Reference
CodeSnippet
Name | Type | Default | Description |
---|---|---|---|
title | string | - | Optional title displayed in the header |
code | string | - | The code content to display |
language | string | "typescript" | Programming language for syntax highlighting |
className | string | - | Additional CSS classes |
border | boolean | true | Whether to show the border around the component |
theme | PrismTheme | - | Custom theme object for syntax highlighting |
showLineNumbers | boolean | true | Whether 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 |
activeTab | string | - | 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 contentcolor
: Default text colorbackgroundColor
: Background color for the code area and header
styles
: Array of style rules for different token typestypes
: 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 commentskeyword
- Language keywords (if, function, const, etc.)string
- String literalsnumber
- Numeric valuesfunction
- Function namesproperty
- Object propertiespunctuation
- Brackets, semicolons, etc.tag
- HTML/JSX tagsattr-name
- HTML/JSX attribute namesattr-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 16 return n * calculate_factorial(n - 1)78def 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}")1516if __name__ == "__main__":17 main()
Theme Customization
Switch between dark and light themes for different visual preferences.
advanced-patterns.js
1// Advanced JavaScript patterns and concepts2class EventEmitter {3 constructor() {4 this.events = new Map();5 }67 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 }1415 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 }2425 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}3839// Usage with modern async/await patterns40const 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 },4849 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};6061// Functional programming with higher-order functions62const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);63const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);6465const addTax = (rate) => (price) => price * (1 + rate);66const applyDiscount = (discount) => (price) => price * (1 - discount);67const formatCurrency = (price) => `$${price.toFixed(2)}`;6869const calculatePrice = pipe(70 addTax(0.08),71 applyDiscount(0.1),72 formatCurrency73);7475console.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}56// Calculate the 10th Fibonacci number7const result = fibonacci(10);8console.log(`Fibonacci(10) = ${result}`);910// More efficient iterative approach11function 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>78// C++20 Concepts9template<typename T>10concept Numeric = std::integral<T> || std::floating_point<T>;1112template<Numeric T>13auto multiply(T a, T b) -> T {14 return a * b;15}1617// C++20 Coroutines18struct Generator {19 struct promise_type {20 int current_value;2122 Generator get_return_object() {23 return Generator{handle_type::from_promise(*this)};24 }2526 std::suspend_always initial_suspend() { return {}; }27 std::suspend_always final_suspend() noexcept { return {}; }28 void unhandled_exception() {}2930 std::suspend_always yield_value(int value) {31 current_value = value;32 return {};33 }34 };3536 using handle_type = std::coroutine_handle<promise_type>;37 handle_type coro;3839 Generator(handle_type h) : coro(h) {}40 ~Generator() { if (coro) coro.destroy(); }41};4243Generator 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}5253int main() {54 // C++20 Ranges and Views55 std::vector<int> numbers{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};5657 auto even_squares = numbers58 | std::views::filter([](int n) { return n % 2 == 0; })59 | std::views::transform([](int n) { return n * n; });6061 // C++20 Format library62 std::cout << std::format("Even squares: ");63 for (auto value : even_squares) {64 std::cout << std::format("{} ", value);65 }66 std::cout << std::endl;6768 // Using concepts69 auto result = multiply(3.14, 2.71);70 std::cout << std::format("Result: {:.2f}\n", result);7172 return 0;73}
Adaptive Dark/Light Mode
Automatically adapts to your system's dark/light mode preference using the adaptiveTheme
prop.
TodoApp.tsx
1import React, { useState, useEffect } from 'react'2import { motion, AnimatePresence } from 'motion/react'34interface TodoItem {5 id: string6 text: string7 completed: boolean8 createdAt: Date9}1011const TodoApp: React.FC = () => {12 const [todos, setTodos] = useState<TodoItem[]>([])13 const [inputValue, setInputValue] = useState('')14 const [filter, setFilter] = useState<'all' | 'active' | 'completed'>('all')1516 useEffect(() => {17 const savedTodos = localStorage.getItem('todos')18 if (savedTodos) {19 setTodos(JSON.parse(savedTodos))20 }21 }, [])2223 useEffect(() => {24 localStorage.setItem('todos', JSON.stringify(todos))25 }, [todos])2627 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 }4041 const toggleTodo = (id: string) => {42 setTodos(prev =>43 prev.map(todo =>44 todo.id === id ? { ...todo, completed: !todo.completed } : todo45 )46 )47 }4849 const deleteTodo = (id: string) => {50 setTodos(prev => prev.filter(todo => todo.id !== id))51 }5253 const filteredTodos = todos.filter(todo => {54 if (filter === 'active') return !todo.completed55 if (filter === 'completed') return todo.completed56 return true57 })5859 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 App63 </h1>6465 <form onSubmit={addTodo} className="mb-6">66 <div className="flex gap-2">67 <input68 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 <button75 type="submit"76 className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"77 >78 Add79 </button>80 </div>81 </form>8283 <div className="flex gap-2 mb-4">84 {(['all', 'active', 'completed'] as const).map(filterType => (85 <button86 key={filterType}87 onClick={() => setFilter(filterType)}88 className={`px-3 py-1 rounded-md text-sm transition-colors ${89 filter === filterType90 ? '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>9899 <AnimatePresence>100 {filteredTodos.map(todo => (101 <motion.div102 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 <input109 type="checkbox"110 checked={todo.completed}111 onChange={() => toggleTodo(todo.id)}112 className="rounded"113 />114 <span115 className={`flex-1 ${116 todo.completed ? 'line-through text-gray-500' : 'text-gray-800'117 }`}118 >119 {todo.text}120 </span>121 <button122 onClick={() => deleteTodo(todo.id)}123 className="text-red-500 hover:text-red-700 transition-colors"124 >125 Delete126 </button>127 </motion.div>128 ))}129 </AnimatePresence>130131 {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}139140export 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