导航菜单

CodePanel

简介

CodePanel 是一个专业的代码展示面板组件,基于 Shiki 提供高质量的代码语法高亮效果。支持 180+ 编程语言和多种 VS Code 主题,为开发者文档和教程提供最佳的代码展示体验。

组件特性:

  • 🎨 语法高亮:基于 Shiki,支持 180+ 编程语言
  • 🎭 多主题支持:支持 VS Code 主题(dark-plus、light-plus、github-dark 等)
  • 🚀 性能优化:服务端渲染,避免客户端重复计算
  • 📱 响应式设计:自适应不同屏幕尺寸
  • 🎯 可访问性:语义化 HTML 结构,支持键盘导航
  • 🔧 高度可定制:支持自定义主题和样式

class

自定义 CSS 类名,用于覆盖默认样式。

<CodePanel code="console.log('class 属性示例');" class="my-custom-class" />

code

要显示的代码字符串(必需)。

复制成功
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" />
---



/**
 * @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" />
---



/**
 * @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" />

language

代码语言,用于语法高亮,默认 ‘typescript’。

复制成功
---



// 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 (
	"encoding/json"
	"fmt"
	"net/http"
)

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,
}

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 = 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;
---



import { CodePanel } from "@coffic/cosy-ui";
import astroCode from "./examples/astro/example.astro?raw";

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

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

<CodePanel code={astroCode} language="astro" />
---



/**
 * @component CodePanelLanguageSupportGo
 * @description CodePanel 组件 Go 语言高亮示例
 */
import { CodePanel } from "@coffic/cosy-ui";
import goCode from "./examples/go/example.go?raw";
---

<CodePanel code={goCode} language="go" />
---



/**
 * @component CodePanelLanguageSupportRust
 * @description CodePanel 组件 Rust 语言高亮示例
 */
import { CodePanel } from "@coffic/cosy-ui";
import rustCode from "./examples/rust/example.rs?raw";
---

<CodePanel code={rustCode} language="rust" />
---



/**
 * @component CodePanelLanguageSupportSQL
 * @description CodePanel 组件 SQL 语言高亮示例
 */
import { CodePanel } from "@coffic/cosy-ui";
import sqlCode from "./examples/sql/example.sql?raw";
---

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

showLineNumbers

是否显示行号,默认 false。

<CodePanel code="console.log('显示行号');" showLineNumbers={true} />

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 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" />
---



/**
 * @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" />
---



/**
 * @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" />
---



/**
 * @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" />

visible

是否显示在面板中,默认 true。

<CodePanel code="console.log('隐藏面板');" visible={false} />

搜索