logo
导航

CodePanel

Introduction

CodePanel is a professional code display panel component that provides high-quality code syntax highlighting based on Shiki. It supports 180+ programming languages and multiple VS Code themes, providing the best code display experience for developer documentation and tutorials.

Component Features:

  • 🎨 Syntax Highlighting: Based on Shiki, supports 180+ programming languages
  • 🎭 Multi-theme Support: Supports VS Code themes (dark-plus, light-plus, github-dark, etc.)
  • 🚀 Performance Optimized: Server-side rendering, avoiding client-side repeated computation
  • 📱 Responsive Design: Adapts to different screen sizes
  • 🎯 Accessibility: Semantic HTML structure with keyboard navigation support
  • 🔧 Highly Customizable: Supports custom themes and styles

Basic Usage

Simple code display:

function greet(name) {
  console.log(`Hello!`);
  return `Welcome to CodePanel!`;
}

greet();
interface User {
  id: number;
  name: string;
  email?: string;
}

const createUser = (userData: Partial<User>): User => {
  return {
    id: Date.now(),
    name: 'Unknown',
    ...userData
  };
};

const user = createUser({ name: 'Alice', email: 'alice@example.com' });
def fibonacci(n):
    """Generate Fibonacci sequence up to n terms"""
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    
    sequence = [0, 1]
    for i in range(2, n):
        sequence.append(sequence[i-1] + sequence[i-2])
    
    return sequence

