"添加前端模板和运行代码模块"

This commit is contained in:
Codex
2026-06-01 13:43:09 +08:00
parent 24045274ad
commit 8092c4b1f8
587 changed files with 99761 additions and 0 deletions

View File

@@ -0,0 +1,318 @@
/**
* @fileoverview 主应用组件
* @description 负责应用的路由配置、布局和设计模式集成
*/
import React, { Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { useDesignModeStore } from './main';
// 页面组件(懒加载)
const Dashboard = React.lazy(() => import('./pages/Dashboard'));
const ComponentEditor = React.lazy(() => import('./pages/ComponentEditor'));
const DesignSystem = React.lazy(() => import('./pages/DesignSystem'));
const LivePreview = React.lazy(() => import('./pages/LivePreview'));
// 布局组件
import AppLayout from './components/layout/AppLayout';
import LoadingSpinner from './components/ui/LoadingSpinner';
// 页面过渡动画配置
const pageVariants = {
initial: {
opacity: 0,
y: 20,
},
in: {
opacity: 1,
y: 0,
},
out: {
opacity: 0,
y: -20,
},
};
const pageTransition = {
type: 'tween',
ease: 'anticipate',
duration: 0.3,
};
/**
* 页面容器组件 - 提供统一的页面布局和动画
*/
const PageContainer: React.FC<{
children: React.ReactNode;
title: string;
description?: string;
className?: string;
}> = ({ children, title, description, className = '' }) => (
<motion.div
initial="initial"
animate="in"
exit="out"
variants={pageVariants}
transition={pageTransition}
className={`page-container ${className}`}
data-page="main-content"
data-component="page-container"
data-element="content-wrapper"
>
<div
className="page-header mb-6"
data-element="page-header"
>
<h1
className="text-3xl font-bold text-neutral-900 dark:text-neutral-100"
data-element="page-title"
data-design-mode-component="PageTitle"
>
{title}
</h1>
{description && (
<p
className="mt-2 text-neutral-600 dark:text-neutral-400"
data-element="page-description"
>
{description}
</p>
)}
</div>
<div
className="page-content"
data-element="page-content"
>
{children}
</div>
</motion.div>
);
/**
* 页面路由配置组件
*/
const AppRoutes: React.FC = () => {
return (
<AppLayout>
<Suspense fallback={<LoadingSpinner />}>
<Routes>
{/* 默认重定向到仪表盘 */}
<Route
path="/"
element={
<Navigate
to="/dashboard"
replace
data-nav="/dashboard"
data-component="Navigation"
/>
}
/>
{/* 仪表盘页面 */}
<Route
path="/dashboard"
element={
<PageContainer
title="Dashboard"
description="Overview of design mode features and system status"
>
<Dashboard />
</PageContainer>
}
/>
{/* 组件编辑器页面 */}
<Route
path="/editor"
element={
<PageContainer
title="Component Editor"
description="Visual editor for building and customizing components"
className="h-full"
>
<ComponentEditor />
</PageContainer>
}
/>
{/* 设计系统页面 */}
<Route
path="/design-system"
element={
<PageContainer
title="Design System"
description="Manage colors, typography, spacing, and component variants"
>
<DesignSystem />
</PageContainer>
}
/>
{/* 实时预览页面 */}
<Route
path="/preview"
element={
<PageContainer
title="Live Preview"
description="Real-time preview of components and design changes"
className="h-full"
>
<LivePreview />
</PageContainer>
}
/>
{/* 404 页面 */}
<Route
path="*"
element={
<PageContainer title="404 - Page Not Found">
<div className="text-center py-12">
<h2 className="text-2xl font-semibold text-neutral-900 mb-4">
Page Not Found
</h2>
<p className="text-neutral-600 mb-6">
The page you're looking for doesn't exist.
</p>
<a
href="/dashboard"
className="inline-flex items-center px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 transition-colors"
data-action="navigate"
data-component="Button"
>
Go to Dashboard
</a>
</div>
</PageContainer>
}
/>
</Routes>
</Suspense>
</AppLayout>
);
};
/**
* 设计模式集成组件
*/
const DesignModeIntegration: React.FC = () => {
const { isDesignModeEnabled, selectedComponent, hoveredComponent } = useDesignModeStore();
// 为组件添加设计模式属性
React.useEffect(() => {
if (!isDesignModeEnabled) return;
const addDesignModeAttributes = () => {
const components = document.querySelectorAll('[data-component]');
components.forEach((element, index) => {
const componentName = element.getAttribute('data-component');
const elementName = element.getAttribute('data-element');
const action = element.getAttribute('data-action');
// 添加设计模式属性
element.setAttribute('data-design-mode', 'true');
element.setAttribute('data-design-mode-component', componentName || 'Unknown');
if (elementName) {
element.setAttribute('data-design-mode-element', elementName);
}
if (action) {
element.setAttribute('data-design-mode-action', action);
}
});
};
// 监听 DOM 变化
const observer = new MutationObserver(addDesignModeAttributes);
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
});
// 初始调用
addDesignModeAttributes();
return () => {
observer.disconnect();
};
}, [isDesignModeEnabled]);
// 添加全局样式
React.useEffect(() => {
if (isDesignModeEnabled) {
const style = document.createElement('style');
style.id = 'design-mode-styles';
style.textContent = `
[data-design-mode="true"] {
cursor: crosshair;
}
[data-design-mode="true"]:hover {
outline: 2px solid #3b82f6 !important;
outline-offset: 2px !important;
background-color: rgba(59, 130, 246, 0.05) !important;
}
[data-design-mode-active="true"] {
outline: 3px solid #ef4444 !important;
outline-offset: 2px !important;
background-color: rgba(239, 68, 68, 0.1) !important;
}
[data-design-mode-hover="true"] {
outline: 2px solid #f59e0b !important;
outline-offset: 2px !important;
background-color: rgba(245, 158, 11, 0.1) !important;
}
`;
document.head.appendChild(style);
return () => {
document.getElementById('design-mode-styles')?.remove();
};
}
}, [isDesignModeEnabled]);
return null;
};
/**
* 主应用组件
*/
const App: React.FC = () => {
const { isDesignModeEnabled } = useDesignModeStore();
return (
<div
className={`app ${isDesignModeEnabled ? 'design-mode-enabled' : ''}`}
data-app="full-featured-showcase"
data-component="App"
data-design-mode={isDesignModeEnabled ? 'true' : 'false'}
>
{/* 设计模式集成 */}
<DesignModeIntegration />
{/* 主要内容 */}
<AnimatePresence mode="wait">
<AppRoutes />
</AnimatePresence>
{/* 开发模式信息 */}
{import.meta.env.DEV && (
<div
className="fixed bottom-4 right-4 bg-neutral-800 text-white p-3 rounded-lg text-xs z-50"
data-component="DevInfo"
data-element="debug-panel"
>
<div>Design Mode: {isDesignModeEnabled ? 'Enabled' : 'Disabled'}</div>
<div>React: {React.version}</div>
<div>Vite: {import.meta.env.MODE}</div>
</div>
)}
</div>
);
};
export default App;

View File

