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

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,612 @@
import React from '../../react';
import { useState, useEffect } from 'react';
import { Card, Button, Input, Select, Space, Row, Col, Divider, Tooltip, Badge } from 'antd';
import {
FontSizeOutlined,
BoldOutlined,
ItalicOutlined,
UnderlineOutlined,
AlignLeftOutlined,
AlignCenterOutlined,
AlignRightOutlined,
EditOutlined,
HistoryOutlined,
ClearOutlined,
SaveOutlined,
UndoOutlined,
EyeOutlined
} from '@ant-design/icons';
import type { ElementInfo, SourceInfo } from '../../../../packages/client-shared/src/messages';
const { TextArea } = Input;
const { Option } = Select;
export interface ContentUpdateData {
sourceInfo: SourceInfo;
newContent: string;
}
export interface ContentPanelProps {
selectedElement: ElementInfo | null;
onUpdateContent: (data: ContentUpdateData) => void;
currentContent: string;
onContentChange: (newContent: string) => void;
}
/**
* 内容编辑工具配置
*/
const contentTools = {
// 文本格式化
formatting: [
{ label: '加粗', value: '**', icon: <BoldOutlined />, description: '添加加粗格式' },
{ label: '斜体', value: '*', icon: <ItalicOutlined />, description: '添加斜体格式' },
{ label: '下划线', value: '__', icon: <UnderlineOutlined />, description: '添加下划线' }
],
// 对齐方式
alignment: [
{ label: '左对齐', value: 'text-left', icon: <AlignLeftOutlined /> },
{ label: '居中对齐', value: 'text-center', icon: <AlignCenterOutlined /> },
{ label: '右对齐', value: 'text-right', icon: <AlignRightOutlined /> }
],
// 文本样式预设
textStyles: [
{ label: '标题 1', value: 'text-4xl font-bold', preview: '大标题' },
{ label: '标题 2', value: 'text-3xl font-semibold', preview: '中标题' },
{ label: '标题 3', value: 'text-2xl font-medium', preview: '小标题' },
{ label: '正文', value: 'text-base', preview: '普通文本' },
{ label: '小字', value: 'text-sm text-gray-600', preview: '小字体' },
{ label: '说明文字', value: 'text-xs text-gray-500', preview: '说明文字' }
],
// 常用的占位符文本
placeholders: [
'请输入内容...',
'点击编辑文本',
'请输入标题',
'请输入描述',
'请输入按钮文本',
'请输入链接文本'
]
};
/**
* 内容历史记录
*/
interface ContentHistory {
id: string;
content: string;
timestamp: number;
description: string;
}
/**
* 内容编辑面板组件
*/
export const ContentPanel: React.FC<ContentPanelProps> = ({
selectedElement,
onUpdateContent,
currentContent,
onContentChange
}) => {
const [activeTab, setActiveTab] = useState<string>('edit');
const [editingContent, setEditingContent] = useState<string>(currentContent);
const [originalContent, setOriginalContent] = useState<string>(currentContent);
const [contentHistory, setContentHistory] = useState<ContentHistory[]>([]);
const [isPreviewMode, setIsPreviewMode] = useState<boolean>(false);
const [autoSave, setAutoSave] = useState<boolean>(true);
const [wordCount, setWordCount] = useState<number>(0);
const [characterCount, setCharacterCount] = useState<number>(0);
useEffect(() => {
setEditingContent(currentContent);
setOriginalContent(currentContent);
updateCounts(currentContent);
}, [currentContent]);
/**
* 更新字符和单词计数
*/
const updateCounts = (content: string) => {
setCharacterCount(content.length);
const words = content.trim().split(/\s+/).filter(word => word.length > 0);
setWordCount(words.length);
};
/**
* 处理内容变化
*/
const handleContentChange = (newContent: string) => {
setEditingContent(newContent);
onContentChange(newContent);
updateCounts(newContent);
// 自动保存历史记录
if (autoSave && newContent !== originalContent) {
addToHistory(newContent, '自动保存');
}
};
/**
* 添加到历史记录
*/
const addToHistory = (content: string, description: string) => {
const historyItem: ContentHistory = {
id: `history_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
content,
timestamp: Date.now(),
description
};
setContentHistory(prev => [historyItem, ...prev.slice(0, 9)]); // 保留最新10条记录
};
/**
* 恢复到历史记录
*/
const restoreFromHistory = (historyItem: ContentHistory) => {
setEditingContent(historyItem.content);
onContentChange(historyItem.content);
updateCounts(historyItem.content);
addToHistory(historyItem.content, '恢复历史记录');
};
/**
* 清除内容
*/
const clearContent = () => {
setEditingContent('');
onContentChange('');
updateCounts('');
addToHistory('', '清除内容');
};
/**
* 恢复原始内容
*/
const restoreOriginal = () => {
setEditingContent(originalContent);
onContentChange(originalContent);
updateCounts(originalContent);
};
/**
* 应用内容更新
*/
const applyChanges = () => {
if (!selectedElement) return;
onUpdateContent({
sourceInfo: selectedElement.sourceInfo,
newContent: editingContent
});
setOriginalContent(editingContent);
addToHistory(editingContent, '应用更改');
};
/**
* 插入格式化文本
*/
const insertFormatting = (format: string) => {
const textarea = document.querySelector('textarea[data-content-editor]') as HTMLTextAreaElement;
if (!textarea) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const selectedText = editingContent.substring(start, end);
let newContent = editingContent;
let newSelectedText = selectedText;
// 根据格式化类型插入
switch (format) {
case '**':
newSelectedText = `**${selectedText}**`;
break;
case '*':
newSelectedText = `*${selectedText}*`;
break;
case '__':
newSelectedText = `__${selectedText}__`;
break;
}
newContent =
editingContent.substring(0, start) +
newSelectedText +
editingContent.substring(end);
handleContentChange(newContent);
// 重新设置光标位置
setTimeout(() => {
textarea.focus();
textarea.setSelectionRange(
start + (format === '**' || format === '__' ? 2 : 1),
start + (format === '**' || format === '__' ? 2 : 1) + selectedText.length
);
}, 0);
};
/**
* 插入占位符
*/
const insertPlaceholder = (placeholder: string) => {
const newContent = editingContent + placeholder;
handleContentChange(newContent);
};
/**
* 应用文本样式
*/
const applyTextStyle = (style: string) => {
// 这里可以应用内联样式或类名
console.log('Applying text style:', style);
};
/**
* 获取文本统计信息
*/
const getTextStats = () => {
const lines = editingContent.split('\n');
const paragraphs = editingContent.split('\n\n').filter(p => p.trim().length > 0);
return {
lines: lines.length,
paragraphs: paragraphs.length,
words: wordCount,
characters: characterCount,
charactersNoSpaces: editingContent.replace(/\s/g, '').length
};
};
if (!selectedElement) {
return (
<Card title="内容编辑" className="h-full">
<div className="flex items-center justify-center h-64 text-gray-500">
<div className="text-center">
<EditOutlined className="text-4xl mb-4" />
<p></p>
</div>
</div>
</Card>
);
}
// Check if element is editable (has static text)
if (selectedElement.isStaticText === false) {
return (
<Card title="内容编辑" className="h-full">
<div className="flex items-center justify-center h-64 text-orange-500">
<div className="text-center">
<EditOutlined className="text-4xl mb-4" />
<p className="font-semibold mb-2"></p>
<p className="text-sm text-gray-600"></p>
<p className="text-xs text-gray-500 mt-1"></p>
</div>
</div>
</Card>
);
}
const stats = getTextStats();
return (
<Card
title={
<div className="flex items-center gap-2">
<EditOutlined />
<span></span>
<Badge count={contentHistory.length} showZero />
</div>
}
className="h-full"
extra={
<Space>
<Tooltip title="预览模式">
<Button
size="small"
icon={isPreviewMode ? <EditOutlined /> : <EyeOutlined />}
onClick={() => setIsPreviewMode(!isPreviewMode)}
type={isPreviewMode ? 'primary' : 'default'}
>
{isPreviewMode ? '编辑' : '预览'}
</Button>
</Tooltip>
<Button size="small" onClick={clearContent} icon={<ClearOutlined />}>
</Button>
<Button
type="primary"
size="small"
onClick={applyChanges}
disabled={!selectedElement || editingContent === originalContent}
icon={<SaveOutlined />}
>
</Button>
</Space>
}
>
<div className="space-y-6">
{/* 元素信息 */}
<div className="bg-green-50 border border-green-200 rounded-lg p-3">
<h4 className="text-sm font-semibold text-green-900 mb-2"></h4>
<div className="text-xs text-green-700 space-y-1">
<div><span className="font-medium">:</span> &lt;{selectedElement.tagName}&gt;</div>
<div><span className="font-medium">:</span> {selectedElement.sourceInfo.fileName.split('/').pop()}:{selectedElement.sourceInfo.lineNumber}</div>
<div><span className="font-medium">:</span> {originalContent.substring(0, 50)}{originalContent.length > 50 ? '...' : ''}</div>
</div>
</div>
{/* 标签页导航 */}
<div className="border-b border-gray-200">
<div className="flex space-x-1">
{[
{ key: 'edit', label: '编辑内容' },
{ key: 'format', label: '格式化' },
{ key: 'style', label: '文本样式' },
{ key: 'history', label: '历史记录' },
{ key: 'stats', label: '统计信息' }
].map(tab => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`px-3 py-2 text-sm font-medium border-b-2 transition-colors ${activeTab === tab.key
? 'border-green-500 text-green-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
>
{tab.label}
</button>
))}
</div>
</div>
{/* 编辑内容 */}
{activeTab === 'edit' && (
<div className="space-y-4">
{isPreviewMode ? (
// 预览模式
<div className="border border-gray-200 rounded-lg p-4 min-h-32 bg-white">
<div dangerouslySetInnerHTML={{ __html: editingContent.replace(/\n/g, '<br>') }} />
</div>
) : (
// 编辑模式
<div>
<TextArea
data-content-editor
value={editingContent}
onChange={(e) => handleContentChange(e.target.value)}
placeholder="输入或编辑文本内容..."
rows={8}
className="font-mono text-sm"
/>
{/* 快速工具栏 */}
<div className="flex items-center justify-between mt-2 pt-2 border-t border-gray-100">
<Space size="small">
<Tooltip title="撤销">
<Button
size="small"
icon={<UndoOutlined />}
disabled={contentHistory.length === 0}
onClick={() => contentHistory.length > 0 && restoreFromHistory(contentHistory[0])}
/>
</Tooltip>
<Divider type="vertical" />
{contentTools.formatting.map((format, index) => (
<Tooltip key={index} title={format.description}>
<Button
size="small"
icon={format.icon}
onClick={() => insertFormatting(format.value)}
/>
</Tooltip>
))}
</Space>
<span className="text-xs text-gray-500">
{wordCount} | {characterCount}
</span>
</div>
</div>
)}
</div>
)}
{/* 格式化工具 */}
{activeTab === 'format' && (
<div className="space-y-6">
{/* 快速格式化 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-3 gap-2">
{contentTools.formatting.map((format, index) => (
<Button
key={index}
icon={format.icon}
onClick={() => insertFormatting(format.value)}
className="flex flex-col items-center p-3 h-auto"
>
<span className="text-xs">{format.label}</span>
<span className="text-xs text-gray-500 mt-1">{format.description}</span>
</Button>
))}
</div>
</div>
{/* 占位符 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="space-y-2">
{contentTools.placeholders.map((placeholder, index) => (
<Button
key={index}
size="small"
onClick={() => insertPlaceholder(placeholder)}
className="w-full text-left justify-start"
>
{placeholder}
</Button>
))}
</div>
</div>
{/* 对齐方式 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-3 gap-2">
{contentTools.alignment.map((align, index) => (
<Button
key={index}
icon={align.icon}
onClick={() => applyTextStyle(align.value)}
className="flex items-center justify-center"
>
{align.label}
</Button>
))}
</div>
</div>
</div>
)}
{/* 文本样式 */}
{activeTab === 'style' && (
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="space-y-2">
{contentTools.textStyles.map((style, index) => (
<button
key={index}
onClick={() => applyTextStyle(style.value)}
className="w-full p-3 text-left border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div className="flex items-center justify-between">
<span className="text-sm font-medium">{style.label}</span>
<span className="text-xs text-gray-500">{style.value}</span>
</div>
<div className={`mt-1 ${style.value}`}>
{style.preview}
</div>
</button>
))}
</div>
</div>
)}
{/* 历史记录 */}
{activeTab === 'history' && (
<div>
<div className="flex items-center justify-between mb-4">
<h4 className="text-sm font-medium text-gray-900"></h4>
<Button
size="small"
icon={<HistoryOutlined />}
onClick={() => setContentHistory([])}
>
</Button>
</div>
{contentHistory.length === 0 ? (
<div className="text-center py-8 text-gray-500">
<HistoryOutlined className="text-2xl mb-2" />
<p></p>
</div>
) : (
<div className="space-y-2 max-h-64 overflow-y-auto">
{contentHistory.map((item, index) => (
<div
key={item.id}
className="p-3 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors cursor-pointer"
onClick={() => restoreFromHistory(item)}
>
<div className="flex items-center justify-between mb-1">
<span className="text-xs font-medium text-gray-900">
{new Date(item.timestamp).toLocaleTimeString()}
</span>
<span className="text-xs text-gray-500">{item.description}</span>
</div>
<div className="text-xs text-gray-600 truncate">
{item.content.substring(0, 60)}{item.content.length > 60 ? '...' : ''}
</div>
</div>
))}
</div>
)}
</div>
)}
{/* 统计信息 */}
{activeTab === 'stats' && (
<div>
<h4 className="text-sm font-medium text-gray-900 mb-4"></h4>
<div className="grid grid-cols-2 gap-4">
<div className="bg-gray-50 p-3 rounded-lg">
<div className="text-2xl font-bold text-gray-900">{stats.words}</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="bg-gray-50 p-3 rounded-lg">
<div className="text-2xl font-bold text-gray-900">{stats.characters}</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="bg-gray-50 p-3 rounded-lg">
<div className="text-2xl font-bold text-gray-900">{stats.charactersNoSpaces}</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="bg-gray-50 p-3 rounded-lg">
<div className="text-2xl font-bold text-gray-900">{stats.lines}</div>
<div className="text-sm text-gray-600"></div>
</div>
<div className="bg-gray-50 p-3 rounded-lg">
<div className="text-2xl font-bold text-gray-900">{stats.paragraphs}</div>
<div className="text-sm text-gray-600"></div>
</div>
</div>
{/* 阅读时间估算 */}
<div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
<div className="text-sm text-blue-900">
<span className="font-medium">:</span> {Math.ceil(stats.words / 200)}
</div>
</div>
</div>
)}
{/* 自动保存设置 */}
<div className="pt-4 border-t border-gray-200">
<Row align="middle" gutter={16}>
<Col span={12}>
<label className="flex items-center gap-2 text-sm text-gray-700">
<input
type="checkbox"
checked={autoSave}
onChange={(e) => setAutoSave(e.target.checked)}
className="rounded"
/>
</label>
</Col>
<Col span={12}>
<Button
size="small"
onClick={restoreOriginal}
disabled={editingContent === originalContent}
block
>
</Button>
</Col>
</Row>
</div>
</div>
</Card>
);
};
export default ContentPanel;

View File

@@ -0,0 +1,856 @@
import React from '../../react';
import { useState, useEffect, useCallback } from 'react';
import {
Card,
Tabs,
Button,
Input,
Select,
Space,
Row,
Col,
Divider,
Switch,
Slider,
InputNumber,
Upload,
Modal,
Form,
List,
Tag,
ColorPicker,
Tooltip,
Popconfirm,
message,
ConfigProvider,
theme
} from 'antd';
import {
SettingOutlined,
SaveOutlined,
UploadOutlined,
DownloadOutlined,
PlusOutlined,
DeleteOutlined,
EditOutlined,
ReloadOutlined,
BulbOutlined,
EyeOutlined,
ToolOutlined,
FontSizeOutlined,
BgColorsOutlined,
BorderOutlined,
LayoutOutlined,
ThunderboltOutlined,
UserOutlined,
HistoryOutlined,
StarOutlined
} from '@ant-design/icons';
import type { ElementInfo, SourceInfo } from '../../../../packages/client-shared/src/messages';
import StylePanel from './StylePanel';
import ContentPanel from './ContentPanel';
const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;
export interface PropertyPanelConfig {
theme: 'light' | 'dark' | 'auto';
autoSave: boolean;
autoSaveInterval: number;
showElementInfo: boolean;
showTooltips: boolean;
enableKeyboardShortcuts: boolean;
defaultPanel: 'style' | 'content' | 'settings';
panelLayout: 'horizontal' | 'vertical';
colorPalette: string[];
customPresets: CustomPreset[];
shortcuts: ShortcutConfig;
}
export interface CustomPreset {
id: string;
name: string;
type: 'style' | 'content';
value: string;
description: string;
tags: string[];
favorite: boolean;
createdAt: number;
}
export interface ShortcutConfig {
save: string;
undo: string;
redo: string;
togglePanel: string;
clearAll: string;
custom1?: string;
custom2?: string;
custom3?: string;
}
export interface PropertyPanelProps {
selectedElement: ElementInfo | null;
currentStyle: string;
currentContent: string;
onStyleUpdate: (data: { sourceInfo: SourceInfo; newClass: string }) => void;
onContentUpdate: (data: { sourceInfo: SourceInfo; newContent: string }) => void;
onStyleChange: (newStyle: string) => void;
onContentChange: (newContent: string) => void;
config?: Partial<PropertyPanelConfig>;
onConfigChange?: (config: PropertyPanelConfig) => void;
}
/**
* 默认配置
*/
const defaultConfig: PropertyPanelConfig = {
theme: 'light',
autoSave: true,
autoSaveInterval: 3000,
showElementInfo: true,
showTooltips: true,
enableKeyboardShortcuts: true,
defaultPanel: 'style',
panelLayout: 'horizontal',
colorPalette: [
'#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff', '#ffff00',
'#ff00ff', '#00ffff', '#ffa500', '#800080', '#008000', '#000080'
],
customPresets: [],
shortcuts: {
save: 'Ctrl+S',
undo: 'Ctrl+Z',
redo: 'Ctrl+Y',
togglePanel: 'F2',
clearAll: 'Ctrl+Delete'
}
};
/**
* 预设管理器
*/
class PresetManager {
private storageKey = 'appdev_property_panel_presets';
getPresets(): CustomPreset[] {
try {
const stored = localStorage.getItem(this.storageKey);
return stored ? JSON.parse(stored) : [];
} catch {
return [];
}
}
savePreset(preset: CustomPreset): void {
const presets = this.getPresets();
const existingIndex = presets.findIndex(p => p.id === preset.id);
if (existingIndex >= 0) {
presets[existingIndex] = { ...preset, createdAt: Date.now() };
} else {
presets.push({ ...preset, id: `preset_${Date.now()}`, createdAt: Date.now() });
}
localStorage.setItem(this.storageKey, JSON.stringify(presets));
}
deletePreset(presetId: string): void {
const presets = this.getPresets().filter(p => p.id !== presetId);
localStorage.setItem(this.storageKey, JSON.stringify(presets));
}
exportPresets(): string {
return JSON.stringify(this.getPresets(), null, 2);
}
importPresets(jsonData: string): void {
try {
const presets: CustomPreset[] = JSON.parse(jsonData);
if (Array.isArray(presets)) {
localStorage.setItem(this.storageKey, JSON.stringify(presets));
}
} catch (error) {
throw new Error('无效的预设数据格式');
}
}
}
/**
* 配置管理器
*/
class ConfigManager {
private storageKey = 'appdev_property_panel_config';
getConfig(): PropertyPanelConfig {
try {
const stored = localStorage.getItem(this.storageKey);
return stored ? { ...defaultConfig, ...JSON.parse(stored) } : defaultConfig;
} catch {
return defaultConfig;
}
}
saveConfig(config: PropertyPanelConfig): void {
localStorage.setItem(this.storageKey, JSON.stringify(config));
}
resetConfig(): PropertyPanelConfig {
localStorage.removeItem(this.storageKey);
return defaultConfig;
}
}
/**
* 快捷键管理器
*/
class ShortcutManager {
private listeners: Map<string, () => void> = new Map();
register(shortcut: string, callback: () => void): void {
this.listeners.set(shortcut, callback);
}
handleKeydown(event: KeyboardEvent): void {
const shortcuts = Array.from(this.listeners.keys());
for (const shortcut of shortcuts) {
if (this.matchShortcut(event, shortcut)) {
event.preventDefault();
this.listeners.get(shortcut)?.();
break;
}
}
}
private matchShortcut(event: KeyboardEvent, shortcut: string): boolean {
const keys = shortcut.toLowerCase().split('+');
const eventKey = event.key.toLowerCase();
const ctrl = event.ctrlKey || event.metaKey;
const shift = event.shiftKey;
const alt = event.altKey;
// 检查修饰键
if (keys.includes('ctrl') && !ctrl) return false;
if (keys.includes('shift') && !shift) return false;
if (keys.includes('alt') && !alt) return false;
// 检查主键
const mainKey = keys[keys.length - 1];
if (mainKey !== eventKey) return false;
return true;
}
}
const presetManager = new PresetManager();
const configManager = new ConfigManager();
const shortcutManager = new ShortcutManager();
/**
* 可自定义的属性面板组件
*/
export const PropertyPanel: React.FC<PropertyPanelProps> = ({
selectedElement,
currentStyle,
currentContent,
onStyleUpdate,
onContentUpdate,
onStyleChange,
onContentChange,
config: userConfig,
onConfigChange
}) => {
const [config, setConfig] = useState<PropertyPanelConfig>(() => ({
...defaultConfig,
...userConfig
}));
const [activeTab, setActiveTab] = useState(config.defaultPanel);
const [presets, setPresets] = useState<CustomPreset[]>(() => presetManager.getPresets());
const [isPresetModalVisible, setIsPresetModalVisible] = useState(false);
const [isConfigModalVisible, setIsConfigModalVisible] = useState(false);
const [newPreset, setNewPreset] = useState<Partial<CustomPreset>>({});
const [messageApi, contextHolder] = message.useMessage();
/**
* 保存配置
*/
const saveConfig = useCallback((newConfig: PropertyPanelConfig) => {
const finalConfig = { ...config, ...newConfig };
setConfig(finalConfig);
configManager.saveConfig(finalConfig);
onConfigChange?.(finalConfig);
messageApi.success('配置已保存');
}, [config, onConfigChange, messageApi]);
/**
* 保存预设
*/
const savePreset = useCallback((preset: CustomPreset) => {
presetManager.savePreset(preset);
const updatedPresets = presetManager.getPresets();
setPresets(updatedPresets);
messageApi.success(`预设 "${preset.name}" 已保存`);
}, [messageApi]);
/**
* 删除预设
*/
const deletePreset = useCallback((presetId: string) => {
presetManager.deletePreset(presetId);
const updatedPresets = presetManager.getPresets();
setPresets(updatedPresets);
messageApi.success('预设已删除');
}, [messageApi]);
/**
* 导出配置
*/
const exportConfig = useCallback(() => {
const exportData = {
config,
presets: presetManager.exportPresets()
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `property-panel-config-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
messageApi.success('配置已导出');
}, [config, messageApi]);
/**
* 导入配置
*/
const importConfig = useCallback((file: File) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const importData = JSON.parse(e.target?.result as string);
if (importData.config) {
saveConfig(importData.config);
}
if (importData.presets) {
presetManager.importPresets(importData.presets);
setPresets(presetManager.getPresets());
}
messageApi.success('配置已导入');
} catch (error) {
messageApi.error('导入失败:无效的配置文件');
}
};
reader.readAsText(file);
}, [saveConfig, messageApi]);
/**
* 处理快捷键
*/
useEffect(() => {
if (!config.enableKeyboardShortcuts) return;
const handleKeydown = (event: KeyboardEvent) => {
shortcutManager.handleKeydown(event);
};
// 注册快捷键
shortcutManager.register(config.shortcuts.save, () => {
// 这里可以添加保存逻辑
console.log('快捷键:保存');
});
shortcutManager.register(config.shortcuts.togglePanel, () => {
setActiveTab(prev => prev === 'style' ? 'content' : prev === 'content' ? 'settings' : 'style');
});
document.addEventListener('keydown', handleKeydown);
return () => document.removeEventListener('keydown', handleKeydown);
}, [config.enableKeyboardShortcuts, config.shortcuts]);
/**
* 创建预设
*/
const handleCreatePreset = () => {
if (!newPreset.name || !newPreset.value) {
messageApi.error('请填写预设名称和值');
return;
}
const preset: CustomPreset = {
id: `preset_${Date.now()}`,
name: newPreset.name!,
type: newPreset.type!,
value: newPreset.value!,
description: newPreset.description || '',
tags: newPreset.tags || [],
favorite: false,
createdAt: Date.now()
};
savePreset(preset);
setIsPresetModalVisible(false);
setNewPreset({});
};
/**
* 获取主题配置
*/
const getThemeConfig = () => {
const theme = config.theme === 'auto'
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
: config.theme;
return {
algorithm: theme === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
token: {
colorPrimary: '#3b82f6',
borderRadius: 6,
}
};
};
/**
* 获取快速操作组件
*/
const QuickActions = () => (
<Card size="small" title="快速操作" className="mb-4">
<Row gutter={[8, 8]}>
<Col span={6}>
<Tooltip title="保存当前设置">
<Button size="small" icon={<SaveOutlined />} block />
</Tooltip>
</Col>
<Col span={6}>
<Tooltip title="恢复默认">
<Button size="small" icon={<ReloadOutlined />} block />
</Tooltip>
</Col>
<Col span={6}>
<Tooltip title="导出配置">
<Button size="small" icon={<DownloadOutlined />} onClick={exportConfig} block />
</Tooltip>
</Col>
<Col span={6}>
<Tooltip title="导入配置">
<Upload
size="small"
showUploadList={false}
beforeUpload={(file) => {
importConfig(file);
return false;
}}
>
<Button size="small" icon={<UploadOutlined />} block />
</Upload>
</Tooltip>
</Col>
</Row>
</Card>
);
/**
* 获取元素信息组件
*/
const ElementInfo = () => (
selectedElement && config.showElementInfo ? (
<Card size="small" title="元素信息" className="mb-4">
<div className="space-y-2 text-sm">
<div><span className="font-medium">:</span> &lt;{selectedElement.tagName}&gt;</div>
<div><span className="font-medium">:</span> {selectedElement.className || '无'}</div>
<div><span className="font-medium">:</span> {selectedElement.sourceInfo.fileName.split('/').pop()}</div>
<div><span className="font-medium">:</span> {selectedElement.sourceInfo.lineNumber}:{selectedElement.sourceInfo.columnNumber}</div>
<div><span className="font-medium">:</span> {selectedElement.textContent.substring(0, 30)}{selectedElement.textContent.length > 30 ? '...' : ''}</div>
</div>
</Card>
) : null
);
/**
* 获取自定义预设组件
*/
const CustomPresets = () => (
<Card
size="small"
title={
<div className="flex items-center justify-between">
<span></span>
<Button
size="small"
icon={<PlusOutlined />}
onClick={() => setIsPresetModalVisible(true)}
>
</Button>
</div>
}
>
<List
size="small"
dataSource={presets}
renderItem={(preset) => (
<List.Item
actions={[
<Tooltip title="应用预设">
<Button
size="small"
icon={<StarOutlined />}
onClick={() => {
if (preset.type === 'style') {
onStyleChange(preset.value);
} else {
onContentChange(preset.value);
}
}}
/>
</Tooltip>,
<Popconfirm
title="确定要删除这个预设吗?"
onConfirm={() => deletePreset(preset.id)}
>
<Button size="small" icon={<DeleteOutlined />} danger />
</Popconfirm>
]}
>
<List.Item.Meta
title={<span className="text-sm">{preset.name}</span>}
description={
<div className="text-xs">
<div>{preset.value}</div>
<div className="mt-1">
{preset.tags.map(tag => (
<Tag key={tag} size="small">{tag}</Tag>
))}
</div>
</div>
}
/>
</List.Item>
)}
/>
</Card>
);
return (
<ConfigProvider theme={getThemeConfig()}>
{contextHolder}
<div className="h-full flex flex-col" style={{ background: 'transparent' }}>
{/* 顶部工具栏 */}
<div className="p-4 border-b border-gray-200 bg-white">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<SettingOutlined />
<span className="font-semibold"></span>
{selectedElement && (
<Tag color="blue">{selectedElement.tagName}</Tag>
)}
</div>
<Space>
<Tooltip title="面板设置">
<Button
size="small"
icon={<ToolOutlined />}
onClick={() => setIsConfigModalVisible(true)}
/>
</Tooltip>
<Tooltip title="主题切换">
<Button
size="small"
icon={config.theme === 'dark' ? <BulbOutlined /> : <EyeOutlined />}
onClick={() => saveConfig({
theme: config.theme === 'light' ? 'dark' : config.theme === 'dark' ? 'auto' : 'light'
})}
/>
</Tooltip>
</Space>
</div>
</div>
{/* 主体内容 */}
<div className="flex-1 overflow-hidden">
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
size="small"
className="h-full flex flex-col"
>
<TabPane tab="样式" key="style" icon={<BgColorsOutlined />}>
<div className="h-full overflow-y-auto p-4 space-y-4">
<QuickActions />
<ElementInfo />
<StylePanel
selectedElement={selectedElement}
onUpdateStyle={onStyleUpdate}
currentClass={currentStyle}
onClassChange={onStyleChange}
/>
<CustomPresets />
</div>
</TabPane>
<TabPane tab="内容" key="content" icon={<EditOutlined />}>
<div className="h-full overflow-y-auto p-4 space-y-4">
<QuickActions />
<ElementInfo />
<ContentPanel
selectedElement={selectedElement}
onUpdateContent={onContentUpdate}
currentContent={currentContent}
onContentChange={onContentChange}
/>
</div>
</TabPane>
<TabPane tab="设置" key="settings" icon={<SettingOutlined />}>
<div className="h-full overflow-y-auto p-4 space-y-4">
<Card size="small" title="面板设置">
<Form layout="vertical">
<Form.Item label="主题">
<Select
value={config.theme}
onChange={(theme) => saveConfig({ theme })}
>
<Option value="light"></Option>
<Option value="dark"></Option>
<Option value="auto"></Option>
</Select>
</Form.Item>
<Form.Item label="默认面板">
<Select
value={config.defaultPanel}
onChange={(defaultPanel) => saveConfig({ defaultPanel })}
>
<Option value="style"></Option>
<Option value="content"></Option>
<Option value="settings"></Option>
</Select>
</Form.Item>
<Row gutter={16}>
<Col span={12}>
<Form.Item label="自动保存">
<Switch
checked={config.autoSave}
onChange={(autoSave) => saveConfig({ autoSave })}
/>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="自动保存间隔 (ms)">
<InputNumber
min={1000}
max={10000}
step={500}
value={config.autoSaveInterval}
onChange={(autoSaveInterval) => saveConfig({ autoSaveInterval })}
style={{ width: '100%' }}
/>
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item label="显示元素信息">
<Switch
checked={config.showElementInfo}
onChange={(showElementInfo) => saveConfig({ showElementInfo })}
/>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="启用工具提示">
<Switch
checked={config.showTooltips}
onChange={(showTooltips) => saveConfig({ showTooltips })}
/>
</Form.Item>
</Col>
</Row>
<Form.Item label="快捷键设置">
<Space direction="vertical" style={{ width: '100%' }}>
<Input
addonBefore="保存"
value={config.shortcuts.save}
onChange={(e) => saveConfig({
shortcuts: { ...config.shortcuts, save: e.target.value }
})}
/>
<Input
addonBefore="撤销"
value={config.shortcuts.undo}
onChange={(e) => saveConfig({
shortcuts: { ...config.shortcuts, undo: e.target.value }
})}
/>
<Input
addonBefore="重做"
value={config.shortcuts.redo}
onChange={(e) => saveConfig({
shortcuts: { ...config.shortcuts, redo: e.target.value }
})}
/>
<Input
addonBefore="切换面板"
value={config.shortcuts.togglePanel}
onChange={(e) => saveConfig({
shortcuts: { ...config.shortcuts, togglePanel: e.target.value }
})}
/>
</Space>
</Form.Item>
</Form>
</Card>
<Card size="small" title="颜色配置">
<div className="space-y-3">
<div>
<label className="block text-sm font-medium mb-2"></label>
<div className="flex flex-wrap gap-2">
{config.colorPalette.map((color, index) => (
<div
key={index}
className="w-8 h-8 rounded border border-gray-300 cursor-pointer hover:scale-110 transition-transform"
style={{ backgroundColor: color }}
onClick={() => {
// 移除颜色
const newPalette = config.colorPalette.filter((_, i) => i !== index);
saveConfig({ colorPalette: newPalette });
}}
/>
))}
<Button
size="small"
icon={<PlusOutlined />}
onClick={() => {
// 添加颜色
const newColor = '#' + Math.floor(Math.random()*16777215).toString(16);
saveConfig({ colorPalette: [...config.colorPalette, newColor] });
}}
>
</Button>
</div>
</div>
</div>
</Card>
<Card size="small" title="数据管理">
<Row gutter={8}>
<Col span={8}>
<Button icon={<DownloadOutlined />} onClick={exportConfig} block>
</Button>
</Col>
<Col span={8}>
<Upload
beforeUpload={(file) => {
importConfig(file);
return false;
}}
showUploadList={false}
>
<Button icon={<UploadOutlined />} block>
</Button>
</Upload>
</Col>
<Col span={8}>
<Popconfirm
title="确定要重置所有配置吗?"
onConfirm={() => {
const resetConfig = configManager.resetConfig();
setConfig(resetConfig);
setPresets(presetManager.getPresets());
messageApi.success('配置已重置');
}}
>
<Button icon={<ReloadOutlined />} danger block>
</Button>
</Popconfirm>
</Col>
</Row>
</Card>
</div>
</TabPane>
</Tabs>
</div>
{/* 创建预设模态框 */}
<Modal
title="创建自定义预设"
open={isPresetModalVisible}
onOk={handleCreatePreset}
onCancel={() => {
setIsPresetModalVisible(false);
setNewPreset({});
}}
okText="创建"
cancelText="取消"
>
<Form layout="vertical">
<Form.Item label="预设名称" required>
<Input
value={newPreset.name}
onChange={(e) => setNewPreset({ ...newPreset, name: e.target.value })}
placeholder="输入预设名称"
/>
</Form.Item>
<Form.Item label="预设类型" required>
<Select
value={newPreset.type}
onChange={(type) => setNewPreset({ ...newPreset, type })}
placeholder="选择预设类型"
>
<Option value="style"></Option>
<Option value="content"></Option>
</Select>
</Form.Item>
<Form.Item label="预设值" required>
<TextArea
value={newPreset.value}
onChange={(e) => setNewPreset({ ...newPreset, value: e.target.value })}
placeholder="输入预设值"
rows={3}
/>
</Form.Item>
<Form.Item label="描述">
<TextArea
value={newPreset.description}
onChange={(e) => setNewPreset({ ...newPreset, description: e.target.value })}
placeholder="输入预设描述"
rows={2}
/>
</Form.Item>
<Form.Item label="标签">
<Input
value={newPreset.tags?.join(',')}
onChange={(e) => setNewPreset({
...newPreset,
tags: e.target.value.split(',').map(tag => tag.trim()).filter(Boolean)
})}
placeholder="输入标签,用逗号分隔"
/>
</Form.Item>
</Form>
</Modal>
</div>
</ConfigProvider>
);
};
export default PropertyPanel;

View File

@@ -0,0 +1,567 @@
import React from '../../react';
import { useState, useEffect } from 'react';
import { Card, Button, Input, Select, Slider, ColorPicker, InputNumber, Divider, Tag, Space, Row, Col } from 'antd';
import { BoldOutlined, ItalicOutlined, UnderlineOutlined, FontSizeOutlined, BgColorsOutlined, BorderOutlined } from '@ant-design/icons';
import type { ElementInfo, SourceInfo } from '../../../../packages/client-shared/src/messages';
const { TextArea } = Input;
const { Option } = Select;
export interface StyleUpdateData {
sourceInfo: SourceInfo;
newClass: string;
}
export interface StylePanelProps {
selectedElement: ElementInfo | null;
onUpdateStyle: (data: StyleUpdateData) => void;
currentClass: string;
onClassChange: (newClass: string) => void;
}
/**
* 样式预设配置
*/
const stylePresets = {
colors: {
backgrounds: [
{ label: '白色', value: 'bg-white', color: '#ffffff' },
{ label: '浅灰色', value: 'bg-gray-100', color: '#f3f4f6' },
{ label: '浅蓝色', value: 'bg-blue-100', color: '#dbeafe' },
{ label: '浅绿色', value: 'bg-green-100', color: '#dcfce7' },
{ label: '浅红色', value: 'bg-red-100', color: '#fee2e2' },
{ label: '浅黄色', value: 'bg-yellow-100', color: '#fef3c7' },
{ label: '浅紫色', value: 'bg-purple-100', color: '#f3e8ff' },
{ label: '深蓝色', value: 'bg-blue-600', color: '#2563eb' },
],
text: [
{ label: '黑色', value: 'text-black', color: '#000000' },
{ label: '深灰色', value: 'text-gray-900', color: '#111827' },
{ label: '中灰色', value: 'text-gray-600', color: '#4b5563' },
{ label: '蓝色', value: 'text-blue-600', color: '#2563eb' },
{ label: '绿色', value: 'text-green-600', color: '#16a34a' },
{ label: '红色', value: 'text-red-600', color: '#dc2626' },
{ label: '黄色', value: 'text-yellow-600', color: '#ca8a04' },
{ label: '紫色', value: 'text-purple-600', color: '#9333ea' },
]
},
spacing: {
padding: [
{ label: '无内边距', value: 'p-0', preview: 'padding: 0px' },
{ label: '小内边距', value: 'p-2', preview: 'padding: 8px' },
{ label: '中等内边距', value: 'p-4', preview: 'padding: 16px' },
{ label: '大内边距', value: 'p-6', preview: 'padding: 24px' },
{ label: '超大内边距', value: 'p-8', preview: 'padding: 32px' },
],
margin: [
{ label: '无外边距', value: 'm-0', preview: 'margin: 0px' },
{ label: '小外边距', value: 'm-2', preview: 'margin: 8px' },
{ label: '中等外边距', value: 'm-4', preview: 'margin: 16px' },
{ label: '大外边距', value: 'm-6', preview: 'margin: 24px' },
]
},
border: {
radius: [
{ label: '无圆角', value: 'rounded-none', preview: 'border-radius: 0px' },
{ label: '小圆角', value: 'rounded-sm', preview: 'border-radius: 2px' },
{ label: '中等圆角', value: 'rounded-md', preview: 'border-radius: 6px' },
{ label: '大圆角', value: 'rounded-lg', preview: 'border-radius: 8px' },
{ label: '超大圆角', value: 'rounded-xl', preview: 'border-radius: 12px' },
{ label: '完全圆角', value: 'rounded-full', preview: 'border-radius: 9999px' },
],
width: [
{ label: '无边框', value: 'border-0', preview: 'border-width: 0px' },
{ label: '细边框', value: 'border', preview: 'border-width: 1px' },
{ label: '中等边框', value: 'border-2', preview: 'border-width: 2px' },
{ label: '粗边框', value: 'border-4', preview: 'border-width: 4px' },
]
},
typography: {
fontSize: [
{ label: '很小', value: 'text-xs', preview: 'font-size: 12px' },
{ label: '小', value: 'text-sm', preview: 'font-size: 14px' },
{ label: '正常', value: 'text-base', preview: 'font-size: 16px' },
{ label: '大', value: 'text-lg', preview: 'font-size: 18px' },
{ label: '很大', value: 'text-xl', preview: 'font-size: 20px' },
{ label: '巨大', value: 'text-2xl', preview: 'font-size: 24px' },
],
fontWeight: [
{ label: '细体', value: 'font-thin', preview: 'font-weight: 100' },
{ label: '特细', value: 'font-extralight', preview: 'font-weight: 200' },
{ label: '细体', value: 'font-light', preview: 'font-weight: 300' },
{ label: '正常', value: 'font-normal', preview: 'font-weight: 400' },
{ label: '中粗', value: 'font-medium', preview: 'font-weight: 500' },
{ label: '半粗', value: 'font-semibold', preview: 'font-weight: 600' },
{ label: '粗体', value: 'font-bold', preview: 'font-weight: 700' },
{ label: '超粗', value: 'font-black', preview: 'font-weight: 900' },
]
},
layout: {
display: [
{ label: '块级', value: 'block', preview: 'display: block' },
{ label: '内联', value: 'inline', preview: 'display: inline' },
{ label: '内联块', value: 'inline-block', preview: 'display: inline-block' },
{ label: '弹性', value: 'flex', preview: 'display: flex' },
{ label: '网格', value: 'grid', preview: 'display: grid' },
{ label: '隐藏', value: 'hidden', preview: 'display: none' },
],
position: [
{ label: '静态', value: 'static', preview: 'position: static' },
{ label: '相对', value: 'relative', preview: 'position: relative' },
{ label: '绝对', value: 'absolute', preview: 'position: absolute' },
{ label: '固定', value: 'fixed', preview: 'position: fixed' },
{ label: '粘性', value: 'sticky', preview: 'position: sticky' },
]
}
};
/**
* 样式编辑面板组件
*/
export const StylePanel: React.FC<StylePanelProps> = ({
selectedElement,
onUpdateStyle,
currentClass,
onClassChange
}) => {
const [activeTab, setActiveTab] = useState<string>('presets');
const [customStyles, setCustomStyles] = useState<string>(currentClass);
const [colorPickerVisible, setColorPickerVisible] = useState(false);
const [customColor, setCustomColor] = useState('#3b82f6');
useEffect(() => {
setCustomStyles(currentClass);
}, [currentClass]);
/**
* 添加样式类
*/
const addStyleClass = (className: string) => {
const newStyles = mergeClasses(customStyles, className);
setCustomStyles(newStyles);
onClassChange(newStyles);
};
/**
* 移除样式类
*/
const removeStyleClass = (className: string) => {
const newStyles = removeClass(customStyles, className);
setCustomStyles(newStyles);
onClassChange(newStyles);
};
/**
* 更新样式
*/
const updateStyles = () => {
if (!selectedElement) return;
onUpdateStyle({
sourceInfo: selectedElement.sourceInfo,
newClass: customStyles
});
};
/**
* 清除所有样式
*/
const clearAllStyles = () => {
setCustomStyles('');
onClassChange('');
};
/**
* 合并样式类
*/
const mergeClasses = (existing: string, newClass: string): string => {
const classes = existing.split(' ').filter(Boolean);
const newClasses = newClass.split(' ').filter(Boolean);
// 移除冲突的同类样式
const filteredClasses = classes.filter(cls => {
return !newClasses.some(newCls =>
(cls.startsWith('bg-') && newCls.startsWith('bg-')) ||
(cls.startsWith('text-') && newCls.startsWith('text-')) ||
(cls.startsWith('p-') && newCls.startsWith('p-')) ||
(cls.startsWith('m-') && newCls.startsWith('m-')) ||
(cls.startsWith('rounded') && newCls.startsWith('rounded')) ||
(cls.startsWith('border-') && newCls.startsWith('border-')) ||
(cls.startsWith('text-') && newCls.startsWith('text-')) ||
(cls.startsWith('font-') && newCls.startsWith('font-')) ||
(cls.startsWith('flex') && newCls.startsWith('flex')) ||
(cls.startsWith('grid') && newCls.startsWith('grid')) ||
cls === newCls
);
});
return [...filteredClasses, ...newClasses].join(' ').trim();
};
/**
* 移除样式类
*/
const removeClass = (existing: string, classToRemove: string): string => {
return existing.split(' ')
.filter(cls => cls !== classToRemove && !cls.startsWith(classToRemove.split('-')[0]))
.join(' ')
.trim();
};
/**
* 获取当前应用的样式类
*/
const getAppliedStyles = (): string[] => {
return customStyles.split(' ').filter(Boolean);
};
if (!selectedElement) {
return (
<Card title="样式编辑" className="h-full">
<div className="flex items-center justify-center h-64 text-gray-500">
<div className="text-center">
<BgColorsOutlined className="text-4xl mb-4" />
<p></p>
</div>
</div>
</Card>
);
}
return (
<Card
title={
<div className="flex items-center gap-2">
<BgColorsOutlined />
<span></span>
</div>
}
className="h-full"
extra={
<Space>
<Button size="small" onClick={clearAllStyles}>
</Button>
<Button
type="primary"
size="small"
onClick={updateStyles}
disabled={!selectedElement}
>
</Button>
</Space>
}
>
<div className="space-y-6">
{/* 元素信息 */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
<h4 className="text-sm font-semibold text-blue-900 mb-2"></h4>
<div className="text-xs text-blue-700 space-y-1">
<div><span className="font-medium">:</span> &lt;{selectedElement.tagName}&gt;</div>
<div><span className="font-medium">:</span> {selectedElement.sourceInfo.fileName.split('/').pop()}:{selectedElement.sourceInfo.lineNumber}</div>
</div>
</div>
{/* 快速预设标签页 */}
<div className="border-b border-gray-200">
<div className="flex space-x-1">
{[
{ key: 'presets', label: '预设样式' },
{ key: 'colors', label: '颜色' },
{ key: 'typography', label: '字体' },
{ key: 'layout', label: '布局' },
{ key: 'custom', label: '自定义' }
].map(tab => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`px-3 py-2 text-sm font-medium border-b-2 transition-colors ${
activeTab === tab.key
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
>
{tab.label}
</button>
))}
</div>
</div>
{/* 预设样式 */}
{activeTab === 'presets' && (
<div className="space-y-6">
{/* 背景颜色 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-2 gap-2">
{stylePresets.colors.backgrounds.map((color, index) => (
<button
key={index}
onClick={() => addStyleClass(color.value)}
className="flex items-center gap-2 p-2 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div
className={`w-4 h-4 rounded ${color.value}`}
style={{ backgroundColor: color.color }}
/>
<span className="text-xs">{color.label}</span>
</button>
))}
</div>
</div>
{/* 圆角 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-2 gap-2">
{stylePresets.border.radius.map((radius, index) => (
<button
key={index}
onClick={() => addStyleClass(radius.value)}
className="p-2 text-xs border border-gray-200 rounded-lg hover:border-gray-300 transition-colors text-left"
>
<div className="font-medium">{radius.label}</div>
<div className="text-gray-500">{radius.preview}</div>
</button>
))}
</div>
</div>
{/* 边距 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-2 gap-2">
{stylePresets.spacing.padding.map((padding, index) => (
<button
key={index}
onClick={() => addStyleClass(padding.value)}
className="p-2 text-xs border border-gray-200 rounded-lg hover:border-gray-300 transition-colors text-left"
>
<div className="font-medium">{padding.label}</div>
<div className="text-gray-500">{padding.preview}</div>
</button>
))}
</div>
</div>
</div>
)}
{/* 颜色面板 */}
{activeTab === 'colors' && (
<div className="space-y-6">
{/* 背景颜色 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-2 gap-2">
{stylePresets.colors.backgrounds.map((color, index) => (
<button
key={index}
onClick={() => addStyleClass(color.value)}
className="flex items-center gap-2 p-2 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div
className={`w-4 h-4 rounded ${color.value}`}
style={{ backgroundColor: color.color }}
/>
<span className="text-xs">{color.label}</span>
</button>
))}
</div>
</div>
{/* 文字颜色 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="grid grid-cols-2 gap-2">
{stylePresets.colors.text.map((color, index) => (
<button
key={index}
onClick={() => addStyleClass(color.value)}
className="flex items-center gap-2 p-2 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div
className="w-4 h-4 rounded border border-gray-300"
style={{ backgroundColor: color.color }}
/>
<span className="text-xs">{color.label}</span>
</button>
))}
</div>
</div>
{/* 自定义颜色 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="space-y-3">
<div className="flex gap-2">
<input
type="color"
value={customColor}
onChange={(e) => setCustomColor(e.target.value)}
className="w-8 h-8 border border-gray-300 rounded cursor-pointer"
/>
<Input
value={customColor}
onChange={(e) => setCustomColor(e.target.value)}
placeholder="#3b82f6"
/>
</div>
<Row gutter={8}>
<Col span={12}>
<Button
block
size="small"
onClick={() => addStyleClass(`bg-[${customColor}]`)}
>
</Button>
</Col>
<Col span={12}>
<Button
block
size="small"
onClick={() => addStyleClass(`text-[${customColor}]`)}
>
</Button>
</Col>
</Row>
</div>
</div>
</div>
)}
{/* 字体面板 */}
{activeTab === 'typography' && (
<div className="space-y-6">
{/* 字体大小 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="space-y-2">
{stylePresets.typography.fontSize.map((fontSize, index) => (
<button
key={index}
onClick={() => addStyleClass(fontSize.value)}
className="w-full p-2 text-left text-xs border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div className="font-medium">{fontSize.label}</div>
<div className="text-gray-500">{fontSize.preview}</div>
</button>
))}
</div>
</div>
{/* 字体粗细 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="space-y-2">
{stylePresets.typography.fontWeight.map((fontWeight, index) => (
<button
key={index}
onClick={() => addStyleClass(fontWeight.value)}
className="w-full p-2 text-left text-xs border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div className="font-medium">{fontWeight.label}</div>
<div className="text-gray-500">{fontWeight.preview}</div>
</button>
))}
</div>
</div>
</div>
)}
{/* 布局面板 */}
{activeTab === 'layout' && (
<div className="space-y-6">
{/* 显示类型 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="space-y-2">
{stylePresets.layout.display.map((display, index) => (
<button
key={index}
onClick={() => addStyleClass(display.value)}
className="w-full p-2 text-left text-xs border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div className="font-medium">{display.label}</div>
<div className="text-gray-500">{display.preview}</div>
</button>
))}
</div>
</div>
{/* 定位 */}
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="space-y-2">
{stylePresets.layout.position.map((position, index) => (
<button
key={index}
onClick={() => addStyleClass(position.value)}
className="w-full p-2 text-left text-xs border border-gray-200 rounded-lg hover:border-gray-300 transition-colors"
>
<div className="font-medium">{position.label}</div>
<div className="text-gray-500">{position.preview}</div>
</button>
))}
</div>
</div>
</div>
)}
{/* 自定义样式 */}
{activeTab === 'custom' && (
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
className
</label>
<TextArea
value={customStyles}
onChange={(e) => setCustomStyles(e.target.value)}
placeholder="输入 CSS 类名..."
rows={4}
className="font-mono text-sm"
/>
</div>
<div className="flex gap-2">
<Button onClick={updateStyles} type="primary" block>
</Button>
<Button onClick={clearAllStyles} block>
</Button>
</div>
</div>
)}
{/* 已应用的样式标签 */}
{getAppliedStyles().length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-900 mb-3"></h4>
<div className="flex flex-wrap gap-1">
{getAppliedStyles().map((styleClass, index) => (
<Tag
key={index}
closable
onClose={() => removeStyleClass(styleClass)}
className="mb-1"
>
{styleClass}
</Tag>
))}
</div>
</div>
)}
</div>
</Card>
);
};
export default StylePanel;