# Generate first 10 Fibonacci numbers
fib_numbers = fibonacci(10)
print(f"Fibonacci sequence: {fib_numbers}")
---
/**
 * @component CodePanelBasicJavascript
 * @description CodePanel 组件 JavaScript 代码高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const javascriptCode = `function greet(name) {
  console.log(\`Hello!\`);
  return \`Welcome to CodePanel!\`;
}

greet();`;
---

<CodePanel code={javascriptCode} language="javascript" />
function greet(name) {
  console.log(`Hello!`);
  return `Welcome to CodePanel!`;
}

greet();
interface User {
  id: number;
  name: string;
  email?: string;
}

const createUser = (userData: Partial<User>): User => {
  return {
    id: Date.now(),
    name: 'Unknown',
    ...userData
  };
};

const user = createUser({ name: 'Alice', email: 'alice@example.com' });
def fibonacci(n):
    """Generate Fibonacci sequence up to n terms"""
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    
    sequence = [0, 1]
    for i in range(2, n):
        sequence.append(sequence[i-1] + sequence[i-2])
    
    return sequence

# Generate first 10 Fibonacci numbers
fib_numbers = fibonacci(10)
print(f"Fibonacci sequence: {fib_numbers}")
---
/**
 * @component CodePanelBasicTypescript
 * @description CodePanel 组件 TypeScript 代码高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const typescriptCode = `interface User {
  id: number;
  name: string;
  email?: string;
}

const createUser = (userData: Partial<User>): User => {
  return {
    id: Date.now(),
    name: 'Unknown',
    ...userData
  };
};

const user = createUser({ name: 'Alice', email: 'alice@example.com' });`;
---

<CodePanel code={typescriptCode} language="typescript" />
function greet(name) {
  console.log(`Hello!`);
  return `Welcome to CodePanel!`;
}

greet();
interface User {
  id: number;
  name: string;
  email?: string;
}

const createUser = (userData: Partial<User>): User => {
  return {
    id: Date.now(),
    name: 'Unknown',
    ...userData
  };
};

const user = createUser({ name: 'Alice', email: 'alice@example.com' });
def fibonacci(n):
    """Generate Fibonacci sequence up to n terms"""
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    
    sequence = [0, 1]
    for i in range(2, n):
        sequence.append(sequence[i-1] + sequence[i-2])
    
    return sequence

# Generate first 10 Fibonacci numbers
fib_numbers = fibonacci(10)
print(f"Fibonacci sequence: {fib_numbers}")
---
/**
 * @component CodePanelBasicPython
 * @description CodePanel 组件 Python 代码高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const pythonCode = `def fibonacci(n):
    """Generate Fibonacci sequence up to n terms"""
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    
    sequence = [0, 1]
    for i in range(2, n):
        sequence.append(sequence[i-1] + sequence[i-2])
    
    return sequence

# Generate first 10 Fibonacci numbers
fib_numbers = fibonacci(10)
print(f"Fibonacci sequence: {fib_numbers}")`;
---

<CodePanel code={pythonCode} language="python" />

Theme Switching

CodePanel supports multiple VS Code themes for consistent code reading experience:

// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
---
/**
 * @component CodePanelThemeDarkPlus
 * @description CodePanel 组件 dark-plus 主题高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const sampleCode = `// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}`;
---

<CodePanel code={sampleCode} language="typescript" theme="dark-plus" />
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
---
/**
 * @component CodePanelThemeLightPlus
 * @description CodePanel 组件 light-plus 主题高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const sampleCode = `// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}`;
---

<CodePanel code={sampleCode} language="typescript" theme="light-plus" />
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
---
/**
 * @component CodePanelThemeGithubDark
 * @description CodePanel 组件 github-dark 主题高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const sampleCode = `// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}`;
---

<CodePanel code={sampleCode} language="typescript" theme="github-dark" />
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}
---
/**
 * @component CodePanelThemeGithubLight
 * @description CodePanel 组件 github-light 主题高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const sampleCode = `// React Hook for theme management
import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');
  
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);
  
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  return { theme, toggleTheme };
}`;
---

<CodePanel code={sampleCode} language="typescript" theme="github-light" />

Multi-language Support

Supports syntax highlighting for 180+ programming languages:

---
// Astro 组件示例
interface Props {
  title: string;
  description?: string;
}

const { title, description } = Astro.props;
---

<div class="card">
  <h2>{title}</h2>
  {description && <p>{description}</p>}
</div>

<style>
  .card {
    padding: 1rem;
    border-radius: 0.5rem;
    background: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
</style>
package main

import (
    "fmt"
    "net/http"
    "encoding/json"
)

type User struct {
    ID   int    'json:"id"'
    Name string 'json:"name"'
    Email string 'json:"email"'
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
    user := User{
        ID:   1,
        Name: "Alice",
        Email: "alice@example.com",
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/user", getUserHandler)
    fmt.Println("Server starting on :8080")
    http.ListenAndServe(":8080", nil)
}
use std::collections::HashMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    email: Option<String>,
}

impl User {
    fn new(id: u64, name: String) -> Self {
        Self {
            id,
            name,
            email: None,
        }
    }
    
    fn with_email(mut self, email: String) -> Self {
        self.email = Some(email);
        self
    }
}

fn main() {
    let mut users: HashMap<u64, User> = HashMap::new();
    
    let user = User::new(1, "Alice".to_string())
        .with_email("alice@example.com".to_string());
    
    users.insert(user.id, user);
    
    println!("Users: {:#?}", users);
}
-- 用户管理系统数据库设计
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

CREATE TABLE profiles (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    bio TEXT,
    avatar_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 查询活跃用户及其资料
SELECT 
    u.id,
    u.username,
    u.email,
    p.first_name,
    p.last_name,
    p.bio
FROM users u
LEFT JOIN profiles p ON u.id = p.user_id
WHERE u.is_active = true
ORDER BY u.created_at DESC
LIMIT 10;
---
/**
 * @component CodePanelLanguageAstro
 * @description CodePanel 组件 Astro 语言高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const astroCode = `---
// Astro 组件示例
interface Props {
  title: string;
  description?: string;
}

const { title, description } = Astro.props;
---

<div class="card">
  <h2>{title}</h2>
  {description && <p>{description}</p>}
</div>

<style>
  .card {
    padding: 1rem;
    border-radius: 0.5rem;
    background: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
</style>`;
---

<CodePanel code={astroCode} language="astro" />
---
// Astro 组件示例
interface Props {
  title: string;
  description?: string;
}

const { title, description } = Astro.props;
---

<div class="card">
  <h2>{title}</h2>
  {description && <p>{description}</p>}
</div>

<style>
  .card {
    padding: 1rem;
    border-radius: 0.5rem;
    background: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
</style>
package main

import (
    "fmt"
    "net/http"
    "encoding/json"
)

type User struct {
    ID   int    'json:"id"'
    Name string 'json:"name"'
    Email string 'json:"email"'
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
    user := User{
        ID:   1,
        Name: "Alice",
        Email: "alice@example.com",
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/user", getUserHandler)
    fmt.Println("Server starting on :8080")
    http.ListenAndServe(":8080", nil)
}
use std::collections::HashMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    email: Option<String>,
}

impl User {
    fn new(id: u64, name: String) -> Self {
        Self {
            id,
            name,
            email: None,
        }
    }
    
    fn with_email(mut self, email: String) -> Self {
        self.email = Some(email);
        self
    }
}

fn main() {
    let mut users: HashMap<u64, User> = HashMap::new();
    
    let user = User::new(1, "Alice".to_string())
        .with_email("alice@example.com".to_string());
    
    users.insert(user.id, user);
    
    println!("Users: {:#?}", users);
}
-- 用户管理系统数据库设计
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

CREATE TABLE profiles (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    bio TEXT,
    avatar_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 查询活跃用户及其资料
SELECT 
    u.id,
    u.username,
    u.email,
    p.first_name,
    p.last_name,
    p.bio
FROM users u
LEFT JOIN profiles p ON u.id = p.user_id
WHERE u.is_active = true
ORDER BY u.created_at DESC
LIMIT 10;
---
/**
 * @component CodePanelLanguageGo
 * @description CodePanel 组件 Go 语言高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const goCode = `package main

import (
    "fmt"
    "net/http"
    "encoding/json"
)

type User struct {
    ID   int    'json:"id"'
    Name string 'json:"name"'
    Email string 'json:"email"'
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
    user := User{
        ID:   1,
        Name: "Alice",
        Email: "alice@example.com",
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/user", getUserHandler)
    fmt.Println("Server starting on :8080")
    http.ListenAndServe(":8080", nil)
}`;
---

<CodePanel code={goCode} language="go" />
---
// Astro 组件示例
interface Props {
  title: string;
  description?: string;
}

const { title, description } = Astro.props;
---

<div class="card">
  <h2>{title}</h2>
  {description && <p>{description}</p>}
</div>

<style>
  .card {
    padding: 1rem;
    border-radius: 0.5rem;
    background: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
</style>
package main

import (
    "fmt"
    "net/http"
    "encoding/json"
)

type User struct {
    ID   int    'json:"id"'
    Name string 'json:"name"'
    Email string 'json:"email"'
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
    user := User{
        ID:   1,
        Name: "Alice",
        Email: "alice@example.com",
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/user", getUserHandler)
    fmt.Println("Server starting on :8080")
    http.ListenAndServe(":8080", nil)
}
use std::collections::HashMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    email: Option<String>,
}

impl User {
    fn new(id: u64, name: String) -> Self {
        Self {
            id,
            name,
            email: None,
        }
    }
    
    fn with_email(mut self, email: String) -> Self {
        self.email = Some(email);
        self
    }
}

fn main() {
    let mut users: HashMap<u64, User> = HashMap::new();
    
    let user = User::new(1, "Alice".to_string())
        .with_email("alice@example.com".to_string());
    
    users.insert(user.id, user);
    
    println!("Users: {:#?}", users);
}
-- 用户管理系统数据库设计
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

CREATE TABLE profiles (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    bio TEXT,
    avatar_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 查询活跃用户及其资料
SELECT 
    u.id,
    u.username,
    u.email,
    p.first_name,
    p.last_name,
    p.bio
FROM users u
LEFT JOIN profiles p ON u.id = p.user_id
WHERE u.is_active = true
ORDER BY u.created_at DESC
LIMIT 10;
---
/**
 * @component CodePanelLanguageRust
 * @description CodePanel 组件 Rust 语言高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const rustCode = `use std::collections::HashMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    email: Option<String>,
}

impl User {
    fn new(id: u64, name: String) -> Self {
        Self {
            id,
            name,
            email: None,
        }
    }
    
    fn with_email(mut self, email: String) -> Self {
        self.email = Some(email);
        self
    }
}

fn main() {
    let mut users: HashMap<u64, User> = HashMap::new();
    
    let user = User::new(1, "Alice".to_string())
        .with_email("alice@example.com".to_string());
    
    users.insert(user.id, user);
    
    println!("Users: {:#?}", users);
}`;
---

<CodePanel code={rustCode} language="rust" />
---
// Astro 组件示例
interface Props {
  title: string;
  description?: string;
}

const { title, description } = Astro.props;
---

<div class="card">
  <h2>{title}</h2>
  {description && <p>{description}</p>}
</div>

<style>
  .card {
    padding: 1rem;
    border-radius: 0.5rem;
    background: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
</style>
package main

import (
    "fmt"
    "net/http"
    "encoding/json"
)

type User struct {
    ID   int    'json:"id"'
    Name string 'json:"name"'
    Email string 'json:"email"'
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
    user := User{
        ID:   1,
        Name: "Alice",
        Email: "alice@example.com",
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/user", getUserHandler)
    fmt.Println("Server starting on :8080")
    http.ListenAndServe(":8080", nil)
}
use std::collections::HashMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    email: Option<String>,
}

impl User {
    fn new(id: u64, name: String) -> Self {
        Self {
            id,
            name,
            email: None,
        }
    }
    
    fn with_email(mut self, email: String) -> Self {
        self.email = Some(email);
        self
    }
}

fn main() {
    let mut users: HashMap<u64, User> = HashMap::new();
    
    let user = User::new(1, "Alice".to_string())
        .with_email("alice@example.com".to_string());
    
    users.insert(user.id, user);
    
    println!("Users: {:#?}", users);
}
-- 用户管理系统数据库设计
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

CREATE TABLE profiles (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    bio TEXT,
    avatar_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 查询活跃用户及其资料
SELECT 
    u.id,
    u.username,
    u.email,
    p.first_name,
    p.last_name,
    p.bio
FROM users u
LEFT JOIN profiles p ON u.id = p.user_id
WHERE u.is_active = true
ORDER BY u.created_at DESC
LIMIT 10;
---
/**
 * @component CodePanelLanguageSQL
 * @description CodePanel 组件 SQL 语言高亮示例
 */