@@ -0,0 +1,484 @@
/**
* @fileoverview 颜色面板组件
* @description 展示和管理设计系统中的颜色令牌
*/
import React, { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Search, Filter, Grid, List, Plus, MoreVertical } from 'lucide-react';
import { Card, CardBody, CardHeader } from '../ui/Card';
import { Button, IconButton } from '../ui/Button';
import { ColorToken } from '../../types/design-system';
import { useColors, useDesignSystemStore } from '../../store/design-system-store';
import { clsx } from 'clsx';
// 颜色面板属性接口
interface ColorPaletteProps {
title?: string;
variant?: 'grid' | 'list' | 'swatch';
showControls?: boolean;
interactive?: boolean;
className?: string;
}
// 颜色色板属性接口
interface ColorSwatchProps {
token: ColorToken;
variant?: 'default' | 'compact' | 'large';
showLabel?: boolean;
showValue?: boolean;
interactive?: boolean;
onClick?: () => void;
className?: string;
}
/**
* 颜色色板组件
*/
const ColorSwatch: React.FC<ColorSwatchProps> = ({
token,
variant = 'default',
showLabel = true,
showValue = true,
interactive = true,
onClick,
className
}) => {
const [copied, setCopied] = useState(false);
const { setSelectedToken } = useDesignSystemStore();
// 复制颜色值
const copyColor = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
await navigator.clipboard.writeText(token.value);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy color:', error);
}
};
// 处理点击
const handleClick = () => {
if (interactive) {
setSelectedToken(token);
onClick?.();
}
};
// 尺寸配置
const sizeConfig = {
default: { width: 'w-full', height: 'h-20', padding: 'p-4' },
compact: { width: 'w-full', height: 'h-12', padding: 'p-2' },
large: { width: 'w-full', height: 'h-32', padding: 'p-6' },
};
const config = sizeConfig[variant];
// 显示文本颜色(基于背景亮度)
const getContrastColor = (hexColor: string) => {
// 简单的亮度计算
const r = parseInt(hexColor.slice(1, 3), 16);
const g = parseInt(hexColor.slice(3, 5), 16);
const b = parseInt(hexColor.slice(5, 7), 16);
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
return brightness > 128 ? '#000000' : '#ffffff';
};
return (
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
whileHover={interactive ? { scale: 1.02 } : {}}
whileTap={interactive ? { scale: 0.98 } : {}}
className={clsx(
'color-swatch cursor-pointer group relative overflow-hidden rounded-lg border border-neutral-200 dark:border-neutral-700 transition-all duration-200',
config.width,
config.height,
{
'hover:shadow-lg': interactive,
'hover:border-primary-300': interactive,
},
className
)}
data-component="ColorSwatch"
data-element="swatch"
data-token-name={token.name}
data-palette={token.palette}
data-scale={token.scale}
style={{ backgroundColor: token.value }}
onClick={handleClick}
>
{/* 颜色背景 */}
<div
className="absolute inset-0"
style={{ backgroundColor: token.value }}
data-element="background"
/>
{/* 覆盖层 */}
<div
className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-10 transition-all duration-200"
data-element="overlay"
/>
{/* 色板内容 */}
<div
className={clsx(
'relative z-10 flex flex-col justify-between h-full',
config.padding
)}
data-element="content"
>
{/* 顶部标签 */}
{showLabel && (
<div className="flex items-center justify-between" data-element="header">
<div className="flex items-center space-x-2" data-element="labels">
<span
className="px-2 py-1 text-xs font-semibold rounded backdrop-blur-sm"
style={{
backgroundColor: 'rgba(0, 0, 0, 0.2)',
color: getContrastColor(token.value)
}}
data-element="name"
>
{token.name}
</span>
{token.deprecated && (
<span className="px-1.5 py-0.5 text-xs bg-warning-500 text-white rounded backdrop-blur-sm">
Deprecated
</span>
)}
</div>
{interactive && (
<IconButton
size="sm"
variant="ghost"
onClick={copyColor}
className="opacity-0 group-hover:opacity-100 transition-opacity"
data-component="IconButton"
data-element="copy-button"
data-action="copy-color"
>
{copied ? (
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
className="text-success-400"
>
</motion.div>
) : (
<span
className="text-sm font-mono"
style={{ color: getContrastColor(token.value) }}
>
#
</span>
)}
</IconButton>
)}
</div>
)}
{/* 底部信息 */}
{showValue && (
<div className="space-y-1" data-element="footer">
<div
className="text-xs font-mono backdrop-blur-sm px-2 py-1 rounded"
style={{
backgroundColor: 'rgba(0, 0, 0, 0.2)',
color: getContrastColor(token.value)
}}
data-element="value"
>
{token.value}
</div>
{token.scale && token.palette && (
<div
className="text-xs backdrop-blur-sm px-2 py-1 rounded"
style={{
backgroundColor: 'rgba(0, 0, 0, 0.1)',
color: getContrastColor(token.value)
}}
data-element="metadata"
>
{token.palette} {token.scale}
</div>
)}
</div>
)}
</div>
{/* 选择指示器 */}
<AnimatePresence>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="absolute top-2 right-2 w-3 h-3 bg-primary-500 rounded-full border-2 border-white shadow-sm"
data-element="selected-indicator"
/>
</AnimatePresence>
</motion.div>
);
};
/**
* 颜色面板主组件
*/
const ColorPalette: React.FC<ColorPaletteProps> = ({
title = 'Color Palette',
variant = 'grid',
showControls = true,
interactive = true,
className
}) => {
const [searchQuery, setSearchQuery] = useState('');
const [selectedPalette, setSelectedPalette] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
const [showFilters, setShowFilters] = useState(false);
const colors = useColors();
const { setSelectedToken, selectedToken } = useDesignSystemStore();
// 过滤和搜索颜色
const filteredColors = useMemo(() => {
return colors.filter(color => {
const matchesSearch = searchQuery === '' ||
color.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
color.value.toLowerCase().includes(searchQuery.toLowerCase()) ||
color.description?.toLowerCase().includes(searchQuery.toLowerCase());
const matchesPalette = selectedPalette === null ||
color.palette === selectedPalette;
return matchesSearch && matchesPalette;
});
}, [colors, searchQuery, selectedPalette]);
// 按调色板分组
const colorsByPalette = useMemo(() => {
const grouped: Record<string, ColorToken[]> = {};
filteredColors.forEach(color => {
const palette = color.palette || 'other';
if (!grouped[palette]) {
grouped[palette] = [];
}
grouped[palette].push(color);
});
return grouped;
}, [filteredColors]);
// 获取所有调色板
const palettes = useMemo(() => {
const paletteSet = new Set(colors.map(color => color.palette || 'other'));
return Array.from(paletteSet);
}, [colors]);
return (
<div
className={clsx('color-palette', className)}
data-component="ColorPalette"
data-element="palette"
data-variant={variant}
data-view-mode={viewMode}
>
{/* 控制面板 */}
{showControls && (
<Card className="mb-6">
<CardBody className="p-4">
<div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
{/* 标题 */}
<h3 className="text-lg font-semibold text-neutral-900 dark:text-neutral-100">
{title}
</h3>
{/* 控制按钮 */}
<div className="flex items-center space-x-3">
{/* 搜索框 */}
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 w-4 h-4" />
<input
type="text"
placeholder="Search colors..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 pr-4 py-2 border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
data-component="Input"
data-element="search-input"
data-placeholder="search-colors"
/>
</div>
{/* 过滤器按钮 */}
<IconButton
variant={showFilters ? 'primary' : 'ghost'}
onClick={() => setShowFilters(!showFilters)}
data-component="IconButton"
data-element="filter-button"
data-action="toggle-filters"
>
<Filter className="w-4 h-4" />
</IconButton>
{/* 视图模式切换 */}
<div className="flex border border-neutral-300 dark:border-neutral-600 rounded-md overflow-hidden">
<button
onClick={() => setViewMode('grid')}
className={clsx(
'px-3 py-2 text-sm transition-colors',
viewMode === 'grid'
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
)}
data-component="ToggleButton"
data-element="grid-view-button"
data-action="set-view-grid"
>
<Grid className="w-4 h-4" />
</button>
<button
onClick={() => setViewMode('list')}
className={clsx(
'px-3 py-2 text-sm transition-colors',
viewMode === 'list'
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
)}
data-component="ToggleButton"
data-element="list-view-button"
data-action="set-view-list"
>
<List className="w-4 h-4" />
</button>
</div>
</div>
</div>
{/* 过滤器面板 */}
<AnimatePresence>
{showFilters && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="mt-4 pt-4 border-t border-neutral-200 dark:border-neutral-800"
data-element="filters"
>
<div className="flex flex-wrap gap-2">
<button
onClick={() => setSelectedPalette(null)}
className={clsx(
'px-3 py-1.5 text-sm rounded-full border transition-colors',
selectedPalette === null
? 'bg-primary-500 text-white border-primary-500'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 border-neutral-300 dark:border-neutral-600 hover:bg-neutral-50 dark:hover:bg-neutral-700'
)}
data-component="FilterChip"
data-element="all-palettes-chip"
data-action="select-all-palettes"
>
All Palettes
</button>
{palettes.map(palette => (
<button
key={palette}
onClick={() => setSelectedPalette(palette)}
className={clsx(
'px-3 py-1.5 text-sm rounded-full border transition-colors capitalize',
selectedPalette === palette
? 'bg-primary-500 text-white border-primary-500'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 border-neutral-300 dark:border-neutral-600 hover:bg-neutral-50 dark:hover:bg-neutral-700'
)}
data-component="FilterChip"
data-element={`${palette}-palette-chip`}
data-action={`select-${palette}-palette`}
>
{palette}
</button>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</CardBody>
</Card>
)}
{/* 颜色网格/列表 */}
<div className="space-y-8">
{Object.entries(colorsByPalette).map(([palette, paletteColors]) => (
<div key={palette} className="palette-group" data-element="palette-group" data-palette={palette}>
<h4 className="text-sm font-semibold text-neutral-700 dark:text-neutral-300 mb-4 capitalize">
{palette} Palette ({paletteColors.length})
</h4>
<div className={clsx(
'grid gap-4',
{
'grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8': viewMode === 'grid',
'space-y-2': viewMode === 'list',
}
)}>
<AnimatePresence>
{paletteColors.map((color, index) => (
<motion.div
key={color.name}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
>
<ColorSwatch
token={color}
variant={viewMode === 'list' ? 'compact' : 'default'}
showLabel={viewMode === 'grid'}
showValue={viewMode === 'grid'}
interactive={interactive}
/>
</motion.div>
))}
</AnimatePresence>
</div>
</div>
))}
</div>
{/* 空状态 */}
{filteredColors.length === 0 && (
<div className="text-center py-12" data-element="empty-state">
<div className="w-12 h-12 bg-neutral-100 dark:bg-neutral-800 rounded-full flex items-center justify-center mx-auto mb-4">
<Search className="w-6 h-6 text-neutral-400" />
</div>
<h3 className="text-lg font-medium text-neutral-900 dark:text-neutral-100 mb-2">
No colors found
</h3>
<p className="text-neutral-600 dark:text-neutral-400 mb-4">
Try adjusting your search or filter criteria.
</p>
<Button
variant="outline"
onClick={() => {
setSearchQuery('');
setSelectedPalette(null);
}}
data-component="Button"
data-element="clear-filters-button"
data-action="clear-all-filters"
>
Clear Filters
</Button>
</div>
)}
</div>
);
};
export { ColorPalette, ColorSwatch };
export type { ColorPaletteProps, ColorSwatchProps };
export default ColorPalette;

View File

@@ -0,0 +1,395 @@
/**
* @fileoverview 令牌卡片组件
* @description 展示设计系统令牌的可视化组件
*/
import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { Copy, Check, Edit3, Trash2, Tag } from 'lucide-react';
import { Card, CardBody, CardHeader } from '../ui/Card';
import { Button, IconButton } from '../ui/Button';
import { DesignToken, ColorToken, TypographyToken, SpacingToken, ShadowToken, BorderRadiusToken, AnimationToken } from '../../types/design-system';
import { useDesignSystemStore } from '../../store/design-system-store';
import { clsx } from 'clsx';
// 令牌卡片属性接口
interface TokenCardProps {
token: DesignToken;
variant?: 'default' | 'compact' | 'detailed';
interactive?: boolean;
showActions?: boolean;
className?: string;
}
/**
* 令牌卡片主组件
*/
const TokenCard: React.FC<TokenCardProps> = ({
token,
variant = 'default',
interactive = true,
showActions = true,
className
}) => {
const [copied, setCopied] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const { setSelectedToken } = useDesignSystemStore();
// 复制令牌值
const copyToken = async () => {
try {
await navigator.clipboard.writeText(String(token.value));
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy token:', error);
}
};
// 选择令牌
const handleSelect = () => {
if (interactive) {
setSelectedToken(token);
}
};
// 渲染令牌预览
const renderTokenPreview = () => {
switch (token.category) {
case 'color':
return <ColorTokenPreview token={token as ColorToken} />;
case 'typography':
return <TypographyTokenPreview token={token as TypographyToken} />;
case 'spacing':
return <SpacingTokenPreview token={token as SpacingToken} />;
case 'shadow':
return <ShadowTokenPreview token={token as ShadowToken} />;
case 'border-radius':
return <BorderRadiusTokenPreview token={token as BorderRadiusToken} />;
case 'animation':
return <AnimationTokenPreview token={token as AnimationToken} />;
default:
return <DefaultTokenPreview token={token} />;
}
};
// 渲染令牌信息
const renderTokenInfo = () => {
const categoryIcons = {
color: '🎨',
typography: '📝',
spacing: '📏',
shadow: '🌑',
'border-radius': '🔘',
'z-index': '📊',
animation: '⚡',
};
return (
<div className="token-info" data-element="info">
<div className="flex items-center space-x-2 mb-2" data-element="header">
<span className="text-lg" data-element="icon">
{categoryIcons[token.category]}
</span>
<h4 className="font-semibold text-sm text-neutral-900 dark:text-neutral-100" data-element="name">
{token.name}
</h4>
{token.deprecated && (
<span className="px-2 py-0.5 text-xs bg-warning-100 text-warning-800 dark:bg-warning-900/40 dark:text-warning-200 rounded-full">
Deprecated
</span>
)}
</div>
{token.description && (
<p className="text-xs text-neutral-600 dark:text-neutral-400 mb-3" data-element="description">
{token.description}
</p>
)}
{token.tags && token.tags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-3" data-element="tags">
{token.tags.slice(0, 3).map((tag, index) => (
<span
key={index}
className="inline-flex items-center px-2 py-0.5 text-xs bg-neutral-100 dark:bg-neutral-800 text-neutral-600 dark:text-neutral-400 rounded"
>
<Tag className="w-3 h-3 mr-1" />
{tag}
</span>
))}
{token.tags.length > 3 && (
<span className="text-xs text-neutral-500">
+{token.tags.length - 3} more
</span>
)}
</div>
)}
</div>
);
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
whileHover={interactive ? { y: -2 } : {}}
className={clsx(
'token-card',
{
'cursor-pointer': interactive,
'opacity-75': token.deprecated,
},
className
)}
data-component="TokenCard"
data-element="card"
data-category={token.category}
data-name={token.name}
onClick={handleSelect}
>
<Card
variant="default"
size="sm"
hover={interactive}
interactive={interactive}
className="h-full"
>
<CardBody className="p-4">
{/* 令牌预览 */}
<div className="token-preview mb-4" data-element="preview">
{renderTokenPreview()}
</div>
{/* 令牌信息 */}
{renderTokenInfo()}
{/* 令牌值和操作 */}
<div className="token-actions flex items-center justify-between mt-4 pt-3 border-t border-neutral-200 dark:border-neutral-800" data-element="actions">
<div className="token-value flex items-center space-x-2" data-element="value">
<code className="text-xs bg-neutral-100 dark:bg-neutral-800 px-2 py-1 rounded font-mono">
{typeof token.value === 'object' ? JSON.stringify(token.value) : token.value}
</code>
</div>
{showActions && (
<div className="token-buttons flex items-center space-x-1" data-element="buttons">
<IconButton
size="sm"
variant="ghost"
onClick={(e) => {
e.stopPropagation();
copyToken();
}}
aria-label="Copy token value"
data-component="IconButton"
data-element="copy-button"
data-action="copy-value"
>
{copied ? (
<Check className="w-3 h-3 text-success-600" />
) : (
<Copy className="w-3 h-3" />
)}
</IconButton>
{interactive && (
<IconButton
size="sm"
variant="ghost"
onClick={(e) => {
e.stopPropagation();
setIsEditing(!isEditing);
}}
aria-label="Edit token"
data-component="IconButton"
data-element="edit-button"
data-action="edit-token"
>
<Edit3 className="w-3 h-3" />
</IconButton>
)}
</div>
)}
</div>
{/* 编辑模式 */}
{isEditing && interactive && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="token-editor mt-3 pt-3 border-t border-neutral-200 dark:border-neutral-800"
data-element="editor"
>
<div className="space-y-2">
<label className="block text-xs font-medium text-neutral-700 dark:text-neutral-300">
Token Value
</label>
<textarea
className="w-full px-2 py-1 text-xs border border-neutral-300 dark:border-neutral-600 rounded bg-white dark:bg-neutral-800"
rows={2}
value={typeof token.value === 'object' ? JSON.stringify(token.value, null, 2) : String(token.value)}
readOnly
/>
<div className="flex justify-end space-x-2">
<Button
size="sm"
variant="ghost"
onClick={() => setIsEditing(false)}
>
Cancel
</Button>
<Button
size="sm"
variant="primary"
>
Save
</Button>
</div>
</div>
</motion.div>
)}
</CardBody>
</Card>
</motion.div>
);
};
// 颜色令牌预览组件
const ColorTokenPreview: React.FC<{ token: ColorToken }> = ({ token }) => {
return (
<div className="color-token-preview" data-element="color-preview">
<div
className="color-swatch w-full h-16 rounded-lg border border-neutral-200 dark:border-neutral-700"
style={{ backgroundColor: token.value }}
data-element="swatch"
/>
<div className="color-info mt-2 text-center">
<div className="text-xs font-mono" data-element="hex-value">
{token.value}
</div>
{token.scale && (
<div className="text-xs text-neutral-500" data-element="scale">
{token.palette} {token.scale}
</div>
)}
</div>
</div>
);
};
// 字体令牌预览组件
const TypographyTokenPreview: React.FC<{ token: TypographyToken }> = ({ token }) => {
const { fontSize, fontWeight, lineHeight } = token.value;
return (
<div className="typography-token-preview p-3 bg-neutral-50 dark:bg-neutral-800 rounded" data-element="typography-preview">
<div
style={{
fontSize: fontSize || '1rem',
fontWeight: fontWeight || 400,
lineHeight: lineHeight || '1.5',
}}
data-element="text-sample"
>
The quick brown fox
</div>
<div className="mt-2 text-xs text-neutral-600 dark:text-neutral-400 space-y-1" data-element="typography-info">
{fontSize && <div>Size: {fontSize}</div>}
{fontWeight && <div>Weight: {fontWeight}</div>}
{lineHeight && <div>Line Height: {lineHeight}</div>}
</div>
</div>
);
};
// 间距令牌预览组件
const SpacingTokenPreview: React.FC<{ token: SpacingToken }> = ({ token }) => {
return (
<div className="spacing-token-preview" data-element="spacing-preview">
<div className="flex items-center space-x-2">
<div
className="bg-primary-200 dark:bg-primary-800 h-4 rounded"
style={{ width: token.value }}
data-element="spacing-bar"
/>
<span className="text-xs font-mono" data-element="spacing-value">
{token.value}
</span>
</div>
</div>
);
};
// 阴影令牌预览组件
const ShadowTokenPreview: React.FC<{ token: ShadowToken }> = ({ token }) => {
const { offsetX = '0', offsetY = '0', blurRadius = '0', spreadRadius = '0', color = 'transparent' } = token.value;
return (
<div className="shadow-token-preview" data-element="shadow-preview">
<div
className="shadow-demo w-full h-16 bg-white dark:bg-neutral-900 rounded-lg border border-neutral-200 dark:border-neutral-700"
style={{
boxShadow: `${offsetX} ${offsetY} ${blurRadius} ${spreadRadius} ${color}`,
}}
data-element="shadow-box"
/>
<div className="mt-2 text-xs text-neutral-600 dark:text-neutral-400 space-y-1" data-element="shadow-info">
<div>X: {offsetX}</div>
<div>Y: {offsetY}</div>
<div>Blur: {blurRadius}</div>
<div>Spread: {spreadRadius}</div>
</div>
</div>
);
};
// 圆角令牌预览组件
const BorderRadiusTokenPreview: React.FC<{ token: BorderRadiusToken }> = ({ token }) => {
return (
<div className="border-radius-token-preview" data-element="radius-preview">
<div
className="radius-demo w-full h-16 bg-primary-100 dark:bg-primary-900/20"
style={{ borderRadius: token.value }}
data-element="radius-box"
/>
<div className="mt-2 text-center text-xs font-mono" data-element="radius-value">
{token.value}
</div>
</div>
);
};
// 动画令牌预览组件
const AnimationTokenPreview: React.FC<{ token: AnimationToken }> = ({ token }) => {
const { duration = '300ms', timingFunction = 'ease' } = token.value;
return (
<div className="animation-token-preview" data-element="animation-preview">
<div className="flex items-center space-x-2">
<div className="animation-demo w-8 h-8 bg-primary-500 rounded-full" data-element="animated-circle" />
<div className="text-xs space-y-1" data-element="animation-info">
<div>Duration: {duration}</div>
<div>Easing: {timingFunction}</div>
</div>
</div>
</div>
);
};
// 默认令牌预览组件
const DefaultTokenPreview: React.FC<{ token: DesignToken }> = ({ token }) => {
return (
<div className="default-token-preview p-3 bg-neutral-50 dark:bg-neutral-800 rounded" data-element="default-preview">
<div className="text-center text-sm font-mono" data-element="value">
{typeof token.value === 'object' ? JSON.stringify(token.value) : String(token.value)}
</div>
</div>
);
};
export { TokenCard, ColorTokenPreview, TypographyTokenPreview, SpacingTokenPreview, ShadowTokenPreview, BorderRadiusTokenPreview, AnimationTokenPreview };
export type { TokenCardProps };
export default TokenCard;

View File

@@ -0,0 +1,283 @@
/**
* @fileoverview 应用布局组件
* @description 提供侧边栏导航、顶部栏和主内容区域的布局结构
*/
import React, { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { useDesignModeStore } from '../../main';
// 导航项目类型定义
interface NavItem {
path: string;
label: string;
icon: string;
description: string;
badge?: string | number;
}
/**
* 应用布局主组件
*/
const AppLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [sidebarOpen, setSidebarOpen] = useState(false);
const location = useLocation();
const { isDesignModeEnabled, toggleDesignMode } = useDesignModeStore();
// 导航菜单配置
const navItems: NavItem[] = [
{
path: '/dashboard',
label: 'Dashboard',
icon: '🏠',
description: 'Overview and system status',
badge: 'Main'
},
{
path: '/editor',
label: 'Component Editor',
icon: '🎨',
description: 'Visual component builder',
badge: 'Pro'
},
{
path: '/design-system',
label: 'Design System',
icon: '🎯',
description: 'Design tokens and guidelines',
badge: 'Core'
},
{
path: '/preview',
label: 'Live Preview',
icon: '⚡',
description: 'Real-time component preview'
}
];
// 导航项目组件
const NavItemComponent: React.FC<{ item: NavItem; isActive: boolean }> = ({ item, isActive }) => (
<Link
to={item.path}
className={`
nav-item group relative flex items-center px-4 py-3 text-sm font-medium rounded-lg
transition-all duration-200 hover:bg-neutral-100 dark:hover:bg-neutral-800
${isActive
? 'bg-primary-50 text-primary-700 dark:bg-primary-900/20 dark:text-primary-300'
: 'text-neutral-700 dark:text-neutral-300'
}
`}
data-component="NavItem"
data-element="nav-link"
data-nav-item={item.path.replace('/', '')}
onClick={() => setSidebarOpen(false)}
>
<span className="nav-item-icon text-lg mr-3" data-element="icon">
{item.icon}
</span>
<div className="nav-item-content flex-1 min-w-0" data-element="content">
<div className="nav-item-label font-medium" data-element="label">
{item.label}
</div>
<div className="nav-item-description text-xs text-neutral-500 dark:text-neutral-400 mt-0.5" data-element="description">
{item.description}
</div>
</div>
{item.badge && (
<span
className="nav-item-badge ml-2 px-2 py-0.5 text-xs font-semibold rounded-full bg-primary-100 text-primary-700 dark:bg-primary-900/40 dark:text-primary-300"
data-element="badge"
>
{item.badge}
</span>
)}
{/* 设计模式属性 */}
<div
className="design-mode-indicator absolute right-2 top-1/2 transform -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity"
data-design-mode={isDesignModeEnabled ? 'true' : 'false'}
>
<div className="w-2 h-2 bg-primary-500 rounded-full"></div>
</div>
</Link>
);
return (
<div
className="app-layout layout-container"
data-component="AppLayout"
data-design-mode={isDesignModeEnabled ? 'true' : 'false'}
>
{/* 移动端遮罩层 */}
<AnimatePresence>
{sidebarOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-30 bg-black bg-opacity-50 lg:hidden"
data-component="MobileOverlay"
data-element="overlay"
onClick={() => setSidebarOpen(false)}
/>
)}
</AnimatePresence>
{/* 侧边栏 */}
<motion.aside
initial={false}
animate={{
x: sidebarOpen ? 0 : '-100%',
}}
transition={{ type: 'spring', damping: 25, stiffness: 200 }}
className={`
layout-sidebar fixed inset-y-0 left-0 z-40 flex flex-col
bg-white dark:bg-neutral-900 border-r border-neutral-200 dark:border-neutral-800
lg:translate-x-0 lg:static lg:inset-0 lg:z-auto
${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}
`}
data-component="Sidebar"
data-element="sidebar"
>
{/* 侧边栏头部 */}
<div className="sidebar-header flex items-center justify-between h-16 px-6 border-b border-neutral-200 dark:border-neutral-800" data-element="header">
<div className="sidebar-brand flex items-center" data-element="brand">
<div className="w-8 h-8 bg-gradient-to-br from-primary-500 to-secondary-500 rounded-lg flex items-center justify-center mr-3">
<span className="text-white font-bold text-sm">AD</span>
</div>
<div className="brand-content">
<h1 className="text-lg font-bold text-neutral-900 dark:text-neutral-100">
Design Mode
</h1>
<p className="text-xs text-neutral-500 dark:text-neutral-400">
Full Featured Showcase
</p>
</div>
</div>
{/* 移动端关闭按钮 */}
<button
onClick={() => setSidebarOpen(false)}
className="lg:hidden p-1 rounded-md hover:bg-neutral-100 dark:hover:bg-neutral-800"
data-component="IconButton"
data-element="close-button"
data-action="close-sidebar"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* 导航菜单 */}
<nav className="sidebar-nav flex-1 px-4 py-6 space-y-2 overflow-y-auto custom-scrollbar" data-element="nav">
{navItems.map((item) => (
<NavItemComponent
key={item.path}
item={item}
isActive={location.pathname === item.path}
/>
))}
</nav>
{/* 侧边栏底部 */}
<div className="sidebar-footer p-4 border-t border-neutral-200 dark:border-neutral-800" data-element="footer">
<div className="sidebar-actions space-y-2" data-element="actions">
<button
onClick={toggleDesignMode}
className={`
w-full flex items-center justify-center px-3 py-2 text-sm font-medium rounded-md
transition-colors duration-200
${isDesignModeEnabled
? 'bg-primary-100 text-primary-700 dark:bg-primary-900/40 dark:text-primary-300'
: 'bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300'
}
`}
data-component="ToggleButton"
data-element="design-mode-toggle"
data-action="toggle-design-mode"
>
<span className="mr-2">{isDesignModeEnabled ? '🎯' : '👁️'}</span>
{isDesignModeEnabled ? 'Design Mode ON' : 'Design Mode OFF'}
</button>
<div className="text-center text-xs text-neutral-500 dark:text-neutral-400">
Version 1.0.0
</div>
</div>
</div>
</motion.aside>
{/* 主内容区域 */}
<div className="layout-main flex flex-col min-h-screen">
{/* 顶部导航栏 */}
<header className="layout-header h-16 bg-white dark:bg-neutral-900 border-b border-neutral-200 dark:border-neutral-800 flex items-center justify-between px-6 relative z-10" data-component="Header" data-element="header">
{/* 移动端菜单按钮 */}
<button
onClick={() => setSidebarOpen(true)}
className="lg:hidden p-2 rounded-md hover:bg-neutral-100 dark:hover:bg-neutral-800"
data-component="IconButton"
data-element="mobile-menu-button"
data-action="toggle-sidebar"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
{/* 页面标题和面包屑 */}
<div className="header-content flex-1" data-element="content">
<h2 className="text-xl font-semibold text-neutral-900 dark:text-neutral-100">
{navItems.find(item => item.path === location.pathname)?.label || 'Unknown Page'}
</h2>
</div>
{/* 顶部操作区域 */}
<div className="header-actions flex items-center space-x-4" data-element="actions">
{/* 设计模式状态指示器 */}
<div
className={`
header-status-indicator flex items-center px-3 py-1 rounded-full text-xs font-medium
${isDesignModeEnabled
? 'bg-primary-100 text-primary-700 dark:bg-primary-900/40 dark:text-primary-300'
: 'bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400'
}
`}
data-element="status-indicator"
>
<div className={`
w-2 h-2 rounded-full mr-2
${isDesignModeEnabled ? 'bg-primary-500' : 'bg-neutral-400'}
`}></div>
{isDesignModeEnabled ? 'Design Mode' : 'Preview Mode'}
</div>
{/* 用户头像/设置 */}
<button
className="header-user-button p-2 rounded-full hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors"
data-component="AvatarButton"
data-element="user-avatar"
data-action="open-user-menu"
>
<div className="w-8 h-8 bg-gradient-to-br from-primary-400 to-secondary-400 rounded-full flex items-center justify-center">
<span className="text-white font-medium text-sm">U</span>
</div>
</button>
</div>
</header>
{/* 主内容 */}
<main
className="layout-content flex-1 overflow-auto bg-neutral-50 dark:bg-neutral-800"
data-component="Main"
data-element="main-content"
>
{children}
</main>
</div>
</div>
);
};
export default AppLayout;

View File

