代码块优化测试文档 #
本文档用于展示优化后的代码块配色方案和语法高亮效果。
概述 #
新的代码块样式采用了GitHub Dark主题配色,提供更好的对比度和可读性。主要特性包括:
- 🎨 深色主题:减少眼部疲劳
- 🌈 语法高亮:支持多种编程语言
- 📱 响应式设计:适配各种屏幕尺寸
- 🔧 自定义滚动条:更好的浏览体验
各种编程语言示例 #
JavaScript 代码 #
// JavaScript 示例 - 现代化的异步函数
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
return {
id: userData.id,
name: userData.name,
email: userData.email,
isActive: userData.status === 'active'
};
} catch (error) {
console.error('获取用户数据失败:', error);
throw new Error('无法获取用户信息');
}
}
// 使用示例
const user = await fetchUserData(123);
console.log(`用户 ${user.name} 的邮箱是: ${user.email}`);
Python 代码 #
# Python 示例 - 数据处理和分析
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
class DataProcessor:
"""数据处理器类"""
def __init__(self, data_source: str):
self.data_source = data_source
self.processed_data = None
def load_data(self) -> pd.DataFrame:
"""加载数据"""
try:
df = pd.read_csv(self.data_source)
print(f"成功加载 {len(df)} 条记录")
return df
except FileNotFoundError:
raise ValueError(f"找不到数据文件: {self.data_source}")
def process_data(self, df: pd.DataFrame) -> pd.DataFrame:
"""处理数据"""
# 数据清洗
df_cleaned = df.dropna()
# 数据转换
df_cleaned['processed_date'] = pd.to_datetime(df_cleaned['date'])
df_cleaned['value_normalized'] = (df_cleaned['value'] - df_cleaned['value'].mean()) / df_cleaned['value'].std()
return df_cleaned
# 使用示例
processor = DataProcessor('data/sales_data.csv')
raw_data = processor.load_data()
processed_data = processor.process_data(raw_data)
Bash/Shell 脚本 #
#!/bin/bash
# Bash 脚本示例 - 自动化部署脚本
# 设置变量
PROJECT_NAME="hugo-project"
DEPLOY_ENV="production"
BUILD_DIR="./public"
REMOTE_SERVER="user@server.com"
REMOTE_PATH="/var/www/html"
# 颜色输出函数
print_success() {
echo -e "\033[32m✅ $1\033[0m"
}
print_error() {
echo -e "\033[31m❌ $1\033[0m"
}
print_info() {
echo -e "\033[34mℹ️ $1\033[0m"
}
# 主要部署函数
deploy_site() {
print_info "开始部署 $PROJECT_NAME 到 $DEPLOY_ENV 环境..."
# 清理旧的构建文件
if [ -d "$BUILD_DIR" ]; then
rm -rf "$BUILD_DIR"
print_success "已清理旧的构建文件"
fi
# 构建站点
print_info "正在构建站点..."
if hugo --environment="$DEPLOY_ENV" --destination="$BUILD_DIR"; then
print_success "站点构建完成"
else
print_error "站点构建失败"
exit 1
fi
# 同步文件到服务器
print_info "正在同步文件到服务器..."
if rsync -avz --delete "$BUILD_DIR/" "$REMOTE_SERVER:$REMOTE_PATH/"; then
print_success "文件同步完成"
else
print_error "文件同步失败"
exit 1
fi
print_success "🎉 部署完成!"
}
# 执行部署
deploy_site
SQL 查询 #
-- SQL 示例 - 复杂的数据分析查询
WITH monthly_sales AS (
SELECT
DATE_TRUNC('month', order_date) AS month,
product_category,
SUM(order_amount) AS total_sales,
COUNT(DISTINCT customer_id) AS unique_customers,
AVG(order_amount) AS avg_order_value
FROM orders o
JOIN products p ON o.product_id = p.id
WHERE order_date >= '2024-01-01'
AND order_status = 'completed'
GROUP BY DATE_TRUNC('month', order_date), product_category
),
category_rankings AS (
SELECT
month,
product_category,
total_sales,
unique_customers,
avg_order_value,
ROW_NUMBER() OVER (PARTITION BY month ORDER BY total_sales DESC) as sales_rank,
LAG(total_sales) OVER (PARTITION BY product_category ORDER BY month) as prev_month_sales
FROM monthly_sales
)
SELECT
month,
product_category,
total_sales,
unique_customers,
ROUND(avg_order_value, 2) as avg_order_value,
sales_rank,
CASE
WHEN prev_month_sales IS NULL THEN 'N/A'
WHEN total_sales > prev_month_sales THEN '📈 增长'
WHEN total_sales < prev_month_sales THEN '📉 下降'
ELSE '➡️ 持平'
END as trend
FROM category_rankings
WHERE sales_rank <= 5 -- 只显示前5名类别
ORDER BY month DESC, sales_rank;
Go 语言 #
// Go 示例 - HTTP API 服务器
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
)
// User 结构体定义
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Created time.Time `json:"created"`
IsActive bool `json:"is_active"`
}
// UserService 用户服务接口
type UserService interface {
GetUser(id int) (*User, error)
CreateUser(user *User) error
UpdateUser(id int, user *User) error
DeleteUser(id int) error
}
// InMemoryUserService 内存用户服务实现
type InMemoryUserService struct {
users map[int]*User
nextID int
}
func NewInMemoryUserService() *InMemoryUserService {
return &InMemoryUserService{
users: make(map[int]*User),
nextID: 1,
}
}
func (s *InMemoryUserService) GetUser(id int) (*User, error) {
user, exists := s.users[id]
if !exists {
return nil, fmt.Errorf("用户 %d 不存在", id)
}
return user, nil
}
func (s *InMemoryUserService) CreateUser(user *User) error {
user.ID = s.nextID
user.Created = time.Now()
s.users[user.ID] = user
s.nextID++
return nil
}
// HTTP 处理器
func getUserHandler(service UserService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
http.Error(w, "无效的用户ID", http.StatusBadRequest)
return
}
user, err := service.GetUser(id)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
}
func main() {
service := NewInMemoryUserService()
r := mux.NewRouter()
r.HandleFunc("/api/users/{id}", getUserHandler(service)).Methods("GET")
fmt.Println("🚀 服务器启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", r))
}
YAML 配置 #
# YAML 示例 - Hugo 配置文件
baseURL: 'https://docs.example.com'
languageCode: 'zh-cn'
title: '技术文档中心'
theme: 'hugo-book'
# 多语言配置
languages:
zh:
languageName: '中文'
weight: 1
params:
BookDateFormat: '2006年1月2日'
BookSearch: true
BookComments: true
en:
languageName: 'English'
weight: 2
params:
BookDateFormat: 'January 2, 2006'
BookSearch: true
BookComments: true
# 主题参数
params:
# Book 主题配置
BookTheme: 'auto' # light, dark, auto
BookMenuBundle: '/menu'
BookSection: '*'
BookRepo: 'https://github.com/username/repo'
BookEditPage: true
BookSearch: true
BookComments: true
# 自定义参数
author: '技术团队'
description: '专业的技术文档和教程'
keywords: ['Hugo', '文档', '技术', '教程']
# 菜单配置
menu:
before:
- name: '首页'
url: '/'
weight: 10
- name: '文档'
url: '/docs/'
weight: 20
# 构建配置
build:
writeStats: true
# 标记配置
markup:
goldmark:
renderer:
unsafe: true
highlight:
style: 'github-dark'
lineNos: true
anchorLineNos: false
codeFences: true
内联代码示例 #
在文本中使用内联代码:const apiKey = 'your-api-key-here',或者引用函数 getUserById(123),以及文件路径 src/components/Header.tsx。
不同代码块大小对比 #
短代码块 #
print("Hello, World!")
中等代码块 #
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
长代码块(带滚动) #
// TypeScript 示例 - 复杂的类型定义和实现
interface APIResponse<T> {
success: boolean;
data?: T;
error?: string;
timestamp: number;
}
interface User {
id: number;
username: string;
email: string;
profile: UserProfile;
permissions: Permission[];
preferences: UserPreferences;
}
interface UserProfile {
firstName: string;
lastName: string;
avatar?: string;
bio?: string;
location?: string;
website?: string;
social: {
twitter?: string;
github?: string;
linkedin?: string;
};
}
interface Permission {
resource: string;
actions: ('read' | 'write' | 'delete' | 'admin')[];
}
interface UserPreferences {
theme: 'light' | 'dark' | 'auto';
language: string;
timezone: string;
notifications: {
email: boolean;
push: boolean;
sms: boolean;
};
}
class UserManager {
private users: Map<number, User> = new Map();
private nextId: number = 1;
async createUser(userData: Omit<User, 'id'>): Promise<APIResponse<User>> {
try {
const newUser: User = {
...userData,
id: this.nextId++,
};
// 验证用户数据
if (!this.validateUser(newUser)) {
return {
success: false,
error: '用户数据验证失败',
timestamp: Date.now(),
};
}
// 检查用户名是否已存在
const existingUser = Array.from(this.users.values())
.find(user => user.username === newUser.username);
if (existingUser) {
return {
success: false,
error: '用户名已存在',
timestamp: Date.now(),
};
}
this.users.set(newUser.id, newUser);
return {
success: true,
data: newUser,
timestamp: Date.now(),
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : '未知错误',
timestamp: Date.now(),
};
}
}
private validateUser(user: User): boolean {
return !!(
user.username &&
user.email &&
user.profile.firstName &&
user.profile.lastName &&
this.isValidEmail(user.email)
);
}
private isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
}
总结 #
新的代码块样式提供了:
- 更好的可读性 - 深色背景减少眼部疲劳
- 清晰的语法高亮 - 不同元素使用不同颜色区分
- 专业的外观 - 类似主流IDE的配色方案
- 响应式设计 - 在各种设备上都有良好表现
这些改进使得技术文档更加专业和易读。
测试完成时间: 2024年12月19日