import { CodePanel } from '@coffic/cosy-ui';

const sqlCode = `-- 用户管理系统数据库设计
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

CREATE TABLE profiles (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    bio TEXT,
    avatar_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 查询活跃用户及其资料
SELECT 
    u.id,
    u.username,
    u.email,
    p.first_name,
    p.last_name,
    p.bio
FROM users u
LEFT JOIN profiles p ON u.id = p.user_id
WHERE u.is_active = true
ORDER BY u.created_at DESC
LIMIT 10;`;
---

<CodePanel code={sqlCode} language="sql" />

Props

PropTypeDefaultDescription
codestring-Code string to display (required)
languagestring'typescript'Code language for syntax highlighting
themestring'dark-plus'Theme name
showLineNumbersbooleanfalseWhether to show line numbers
visiblebooleantrueWhether to show in panel
classstring-Custom class name

Supported Themes

  • dark-plus - VS Code default dark theme
  • light-plus - VS Code default light theme
  • github-dark - GitHub dark theme
  • github-light - GitHub light theme
  • nord - Nord theme
  • dracula - Dracula theme

Supported Languages

CodePanel supports all programming languages supported by Shiki, including but not limited to:

  • Frontend: JavaScript, TypeScript, HTML, CSS, SCSS, Vue, React, Astro
  • Backend: Python, Java, C#, Go, Rust, PHP, Ruby, Node.js
  • Database: SQL, MongoDB, Redis
  • Configuration: JSON, YAML, TOML, XML
  • Scripts: Shell, PowerShell, Bash
  • Others: Markdown, Docker, Kubernetes, Terraform