@@ -0,0 +1,274 @@
/**
* @fileoverview 按钮组件
* @description 提供各种样式和状态的按钮组件
*/
import React, { forwardRef } from 'react';
import { motion } from 'framer-motion';
import { clsx } from 'clsx';
// 按钮变体类型
type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'link' | 'danger';
// 按钮尺寸类型
type ButtonSize = 'sm' | 'md' | 'lg' | 'xl';
// 按钮属性接口
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
loading?: boolean;
loadingText?: string;
icon?: React.ReactNode;
iconPosition?: 'left' | 'right';
fullWidth?: boolean;
children?: React.ReactNode;
className?: string;
variantClass?: string;
sizeClass?: string;
}
/**
* 按钮组件实现
*/
const Button = forwardRef<HTMLButtonElement, ButtonProps>(({
variant = 'primary',
size = 'md',
loading = false,
loadingText,
icon,
iconPosition = 'left',
fullWidth = false,
children,
className,
disabled,
variantClass,
sizeClass,
onClick,
...props
}, ref) => {
// 按钮变体样式配置
const variantStyles: Record<ButtonVariant, string> = {
primary: `
bg-primary-600 border-primary-600 text-white
hover:bg-primary-700 hover:border-primary-700
focus:ring-primary-500 focus:ring-offset-2
active:bg-primary-800 active:border-primary-800
disabled:bg-primary-300 disabled:border-primary-300
`,
secondary: `
bg-neutral-200 border-neutral-300 text-neutral-900
hover:bg-neutral-300 hover:border-neutral-400
focus:ring-neutral-500 focus:ring-offset-2
active:bg-neutral-400 active:border-neutral-500
disabled:bg-neutral-100 disabled:border-neutral-200
dark:bg-neutral-700 dark:border-neutral-600 dark:text-neutral-100
dark:hover:bg-neutral-600 dark:hover:border-neutral-500
dark:active:bg-neutral-500 dark:active:border-neutral-400
dark:disabled:bg-neutral-800 dark:disabled:border-neutral-700
`,
outline: `
bg-transparent border-primary-600 text-primary-600
hover:bg-primary-600 hover:text-white
focus:ring-primary-500 focus:ring-offset-2
active:bg-primary-700 active:border-primary-700
disabled:text-primary-300 disabled:border-primary-300
disabled:hover:bg-transparent disabled:hover:text-primary-300
`,
ghost: `
bg-transparent border-transparent text-neutral-700
hover:bg-neutral-100 hover:text-neutral-900
focus:ring-neutral-500 focus:ring-offset-2
active:bg-neutral-200 active:text-neutral-900
disabled:text-neutral-400
dark:text-neutral-300 dark:hover:bg-neutral-800 dark:hover:text-neutral-100
dark:active:bg-neutral-700 dark:active:text-neutral-100
`,
link: `
bg-transparent border-transparent text-primary-600
hover:text-primary-700 hover:underline
focus:ring-primary-500 focus:ring-offset-2
active:text-primary-800
disabled:text-primary-300 disabled:no-underline
`,
danger: `
bg-error-600 border-error-600 text-white
hover:bg-error-700 hover:border-error-700
focus:ring-error-500 focus:ring-offset-2
active:bg-error-800 active:border-error-800
disabled:bg-error-300 disabled:border-error-300
`,
};
// 按钮尺寸样式配置
const sizeStyles: Record<ButtonSize, string> = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2 text-sm',
lg: 'px-6 py-3 text-base',
xl: 'px-8 py-4 text-lg',
};
// 计算按钮内容
const buttonContent = (
<span className="button-content flex items-center justify-center space-x-2">
{icon && iconPosition === 'left' && !loading && (
<span className="button-icon-left" data-element="icon-left">
{icon}
</span>
)}
{loading && (
<span className="button-loading-icon" data-element="loading-icon">
<div className="loading-spinner w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
</span>
)}
<span className="button-text" data-element="text">
{loading && loadingText ? loadingText : children}
</span>
{icon && iconPosition === 'right' && !loading && (
<span className="button-icon-right" data-element="icon-right">
{icon}
</span>
)}
</span>
);
// 应用自定义样式类
const combinedVariantClass = variantClass || variantStyles[variant];
const combinedSizeClass = sizeClass || sizeStyles[size];
return (
<motion.button
ref={ref}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
className={clsx(
// 基础样式
`
inline-flex items-center justify-center font-medium rounded-md border
transition-all duration-200 focus:outline-none focus:ring-2
disabled:opacity-50 disabled:cursor-not-allowed
disabled:transform-none
`,
// 变体样式
combinedVariantClass,
// 尺寸样式
combinedSizeClass,
// 全宽度
fullWidth && 'w-full',
// 自定义类名
className
)}
disabled={disabled || loading}
onClick={onClick}
data-component="Button"
data-element="button"
data-variant={variant}
data-size={size}
data-loading={loading ? 'true' : 'false'}
data-disabled={disabled ? 'true' : 'false'}
{...props}
>
{buttonContent}
</motion.button>
);
});
// 显示名称
Button.displayName = 'Button';
/**
* 图标按钮组件
*/
interface IconButtonProps extends Omit<ButtonProps, 'children' | 'size'> {
size?: Exclude<ButtonSize, 'xl'>;
'aria-label': string; // 无障碍属性必需
}
const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(({
size = 'md',
className,
...props
}, ref) => {
const iconSizeStyles: Record<ButtonSize, string> = {
sm: 'w-8 h-8 p-1.5',
md: 'w-10 h-10 p-2',
lg: 'w-12 h-12 p-2.5',
xl: 'w-14 h-14 p-3',
};
return (
<Button
ref={ref}
size={size}
className={clsx(
'!p-0 !rounded-full',
iconSizeStyles[size],
className
)}
{...props}
/>
);
});
IconButton.displayName = 'IconButton';
/**
* 浮动操作按钮
*/
interface FloatingActionButtonProps extends Omit<IconButtonProps, 'variant'> {
variant?: ButtonVariant;
position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
}
const FloatingActionButton = forwardRef<HTMLButtonElement, FloatingActionButtonProps>(({
position = 'bottom-right',
className,
...props
}, ref) => {
const positionStyles = {
'bottom-right': 'fixed bottom-6 right-6 z-50',
'bottom-left': 'fixed bottom-6 left-6 z-50',
'top-right': 'fixed top-6 right-6 z-50',
'top-left': 'fixed top-6 left-6 z-50',
};
return (
<motion.div
initial={{ scale: 0, rotate: -180 }}
animate={{ scale: 1, rotate: 0 }}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
className={clsx('floating-action-button', positionStyles[position])}
data-component="FloatingActionButton"
data-element="fab"
data-position={position}
>
<IconButton
ref={ref}
size="lg"
variant="primary"
className={clsx(
`
!rounded-full !shadow-lg !shadow-primary-500/25
hover:!shadow-xl hover:!shadow-primary-500/30
bg-gradient-to-br from-primary-500 to-primary-600
hover:from-primary-600 hover:to-primary-700
border-0
`,
className
)}
{...props}
/>
</motion.div>
);
});
FloatingActionButton.displayName = 'FloatingActionButton';
export { Button, IconButton, FloatingActionButton };
export type { ButtonProps, IconButtonProps, FloatingActionButtonProps, ButtonVariant, ButtonSize };
export default Button;

View File

@@ -0,0 +1,421 @@
/**
* @fileoverview 卡片组件
* @description 提供各种样式和布局的卡片容器组件
*/
import React, { forwardRef } from 'react';
import { motion } from 'framer-motion';
import { clsx } from 'clsx';
// 卡片变体类型
type CardVariant = 'default' | 'elevated' | 'outlined' | 'ghost' | 'filled';
// 卡片尺寸类型
type CardSize = 'sm' | 'md' | 'lg' | 'xl';
// 卡片属性接口
interface CardProps extends React.HTMLAttributes<HTMLDivElement> {
variant?: CardVariant;
size?: CardSize;
hover?: boolean;
interactive?: boolean;
loading?: boolean;
children?: React.ReactNode;
className?: string;
variantClass?: string;
sizeClass?: string;
}
// 卡片标题属性接口
interface CardHeaderProps extends React.HTMLAttributes<HTMLDivElement> {
title?: string;
subtitle?: string;
action?: React.ReactNode;
children?: React.ReactNode;
className?: string;
}
// 卡片内容属性接口
interface CardBodyProps extends React.HTMLAttributes<HTMLDivElement> {
children?: React.ReactNode;
className?: string;
}
// 卡片底部属性接口
interface CardFooterProps extends React.HTMLAttributes<HTMLDivElement> {
children?: React.ReactNode;
className?: string;
}
// 卡片图片属性接口
interface CardImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
src: string;
alt: string;
overlay?: boolean;
height?: string | number;
className?: string;
}
/**
* 卡片组件实现
*/
const Card = forwardRef<HTMLDivElement, CardProps>(({
variant = 'default',
size = 'md',
hover = false,
interactive = false,
loading = false,
children,
className,
variantClass,
sizeClass,
onClick,
...props
}, ref) => {
// 卡片变体样式配置
const variantStyles: Record<CardVariant, string> = {
default: `
bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800
`,
elevated: `
bg-white dark:bg-neutral-900 border-0 shadow-lg dark:shadow-neutral-900/20
hover:shadow-xl transition-shadow duration-300
`,
outlined: `
bg-transparent border-2 border-primary-200 dark:border-primary-800
hover:border-primary-300 dark:hover:border-primary-700
`,
ghost: `
bg-transparent border-0
hover:bg-neutral-50 dark:hover:bg-neutral-800/50
`,
filled: `
bg-neutral-50 dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700
`,
};
// 卡片尺寸样式配置
const sizeStyles: Record<CardSize, string> = {
sm: 'p-3 space-y-2',
md: 'p-4 space-y-3',
lg: 'p-6 space-y-4',
xl: 'p-8 space-y-6',
};
// 悬停效果样式
const hoverStyles = hover || interactive ? `
transition-all duration-200 ease-in-out cursor-pointer
hover:shadow-md hover:-translate-y-1
hover:shadow-neutral-500/10 dark:hover:shadow-neutral-900/20
` : '';
// 交互样式
const interactiveStyles = interactive ? `
active:scale-95 active:shadow-sm
` : '';
return (
<motion.div
ref={ref}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
whileHover={hover || interactive ? { y: -4 } : {}}
whileTap={interactive ? { scale: 0.98 } : {}}
className={clsx(
// 基础样式
`
card rounded-lg overflow-hidden
${interactive ? 'cursor-pointer' : ''}
${loading ? 'pointer-events-none' : ''}
`,
// 变体样式
variantStyles[variant],
// 尺寸样式
sizeStyles[size],
// 悬停和交互样式
hoverStyles,
interactiveStyles,
// 自定义类名
className
)}
onClick={interactive ? onClick : undefined}
data-component="Card"
data-element="card"
data-variant={variant}
data-size={size}
data-hover={hover ? 'true' : 'false'}
data-interactive={interactive ? 'true' : 'false'}
data-loading={loading ? 'true' : 'false'}
{...props}
>
{loading ? (
<CardSkeleton variant={variant} size={size} />
) : (
children
)}
</motion.div>
);
});
Card.displayName = 'Card';
/**
* 卡片头部组件
*/
const CardHeader = forwardRef<HTMLDivElement, CardHeaderProps>(({
title,
subtitle,
action,
children,
className,
...props
}, ref) => {
return (
<div
ref={ref}
className={clsx(
'card-header flex items-start justify-between',
className
)}
data-component="CardHeader"
data-element="header"
{...props}
>
<div className="header-content flex-1" data-element="content">
{title && (
<h3
className="text-lg font-semibold text-neutral-900 dark:text-neutral-100"
data-element="title"
>
{title}
</h3>
)}
{subtitle && (
<p
className="text-sm text-neutral-600 dark:text-neutral-400 mt-1"
data-element="subtitle"
>
{subtitle}
</p>
)}
{children}
</div>
{action && (
<div className="header-action ml-4 flex-shrink-0" data-element="action">
{action}
</div>
)}
</div>
);
});
CardHeader.displayName = 'CardHeader';
/**
* 卡片内容组件
*/
const CardBody = forwardRef<HTMLDivElement, CardBodyProps>(({
children,
className,
...props
}, ref) => {
return (
<div
ref={ref}
className={clsx('card-body', className)}
data-component="CardBody"
data-element="body"
{...props}
>
{children}
</div>
);
});
CardBody.displayName = 'CardBody';
/**
* 卡片底部组件
*/
const CardFooter = forwardRef<HTMLDivElement, CardFooterProps>(({
children,
className,
...props
}, ref) => {
return (
<div
ref={ref}
className={clsx(
'card-footer flex items-center justify-between',
'border-t border-neutral-200 dark:border-neutral-800 pt-4 mt-4',
className
)}
data-component="CardFooter"
data-element="footer"
{...props}
>
{children}
</div>
);
});
CardFooter.displayName = 'CardFooter';
/**
* 卡片图片组件
*/
const CardImage = forwardRef<HTMLImageElement, CardImageProps>(({
src,
alt,
overlay = false,
height = 200,
className,
...props
}, ref) => {
return (
<div
className={clsx(
'card-image relative overflow-hidden',
className
)}
data-component="CardImage"
data-element="image"
data-overlay={overlay ? 'true' : 'false'}
>
<img
ref={ref}
src={src}
alt={alt}
className={clsx(
'w-full object-cover',
overlay && 'absolute inset-0 h-full'
)}
style={{ height }}
data-element="img"
{...props}
/>
{overlay && (
<div
className="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent"
data-element="overlay"
/>
)}
</div>
);
});
CardImage.displayName = 'CardImage';
/**
* 卡片骨架屏组件
*/
const CardSkeleton: React.FC<{ variant: CardVariant; size: CardSize }> = ({ variant, size }) => {
const skeletonSizes = {
sm: { padding: 'p-3', gap: 'space-y-2' },
md: { padding: 'p-4', gap: 'space-y-3' },
lg: { padding: 'p-6', gap: 'space-y-4' },
xl: { padding: 'p-8', gap: 'space-y-6' },
};
const { padding, gap } = skeletonSizes[size];
return (
<div className={`card-skeleton ${padding} ${gap}`} data-element="skeleton">
{/* 头部骨架 */}
<div className="flex items-start justify-between" data-element="header-skeleton">
<div className="flex-1" data-element="content-skeleton">
<div className="h-5 bg-neutral-200 dark:bg-neutral-700 rounded w-3/4 mb-2" />
<div className="h-4 bg-neutral-200 dark:bg-neutral-700 rounded w-1/2" />
</div>
<div className="ml-4" data-element="action-skeleton">
<div className="w-8 h-8 bg-neutral-200 dark:bg-neutral-700 rounded" />
</div>
</div>
{/* 内容骨架 */}
<div className="space-y-3" data-element="body-skeleton">
<div className="h-4 bg-neutral-200 dark:bg-neutral-700 rounded" />
<div className="h-4 bg-neutral-200 dark:bg-neutral-700 rounded w-5/6" />
<div className="h-4 bg-neutral-200 dark:bg-neutral-700 rounded w-4/6" />
</div>
{/* 底部骨架 */}
<div className="flex items-center justify-between pt-4 border-t border-neutral-200 dark:border-neutral-800" data-element="footer-skeleton">
<div className="h-4 bg-neutral-200 dark:bg-neutral-700 rounded w-1/3" />
<div className="h-8 w-20 bg-neutral-200 dark:bg-neutral-700 rounded" />
</div>
</div>
);
};
/**
* 卡片组组件
*/
interface CardGroupProps extends React.HTMLAttributes<HTMLDivElement> {
columns?: 1 | 2 | 3 | 4;
gap?: 'sm' | 'md' | 'lg' | 'xl';
children?: React.ReactNode;
}
const CardGroup: React.FC<CardGroupProps> = ({
columns = 3,
gap = 'md',
children,
className,
...props
}) => {
const columnClasses = {
1: 'grid-cols-1',
2: 'grid-cols-1 md:grid-cols-2',
3: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
4: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gapClasses = {
sm: 'gap-3',
md: 'gap-4',
lg: 'gap-6',
xl: 'gap-8',
};
return (
<div
className={clsx(
'card-group grid',
columnClasses[columns],
gapClasses[gap],
className
)}
data-component="CardGroup"
data-element="group"
data-columns={columns}
data-gap={gap}
{...props}
>
{children}
</div>
);
};
export {
Card,
CardHeader,
CardBody,
CardFooter,
CardImage,
CardGroup,
CardSkeleton
};
export type {
CardProps,
CardHeaderProps,
CardBodyProps,
CardFooterProps,
CardImageProps,
CardGroupProps,
CardVariant,
CardSize
};
export default Card;

View File

@@ -0,0 +1,297 @@
/**
* @fileoverview 加载动画组件
* @description 提供各种加载状态的可复用组件
*/
import React from 'react';
import { motion } from 'framer-motion';
/**
* 旋转加载器组件
*/
const LoadingSpinner: React.FC<{
size?: 'sm' | 'md' | 'lg' | 'xl';
color?: 'primary' | 'secondary' | 'neutral' | 'white';
className?: string;
}> = ({
size = 'md',
color = 'primary',
className = ''
}) => {
const sizeClasses = {
sm: 'w-4 h-4',
md: 'w-6 h-6',
lg: 'w-8 h-8',
xl: 'w-12 h-12'
};
const colorClasses = {
primary: 'border-primary-600 border-t-transparent',
secondary: 'border-secondary-600 border-t-transparent',
neutral: 'border-neutral-400 border-t-transparent',
white: 'border-white border-t-transparent'
};
return (
<div
className={`
inline-block border-2 rounded-full animate-spin
${sizeClasses[size]}
${colorClasses[color]}
${className}
`}
data-component="LoadingSpinner"
data-element="spinner"
data-size={size}
data-color={color}
/>
);
};
/**
* 点状加载器组件
*/
const LoadingDots: React.FC<{
size?: 'sm' | 'md' | 'lg';
color?: 'primary' | 'secondary' | 'neutral' | 'white';
className?: string;
}> = ({
size = 'md',
color = 'primary',
className = ''
}) => {
const sizeClasses = {
sm: 'w-1 h-1',
md: 'w-2 h-2',
lg: 'w-3 h-3'
};
const colorClasses = {
primary: 'bg-primary-600',
secondary: 'bg-secondary-600',
neutral: 'bg-neutral-400',
white: 'bg-white'
};
return (
<div
className={`
loading-dots flex space-x-1
${className}
`}
data-component="LoadingDots"
data-element="dots"
data-size={size}
data-color={color}
>
{[0, 1, 2].map((index) => (
<motion.div
key={index}
className={`
${sizeClasses[size]} ${colorClasses[color]} rounded-full
`}
data-element="dot"
data-dot-index={index}
animate={{
scale: [1, 1.2, 1],
opacity: [0.7, 1, 0.7],
}}
transition={{
duration: 1.4,
repeat: Infinity,
delay: index * 0.16,
ease: 'easeInOut'
}}
/>
))}
</div>
);
};
/**
* 脉冲加载器组件
*/
const LoadingPulse: React.FC<{
size?: 'sm' | 'md' | 'lg' | 'xl';
color?: 'primary' | 'secondary' | 'neutral' | 'white';
className?: string;
}> = ({
size = 'md',
color = 'primary',
className = ''
}) => {
const sizeClasses = {
sm: 'w-4 h-4',
md: 'w-6 h-6',
lg: 'w-8 h-8',
xl: 'w-12 h-12'
};
const colorClasses = {
primary: 'bg-primary-600',
secondary: 'bg-secondary-600',
neutral: 'bg-neutral-400',
white: 'bg-white'
};
return (
<div
className={`
${sizeClasses[size]} ${colorClasses[color]} rounded-full
animate-pulse
${className}
`}
data-component="LoadingPulse"
data-element="pulse"
data-size={size}
data-color={color}
/>
);
};
/**
* 页面级加载组件
*/
const PageLoading: React.FC<{
title?: string;
description?: string;
variant?: 'spinner' | 'dots' | 'pulse';
className?: string;
}> = ({
title = 'Loading...',
description = 'Please wait while we prepare your content.',
variant = 'spinner',
className = ''
}) => {
const renderLoader = () => {
switch (variant) {
case 'dots':
return <LoadingDots size="lg" color="primary" />;
case 'pulse':
return <LoadingPulse size="xl" color="primary" />;
default:
return <LoadingSpinner size="lg" color="primary" />;
}
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className={`
page-loading flex flex-col items-center justify-center min-h-[400px]
text-center p-8
${className}
`}
data-component="PageLoading"
data-element="loading-container"
data-variant={variant}
>
<motion.div
initial={{ scale: 0.8 }}
animate={{ scale: 1 }}
transition={{ duration: 0.3, ease: 'easeOut' }}
className="loading-animation mb-6"
data-element="animation"
>
{renderLoader()}
</motion.div>
<motion.h3
initial={{ y: 10, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 0.1 }}
className="text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-2"
data-element="title"
>
{title}
</motion.h3>
<motion.p
initial={{ y: 10, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 0.2 }}
className="text-neutral-600 dark:text-neutral-400 max-w-sm"
data-element="description"
>
{description}
</motion.p>
</motion.div>
);
};
/**
* 按钮内加载组件
*/
const ButtonLoading: React.FC<{
size?: 'sm' | 'md' | 'lg';
color?: 'primary' | 'secondary' | 'neutral' | 'white';
text?: string;
}> = ({
size = 'sm',
color = 'white',
text = 'Loading...'
}) => {
return (
<div
className="button-loading flex items-center space-x-2"
data-component="ButtonLoading"
data-element="button-loading"
>
<LoadingSpinner size={size} color={color} />
<span className="sr-only">{text}</span>
</div>
);
};
/**
* 骨架屏加载组件
*/
const SkeletonLoader: React.FC<{
lines?: number;
className?: string;
}> = ({
lines = 3,
className = ''
}) => {
return (
<div
className={`skeleton-loader space-y-3 ${className}`}
data-component="SkeletonLoader"
data-element="skeleton"
>
{Array.from({ length: lines }).map((_, index) => (
<motion.div
key={index}
className={`
skeleton-line h-4 bg-neutral-200 dark:bg-neutral-700 rounded
${index === lines - 1 ? 'w-3/4' : 'w-full'}
`}
data-element="skeleton-line"
data-line-index={index}
animate={{
opacity: [0.5, 1, 0.5],
}}
transition={{
duration: 1.5,
repeat: Infinity,
delay: index * 0.1,
ease: 'easeInOut'
}}
/>
))}
</div>
);
};
export {
LoadingSpinner,
LoadingDots,
LoadingPulse,
PageLoading,
ButtonLoading,
SkeletonLoader
};
export default LoadingSpinner;

View File

@@ -0,0 +1,388 @@
/**
* @fileoverview 全局样式文件
* @description 包含 TailwindCSS 导入、基础样式重置和应用级样式
*/
/* TailwindCSS 基础导入 */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* 自定义 CSS 变量 */
:root {
/* 颜色变量 */
--color-primary-50: #eff6ff;
--color-primary-500: #3b82f6;
--color-primary-600: #2563eb;
--color-primary-700: #1d4ed8;
--color-secondary-50: #faf5ff;
--color-secondary-500: #a855f7;
--color-secondary-600: #9333ea;
/* 字体变量 */
--font-family-sans: 'Inter', ui-sans-serif, system-ui, sans-serif;
--font-family-mono: 'JetBrains Mono', ui-monospace, monospace;
/* 阴影变量 */
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
/* 圆角变量 */
--radius-sm: 0.25rem;
--radius-md: 0.375rem;
--radius-lg: 0.5rem;
--radius-xl: 0.75rem;
}
/* 暗色主题变量 */
.dark {
--color-bg-primary: #0a0a0a;
--color-bg-secondary: #171717;
--color-text-primary: #fafafa;
--color-text-secondary: #a3a3a3;
}
/* 基础样式重置 */
* {
box-sizing: border-box;
}
html {
font-family: var(--font-family-sans);
line-height: 1.5;
-webkit-text-size-adjust: 100%;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
body {
margin: 0;
padding: 0;
min-height: 100vh;
background-color: #fafafa;
color: #171717;
overflow-x: hidden;
}
/* 应用容器样式 */
.app {
min-height: 100vh;
position: relative;
transition: all 0.3s ease;
}
.app.design-mode-enabled {
cursor: crosshair;
}
/* 页面容器 */
.page-container {
@apply max-w-7xl mx-auto px-4 sm:px-6 lg:px-8;
padding-top: 2rem;
padding-bottom: 2rem;
}
.page-header {
@apply mb-8;
border-bottom: 1px solid #e5e5e5;
padding-bottom: 1.5rem;
}
.page-content {
@apply w-full;
}
/* 布局组件样式 */
.layout-container {
@apply min-h-screen flex flex-col;
}
.layout-sidebar {
@apply w-64 bg-white dark:bg-neutral-900 border-r border-neutral-200 dark:border-neutral-800;
transition: width 0.3s ease;
}
.layout-main {
@apply flex-1 flex flex-col overflow-hidden;
}
.layout-header {
@apply h-16 bg-white dark:bg-neutral-900 border-b border-neutral-200 dark:border-neutral-800 flex items-center px-6;
}
.layout-content {
@apply flex-1 overflow-auto bg-neutral-50 dark:bg-neutral-800;
}
/* 组件高亮样式 */
.component-highlight {
@apply transition-all duration-200 ease-in-out;
position: relative;
}
.component-highlight:hover {
@apply bg-primary-50 dark:bg-primary-900/20;
transform: translateY(-1px);
box-shadow: var(--shadow-md);
}
/* 设计模式样式 */
[data-design-mode="true"] {
transition: all 0.2s ease;
}
[data-design-mode="true"]:hover {
@apply bg-primary-50 border-primary-200;
outline: 2px solid theme('colors.primary.500');
outline-offset: 2px;
}
[data-design-mode-active="true"] {
@apply bg-error-50 border-error-200;
outline: 3px solid theme('colors.error.500');
outline-offset: 2px;
animation: pulse-error 1s ease-in-out;
}
[data-design-mode-hover="true"] {
@apply bg-warning-50 border-warning-200;
outline: 2px solid theme('colors.warning.500');
outline-offset: 2px;
}
@keyframes pulse-error {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
/* 表单组件样式 */
.form-group {
@apply space-y-2;
}
.form-label {
@apply block text-sm font-medium text-neutral-700 dark:text-neutral-300;
}
.form-input {
@apply w-full px-3 py-2 border border-neutral-300 dark:border-neutral-600 rounded-md shadow-sm;
@apply focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500;
@apply dark:bg-neutral-700 dark:text-neutral-100;
}
.form-input:invalid {
@apply border-error-300 focus:ring-error-500 focus:border-error-500;
}
/* 按钮组件样式 */
.btn {
@apply inline-flex items-center justify-center px-4 py-2 border font-medium rounded-md;
@apply transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2;
@apply disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-primary {
@apply btn bg-primary-600 border-primary-600 text-white;
@apply hover:bg-primary-700 hover:border-primary-700 focus:ring-primary-500;
}
.btn-secondary {
@apply btn bg-neutral-200 border-neutral-300 text-neutral-900;
@apply hover:bg-neutral-300 hover:border-neutral-400 focus:ring-neutral-500;
@apply dark:bg-neutral-700 dark:border-neutral-600 dark:text-neutral-100;
@apply dark:hover:bg-neutral-600 dark:hover:border-neutral-500;
}
.btn-outline {
@apply btn border-primary-600 text-primary-600 bg-transparent;
@apply hover:bg-primary-600 hover:text-white focus:ring-primary-500;
}
.btn-sm {
@apply px-3 py-1.5 text-sm;
}
.btn-lg {
@apply px-6 py-3 text-lg;
}
/* 卡片组件样式 */
.card {
@apply bg-white dark:bg-neutral-900 rounded-lg shadow border border-neutral-200 dark:border-neutral-800;
@apply transition-shadow duration-200;
}
.card:hover {
box-shadow: var(--shadow-lg);
}
.card-header {
@apply px-6 py-4 border-b border-neutral-200 dark:border-neutral-800;
}
.card-body {
@apply px-6 py-4;
}
.card-footer {
@apply px-6 py-4 border-t border-neutral-200 dark:border-neutral-800;
}
/* 模态框样式 */
.modal-overlay {
@apply fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50;
backdrop-filter: blur(4px);
}
.modal-content {
@apply bg-white dark:bg-neutral-900 rounded-lg shadow-xl max-w-md w-full mx-4;
@apply animate-in fade-in duration-200;
}
/* 工具提示样式 */
.tooltip {
@apply absolute z-50 px-2 py-1 text-xs text-white bg-neutral-900 rounded shadow-lg;
@apply pointer-events-none opacity-0 transition-opacity duration-200;
}
.tooltip.show {
@apply opacity-100;
}
/* 加载状态样式 */
.loading-spinner {
@apply inline-block w-4 h-4 border-2 border-current border-t-transparent rounded-full;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.loading-dots {
@apply flex space-x-1;
}
.loading-dots > div {
@apply w-2 h-2 bg-current rounded-full;
animation: loading-dots 1.4s ease-in-out infinite both;
}
.loading-dots > div:nth-child(1) { animation-delay: -0.32s; }
.loading-dots > div:nth-child(2) { animation-delay: -0.16s; }
@keyframes loading-dots {
0%, 80%, 100% {
transform: scale(0);
}
40% {
transform: scale(1);
}
}
/* 响应式设计增强 */
@media (max-width: 768px) {
.layout-sidebar {
@apply fixed inset-y-0 left-0 z-40 transform -translate-x-full;
transition: transform 0.3s ease;
}
.layout-sidebar.open {
@apply translate-x-0;
}
.page-container {
@apply px-4;
padding-top: 1rem;
padding-bottom: 1rem;
}
}
/* 无障碍支持 */
.sr-only {
@apply absolute w-px h-px p-0 -m-px overflow-hidden whitespace-nowrap border-0;
clip: rect(0, 0, 0, 0);
}
/* 高对比度模式支持 */
@media (prefers-contrast: high) {
.card {
@apply border-2;
}
.btn {
@apply border-2;
}
}
/* 减少动画支持 */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
/* 打印样式 */
@media print {
.layout-sidebar,
.layout-header {
@apply hidden;
}
.layout-content {
@apply ml-0;
}
.page-container {
@apply max-w-none px-0;
}
}
/* 自定义滚动条 */
.custom-scrollbar {
scrollbar-width: thin;
scrollbar-color: theme('colors.neutral.400') theme('colors.neutral.100');
}
.custom-scrollbar::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: theme('colors.neutral.100');
border-radius: 3px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: theme('colors.neutral.400');
border-radius: 3px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: theme('colors.neutral.500');
}
/* 暗色主题滚动条 */
.dark .custom-scrollbar {
scrollbar-color: theme('colors.neutral.600') theme('colors.neutral.800');
}
.dark .custom-scrollbar::-webkit-scrollbar-track {
background: theme('colors.neutral.800');
}
.dark .custom-scrollbar::-webkit-scrollbar-thumb {
background: theme('colors.neutral.600');
}
.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: theme('colors.neutral.500');
}

View File

@@ -0,0 +1,215 @@
/**
* @fileoverview 应用程序入口文件
* @description 负责初始化 React 应用、路由、状态管理和设计模式桥接
*/
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { devtools } from 'zustand/middleware';
import { AnimatePresence } from 'framer-motion';
// 导入应用样式
import './index.css';
// 导入主要组件
import App from './App';
// 创建设计模式状态存储
const useDesignModeStore = create<{
isDesignModeEnabled: boolean;
selectedComponent: any;
hoveredComponent: any;
componentTree: any[];
toggleDesignMode: () => void;
setSelectedComponent: (component: any) => void;
setHoveredComponent: (component: any) => void;
setComponentTree: (tree: any[]) => void;
clearSelection: () => void;
}>()(
devtools(
subscribeWithSelector((set, get) => ({
// 设计模式状态
isDesignModeEnabled: true,
selectedComponent: null,
hoveredComponent: null,
componentTree: [],
// 操作方法
toggleDesignMode: () => set((state) => ({
isDesignModeEnabled: !state.isDesignModeEnabled
})),
setSelectedComponent: (component) => set({ selectedComponent: component }),
setHoveredComponent: (component) => set({ hoveredComponent: component }),
setComponentTree: (tree) => set({ componentTree: tree }),
// 清除选择
clearSelection: () => set({
selectedComponent: null,
hoveredComponent: null
}),
})),
{
name: 'design-mode-store',
}
)
);
// 创建 React Query 客户端配置
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5分钟
gcTime: 1000 * 60 * 30, // 30分钟
retry: (failureCount, error) => {
if (error instanceof Error && error.message.includes('404')) {
return false;
}
return failureCount < 3;
},
refetchOnWindowFocus: false,
},
mutations: {
retry: 1,
},
},
});
// 错误处理组件
const ErrorBoundary: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [hasError, setHasError] = React.useState(false);
const [error, setError] = React.useState<Error | null>(null);
React.useEffect(() => {
const handleError = (error: ErrorEvent) => {
console.error('Global error caught:', error);
setHasError(true);
setError(error.error || new Error(error.message));
};
const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
console.error('Unhandled promise rejection:', event.reason);
setHasError(true);
setError(event.reason instanceof Error ? event.reason : new Error(String(event.reason)));
};
window.addEventListener('error', handleError);
window.addEventListener('unhandledrejection', handleUnhandledRejection);
return () => {
window.removeEventListener('error', handleError);
window.removeEventListener('unhandledrejection', handleUnhandledRejection);
};
}, []);
if (hasError) {
return (
<div className="min-h-screen flex items-center justify-center bg-neutral-50">
<div className="max-w-md p-6 bg-white rounded-lg shadow-lg">
<div className="flex items-center mb-4">
<div className="w-8 h-8 bg-error-100 rounded-full flex items-center justify-center mr-3">
<svg className="w-4 h-4 text-error-600" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
</svg>
</div>
<h2 className="text-lg font-semibold text-neutral-900">Application Error</h2>
</div>
<p className="text-neutral-600 mb-4">
Something went wrong while loading the application. Please try refreshing the page.
</p>
{error && (
<details className="mb-4 p-3 bg-neutral-50 rounded border">
<summary className="cursor-pointer text-sm font-medium text-neutral-700 mb-2">
Error Details
</summary>
<pre className="text-xs text-neutral-600 overflow-auto">
{error.message}
{error.stack && `\n\n${error.stack}`}
</pre>
</details>
)}
<div className="flex space-x-3">
<button
onClick={() => window.location.reload()}
className="flex-1 px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 transition-colors"
>
Reload Page
</button>
<button
onClick={() => {
setHasError(false);
setError(null);
}}
className="flex-1 px-4 py-2 bg-neutral-200 text-neutral-700 rounded-md hover:bg-neutral-300 transition-colors"
>
Try Again
</button>
</div>
</div>
</div>
);
}
return <>{children}</>;
};
// 主应用组件
const RootApp: React.FC = () => {
return (
<ErrorBoundary>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AnimatePresence mode="wait">
<App />
</AnimatePresence>
</BrowserRouter>
</QueryClientProvider>
</ErrorBoundary>
);
};
// 渲染应用
const rootElement = document.getElementById('root');
if (!rootElement) {
throw new Error('Root element not found');
}
const root = ReactDOM.createRoot(rootElement);
root.render(<RootApp />);
// 开发环境下的热模块替换
if (import.meta.hot) {
import.meta.hot.accept();
}
// 设计模式桥接(如果存在)
declare global {
interface Window {
__APPDEV_DESIGN_MODE__?: {
store: typeof useDesignModeStore;
toggleDesignMode: () => void;
selectComponent: (component: any) => void;
highlightComponent: (component: any) => void;
};
}
}
// 初始化设计模式桥接
if (typeof window !== 'undefined') {
window.__APPDEV_DESIGN_MODE__ = {
store: useDesignModeStore,
toggleDesignMode: () => useDesignModeStore.getState().toggleDesignMode(),
selectComponent: (component) => useDesignModeStore.getState().setSelectedComponent(component),
highlightComponent: (component) => useDesignModeStore.getState().setHoveredComponent(component),
};
}
export { useDesignModeStore };
export default RootApp;

View File

@@ -0,0 +1,711 @@
/**
* @fileoverview 组件编辑器页面
* @description 提供可视化的组件编辑功能,支持拖拽、属性编辑和实时预览
*/
import React, { useState, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
Plus,
Play,
Square,
Save,
Download,
Upload,
Eye,
EyeOff,
Settings,
Layers,
Code,
Smartphone,
Monitor,
Tablet
} from 'lucide-react';
import { Card, CardBody, CardHeader } from '../components/ui/Card';
import { Button, IconButton } from '../components/ui/Button';
import { LoadingSpinner } from '../components/ui/LoadingSpinner';
import { useDesignModeStore } from '../main';
// 编辑模式类型
type EditMode = 'design' | 'code' | 'preview';
// 设备类型
type DeviceType = 'desktop' | 'tablet' | 'mobile';
// 组件库数据
const COMPONENT_LIBRARY = [
{
id: 'button',
name: 'Button',
category: 'Input',
icon: '🔘',
description: 'Interactive button component',
props: {
variant: 'primary',
size: 'md',
disabled: false,
loading: false
},
variants: ['primary', 'secondary', 'outline', 'ghost', 'danger'],
sizes: ['sm', 'md', 'lg', 'xl']
},
{
id: 'card',
name: 'Card',
category: 'Layout',
icon: '🃏',
description: 'Container component with header, body, and footer',
props: {
variant: 'default',
size: 'md',
hover: false,
interactive: false
},
variants: ['default', 'elevated', 'outlined', 'ghost', 'filled'],
sizes: ['sm', 'md', 'lg', 'xl']
},
{
id: 'input',
name: 'Input',
category: 'Form',
icon: '📝',
description: 'Text input field component',
props: {
type: 'text',
placeholder: 'Enter text...',
disabled: false,
required: false,
error: false
},
variants: ['default', 'filled', 'underlined'],
sizes: ['sm', 'md', 'lg']
},
{
id: 'modal',
name: 'Modal',
category: 'Overlay',
icon: '🪟',
description: 'Overlay modal dialog',
props: {
open: false,
size: 'md',
closable: true,
maskClosable: true
},
variants: ['default', 'fullscreen', 'drawer'],
sizes: ['sm', 'md', 'lg', 'xl']
}
];
// 组件预览组件
const ComponentPreview: React.FC<{
component: any;
deviceType: DeviceType;
isPlaying: boolean;
}> = ({ component, deviceType, isPlaying }) => {
const renderComponent = () => {
switch (component.id) {
case 'button':
return (
<button
className={`
px-4 py-2 rounded-md font-medium transition-colors
${component.props.variant === 'primary' ? 'bg-primary-600 text-white hover:bg-primary-700' :
component.props.variant === 'secondary' ? 'bg-neutral-200 text-neutral-900 hover:bg-neutral-300' :
component.props.variant === 'outline' ? 'border border-primary-600 text-primary-600 hover:bg-primary-600 hover:text-white' :
component.props.variant === 'danger' ? 'bg-error-600 text-white hover:bg-error-700' :
'bg-transparent text-neutral-700 hover:bg-neutral-100'
}
${component.props.size === 'sm' ? 'px-3 py-1.5 text-sm' :
component.props.size === 'lg' ? 'px-6 py-3 text-lg' :
component.props.size === 'xl' ? 'px-8 py-4 text-xl' :
'px-4 py-2 text-sm'
}
${component.props.disabled ? 'opacity-50 cursor-not-allowed' : ''}
`}
disabled={component.props.disabled}
data-component="Button"
data-element="preview-button"
data-variant={component.props.variant}
data-size={component.props.size}
>
{isPlaying ? 'Loading...' : 'Button Component'}
</button>
);
case 'card':
return (
<div
className={`
bg-white dark:bg-neutral-900 rounded-lg overflow-hidden
${component.props.variant === 'elevated' ? 'shadow-lg' :
component.props.variant === 'outlined' ? 'border-2 border-primary-200 dark:border-primary-800' :
component.props.variant === 'filled' ? 'bg-neutral-50 dark:bg-neutral-800' :
'border border-neutral-200 dark:border-neutral-800'
}
${component.props.hover ? 'hover:shadow-md transition-shadow' : ''}
${component.props.size === 'sm' ? 'p-3' :
component.props.size === 'lg' ? 'p-6' :
component.props.size === 'xl' ? 'p-8' :
'p-4'
}
`}
data-component="Card"
data-element="preview-card"
data-variant={component.props.variant}
data-size={component.props.size}
>
<div className="font-semibold text-neutral-900 dark:text-neutral-100 mb-2">
Card Header
</div>
<div className="text-neutral-600 dark:text-neutral-400 text-sm mb-4">
This is a preview of the {component.name} component.
</div>
<div className="text-xs text-neutral-500">
Card content goes here...
</div>
</div>
);
case 'input':
return (
<div className="space-y-2">
<label className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Input Label
</label>
<input
type={component.props.type}
placeholder={component.props.placeholder}
disabled={component.props.disabled}
required={component.props.required}
className={`
w-full px-3 py-2 border rounded-md transition-colors
${component.props.error ? 'border-error-300 focus:border-error-500 focus:ring-error-500' :
'border-neutral-300 dark:border-neutral-600 focus:border-primary-500 focus:ring-primary-500'
}
${component.props.variant === 'filled' ? 'bg-neutral-50 dark:bg-neutral-800' : 'bg-white dark:bg-neutral-900'}
disabled:opacity-50 disabled:cursor-not-allowed
`}
data-component="Input"
data-element="preview-input"
data-variant={component.props.variant}
data-error={component.props.error ? 'true' : 'false'}
/>
</div>
);
case 'modal':
return (
<div className="relative">
<div className="p-8 bg-neutral-100 dark:bg-neutral-800 rounded-lg border-2 border-dashed border-neutral-300 dark:border-neutral-600">
<div className="text-center text-neutral-500 dark:text-neutral-400">
<div className="w-16 h-16 bg-neutral-200 dark:bg-neutral-700 rounded-full flex items-center justify-center mx-auto mb-4">
🪟
</div>
<p className="text-sm">
{component.props.open ? 'Modal is open' : 'Click to open modal'}
</p>
<p className="text-xs mt-2">
Size: {component.props.size} Closable: {component.props.closable ? 'Yes' : 'No'}
</p>
</div>
</div>
</div>
);
default:
return (
<div className="p-8 bg-neutral-100 dark:bg-neutral-800 rounded-lg border-2 border-dashed border-neutral-300 dark:border-neutral-600 text-center">
<p className="text-neutral-500 dark:text-neutral-400">
Component preview not available
</p>
</div>
);
}
};
const getDeviceClasses = () => {
switch (deviceType) {
case 'mobile':
return 'max-w-sm mx-auto';
case 'tablet':
return 'max-w-2xl mx-auto';
default:
return 'w-full';
}
};
return (
<div
className={`component-preview ${getDeviceClasses()}`}
data-component="ComponentPreview"
data-element="preview"
data-device={deviceType}
data-component-id={component.id}
>
{renderComponent()}
</div>
);
};
// 属性面板组件
const PropertyPanel: React.FC<{
component: any;
onUpdate: (props: any) => void;
}> = ({ component, onUpdate }) => {
const updateProp = (key: string, value: any) => {
onUpdate({
...component.props,
[key]: value
});
};
return (
<Card>
<CardHeader
title={`${component.name} Properties`}
subtitle={`${component.category}${component.id}`}
/>
<CardBody className="space-y-6">
{/* 变体选择 */}
{component.variants && (
<div className="space-y-2">
<label className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Variant
</label>
<select
value={component.props.variant}
onChange={(e) => updateProp('variant', e.target.value)}
className="w-full px-3 py-2 border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
data-component="Select"
data-element="variant-select"
data-component-prop="variant"
>
{component.variants.map((variant: string) => (
<option key={variant} value={variant}>
{variant.charAt(0).toUpperCase() + variant.slice(1)}
</option>
))}
</select>
</div>
)}
{/* 尺寸选择 */}
{component.sizes && (
<div className="space-y-2">
<label className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Size
</label>
<select
value={component.props.size}
onChange={(e) => updateProp('size', e.target.value)}
className="w-full px-3 py-2 border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
data-component="Select"
data-element="size-select"
data-component-prop="size"
>
{component.sizes.map((size: string) => (
<option key={size} value={size}>
{size.toUpperCase()}
</option>
))}
</select>
</div>
)}
{/* 布尔属性 */}
{['disabled', 'loading', 'hover', 'interactive', 'required', 'error'].map((prop) => {
if (!(prop in component.props)) return null;
return (
<div key={prop} className="flex items-center justify-between">
<label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
{prop.charAt(0).toUpperCase() + prop.slice(1)}
</label>
<button
onClick={() => updateProp(prop, !component.props[prop])}
className={`
relative inline-flex h-6 w-11 items-center rounded-full transition-colors
${component.props[prop] ? 'bg-primary-600' : 'bg-neutral-200 dark:bg-neutral-700'}
`}
data-component="Toggle"
data-element="boolean-toggle"
data-prop={prop}
data-value={component.props[prop] ? 'true' : 'false'}
>
<span
className={`
inline-block h-4 w-4 transform rounded-full bg-white transition-transform
${component.props[prop] ? 'translate-x-6' : 'translate-x-1'}
`}
/>
</button>
</div>
);
})}
{/* 文本属性 */}
{['placeholder', 'type'].map((prop) => {
if (!(prop in component.props)) return null;
return (
<div key={prop} className="space-y-2">
<label className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
{prop.charAt(0).toUpperCase() + prop.slice(1)}
</label>
<input
type="text"
value={component.props[prop]}
onChange={(e) => updateProp(prop, e.target.value)}
className="w-full px-3 py-2 border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
data-component="Input"
data-element="text-input"
data-component-prop={prop}
/>
</div>
);
})}
</CardBody>
</Card>
);
};
/**
* 组件编辑器主页面
*/
const ComponentEditor: React.FC = () => {
const [selectedComponent, setSelectedComponent] = useState(COMPONENT_LIBRARY[0]);
const [editMode, setEditMode] = useState<EditMode>('design');
const [deviceType, setDeviceType] = useState<DeviceType>('desktop');
const [isPlaying, setIsPlaying] = useState(false);
const [code, setCode] = useState('');
const { isDesignModeEnabled } = useDesignModeStore();
// 组件属性更新处理
const handleComponentUpdate = useCallback((newProps: any) => {
setSelectedComponent((prev: any) => ({
...prev,
props: newProps
}));
}, []);
// 开始/停止播放状态
const togglePlayState = () => {
setIsPlaying(!isPlaying);
};
// 生成代码
const generateCode = () => {
const propsString = Object.entries(selectedComponent.props)
.map(([key, value]) => `${key}="${value}"`)
.join(' ');
const codeString = `<${selectedComponent.id}${propsString ? ' ' + propsString : ''} />`;
setCode(codeString);
setEditMode('code');
};
// 复制代码
const copyCode = async () => {
try {
await navigator.clipboard.writeText(code);
// 可以添加成功提示
} catch (error) {
console.error('Failed to copy code:', error);
}
};
return (
<div
className="component-editor h-full flex flex-col"
data-component="ComponentEditor"
data-design-mode={isDesignModeEnabled ? 'true' : 'false'}
data-edit-mode={editMode}
data-device={deviceType}
>
{/* 编辑器工具栏 */}
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="editor-toolbar border-b border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-4"
data-element="toolbar"
>
<div className="flex items-center justify-between">
{/* 左侧:组件库和模式切换 */}
<div className="flex items-center space-x-4" data-element="left-controls">
{/* 组件库选择 */}
<div className="flex items-center space-x-2" data-element="component-selector">
<label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
Component:
</label>
<select
value={selectedComponent.id}
onChange={(e) => {
const component = COMPONENT_LIBRARY.find(c => c.id === e.target.value);
if (component) setSelectedComponent(component);
}}
className="px-3 py-1.5 border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
data-component="Select"
data-element="component-select"
>
{COMPONENT_LIBRARY.map((component) => (
<option key={component.id} value={component.id}>
{component.icon} {component.name}
</option>
))}
</select>
</div>
{/* 模式切换 */}
<div className="flex border border-neutral-300 dark:border-neutral-600 rounded-md overflow-hidden" data-element="mode-toggle">
{(['design', 'code', 'preview'] as EditMode[]).map((mode) => (
<button
key={mode}
onClick={() => setEditMode(mode)}
className={`
px-3 py-1.5 text-sm transition-colors flex items-center space-x-1
${editMode === mode
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
}
`}
data-component="ModeButton"
data-element="mode-button"
data-mode={mode}
>
{mode === 'design' && <Settings className="w-4 h-4" />}
{mode === 'code' && <Code className="w-4 h-4" />}
{mode === 'preview' && <Eye className="w-4 h-4" />}
<span className="capitalize">{mode}</span>
</button>
))}
</div>
</div>
{/* 右侧:操作按钮 */}
<div className="flex items-center space-x-3" data-element="right-controls">
{/* 设备切换 */}
{editMode === 'preview' && (
<div className="flex border border-neutral-300 dark:border-neutral-600 rounded-md overflow-hidden" data-element="device-toggle">
{[
{ type: 'desktop', icon: Monitor, label: 'Desktop' },
{ type: 'tablet', icon: Tablet, label: 'Tablet' },
{ type: 'mobile', icon: Smartphone, label: 'Mobile' }
].map(({ type, icon: Icon, label }) => (
<button
key={type}
onClick={() => setDeviceType(type as DeviceType)}
className={`
px-3 py-1.5 text-sm transition-colors flex items-center space-x-1
${deviceType === type
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
}
`}
data-component="DeviceButton"
data-element="device-button"
data-device={type}
title={label}
>
<Icon className="w-4 h-4" />
</button>
))}
</div>
)}
{/* 播放按钮 */}
{selectedComponent.props.hasOwnProperty('loading') && (
<IconButton
variant={isPlaying ? 'primary' : 'ghost'}
onClick={togglePlayState}
data-component="IconButton"
data-element="play-button"
data-action="toggle-play-state"
>
{isPlaying ? <Square className="w-4 h-4" /> : <Play className="w-4 h-4" />}
</IconButton>
)}
{/* 生成代码 */}
<Button
variant="outline"
onClick={generateCode}
data-component="Button"
data-element="generate-code-button"
data-action="generate-code"
>
<Code className="w-4 h-4 mr-2" />
Generate Code
</Button>
{/* 保存 */}
<IconButton
variant="ghost"
data-component="IconButton"
data-element="save-button"
data-action="save-component"
>
<Save className="w-4 h-4" />
</IconButton>
</div>
</div>
</motion.div>
{/* 编辑器主要内容 */}
<div className="flex-1 flex overflow-hidden">
{/* 组件库面板 */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
className="component-library w-64 border-r border-neutral-200 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-800 overflow-y-auto"
data-element="library-panel"
>
<div className="p-4" data-element="library-content">
<h3 className="text-sm font-semibold text-neutral-700 dark:text-neutral-300 mb-4">
Component Library
</h3>
<div className="space-y-2">
{COMPONENT_LIBRARY.map((component) => (
<button
key={component.id}
onClick={() => setSelectedComponent(component)}
className={`
w-full text-left p-3 rounded-lg border transition-colors
${selectedComponent.id === component.id
? 'bg-primary-50 dark:bg-primary-900/20 border-primary-200 dark:border-primary-800'
: 'bg-white dark:bg-neutral-900 border-neutral-200 dark:border-neutral-700 hover:bg-neutral-50 dark:hover:bg-neutral-700'
}
`}
data-component="LibraryItem"
data-element="library-item"
data-component-id={component.id}
>
<div className="flex items-center space-x-3">
<span className="text-lg">{component.icon}</span>
<div className="flex-1 min-w-0">
<div className="font-medium text-sm text-neutral-900 dark:text-neutral-100 truncate">
{component.name}
</div>
<div className="text-xs text-neutral-500 truncate">
{component.category}
</div>
</div>
</div>
</button>
))}
</div>
</div>
</motion.div>
{/* 主编辑区域 */}
<div className="flex-1 flex flex-col overflow-hidden">
<AnimatePresence mode="wait">
{editMode === 'design' && (
<motion.div
key="design"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
className="flex-1 flex"
data-element="design-mode"
>
{/* 设计画布 */}
<div className="flex-1 bg-neutral-100 dark:bg-neutral-900 p-8 overflow-auto">
<div className="max-w-4xl mx-auto">
<div className="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8 min-h-96">
<ComponentPreview
component={selectedComponent}
deviceType={deviceType}
isPlaying={isPlaying}
/>
</div>
</div>
</div>
{/* 属性面板 */}
<div className="w-80 border-l border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 overflow-y-auto">
<div className="p-4">
<PropertyPanel
component={selectedComponent}
onUpdate={handleComponentUpdate}
/>
</div>
</div>
</motion.div>
)}
{editMode === 'code' && (
<motion.div
key="code"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
className="flex-1 flex flex-col"
data-element="code-mode"
>
{/* 代码编辑器 */}
<div className="flex-1 p-6 bg-neutral-900 text-green-400 font-mono text-sm overflow-auto">
<div className="flex items-center justify-between mb-4">
<h3 className="text-white font-semibold">Generated Code</h3>
<Button
variant="ghost"
size="sm"
onClick={copyCode}
data-component="Button"
data-element="copy-code-button"
data-action="copy-code"
>
Copy
</Button>
</div>
<pre className="bg-neutral-800 p-4 rounded-lg overflow-x-auto">
<code data-element="code-content">
{code || '// Click "Generate Code" to create component code'}
</code>
</pre>
</div>
{/* 代码预览 */}
<div className="h-64 border-t border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-6">
<ComponentPreview
component={selectedComponent}
deviceType={deviceType}
isPlaying={isPlaying}
/>
</div>
</motion.div>
)}
{editMode === 'preview' && (
<motion.div
key="preview"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
className="flex-1 bg-neutral-100 dark:bg-neutral-900 overflow-auto"
data-element="preview-mode"
>
<div className="min-h-full p-8">
<div className="max-w-6xl mx-auto">
<div className="bg-white dark:bg-neutral-800 rounded-lg shadow-lg overflow-hidden">
<div className="p-8">
<ComponentPreview
component={selectedComponent}
deviceType={deviceType}
isPlaying={isPlaying}
/>
</div>
</div>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
</div>
);
};
export default ComponentEditor;

View File

@@ -0,0 +1,527 @@
/**
* @fileoverview 仪表盘页面组件
* @description 设计系统的概览仪表盘,展示系统状态、统计信息和快速入口
*/
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
Palette,
Type,
Layout,
Zap,
ArrowRight,
TrendingUp,
Users,
Activity,
CheckCircle,
AlertCircle,
Clock
} from 'lucide-react';
import { Card, CardBody, CardHeader, CardGroup } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { LoadingSpinner } from '../components/ui/LoadingSpinner';
import { useDesignTokens, useColors, useTypography, useSpacing, useEvents } from '../store/design-system-store';
// 简化统计卡片组件
interface StatsCardProps {
title: string;
value: string | number;
icon: React.ReactNode;
trend?: {
value: number;
label: string;
};
color: 'primary' | 'secondary' | 'success' | 'warning' | 'error';
}
// 统计卡片组件
const StatsCard: React.FC<StatsCardProps> = ({ title, value, icon, trend, color }) => {
const colorClasses = {
primary: 'from-primary-500 to-primary-600',
secondary: 'from-secondary-500 to-secondary-600',
success: 'from-success-500 to-success-600',
warning: 'from-warning-500 to-warning-600',
error: 'from-error-500 to-error-600',
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
whileHover={{ y: -2 }}
className="stats-card"
data-component="StatsCard"
data-element="card"
data-color={color}
>
<Card interactive className="h-full">
<CardBody className="p-6">
<div className="flex items-center justify-between mb-4">
<div className={`
w-12 h-12 rounded-lg bg-gradient-to-br ${colorClasses[color]}
flex items-center justify-center text-white shadow-lg
`} data-element="icon">
{icon}
</div>
{trend && (
<div className="flex items-center text-sm" data-element="trend">
<TrendingUp className="w-4 h-4 text-success-500 mr-1" />
<span className="text-success-600 dark:text-success-400">
+{trend.value}%
</span>
</div>
)}
</div>
<div className="space-y-2" data-element="content">
<h3 className="text-2xl font-bold text-neutral-900 dark:text-neutral-100" data-element="value">
{value}
</h3>
<p className="text-neutral-600 dark:text-neutral-400 text-sm" data-element="label">
{title}
</p>
{trend && (
<p className="text-xs text-neutral-500" data-element="trend-label">
{trend.label}
</p>
)}
</div>
</CardBody>
</Card>
</motion.div>
);
};
// 活动项组件
interface ActivityItemProps {
type: 'token' | 'component' | 'library' | 'theme';
title: string;
description: string;
timestamp: string;
status: 'success' | 'pending' | 'error';
}
// 活动项组件
const ActivityItem: React.FC<ActivityItemProps> = ({ type, title, description, timestamp, status }) => {
const getTypeIcon = () => {
switch (type) {
case 'token':
return <Palette className="w-4 h-4" />;
case 'component':
return <Layout className="w-4 h-4" />;
case 'library':
return <Type className="w-4 h-4" />;
case 'theme':
return <Zap className="w-4 h-4" />;
default:
return <Activity className="w-4 h-4" />;
}
};
const getStatusColor = () => {
switch (status) {
case 'success':
return 'text-success-500';
case 'pending':
return 'text-warning-500';
case 'error':
return 'text-error-500';
default:
return 'text-neutral-500';
}
};
const getStatusIcon = () => {
switch (status) {
case 'success':
return <CheckCircle className="w-4 h-4" />;
case 'pending':
return <Clock className="w-4 h-4" />;
case 'error':
return <AlertCircle className="w-4 h-4" />;
default:
return null;
}
};
return (
<div className="activity-item flex items-start space-x-3 p-3 hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg transition-colors" data-component="ActivityItem" data-element="item" data-type={type} data-status={status}>
<div className={`
w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0
${status === 'success' ? 'bg-success-100 dark:bg-success-900/20' :
status === 'pending' ? 'bg-warning-100 dark:bg-warning-900/20' :
'bg-error-100 dark:bg-error-900/20'
}
`} data-element="icon-container">
{getTypeIcon()}
</div>
<div className="flex-1 min-w-0" data-element="content">
<div className="flex items-center justify-between mb-1" data-element="header">
<p className="text-sm font-medium text-neutral-900 dark:text-neutral-100 truncate" data-element="title">
{title}
</p>
<div className={`flex items-center ${getStatusColor()}`} data-element="status">
{getStatusIcon()}
</div>
</div>
<p className="text-xs text-neutral-600 dark:text-neutral-400 mb-2" data-element="description">
{description}
</p>
<p className="text-xs text-neutral-500" data-element="timestamp">
{timestamp}
</p>
</div>
</div>
);
};
/**
* 仪表盘主组件
*/
const Dashboard: React.FC = () => {
const [isLoading, setIsLoading] = useState(true);
// 获取设计系统数据
const colors = useColors();
const typography = useTypography();
const spacing = useSpacing();
const events = useEvents();
// 模拟数据加载
useEffect(() => {
const timer = setTimeout(() => {
setIsLoading(false);
}, 1000);
return () => clearTimeout(timer);
}, []);
// 统计数据
const stats = {
totalTokens: colors.length + typography.length + spacing.length,
totalColors: colors.length,
totalTypography: typography.length,
totalSpacing: spacing.length,
totalComponents: 24, // 模拟数据
totalLibraries: 3, // 模拟数据
designScore: 94, // 模拟数据
};
// 最近活动(基于真实事件)
const recentActivities = events.slice(0, 5).map((event, index) => ({
type: event.type.includes('token') ? 'token' : event.type.includes('component') ? 'component' : 'theme',
title: `System ${event.type}`,
description: `System ${event.type} was updated`,
timestamp: new Date(event.timestamp).toLocaleTimeString(),
status: 'success' as const
}));
// 如果加载中,显示加载状态
if (isLoading) {
return (
<div className="dashboard-loading" data-component="DashboardLoading" data-element="loading">
<div className="flex items-center justify-center h-64">
<LoadingSpinner size="lg" />
<span className="ml-3 text-neutral-600 dark:text-neutral-400">Loading dashboard...</span>
</div>
</div>
);
}
return (
<div className="dashboard space-y-8" data-component="Dashboard" data-element="dashboard">
{/* 欢迎区域 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="welcome-section" data-element="welcome-section"
>
<div className="bg-gradient-to-r from-primary-500 to-secondary-500 rounded-xl p-8 text-white" data-element="hero">
<div className="max-w-3xl" data-element="content">
<h1 className="text-3xl font-bold mb-4" data-element="title">
Welcome to Design System Studio
</h1>
<p className="text-primary-100 mb-6 text-lg" data-element="subtitle">
Manage your design tokens, components, and build consistent user interfaces.
</p>
<div className="flex flex-wrap gap-3" data-element="actions">
<Button
variant="secondary"
className="bg-white/20 border-white/30 text-white hover:bg-white/30"
data-component="Button"
data-element="get-started-button"
data-action="navigate-editor"
>
Get Started
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
<Button
variant="ghost"
className="text-white border-white/30 hover:bg-white/10"
data-component="Button"
data-element="learn-more-button"
data-action="navigate-docs"
>
Learn More
</Button>
</div>
</div>
</div>
</motion.div>
{/* 统计卡片 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="stats-section" data-element="stats-section"
>
<h2 className="text-xl font-semibold text-neutral-900 dark:text-neutral-100 mb-6" data-element="section-title">
System Overview
</h2>
<CardGroup columns={4} gap="lg" data-element="stats-grid">
<StatsCard
title="Total Tokens"
value={stats.totalTokens}
icon={<span className="text-2xl">🎨</span>}
trend={{ value: 12, label: 'from last month' }}
color="primary"
/>
<StatsCard
title="Design Score"
value={`${stats.designScore}%`}
icon={<span className="text-2xl"></span>}
trend={{ value: 5, label: 'improvement' }}
color="success"
/>
<StatsCard
title="Components"
value={stats.totalComponents}
icon={<span className="text-2xl">🧩</span>}
trend={{ value: 8, label: 'new this month' }}
color="secondary"
/>
<StatsCard
title="Libraries"
value={stats.totalLibraries}
icon={<span className="text-2xl">📚</span>}
color="warning"
/>
</CardGroup>
</motion.div>
{/* 内容区域 */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8" data-element="content-grid">
{/* 左侧列 */}
<div className="lg:col-span-2 space-y-8" data-element="left-column">
{/* 快速访问 */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.2 }}
className="quick-access" data-element="quick-access"
>
<Card>
<CardHeader title="Quick Access" />
<CardBody>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4" data-element="access-grid">
<Button
variant="outline"
className="justify-start h-auto p-4"
data-component="Button"
data-element="design-system-button"
data-action="navigate-design-system"
>
<div className="flex items-center space-x-3" data-element="content">
<Palette className="w-5 h-5 text-primary-500" />
<div className="text-left">
<div className="font-medium">Design System</div>
<div className="text-sm text-neutral-500">Manage tokens & themes</div>
</div>
</div>
</Button>
<Button
variant="outline"
className="justify-start h-auto p-4"
data-component="Button"
data-element="component-editor-button"
data-action="navigate-editor"
>
<div className="flex items-center space-x-3" data-element="content">
<Layout className="w-5 h-5 text-secondary-500" />
<div className="text-left">
<div className="font-medium">Component Editor</div>
<div className="text-sm text-neutral-500">Build & customize</div>
</div>
</div>
</Button>
<Button
variant="outline"
className="justify-start h-auto p-4"
data-component="Button"
data-element="live-preview-button"
data-action="navigate-preview"
>
<div className="flex items-center space-x-3" data-element="content">
<Zap className="w-5 h-5 text-success-500" />
<div className="text-left">
<div className="font-medium">Live Preview</div>
<div className="text-sm text-neutral-500">Real-time testing</div>
</div>
</div>
</Button>
<Button
variant="outline"
className="justify-start h-auto p-4"
data-component="Button"
data-element="libraries-button"
data-action="navigate-libraries"
>
<div className="flex items-center space-x-3" data-element="content">
<Users className="w-5 h-5 text-warning-500" />
<div className="text-left">
<div className="font-medium">Libraries</div>
<div className="text-sm text-neutral-500">Component collections</div>
</div>
</div>
</Button>
</div>
</CardBody>
</Card>
</motion.div>
{/* 令牌统计 */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.3 }}
className="token-stats" data-element="token-stats"
>
<Card>
<CardHeader title="Token Distribution" />
<CardBody>
<div className="space-y-4" data-element="token-grid">
<div className="flex items-center justify-between p-3 bg-neutral-50 dark:bg-neutral-800 rounded-lg">
<div className="flex items-center space-x-3">
<div className="w-3 h-3 bg-primary-500 rounded-full"></div>
<span className="text-sm font-medium">Colors</span>
</div>
<span className="text-sm text-neutral-600 dark:text-neutral-400">{stats.totalColors} tokens</span>
</div>
<div className="flex items-center justify-between p-3 bg-neutral-50 dark:bg-neutral-800 rounded-lg">
<div className="flex items-center space-x-3">
<div className="w-3 h-3 bg-secondary-500 rounded-full"></div>
<span className="text-sm font-medium">Typography</span>
</div>
<span className="text-sm text-neutral-600 dark:text-neutral-400">{stats.totalTypography} tokens</span>
</div>
<div className="flex items-center justify-between p-3 bg-neutral-50 dark:bg-neutral-800 rounded-lg">
<div className="flex items-center space-x-3">
<div className="w-3 h-3 bg-success-500 rounded-full"></div>
<span className="text-sm font-medium">Spacing</span>
</div>
<span className="text-sm text-neutral-600 dark:text-neutral-400">{stats.totalSpacing} tokens</span>
</div>
</div>
</CardBody>
</Card>
</motion.div>
</div>
{/* 右侧列 */}
<div className="space-y-8" data-element="right-column">
{/* 最近活动 */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.4 }}
className="recent-activity" data-element="recent-activity"
>
<Card>
<CardHeader title="Recent Activity" />
<CardBody>
<div className="space-y-3" data-element="activity-list">
{recentActivities.length > 0 ? (
recentActivities.map((activity, index) => (
<ActivityItem key={index} {...activity} />
))
) : (
<div className="text-center py-8 text-neutral-500 dark:text-neutral-400">
<Activity className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No recent activity</p>
</div>
)}
</div>
{events.length > 5 && (
<div className="mt-4 pt-4 border-t border-neutral-200 dark:border-neutral-800">
<Button
variant="ghost"
size="sm"
className="w-full"
data-component="Button"
data-element="view-all-activity-button"
data-action="navigate-activity"
>
View All Activity
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</div>
)}
</CardBody>
</Card>
</motion.div>
{/* 系统状态 */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.5 }}
className="system-status" data-element="system-status"
>
<Card>
<CardHeader title="System Status" />
<CardBody>
<div className="space-y-4" data-element="status-items">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<CheckCircle className="w-5 h-5 text-success-500" />
<span className="text-sm font-medium">Design Mode</span>
</div>
<span className="text-sm text-success-600 dark:text-success-400">Active</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<CheckCircle className="w-5 h-5 text-success-500" />
<span className="text-sm font-medium">Token Sync</span>
</div>
<span className="text-sm text-success-600 dark:text-success-400">Synced</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<CheckCircle className="w-5 h-5 text-success-500" />
<span className="text-sm font-medium">Component Library</span>
</div>
<span className="text-sm text-success-600 dark:text-success-400">Updated</span>
</div>
</div>
</CardBody>
</Card>
</motion.div>
</div>
</div>
</div>
);
};
export default Dashboard;