Best Practices

1. Performance Optimization

<!-- Recommended: Specify exact language, avoid auto-detection -->
<CodePanel 
  code={code}
  language="typescript"
/>

<!-- Avoid: Using generic language may affect highlighting quality -->
<CodePanel 
  code={code}
  language="text"
/>

2. Theme Selection

<!-- Choose appropriate code theme based on page theme -->
<CodePanel 
  code={code}
  language="javascript"
  theme="github-light"  // Suitable for light pages
/>

<CodePanel 
  code={code}
  language="javascript"  
  theme="github-dark"   // Suitable for dark pages
/>

3. Use in Container

---
import { CodeContainer, CodePanel } from '@coffic/cosy-ui';
---

<CodeContainer codes={[sourceCode]}>
  <div id="tab-1">
    <YourComponent />
  </div>
</CodeContainer>

Notes

  1. Code Escaping: Ensure the input code string properly escapes special characters
  2. Theme Consistency: Maintain theme consistency within the same page for better user experience
  3. Performance Considerations: Large amounts of code blocks may affect page loading speed, consider lazy loading
  4. Mobile Adaptation: Long code lines will produce horizontal scrolling on mobile devices, pay attention to code formatting

FAQ

Q: Why is the highlighting effect poor for some languages?

A: Please ensure the specified language parameter matches the actual code language and that the language is supported by Shiki.

Q: How to customize code styles?

A: You can add custom CSS classes through the class attribute, or override default styles through CSS variables.

Q: How to handle very long code?

A: The component automatically adds horizontal scroll bars. For extremely long code, consider segmented display or providing download links.