View File

@@ -0,0 +1,496 @@
/**
* @fileoverview 设计系统管理页面
* @description 展示和管理设计系统的所有令牌,包括颜色、字体、间距等
*/
import React, { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
Palette,
Type,
Ruler,
Shadow,
Circle,
Zap,
Search,
Filter,
Grid,
List,
Download,
Upload,
Settings,
Plus,
Eye,
EyeOff
} from 'lucide-react';
import { Card, CardBody, CardHeader } from '../components/ui/Card';
import { Button, IconButton } from '../components/ui/Button';
import { TokenCard } from '../components/design-system/TokenCard';
import { ColorPalette } from '../components/design-system/ColorPalette';
import {
useColors,
useTypography,
useSpacing,
useShadows,
useBorderRadius,
useAnimations,
useSelectedToken,
useDesignSystemStore
} from '../store/design-system-store';
import { clsx } from 'clsx';
// 令牌类型定义
type TokenType = 'all' | 'color' | 'typography' | 'spacing' | 'shadow' | 'border-radius' | 'animation';
// 令牌类别配置
const TOKEN_CATEGORIES = {
all: { label: 'All Tokens', icon: Settings, color: 'neutral' },
color: { label: 'Colors', icon: Palette, color: 'primary' },
typography: { label: 'Typography', icon: Type, color: 'secondary' },
spacing: { label: 'Spacing', icon: Ruler, color: 'success' },
shadow: { label: 'Shadows', icon: Shadow, color: 'warning' },
'border-radius': { label: 'Border Radius', icon: Circle, color: 'error' },
animation: { label: 'Animation', icon: Zap, color: 'info' },
} as const;
/**
* 设计系统主页面组件
*/
const DesignSystem: React.FC = () => {
const [activeCategory, setActiveCategory] = useState<TokenType>('all');
const [searchQuery, setSearchQuery] = useState('');
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
const [showDeprecated, setShowDeprecated] = useState(true);
const [selectedToken, setSelectedToken] = useState(null);
// 获取所有令牌数据
const colors = useColors();
const typography = useTypography();
const spacing = useSpacing();
const shadows = useShadows();
const borderRadius = useBorderRadius();
const animations = useAnimations();
// 合并所有令牌
const allTokens = useMemo(() => {
return [
...colors,
...typography,
...spacing,
...shadows,
...borderRadius,
...animations,
];
}, [colors, typography, spacing, shadows, borderRadius, animations]);
// 过滤令牌
const filteredTokens = useMemo(() => {
return allTokens.filter(token => {
// 类别过滤
const matchesCategory = activeCategory === 'all' || token.category === activeCategory;
// 搜索过滤
const matchesSearch = searchQuery === '' ||
token.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
token.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
token.value.toString().toLowerCase().includes(searchQuery.toLowerCase());
// 废弃状态过滤
const matchesDeprecated = showDeprecated || !token.deprecated;
return matchesCategory && matchesSearch && matchesDeprecated;
});
}, [allTokens, activeCategory, searchQuery, showDeprecated]);
// 渲染特定类别的内容
const renderCategoryContent = () => {
switch (activeCategory) {
case 'color':
return (
<ColorPalette
variant="grid"
showControls={false}
interactive={true}
/>
);
case 'typography':
return (
<div className="token-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{typography.map((token, index) => (
<motion.div
key={token.name}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
>
<TokenCard token={token} interactive={true} />
</motion.div>
))}
</div>
);
case 'spacing':
return (
<div className="token-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{spacing.map((token, index) => (
<motion.div
key={token.name}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
>
<TokenCard token={token} variant="compact" interactive={true} />
</motion.div>
))}
</div>
);
case 'shadow':
return (
<div className="token-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{shadows.map((token, index) => (
<motion.div
key={token.name}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
>
<TokenCard token={token} interactive={true} />
</motion.div>
))}
</div>
);
case 'border-radius':
return (
<div className="token-grid grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
{borderRadius.map((token, index) => (
<motion.div
key={token.name}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
>
<TokenCard token={token} variant="compact" interactive={true} />
</motion.div>
))}
</div>
);
case 'animation':
return (
<div className="token-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{animations.map((token, index) => (
<motion.div
key={token.name}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
>
<TokenCard token={token} interactive={true} />
</motion.div>
))}
</div>
);
default:
return (
<div className="token-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<AnimatePresence>
{filteredTokens.map((token, index) => (
<motion.div
key={token.name}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ delay: index * 0.02 }}
>
<TokenCard token={token} interactive={true} />
</motion.div>
))}
</AnimatePresence>
</div>
);
}
};
// 获取类别统计
const getCategoryStats = (type: TokenType) => {
switch (type) {
case 'color': return colors.length;
case 'typography': return typography.length;
case 'spacing': return spacing.length;
case 'shadow': return shadows.length;
case 'border-radius': return borderRadius.length;
case 'animation': return animations.length;
default: return allTokens.length;
}
};
return (
<div className="design-system-page" data-component="DesignSystemPage">
{/* 页面头部 */}
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="page-header mb-8" data-element="header"
>
<div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
<div className="space-y-2" data-element="title-section">
<h1 className="text-3xl font-bold text-neutral-900 dark:text-neutral-100">
Design System
</h1>
<p className="text-neutral-600 dark:text-neutral-400">
Manage your design tokens, typography, colors, and component guidelines
</p>
</div>
<div className="flex items-center space-x-3" data-element="actions">
<Button
variant="outline"
icon={<Upload className="w-4 h-4" />}
data-component="Button"
data-element="import-button"
data-action="import-tokens"
>
Import
</Button>
<Button
variant="outline"
icon={<Download className="w-4 h-4" />}
data-component="Button"
data-element="export-button"
data-action="export-tokens"
>
Export
</Button>
<Button
icon={<Plus className="w-4 h-4" />}
data-component="Button"
data-element="add-token-button"
data-action="add-token"
>
Add Token
</Button>
</div>
</div>
</motion.div>
{/* 控制面板 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="control-panel mb-8" data-element="controls"
>
<Card>
<CardBody className="p-4">
<div className="flex flex-col lg:flex-row lg:items-center space-y-4 lg:space-y-0 lg:space-x-6">
{/* 搜索框 */}
<div className="flex-1 max-w-md" data-element="search">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 w-4 h-4" />
<input
type="text"
placeholder="Search tokens..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 pr-4 py-2 w-full border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
data-component="Input"
data-element="search-input"
data-placeholder="search-tokens"
/>
</div>
</div>
{/* 视图模式切换 */}
<div className="flex items-center space-x-2" data-element="view-mode">
<span className="text-sm text-neutral-600 dark:text-neutral-400">View:</span>
<div className="flex border border-neutral-300 dark:border-neutral-600 rounded-md overflow-hidden">
<button
onClick={() => setViewMode('grid')}
className={clsx(
'px-3 py-1.5 text-sm transition-colors',
viewMode === 'grid'
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
)}
data-component="ToggleButton"
data-element="grid-view-button"
data-action="set-view-grid"
>
<Grid className="w-4 h-4" />
</button>
<button
onClick={() => setViewMode('list')}
className={clsx(
'px-3 py-1.5 text-sm transition-colors',
viewMode === 'list'
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
)}
data-component="ToggleButton"
data-element="list-view-button"
data-action="set-view-list"
>
<List className="w-4 h-4" />
</button>
</div>
</div>
{/* 废弃令牌切换 */}
<div className="flex items-center space-x-2" data-element="deprecated-filter">
<IconButton
variant={showDeprecated ? 'primary' : 'ghost'}
onClick={() => setShowDeprecated(!showDeprecated)}
size="sm"
data-component="IconButton"
data-element="deprecated-toggle"
data-action="toggle-deprecated"
>
{showDeprecated ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
</IconButton>
<span className="text-sm text-neutral-600 dark:text-neutral-400">
Show deprecated
</span>
</div>
</div>
</CardBody>
</Card>
</motion.div>
{/* 类别选择器 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="category-tabs mb-8" data-element="categories"
>
<div className="flex flex-wrap gap-2" data-element="tab-list">
{Object.entries(TOKEN_CATEGORIES).map(([key, config]) => {
const Icon = config.icon;
const count = getCategoryStats(key as TokenType);
const isActive = activeCategory === key;
return (
<button
key={key}
onClick={() => setActiveCategory(key as TokenType)}
className={clsx(
'flex items-center space-x-2 px-4 py-2 rounded-lg border transition-all duration-200',
isActive
? 'bg-primary-500 text-white border-primary-500 shadow-md'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 border-neutral-300 dark:border-neutral-600 hover:bg-neutral-50 dark:hover:bg-neutral-700'
)}
data-component="CategoryTab"
data-element="category-tab"
data-category={key}
data-active={isActive ? 'true' : 'false'}
>
<Icon className="w-4 h-4" />
<span className="font-medium">{config.label}</span>
<span className={clsx(
'px-2 py-0.5 text-xs rounded-full',
isActive
? 'bg-white/20 text-white'
: 'bg-neutral-100 dark:bg-neutral-700 text-neutral-600 dark:text-neutral-400'
)}>
{count}
</span>
</button>
);
})}
</div>
</motion.div>
{/* 主要内容区域 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
className="main-content" data-element="content"
>
{/* 空状态 */}
{filteredTokens.length === 0 && activeCategory !== 'color' ? (
<Card>
<CardBody className="p-12 text-center">
<div className="w-16 h-16 bg-neutral-100 dark:bg-neutral-800 rounded-full flex items-center justify-center mx-auto mb-4">
<Search className="w-8 h-8 text-neutral-400" />
</div>
<h3 className="text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-2">
No tokens found
</h3>
<p className="text-neutral-600 dark:text-neutral-400 mb-6">
Try adjusting your search criteria or browse different categories.
</p>
<Button
variant="outline"
onClick={() => {
setSearchQuery('');
setActiveCategory('all');
}}
data-component="Button"
data-element="clear-filters-button"
data-action="clear-filters"
>
Clear Filters
</Button>
</CardBody>
</Card>
) : (
<AnimatePresence mode="wait">
<motion.div
key={activeCategory}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
className="category-content" data-element="category-content"
>
{renderCategoryContent()}
</motion.div>
</AnimatePresence>
)}
</motion.div>
{/* 统计信息 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.4 }}
className="stats-footer mt-12 pt-8 border-t border-neutral-200 dark:border-neutral-800" data-element="stats"
>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 text-center" data-element="stats-grid">
{Object.entries(TOKEN_CATEGORIES).slice(1).map(([key, config]) => {
const Icon = config.icon;
const count = getCategoryStats(key as TokenType);
return (
<div
key={key}
className="stat-item p-4 bg-neutral-50 dark:bg-neutral-800 rounded-lg"
data-component="StatItem"
data-element="stat-item"
data-category={key}
>
<Icon className={clsx(
'w-6 h-6 mx-auto mb-2',
`text-${config.color}-500`
)} />
<div className="text-2xl font-bold text-neutral-900 dark:text-neutral-100">
{count}
</div>
<div className="text-sm text-neutral-600 dark:text-neutral-400">
{config.label}
</div>
</div>
);
})}
</div>
</motion.div>
</div>
);
};
export default DesignSystem;

View File

@@ -0,0 +1,566 @@
/**
* @fileoverview 实时预览页面
* @description 展示组件的实时预览效果,支持不同设备和主题切换
*/
import React, { useState, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
RefreshCw,
Maximize,
Smartphone,
Tablet,
Monitor,
Moon,
Sun,
Settings,
Eye,
EyeOff,
Play,
Pause,
Download,
Share2
} from 'lucide-react';
import { Card, CardBody, CardHeader } from '../components/ui/Card';
import { Button, IconButton } from '../components/ui/Button';
import { LoadingSpinner } from '../components/ui/LoadingSpinner';
import { useDesignModeStore } from '../main';
// 设备类型
type DeviceType = 'desktop' | 'tablet' | 'mobile';
// 主题类型
type ThemeType = 'light' | 'dark' | 'system';
// 预览模式
type PreviewMode = 'component' | 'page' | 'interaction';
// 示例组件数据
const PREVIEW_COMPONENTS = [
{
id: 'hero-section',
name: 'Hero Section',
description: 'Landing page hero with call-to-action',
category: 'Layout',
component: (
<div className="bg-gradient-to-r from-primary-600 to-secondary-600 text-white py-20 px-8 text-center">
<h1 className="text-5xl font-bold mb-6">Design System Studio</h1>
<p className="text-xl mb-8 max-w-2xl mx-auto">
Build consistent and beautiful user interfaces with our comprehensive design system toolkit.
</p>
<div className="flex justify-center space-x-4">
<button className="bg-white text-primary-600 px-8 py-3 rounded-lg font-semibold hover:bg-gray-100 transition-colors">
Get Started
</button>
<button className="border-2 border-white text-white px-8 py-3 rounded-lg font-semibold hover:bg-white hover:text-primary-600 transition-colors">
Learn More
</button>
</div>
</div>
)
},
{
id: 'feature-grid',
name: 'Feature Grid',
description: 'Grid of features with icons and descriptions',
category: 'Content',
component: (
<div className="py-16 px-8">
<div className="text-center mb-16">
<h2 className="text-3xl font-bold text-gray-900 mb-4">Powerful Features</h2>
<p className="text-gray-600 max-w-2xl mx-auto">
Everything you need to build and maintain a consistent design system.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto">
{[
{ icon: '🎨', title: 'Design Tokens', desc: 'Centralized design decisions' },
{ icon: '🔧', title: 'Component Library', desc: 'Reusable UI components' },
{ icon: '📱', title: 'Responsive Design', desc: 'Mobile-first approach' },
{ icon: '⚡', title: 'Fast Performance', desc: 'Optimized for speed' },
{ icon: '🎯', title: 'Accessibility', desc: 'WCAG compliant design' },
{ icon: '🔄', title: 'Real-time Sync', desc: 'Instant updates across team' }
].map((feature, index) => (
<div key={index} className="text-center p-6 bg-gray-50 rounded-lg">
<div className="text-4xl mb-4">{feature.icon}</div>
<h3 className="text-xl font-semibold text-gray-900 mb-2">{feature.title}</h3>
<p className="text-gray-600">{feature.desc}</p>
</div>
))}
</div>
</div>
)
},
{
id: 'form-example',
name: 'Contact Form',
description: 'Complete contact form with validation',
category: 'Form',
component: (
<div className="max-w-2xl mx-auto py-16 px-8">
<div className="text-center mb-8">
<h2 className="text-3xl font-bold text-gray-900 mb-4">Contact Us</h2>
<p className="text-gray-600">We'd love to hear from you. Send us a message!</p>
</div>
<form className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">First Name</label>
<input
type="text"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
placeholder="John"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Last Name</label>
<input
type="text"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
placeholder="Doe"
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Email</label>
<input
type="email"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
placeholder="john@example.com"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Message</label>
<textarea
rows={4}
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
placeholder="Tell us more about your project..."
/>
</div>
<div className="flex items-center">
<input
type="checkbox"
className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
/>
<label className="ml-2 text-sm text-gray-600">
I agree to the <a href="#" className="text-primary-600 hover:underline">Terms of Service</a> and <a href="#" className="text-primary-600 hover:underline">Privacy Policy</a>
</label>
</div>
<button
type="submit"
className="w-full bg-primary-600 text-white py-3 px-6 rounded-lg font-semibold hover:bg-primary-700 transition-colors"
>
Send Message
</button>
</form>
</div>
)
}
];
// 设备预览组件
const DevicePreview: React.FC<{
component: React.ReactNode;
deviceType: DeviceType;
theme: ThemeType;
isLoading?: boolean;
}> = ({ component, deviceType, theme, isLoading = false }) => {
const getDeviceStyles = () => {
switch (deviceType) {
case 'mobile':
return {
width: '375px',
height: '667px',
maxWidth: '100%',
borderRadius: '25px',
border: '1px solid #e5e5e5'
};
case 'tablet':
return {
width: '768px',
height: '1024px',
maxWidth: '100%',
borderRadius: '15px',
border: '1px solid #e5e5e5'
};
default:
return {
width: '100%',
height: '600px',
borderRadius: '8px',
border: '1px solid #e5e5e5'
};
}
};
const deviceStyles = getDeviceStyles();
return (
<div
className="device-preview flex justify-center items-center bg-gray-100 dark:bg-gray-900 p-8"
data-component="DevicePreview"
data-element="preview-container"
data-device={deviceType}
data-theme={theme}
>
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="device-frame bg-white dark:bg-gray-800 overflow-hidden shadow-2xl"
style={deviceStyles}
data-element="device-frame"
>
{isLoading ? (
<div className="flex items-center justify-center h-full">
<LoadingSpinner size="lg" />
</div>
) : (
<div
className="preview-content h-full overflow-auto"
data-element="preview-content"
>
{component}
</div>
)}
</motion.div>
</div>
);
};
/**
* 实时预览主页面
*/
const LivePreview: React.FC = () => {
const [selectedComponent, setSelectedComponent] = useState(PREVIEW_COMPONENTS[0]);
const [deviceType, setDeviceType] = useState<DeviceType>('desktop');
const [theme, setTheme] = useState<ThemeType>('light');
const [previewMode, setPreviewMode] = useState<PreviewMode>('component');
const [isFullscreen, setIsFullscreen] = useState(false);
const [isAutoRefresh, setIsAutoRefresh] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [lastUpdate, setLastUpdate] = useState(new Date());
const { isDesignModeEnabled } = useDesignModeStore();
const previewRef = useRef<HTMLDivElement>(null);
// 刷新预览
const refreshPreview = useCallback(async () => {
setIsLoading(true);
// 模拟加载延迟
await new Promise(resolve => setTimeout(resolve, 500));
setIsLoading(false);
setLastUpdate(new Date());
}, []);
// 切换全屏
const toggleFullscreen = useCallback(() => {
if (!document.fullscreenElement) {
previewRef.current?.requestFullscreen();
setIsFullscreen(true);
} else {
document.exitFullscreen();
setIsFullscreen(false);
}
}, []);
// 应用主题
const applyTheme = useCallback((newTheme: ThemeType) => {
setTheme(newTheme);
const root = document.documentElement;
switch (newTheme) {
case 'dark':
root.classList.add('dark');
break;
case 'light':
root.classList.remove('dark');
break;
case 'system':
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
root.classList.toggle('dark', prefersDark);
break;
}
}, []);
// 初始化主题
React.useEffect(() => {
applyTheme(theme);
}, [theme, applyTheme]);
// 设备切换时刷新
React.useEffect(() => {
if (isAutoRefresh) {
refreshPreview();
}
}, [deviceType, selectedComponent, isAutoRefresh, refreshPreview]);
return (
<div
ref={previewRef}
className="live-preview h-full flex flex-col"
data-component="LivePreview"
data-design-mode={isDesignModeEnabled ? 'true' : 'false'}
data-preview-mode={previewMode}
data-device={deviceType}
data-theme={theme}
>
{/* 预览控制栏 */}
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="preview-toolbar border-b border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-4"
data-element="toolbar"
>
<div className="flex items-center justify-between">
{/* 左侧:组件选择和模式 */}
<div className="flex items-center space-x-4" data-element="left-controls">
{/* 组件选择 */}
<div className="flex items-center space-x-2">
<label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
Preview:
</label>
<select
value={selectedComponent.id}
onChange={(e) => {
const component = PREVIEW_COMPONENTS.find(c => c.id === e.target.value);
if (component) setSelectedComponent(component);
}}
className="px-3 py-1.5 border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
data-component="Select"
data-element="component-select"
>
{PREVIEW_COMPONENTS.map((component) => (
<option key={component.id} value={component.id}>
{component.name}
</option>
))}
</select>
</div>
{/* 预览模式切换 */}
<div className="flex border border-neutral-300 dark:border-neutral-600 rounded-md overflow-hidden">
{[
{ mode: 'component' as PreviewMode, icon: Settings, label: 'Component' },
{ mode: 'page' as PreviewMode, icon: Monitor, label: 'Page' },
{ mode: 'interaction' as PreviewMode, icon: Play, label: 'Interaction' }
].map(({ mode, icon: Icon, label }) => (
<button
key={mode}
onClick={() => setPreviewMode(mode)}
className={`
px-3 py-1.5 text-sm transition-colors flex items-center space-x-1
${previewMode === mode
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
}
`}
data-component="ModeButton"
data-element="mode-button"
data-mode={mode}
>
<Icon className="w-4 h-4" />
<span>{label}</span>
</button>
))}
</div>
</div>
{/* 右侧:控制按钮 */}
<div className="flex items-center space-x-3" data-element="right-controls">
{/* 设备切换 */}
<div className="flex border border-neutral-300 dark:border-neutral-600 rounded-md overflow-hidden" data-element="device-toggle">
{[
{ type: 'mobile' as DeviceType, icon: Smartphone, label: 'Mobile' },
{ type: 'tablet' as DeviceType, icon: Tablet, label: 'Tablet' },
{ type: 'desktop' as DeviceType, icon: Monitor, label: 'Desktop' }
].map(({ type, icon: Icon, label }) => (
<button
key={type}
onClick={() => setDeviceType(type)}
className={`
px-3 py-1.5 text-sm transition-colors flex items-center space-x-1
${deviceType === type
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
}
`}
data-component="DeviceButton"
data-element="device-button"
data-device={type}
title={label}
>
<Icon className="w-4 h-4" />
</button>
))}
</div>
{/* 主题切换 */}
<div className="flex border border-neutral-300 dark:border-neutral-600 rounded-md overflow-hidden">
{[
{ type: 'light' as ThemeType, icon: Sun, label: 'Light' },
{ type: 'dark' as ThemeType, icon: Moon, label: 'Dark' },
{ type: 'system' as ThemeType, icon: Settings, label: 'System' }
].map(({ type, icon: Icon, label }) => (
<button
key={type}
onClick={() => applyTheme(type)}
className={`
px-3 py-1.5 text-sm transition-colors flex items-center space-x-1
${theme === type
? 'bg-primary-500 text-white'
: 'bg-white dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 dark:hover:bg-neutral-700'
}
`}
data-component="ThemeButton"
data-element="theme-button"
data-theme={type}
title={label}
>
<Icon className="w-4 h-4" />
</button>
))}
</div>
{/* 自动刷新切换 */}
<IconButton
variant={isAutoRefresh ? 'primary' : 'ghost'}
onClick={() => setIsAutoRefresh(!isAutoRefresh)}
title="Auto Refresh"
data-component="IconButton"
data-element="auto-refresh-toggle"
data-action="toggle-auto-refresh"
>
{isAutoRefresh ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
</IconButton>
{/* 刷新按钮 */}
<IconButton
variant="ghost"
onClick={refreshPreview}
disabled={isLoading}
title="Refresh Preview"
data-component="IconButton"
data-element="refresh-button"
data-action="refresh-preview"
>
<RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
</IconButton>
{/* 全屏按钮 */}
<IconButton
variant="ghost"
onClick={toggleFullscreen}
title="Fullscreen"
data-component="IconButton"
data-element="fullscreen-button"
data-action="toggle-fullscreen"
>
<Maximize className="w-4 h-4" />
</IconButton>
</div>
</div>
</motion.div>
{/* 预览信息栏 */}
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="preview-info bg-neutral-50 dark:bg-neutral-800 px-4 py-2 text-sm text-neutral-600 dark:text-neutral-400 border-b border-neutral-200 dark:border-neutral-700"
data-element="info-bar"
>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4" data-element="preview-info-left">
<span data-element="component-name">
{selectedComponent.name} • {selectedComponent.category}
</span>
<span data-element="device-info">
{deviceType.charAt(0).toUpperCase() + deviceType.slice(1)} • {theme.charAt(0).toUpperCase() + theme.slice(1)} Mode
</span>
</div>
<div className="flex items-center space-x-4" data-element="preview-info-right">
<span data-element="last-update">
Last updated: {lastUpdate.toLocaleTimeString()}
</span>
{isAutoRefresh && (
<span className="text-success-600 dark:text-success-400" data-element="auto-refresh-status">
● Auto-refresh ON
</span>
)}
</div>
</div>
</motion.div>
{/* 主要预览区域 */}
<div className="flex-1 relative overflow-hidden">
<AnimatePresence mode="wait">
<motion.div
key={`${selectedComponent.id}-${deviceType}-${theme}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3 }}
className="preview-area h-full"
data-element="preview-area"
>
<DevicePreview
component={selectedComponent.component}
deviceType={deviceType}
theme={theme}
isLoading={isLoading}
/>
</motion.div>
</AnimatePresence>
{/* 覆盖层指示器 */}
<div className="absolute top-4 right-4 bg-black bg-opacity-50 text-white px-3 py-1 rounded text-sm">
{selectedComponent.description}
</div>
</div>
{/* 操作栏 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="preview-actions border-t border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-4"
data-element="actions-bar"
>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3" data-element="left-actions">
<Button
variant="outline"
size="sm"
icon={<Download className="w-4 h-4" />}
data-component="Button"
data-element="download-button"
data-action="download-preview"
>
Download
</Button>
<Button
variant="outline"
size="sm"
icon={<Share2 className="w-4 h-4" />}
data-component="Button"
data-element="share-button"
data-action="share-preview"
>
Share
</Button>
</div>
<div className="flex items-center space-x-3" data-element="right-actions">
<div className="text-sm text-neutral-600 dark:text-neutral-400">
Preview Mode: {previewMode.charAt(0).toUpperCase() + previewMode.slice(1)}
</div>
<div className="w-3 h-3 bg-success-500 rounded-full animate-pulse"></div>
</div>
</div>
</motion.div>
</div>
);
};
export default LivePreview;

View File

@@ -0,0 +1,599 @@
/**
* @fileoverview 设计系统状态管理
* @description 使用 Zustand 管理设计系统的全局状态
*/
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { devtools } from 'zustand/middleware';
import {
DesignSystemState,
DesignSystemAction,
DesignToken,
ComponentVariant,
ComponentLibrary,
DesignSystemConfig,
DesignSystemEvent
} from '../types/design-system';
/**
* 设计系统默认配置
*/
const defaultDesignSystemConfig: DesignSystemConfig = {
name: 'Full Featured Design System',
version: '1.0.0',
description: 'A comprehensive design system with tokens, components, and utilities',
author: 'XAGI Team',
license: 'MIT',
tokens: {
colors: [
{
name: 'primary.50',
value: '#eff6ff',
category: 'color',
description: 'Lightest primary color',
palette: 'primary',
scale: '50',
tags: ['primary', 'light', 'background']
},
{
name: 'primary.500',
value: '#3b82f6',
category: 'color',
description: 'Main primary color',
palette: 'primary',
scale: '500',
tags: ['primary', 'main', 'interactive']
},
{
name: 'primary.900',
value: '#1e3a8a',
category: 'color',
description: 'Darkest primary color',
palette: 'primary',
scale: '900',
tags: ['primary', 'dark', 'text']
},
{
name: 'neutral.50',
value: '#fafafa',
category: 'color',
description: 'Lightest neutral color',
palette: 'neutral',
scale: '50',
tags: ['neutral', 'light', 'background']
},
{
name: 'neutral.500',
value: '#737373',
category: 'color',
description: 'Main neutral color',
palette: 'neutral',
scale: '500',
tags: ['neutral', 'main', 'text']
},
{
name: 'neutral.900',
value: '#171717',
category: 'color',
description: 'Darkest neutral color',
palette: 'neutral',
scale: '900',
tags: ['neutral', 'dark', 'text']
}
],
typography: [
{
name: 'font-family.sans',
value: {
fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
},
category: 'typography',
description: 'Default sans-serif font family',
type: 'body',
tags: ['typography', 'font', 'sans-serif']
},
{
name: 'font-family.mono',
value: {
fontFamily: 'JetBrains Mono, ui-monospace, monospace',
},
category: 'typography',
description: 'Default monospace font family',
type: 'code',
tags: ['typography', 'font', 'monospace']
},
{
name: 'font-size.base',
value: {
fontSize: '1rem',
lineHeight: '1.5',
},
category: 'typography',
description: 'Base font size',
type: 'body',
scale: 'base',
tags: ['typography', 'font-size', 'base']
},
{
name: 'font-size.lg',
value: {
fontSize: '1.125rem',
lineHeight: '1.75',
},
category: 'typography',
description: 'Large font size',
type: 'body',
scale: 'lg',
tags: ['typography', 'font-size', 'large']
}
],
spacing: [
{
name: 'spacing.0',
value: '0',
category: 'spacing',
description: 'No spacing',
scale: '0',
tags: ['spacing', 'zero']
},
{
name: 'spacing.1',
value: '0.25rem',
category: 'spacing',
description: 'Extra small spacing',
scale: '1',
tags: ['spacing', 'extra-small']
},
{
name: 'spacing.4',
value: '1rem',
category: 'spacing',
description: 'Medium spacing',
scale: '4',
tags: ['spacing', 'medium']
},
{
name: 'spacing.8',
value: '2rem',
category: 'spacing',
description: 'Large spacing',
scale: '8',
tags: ['spacing', 'large']
}
],
shadows: [
{
name: 'shadow.sm',
value: {
offsetX: '0',
offsetY: '1px',
blurRadius: '2px',
spreadRadius: '0',
color: 'rgb(0 0 0 / 0.05)',
},
category: 'shadow',
description: 'Small shadow',
elevation: 1,
tags: ['shadow', 'small', 'subtle']
},
{
name: 'shadow.md',
value: {
offsetX: '0',
offsetY: '4px',
blurRadius: '6px',
spreadRadius: '-1px',
color: 'rgb(0 0 0 / 0.1)',
},
category: 'shadow',
description: 'Medium shadow',
elevation: 2,
tags: ['shadow', 'medium', 'elevated']
},
{
name: 'shadow.lg',
value: {
offsetX: '0',
offsetY: '10px',
blurRadius: '15px',
spreadRadius: '-3px',
color: 'rgb(0 0 0 / 0.1)',
},
category: 'shadow',
description: 'Large shadow',
elevation: 3,
tags: ['shadow', 'large', 'prominent']
}
],
borderRadius: [
{
name: 'radius.sm',
value: '0.125rem',
category: 'border-radius',
description: 'Small border radius',
shape: 'small',
tags: ['border-radius', 'small', 'subtle']
},
{
name: 'radius.md',
value: '0.375rem',
category: 'border-radius',
description: 'Medium border radius',
shape: 'medium',
tags: ['border-radius', 'medium', 'standard']
},
{
name: 'radius.lg',
value: '0.5rem',
category: 'border-radius',
description: 'Large border radius',
shape: 'large',
tags: ['border-radius', 'large', 'prominent']
},
{
name: 'radius.full',
value: '9999px',
category: 'border-radius',
description: 'Full border radius',
shape: 'full',
tags: ['border-radius', 'full', 'circular']
}
],
animations: [
{
name: 'duration.fast',
value: {
duration: '150ms',
timingFunction: 'ease-in-out',
},
category: 'animation',
description: 'Fast animation duration',
type: 'transition',
tags: ['animation', 'duration', 'fast']
},
{
name: 'duration.medium',
value: {
duration: '300ms',
timingFunction: 'ease-in-out',
},
category: 'animation',
description: 'Medium animation duration',
type: 'transition',
tags: ['animation', 'duration', 'medium']
},
{
name: 'duration.slow',
value: {
duration: '500ms',
timingFunction: 'ease-in-out',
},
category: 'animation',
description: 'Slow animation duration',
type: 'transition',
tags: ['animation', 'duration', 'slow']
}
]
},
meta: {
created: new Date().toISOString(),
updated: new Date().toISOString(),
tags: ['design-system', 'tokens', 'components'],
category: 'light'
}
};
/**
* 设计系统状态管理 Store
*/
const useDesignSystemStore = create<DesignSystemState & {
dispatch: React.Dispatch<DesignSystemAction>;
events: DesignSystemEvent[];
addEvent: (event: Omit<DesignSystemEvent, 'timestamp'>) => void;
clearEvents: () => void;
}>()(
devtools(
subscribeWithSelector((set, get) => ({
// 初始状态
config: defaultDesignSystemConfig,
libraries: [],
selectedToken: null,
selectedComponent: null,
selectedLibrary: null,
searchQuery: '',
filterBy: {
category: null,
status: null,
tags: []
},
viewMode: 'grid',
theme: 'light',
isLoading: false,
error: null,
// 事件历史
events: [],
// 分发器函数
dispatch: (action: DesignSystemAction) => {
set((state) => {
const newState = reducer(state, action);
// 添加事件
if (action.type !== 'RESET_STATE') {
get().addEvent({
type: getActionType(action),
payload: action.payload,
});
}
return newState;
});
},
// 事件管理
addEvent: (event: Omit<DesignSystemEvent, 'timestamp'>) => {
set((state) => ({
events: [
{
...event,
timestamp: new Date().toISOString()
},
...state.events.slice(0, 99) // 保留最近100个事件
]
}));
},
clearEvents: () => {
set({ events: [] });
},
// 便捷操作方法
setConfig: (config: DesignSystemConfig) => {
get().dispatch({ type: 'SET_CONFIG', payload: config });
},
setSelectedToken: (token: DesignToken | null) => {
get().dispatch({ type: 'SET_SELECTED_TOKEN', payload: token });
},
setSelectedComponent: (component: ComponentVariant | null) => {
get().dispatch({ type: 'SET_SELECTED_COMPONENT', payload: component });
},
setSearchQuery: (query: string) => {
get().dispatch({ type: 'SET_SEARCH_QUERY', payload: query });
},
setFilter: (filter: Partial<DesignSystemState['filterBy']>) => {
get().dispatch({ type: 'SET_FILTER', payload: filter });
},
resetState: () => {
get().dispatch({ type: 'RESET_STATE' });
},
})),
{
name: 'design-system-store',
}
)
);
/**
* Reducer 函数处理状态更新
*/
function reducer(state: DesignSystemState, action: DesignSystemAction): DesignSystemState {
switch (action.type) {
case 'SET_CONFIG':
return {
...state,
config: action.payload,
error: null,
};
case 'SET_LIBRARIES':
return {
...state,
libraries: action.payload,
error: null,
};
case 'ADD_LIBRARY':
return {
...state,
libraries: [...state.libraries, action.payload],
error: null,
};
case 'UPDATE_LIBRARY':
return {
...state,
libraries: state.libraries.map(lib =>
lib.id === action.payload.id ? action.payload : lib
),
error: null,
};
case 'DELETE_LIBRARY':
return {
...state,
libraries: state.libraries.filter(lib => lib.id !== action.payload),
error: null,
};
case 'SET_SELECTED_TOKEN':
return {
...state,
selectedToken: action.payload,
};
case 'SET_SELECTED_COMPONENT':
return {
...state,
selectedComponent: action.payload,
};
case 'SET_SELECTED_LIBRARY':
return {
...state,
selectedLibrary: action.payload,
};
case 'SET_SEARCH_QUERY':
return {
...state,
searchQuery: action.payload,
};
case 'SET_FILTER':
return {
...state,
filterBy: {
...state.filterBy,
...action.payload,
},
};
case 'SET_VIEW_MODE':
return {
...state,
viewMode: action.payload,
};
case 'SET_THEME':
return {
...state,
theme: action.payload,
};
case 'SET_LOADING':
return {
...state,
isLoading: action.payload,
};
case 'SET_ERROR':
return {
...state,
error: action.payload,
isLoading: false,
};
case 'RESET_STATE':
return {
...state,
selectedToken: null,
selectedComponent: null,
selectedLibrary: null,
searchQuery: '',
filterBy: {
category: null,
status: null,
tags: [],
},
error: null,
isLoading: false,
};
default:
return state;
}
}
/**
* 获取操作类型
*/
function getActionType(action: DesignSystemAction): DesignSystemEvent['type'] {
switch (action.type) {
case 'SET_CONFIG':
return 'library_imported';
case 'ADD_LIBRARY':
return 'library_imported';
case 'UPDATE_LIBRARY':
return 'component_updated';
case 'DELETE_LIBRARY':
return 'component_deleted';
case 'SET_SELECTED_TOKEN':
return action.payload ? 'token_created' : 'component_deleted';
case 'SET_SELECTED_COMPONENT':
return action.payload ? 'component_created' : 'component_deleted';
case 'SET_THEME':
return 'theme_switched';
default:
return 'token_updated';
}
}
/**
* 选择器函数
*/
export const useDesignTokens = () => {
const config = useDesignSystemStore(state => state.config);
return config?.tokens || { colors: [], typography: [], spacing: [], shadows: [], borderRadius: [], animations: [] };
};
export const useColors = () => {
const tokens = useDesignTokens();
return tokens.colors || [];
};
export const useTypography = () => {
const tokens = useDesignTokens();
return tokens.typography || [];
};
export const useSpacing = () => {
const tokens = useDesignTokens();
return tokens.spacing || [];
};
export const useShadows = () => {
const tokens = useDesignTokens();
return tokens.shadows || [];
};
export const useBorderRadius = () => {
const tokens = useDesignTokens();
return tokens.borderRadius || [];
};
export const useAnimations = () => {
const tokens = useDesignTokens();
return tokens.animations || [];
};
export const useLibraries = () => {
return useDesignSystemStore(state => state.libraries);
};
export const useSelectedToken = () => {
return useDesignSystemStore(state => state.selectedToken);
};
export const useSelectedComponent = () => {
return useDesignSystemStore(state => state.selectedComponent);
};
export const useSearchAndFilters = () => {
return useDesignSystemStore(state => ({
searchQuery: state.searchQuery,
filterBy: state.filterBy,
viewMode: state.viewMode,
theme: state.theme,
}));
};
export const useLoadingAndError = () => {
return useDesignSystemStore(state => ({
isLoading: state.isLoading,
error: state.error,
}));
};
export const useEvents = () => {
return useDesignSystemStore(state => state.events);
};
// 导出 Store 和选择器
export default useDesignSystemStore;

View File

@@ -0,0 +1,364 @@
/**
* @fileoverview 设计系统类型定义
* @description 定义设计系统相关的TypeScript类型和接口
*/
// 设计令牌基础类型
export interface DesignToken {
name: string;
value: string | number | Record<string, any>; // 允许复杂对象
category: 'color' | 'typography' | 'spacing' | 'shadow' | 'border-radius' | 'z-index' | 'animation';
description?: string;
deprecated?: boolean;
tags?: string[];
}
// 色彩令牌
export interface ColorToken extends DesignToken {
category: 'color';
value: string;
hue?: number;
saturation?: number;
lightness?: number;
alpha?: number;
palette?: 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'neutral';
scale?: string; // e.g., '50', '100', '500', '900'
}
// 字体令牌
export interface TypographyToken extends DesignToken {
category: 'typography';
value: {
fontFamily?: string;
fontSize?: string;
fontWeight?: number | string;
lineHeight?: string | number;
letterSpacing?: string;
textTransform?: 'none' | 'uppercase' | 'lowercase' | 'capitalize';
};
type?: 'heading' | 'body' | 'caption' | 'code' | 'display';
scale?: string;
}
// 间距令牌
export interface SpacingToken extends DesignToken {
category: 'spacing';
value: string | number;
scale?: string;
unit?: 'px' | 'rem' | 'em' | 'vh' | 'vw' | '%';
}
// 阴影令牌
export interface ShadowToken extends DesignToken {
category: 'shadow';
value: {
offsetX?: string | number;
offsetY?: string | number;
blurRadius?: string | number;
spreadRadius?: string | number;
color: string;
inset?: boolean;
};
elevation?: number;
}
// 圆角令牌
export interface BorderRadiusToken extends DesignToken {
category: 'border-radius';
value: string | number;
unit?: 'px' | 'rem' | 'em' | '%';
shape?: 'none' | 'small' | 'medium' | 'large' | 'full';
}
// 动画令牌
export interface AnimationToken extends DesignToken {
category: 'animation';
value: {
duration?: string;
timingFunction?: string;
delay?: string;
iterationCount?: number | 'infinite';
direction?: 'normal' | 'reverse' | 'alternate' | 'alternate-reverse';
fillMode?: 'none' | 'forwards' | 'backwards' | 'both';
};
type?: 'transition' | 'animation' | 'transform';
}
// 设计系统配置
export interface DesignSystemConfig {
name: string;
version: string;
description: string;
author: string;
license: string;
tokens: {
colors: ColorToken[];
typography: TypographyToken[];
spacing: SpacingToken[];
shadows: ShadowToken[];
borderRadius: BorderRadiusToken[];
animations: AnimationToken[];
};
meta: {
created: string;
updated: string;
tags: string[];
category: 'light' | 'dark' | 'auto';
};
}
// 组件变体
export interface ComponentVariant {
id: string;
name: string;
description: string;
category: string;
props: Record<string, any>;
styles: Record<string, any>;
preview?: string;
code?: string;
usage?: string;
accessibility?: string[];
status: 'draft' | 'review' | 'approved' | 'deprecated';
}
// 组件库
export interface ComponentLibrary {
id: string;
name: string;
version: string;
description: string;
author: string;
components: ComponentVariant[];
categories: string[];
tags: string[];
license: string;
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
}
// 设计系统状态
export interface DesignSystemState {
config: DesignSystemConfig | null;
libraries: ComponentLibrary[];
selectedToken: DesignToken | null;
selectedComponent: ComponentVariant | null;
selectedLibrary: ComponentLibrary | null;
searchQuery: string;
filterBy: {
category: string | null;
status: string | null;
tags: string[];
};
viewMode: 'grid' | 'list' | 'table';
theme: 'light' | 'dark' | 'auto';
isLoading: boolean;
error: string | null;
}
// 操作类型
export type DesignSystemAction =
| { type: 'SET_CONFIG'; payload: DesignSystemConfig }
| { type: 'SET_LIBRARIES'; payload: ComponentLibrary[] }
| { type: 'ADD_LIBRARY'; payload: ComponentLibrary }
| { type: 'UPDATE_LIBRARY'; payload: ComponentLibrary }
| { type: 'DELETE_LIBRARY'; payload: string }
| { type: 'SET_SELECTED_TOKEN'; payload: DesignToken | null }
| { type: 'SET_SELECTED_COMPONENT'; payload: ComponentVariant | null }
| { type: 'SET_SELECTED_LIBRARY'; payload: ComponentLibrary | null }
| { type: 'SET_SEARCH_QUERY'; payload: string }
| { type: 'SET_FILTER'; payload: Partial<DesignSystemState['filterBy']> }
| { type: 'SET_VIEW_MODE'; payload: 'grid' | 'list' | 'table' }
| { type: 'SET_THEME'; payload: 'light' | 'dark' | 'auto' }
| { type: 'SET_LOADING'; payload: boolean }
| { type: 'SET_ERROR'; payload: string | null }
| { type: 'RESET_STATE' };
// 导出配置
export interface ExportConfig {
format: 'json' | 'css' | 'scss' | 'tailwind' | 'typescript' | 'figma';
include: {
tokens: boolean;
components: boolean;
utilities: boolean;
comments: boolean;
};
output: {
fileName?: string;
directory?: string;
structure: 'flat' | 'nested';
};
options: {
prefix?: string;
suffix?: string;
transform?: (value: any, key: string) => any;
filter?: (token: DesignToken) => boolean;
};
}
// 导入配置
export interface ImportConfig {
source: {
type: 'file' | 'url' | 'api' | 'clipboard';
path?: string;
url?: string;
api?: {
endpoint: string;
method: 'GET' | 'POST';
headers?: Record<string, string>;
body?: any;
};
};
options: {
merge: boolean;
validate: boolean;
backup: boolean;
overwrite: boolean;
};
}
// 验证结果
export interface ValidationResult {
isValid: boolean;
errors: ValidationError[];
warnings: ValidationWarning[];
suggestions: ValidationSuggestion[];
}
export interface ValidationError {
code: string;
message: string;
path: string;
severity: 'error' | 'critical';
fix?: string;
}
export interface ValidationWarning {
code: string;
message: string;
path: string;
severity: 'warning' | 'info';
suggestion?: string;
}
export interface ValidationSuggestion {
message: string;
action: string;
impact: 'low' | 'medium' | 'high';
}
// 设计系统分析
export interface DesignSystemAnalytics {
overview: {
totalTokens: number;
totalComponents: number;
totalLibraries: number;
coverage: number;
};
usage: {
mostUsedTokens: { token: string; count: number }[];
mostUsedComponents: { component: string; count: number }[];
componentDistribution: { category: string; count: number }[];
};
quality: {
accessibilityScore: number;
consistencyScore: number;
documentationScore: number;
testCoverage: number;
};
performance: {
bundleSize: number;
loadTime: number;
renderTime: number;
};
}
// 主题配置
export interface ThemeConfig {
id: string;
name: string;
displayName: string;
description: string;
type: 'light' | 'dark' | 'auto';
tokens: Partial<DesignSystemConfig['tokens']>;
overrides: Record<string, any>;
meta: {
author: string;
version: string;
tags: string[];
category: 'default' | 'accessibility' | 'branded' | 'custom';
};
}
// 组件生成器配置
export interface ComponentGeneratorConfig {
name: string;
template: string;
props: {
name: string;
type: string;
required: boolean;
default?: any;
description?: string;
}[];
styles: {
[key: string]: any;
};
variants: {
[key: string]: ComponentVariant;
};
accessibility: {
ariaRoles: string[];
ariaProperties: Record<string, string>;
keyboardNavigation: string[];
screenReaderSupport: string[];
};
}
// 设计系统工具函数参数
export interface ToolFunction {
id: string;
name: string;
description: string;
category: 'validation' | 'conversion' | 'generation' | 'analysis' | 'export';
parameters: {
name: string;
type: string;
required: boolean;
description: string;
default?: any;
}[];
returns: {
type: string;
description: string;
};
execute: (params: Record<string, any>) => Promise<any>;
}
// 设计系统事件
export interface DesignSystemEvent {
type: 'token_created' | 'token_updated' | 'token_deleted' | 'component_created' | 'component_updated' | 'component_deleted' | 'theme_switched' | 'library_imported' | 'library_exported';
payload: any;
timestamp: string;
userId?: string;
sessionId?: string;
}
// 设计系统通知
export interface DesignSystemNotification {
id: string;
type: 'info' | 'success' | 'warning' | 'error';
title: string;
message: string;
actions?: {
label: string;
action: string;
primary?: boolean;
}[];
timestamp: string;
read: boolean;
persistent?: boolean;
}
// 具体接口已经在上面定义了,这里不需要重复导出

View File

@@ -0,0 +1,395 @@
/**
* @fileoverview 工具函数集合
* @description 提供项目中常用的工具函数
*/
import { clsx, type ClassValue } from 'clsx';
/**
* 合并 CSS 类名
* @param inputs - CSS 类名数组
* @returns 合并后的 CSS 类名字符串
*/
export function cn(...inputs: ClassValue[]) {
return clsx(inputs);
}
/**
* 格式化日期
* @param date - 日期对象或字符串
* @param locale - 语言代码,默认 'zh-CN'
* @returns 格式化后的日期字符串
*/
export function formatDate(date: Date | string, locale: string = 'zh-CN'): string {
const dateObj = typeof date === 'string' ? new Date(date) : date;
return dateObj.toLocaleDateString(locale, {
year: 'numeric',
month: 'long',
day: 'numeric',
});
}
/**
* 格式化时间
* @param date - 日期对象或字符串
* @param locale - 语言代码,默认 'zh-CN'
* @returns 格式化后的时间字符串
*/
export function formatTime(date: Date | string, locale: string = 'zh-CN'): string {
const dateObj = typeof date === 'string' ? new Date(date) : date;
return dateObj.toLocaleTimeString(locale, {
hour: '2-digit',
minute: '2-digit',
});
}
/**
* 格式化日期时间
* @param date - 日期对象或字符串
* @param locale - 语言代码,默认 'zh-CN'
* @returns 格式化后的日期时间字符串
*/
export function formatDateTime(
date: Date | string,
locale: string = 'zh-CN'
): string {
const dateObj = typeof date === 'string' ? new Date(date) : date;
return `${formatDate(dateObj, locale)} ${formatTime(dateObj, locale)}`;
}
/**
* 生成随机 ID
* @param length - ID 长度,默认 8
* @returns 随机 ID 字符串
*/
export function generateId(length: number = 8): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
/**
* 防抖函数
* @param func - 要防抖的函数
* @param delay - 延迟时间(毫秒)
* @returns 防抖后的函数
*/
export function debounce<T extends (...args: any[]) => any>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: NodeJS.Timeout;
return (...args: Parameters<T>) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(null, args), delay);
};
}
/**
* 节流函数
* @param func - 要节流的函数
* @param delay - 延迟时间(毫秒)
* @returns 节流后的函数
*/
export function throttle<T extends (...args: any[]) => any>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let lastCall = 0;
return (...args: Parameters<T>) => {
const now = new Date().getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return func.apply(null, args);
};
}
/**
* 深拷贝对象
* @param obj - 要拷贝的对象
* @returns 深拷贝后的对象
*/
export function deepClone<T>(obj: T): T {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime()) as unknown as T;
}
if (obj instanceof Array) {
return obj.map(item => deepClone(item)) as unknown as T;
}
if (typeof obj === 'object') {
const clonedObj = {} as T;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}
return clonedObj;
}
return obj;
}
/**
* 检查是否为移动设备
* @returns 是否为移动设备
*/
export function isMobile(): boolean {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
);
}
/**
* 检查是否为平板设备
* @returns 是否为平板设备
*/
export function isTablet(): boolean {
return /iPad|Android(?=.*\bTablet\b)|Windows(?=.*\bTouch\b)/i.test(
navigator.userAgent
);
}
/**
* 检查是否支持触摸
* @returns 是否支持触摸
*/
export function isTouchDevice(): boolean {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
}
/**
* 获取文件扩展名
* @param filename - 文件名
* @returns 文件扩展名
*/
export function getFileExtension(filename: string): string {
return filename.slice(((filename.lastIndexOf('.') - 1) >>> 0) + 2);
}
/**
* 格式化文件大小
* @param bytes - 字节数
* @param decimals - 小数位数,默认 2
* @returns 格式化后的文件大小字符串
*/
export function formatFileSize(bytes: number, decimals: number = 2): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
/**
* 复制文本到剪贴板
* @param text - 要复制的文本
* @returns Promise<boolean> 是否复制成功
*/
export async function copyToClipboard(text: string): Promise<boolean> {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return true;
} else {
// 降级方案
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const result = document.execCommand('copy');
textArea.remove();
return result;
}
} catch (error) {
console.error('Failed to copy text:', error);
return false;
}
}
/**
* 下载文件
* @param content - 文件内容
* @param filename - 文件名
* @param mimeType - MIME 类型
*/
export function downloadFile(
content: string,
filename: string,
mimeType: string = 'text/plain'
): void {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
/**
* 获取 URL 参数
* @param key - 参数名
* @returns 参数值或 null
*/
export function getUrlParam(key: string): string | null {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(key);
}
/**
* 设置 URL 参数
* @param key - 参数名
* @param value - 参数值
*/
export function setUrlParam(key: string, value: string): void {
const url = new URL(window.location.href);
url.searchParams.set(key, value);
window.history.replaceState({}, '', url.toString());
}
/**
* 移除 URL 参数
* @param key - 参数名
*/
export function removeUrlParam(key: string): void {
const url = new URL(window.location.href);
url.searchParams.delete(key);
window.history.replaceState({}, '', url.toString());
}
/**
* 检查对象是否为空
* @param obj - 要检查的对象
* @returns 是否为空
*/
export function isEmpty(obj: any): boolean {
if (obj == null) return true;
if (Array.isArray(obj) || typeof obj === 'string') return obj.length === 0;
if (obj instanceof Date) return false;
return Object.keys(obj).length === 0;
}
/**
* 唯一数组
* @param array - 原数组
* @returns 去重后的数组
*/
export function uniqueArray<T>(array: T[]): T[] {
return [...new Set(array)];
}
/**
* 数组分组
* @param array - 原数组
* @param size - 每组大小
* @returns 分组后的二维数组
*/
export function chunkArray<T>(array: T[], size: number): T[][] {
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
/**
* 对象数组根据某个属性分组
* @param array - 对象数组
* @param key - 分组键
* @returns 分组后的对象
*/
export function groupBy<T extends Record<string, any>>(
array: T[],
key: keyof T
): Record<string, T[]> {
return array.reduce((groups, item) => {
const group = String(item[key]);
groups[group] = groups[group] || [];
groups[group].push(item);
return groups;
}, {} as Record<string, T[]>);
}
/**
* 等待指定时间
* @param ms - 等待时间(毫秒)
* @returns Promise
*/
export function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* 重试函数
* @param fn - 要重试的函数
* @param retries - 重试次数
* @param delay - 重试间隔(毫秒)
* @returns Promise
*/
export async function retry<T>(
fn: () => Promise<T>,
retries: number = 3,
delay: number = 1000
): Promise<T> {
try {
return await fn();
} catch (error) {
if (retries > 0) {
await sleep(delay);
return retry(fn, retries - 1, delay);
}
throw error;
}
}
/**
* 获取随机颜色
* @returns 随机颜色十六进制字符串
*/
export function getRandomColor(): string {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
/**
* 计算相对时间
* @param date - 日期
* @returns 相对时间字符串
*/
export function getRelativeTime(date: Date | string): string {
const now = new Date();
const target = typeof date === 'string' ? new Date(date) : date;
const diffInSeconds = Math.floor((now.getTime() - target.getTime()) / 1000);
if (diffInSeconds < 60) {
return '刚刚';
} else if (diffInSeconds < 3600) {
return `${Math.floor(diffInSeconds / 60)} 分钟前`;
} else if (diffInSeconds < 86400) {
return `${Math.floor(diffInSeconds / 3600)} 小时前`;
} else if (diffInSeconds < 2592000) {
return `${Math.floor(diffInSeconds / 86400)} 天前`;
} else {
return formatDate(target);
}
}