"添加前端模板和运行代码模块"
This commit is contained in:
24
qiming-vite-plugin-design-mode/examples/demo/.gitignore
vendored
Normal file
24
qiming-vite-plugin-design-mode/examples/demo/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
61
qiming-vite-plugin-design-mode/examples/demo/README.md
Normal file
61
qiming-vite-plugin-design-mode/examples/demo/README.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Design Mode Demo
|
||||
|
||||
这是一个完整的示例项目,展示了 `@xagi/vite-plugin-design-mode` 的所有功能。
|
||||
|
||||
## 功能演示
|
||||
|
||||
### 1. 样式编辑
|
||||
- 点击任意元素查看编辑面板
|
||||
- 实时修改 Tailwind CSS 类
|
||||
- 自动保存到源文件
|
||||
|
||||
### 2. 内容编辑
|
||||
- 双击文本元素进入编辑模式
|
||||
- 修改后自动更新源代码
|
||||
- 支持纯文本内容
|
||||
|
||||
### 3. Iframe 支持
|
||||
- 在 iframe 中自动隐藏 UI
|
||||
- 通过 postMessage 通信
|
||||
- 支持外部设计面板控制
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 安装依赖
|
||||
npm install
|
||||
|
||||
# 启动开发服务器
|
||||
npm run dev
|
||||
```
|
||||
|
||||
访问 `http://localhost:5175` 查看演示。
|
||||
|
||||
## 使用说明
|
||||
|
||||
1. **启用设计模式**:点击右下角的 "Design Mode" 开关
|
||||
2. **选择元素**:点击页面上的任意元素
|
||||
3. **修改样式**:使用右侧面板修改背景、文字颜色、内边距等
|
||||
4. **编辑内容**:双击文本元素直接编辑
|
||||
5. **查看源码**:所有修改会自动保存到对应的 `.tsx` 文件
|
||||
|
||||
## 页面说明
|
||||
|
||||
- **Home**: 主页,展示核心功能卡片和可编辑示例
|
||||
- **Features**: 详细功能展示,包含各种可编辑元素
|
||||
- **Iframe Demo**: 演示 iframe 集成和通信机制
|
||||
|
||||
## 技术栈
|
||||
|
||||
- React 18
|
||||
- TypeScript
|
||||
- Vite 6
|
||||
- Tailwind CSS 4
|
||||
- Radix UI
|
||||
- @xagi/vite-plugin-design-mode
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 仅支持静态字符串 className 的修改
|
||||
- 内容编辑仅支持纯文本节点
|
||||
- 所有修改会直接写入源文件,建议使用版本控制
|
||||
@@ -0,0 +1,580 @@
|
||||
# 可自定义属性面板配置指南
|
||||
|
||||
## 概述
|
||||
|
||||
本文档详细介绍了如何使用和配置可自定义的属性面板系统,该系统支持用户自定义配置,提供完整的双向同步设计模式架构。
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 🎨 样式自定义
|
||||
- **颜色方案**: 自定义颜色库,支持导入导出
|
||||
- **样式预设**: 保存和管理常用样式组合
|
||||
- **主题切换**: 浅色/深色/跟随系统主题
|
||||
- **响应式布局**: 自适应不同屏幕尺寸
|
||||
|
||||
### 📝 内容自定义
|
||||
- **富文本编辑**: 支持格式化文本编辑
|
||||
- **历史记录**: 自动保存编辑历史,支持回溯
|
||||
- **模板系统**: 自定义内容模板和占位符
|
||||
- **快捷操作**: 支持快捷键和批量操作
|
||||
|
||||
### ⚙️ 高级配置
|
||||
- **面板布局**: 水平和垂直布局切换
|
||||
- **快捷键自定义**: 用户可自定义键盘快捷键
|
||||
- **自动保存**: 配置自动保存间隔和策略
|
||||
- **数据管理**: 支持配置的导入导出和重置
|
||||
|
||||
## 安装和配置
|
||||
|
||||
### 1. 基础安装
|
||||
|
||||
```bash
|
||||
# 安装依赖
|
||||
npm install antd @ant-design/icons
|
||||
|
||||
# 或使用 yarn
|
||||
yarn add antd @ant-design/icons
|
||||
```
|
||||
|
||||
### 2. 配置文件
|
||||
|
||||
创建 `vite.config.ts`:
|
||||
|
||||
```typescript
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import appdevDesignMode from '@xagi/vite-plugin-design-mode';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
appdevDesignMode({
|
||||
enabled: true,
|
||||
iframeMode: {
|
||||
enabled: true,
|
||||
hideUI: true,
|
||||
enableSelection: true,
|
||||
enableDirectEdit: true,
|
||||
},
|
||||
batchUpdate: {
|
||||
enabled: true,
|
||||
debounceMs: 300,
|
||||
},
|
||||
bridge: {
|
||||
timeout: 10000,
|
||||
retryAttempts: 3,
|
||||
heartbeatInterval: 30000,
|
||||
debug: true,
|
||||
}
|
||||
})
|
||||
]
|
||||
});
|
||||
```
|
||||
|
||||
### 3. 基础组件使用
|
||||
|
||||
```tsx
|
||||
import React, { useState } from 'react';
|
||||
import { PropertyPanel } from '@xagi/design-mode';
|
||||
import type { PropertyPanelConfig } from '@xagi/design-mode';
|
||||
|
||||
function MyApp() {
|
||||
const [selectedElement, setSelectedElement] = useState(null);
|
||||
const [currentStyle, setCurrentStyle] = useState('');
|
||||
const [currentContent, setCurrentContent] = useState('');
|
||||
|
||||
const handleStyleUpdate = (data) => {
|
||||
console.log('Style updated:', data);
|
||||
};
|
||||
|
||||
const handleContentUpdate = (data) => {
|
||||
console.log('Content updated:', data);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="app-layout">
|
||||
<PropertyPanel
|
||||
selectedElement={selectedElement}
|
||||
currentStyle={currentStyle}
|
||||
currentContent={currentContent}
|
||||
onStyleUpdate={handleStyleUpdate}
|
||||
onContentUpdate={handleContentUpdate}
|
||||
onStyleChange={setCurrentStyle}
|
||||
onContentChange={setCurrentContent}
|
||||
config={{
|
||||
theme: 'light',
|
||||
autoSave: true,
|
||||
autoSaveInterval: 3000,
|
||||
showElementInfo: true,
|
||||
enableKeyboardShortcuts: true,
|
||||
defaultPanel: 'style'
|
||||
}}
|
||||
onConfigChange={(config) => {
|
||||
console.log('Config changed:', config);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 高级配置
|
||||
|
||||
### 自定义配置接口
|
||||
|
||||
```typescript
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
### 快捷键配置
|
||||
|
||||
```typescript
|
||||
const shortcuts = {
|
||||
save: 'Ctrl+S', // 保存当前设置
|
||||
undo: 'Ctrl+Z', // 撤销操作
|
||||
redo: 'Ctrl+Y', // 重做操作
|
||||
togglePanel: 'F2', // 切换面板
|
||||
clearAll: 'Ctrl+Delete', // 清除所有
|
||||
custom1: 'Ctrl+1', // 自定义快捷键1
|
||||
custom2: 'Ctrl+2', // 自定义快捷键2
|
||||
custom3: 'Ctrl+3' // 自定义快捷键3
|
||||
};
|
||||
```
|
||||
|
||||
### 自定义预设管理
|
||||
|
||||
```typescript
|
||||
interface CustomPreset {
|
||||
id: string;
|
||||
name: string; // 预设名称
|
||||
type: 'style' | 'content'; // 预设类型
|
||||
value: string; // 预设值
|
||||
description: string; // 预设描述
|
||||
tags: string[]; // 标签数组
|
||||
favorite: boolean; // 是否收藏
|
||||
createdAt: number; // 创建时间
|
||||
}
|
||||
|
||||
// 创建自定义预设
|
||||
const myPreset: CustomPreset = {
|
||||
id: 'preset_001',
|
||||
name: '主要按钮样式',
|
||||
type: 'style',
|
||||
value: 'bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600',
|
||||
description: '常用的主要按钮样式',
|
||||
tags: ['按钮', '主要', '蓝色'],
|
||||
favorite: true,
|
||||
createdAt: Date.now()
|
||||
};
|
||||
```
|
||||
|
||||
## API 接口
|
||||
|
||||
### 组件属性
|
||||
|
||||
| 属性名 | 类型 | 描述 | 默认值 |
|
||||
|--------|------|------|--------|
|
||||
| `selectedElement` | `ElementInfo \| null` | 当前选中的元素信息 | `null` |
|
||||
| `currentStyle` | `string` | 当前样式类名 | `''` |
|
||||
| `currentContent` | `string` | 当前内容 | `''` |
|
||||
| `onStyleUpdate` | `(data) => void` | 样式更新回调 | 必填 |
|
||||
| `onContentUpdate` | `(data) => void` | 内容更新回调 | 必填 |
|
||||
| `onStyleChange` | `(style) => void` | 样式变化回调 | 必填 |
|
||||
| `onContentChange` | `(content) => void` | 内容变化回调 | 必填 |
|
||||
| `config` | `Partial<PropertyPanelConfig>` | 面板配置 | `undefined` |
|
||||
| `onConfigChange` | `(config) => void` | 配置变化回调 | `undefined` |
|
||||
|
||||
### 回调函数参数
|
||||
|
||||
#### onStyleUpdate
|
||||
```typescript
|
||||
{
|
||||
sourceInfo: {
|
||||
fileName: string;
|
||||
lineNumber: number;
|
||||
columnNumber: number;
|
||||
};
|
||||
newClass: string;
|
||||
}
|
||||
```
|
||||
|
||||
#### onContentUpdate
|
||||
```typescript
|
||||
{
|
||||
sourceInfo: {
|
||||
fileName: string;
|
||||
lineNumber: number;
|
||||
columnNumber: number;
|
||||
};
|
||||
newContent: string;
|
||||
}
|
||||
```
|
||||
|
||||
## 事件处理
|
||||
|
||||
### 键盘事件
|
||||
|
||||
组件支持以下键盘事件:
|
||||
|
||||
- **Ctrl+S**: 保存当前设置
|
||||
- **Ctrl+Z**: 撤销操作
|
||||
- **Ctrl+Y**: 重做操作
|
||||
- **F2**: 切换面板
|
||||
- **Ctrl+Delete**: 清除所有
|
||||
|
||||
### 鼠标事件
|
||||
|
||||
- **单击**: 选择元素
|
||||
- **双击**: 进入编辑模式
|
||||
- **右键**: 显示上下文菜单
|
||||
- **悬停**: 显示工具提示
|
||||
|
||||
## 样式定制
|
||||
|
||||
### 主题定制
|
||||
|
||||
```typescript
|
||||
import { ConfigProvider } from 'antd';
|
||||
|
||||
// 自定义主题
|
||||
const customTheme = {
|
||||
algorithm: theme.darkAlgorithm,
|
||||
token: {
|
||||
colorPrimary: '#your-primary-color',
|
||||
borderRadius: 8,
|
||||
// 更多主题配置...
|
||||
}
|
||||
};
|
||||
|
||||
<ConfigProvider theme={customTheme}>
|
||||
<PropertyPanel {...props} />
|
||||
</ConfigProvider>
|
||||
```
|
||||
|
||||
### 自定义样式类
|
||||
|
||||
```css
|
||||
/* 自定义面板样式 */
|
||||
.custom-property-panel {
|
||||
--panel-bg: #f8f9fa;
|
||||
--panel-border: #e9ecef;
|
||||
--panel-text: #212529;
|
||||
}
|
||||
|
||||
.custom-property-panel .ant-card {
|
||||
background: var(--panel-bg);
|
||||
border-color: var(--panel-border);
|
||||
}
|
||||
|
||||
.custom-property-panel .ant-tabs-tab {
|
||||
color: var(--panel-text);
|
||||
}
|
||||
```
|
||||
|
||||
## 数据存储
|
||||
|
||||
### LocalStorage 键值
|
||||
|
||||
- `appdev_property_panel_config`: 面板配置
|
||||
- `appdev_property_panel_presets`: 自定义预设
|
||||
|
||||
### 数据格式
|
||||
|
||||
#### 配置数据格式
|
||||
```json
|
||||
{
|
||||
"theme": "light",
|
||||
"autoSave": true,
|
||||
"autoSaveInterval": 3000,
|
||||
"showElementInfo": true,
|
||||
"showTooltips": true,
|
||||
"enableKeyboardShortcuts": true,
|
||||
"defaultPanel": "style",
|
||||
"panelLayout": "horizontal",
|
||||
"colorPalette": ["#000000", "#ffffff", "#3b82f6"],
|
||||
"customPresets": [],
|
||||
"shortcuts": {
|
||||
"save": "Ctrl+S",
|
||||
"undo": "Ctrl+Z",
|
||||
"redo": "Ctrl+Y",
|
||||
"togglePanel": "F2",
|
||||
"clearAll": "Ctrl+Delete"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 预设数据格式
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": "preset_001",
|
||||
"name": "主要按钮样式",
|
||||
"type": "style",
|
||||
"value": "bg-blue-500 text-white px-4 py-2 rounded-lg",
|
||||
"description": "常用的主要按钮样式",
|
||||
"tags": ["按钮", "主要", "蓝色"],
|
||||
"favorite": true,
|
||||
"createdAt": 1640995200000
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
### 常见错误
|
||||
|
||||
#### 1. 导入配置失败
|
||||
```typescript
|
||||
try {
|
||||
const config = JSON.parse(configString);
|
||||
// 验证配置格式
|
||||
if (!config.theme || !config.shortcuts) {
|
||||
throw new Error('配置格式不完整');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('导入配置失败:', error);
|
||||
message.error('配置格式错误,请检查文件格式');
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. 预设保存失败
|
||||
```typescript
|
||||
const savePreset = (preset) => {
|
||||
try {
|
||||
// 验证预设格式
|
||||
if (!preset.name || !preset.value) {
|
||||
throw new Error('预设名称和值不能为空');
|
||||
}
|
||||
|
||||
// 保存预设
|
||||
presetManager.savePreset(preset);
|
||||
message.success('预设保存成功');
|
||||
} catch (error) {
|
||||
console.error('保存预设失败:', error);
|
||||
message.error('保存失败: ' + error.message);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 错误边界
|
||||
|
||||
```typescript
|
||||
import { ErrorBoundary } from 'react-error-boundary';
|
||||
|
||||
function ErrorFallback({ error }) {
|
||||
return (
|
||||
<div className="error-boundary">
|
||||
<h3>配置面板出现错误</h3>
|
||||
<pre>{error.message}</pre>
|
||||
<button onClick={() => window.location.reload()}>
|
||||
重新加载
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 使用错误边界包装组件
|
||||
<ErrorBoundary FallbackComponent={ErrorFallback}>
|
||||
<PropertyPanel {...props} />
|
||||
</ErrorBoundary>
|
||||
```
|
||||
|
||||
## 性能优化
|
||||
|
||||
### 1. 组件优化
|
||||
|
||||
```typescript
|
||||
// 使用 React.memo 优化重渲染
|
||||
const PropertyPanel = React.memo<PropertyPanelProps>(({
|
||||
selectedElement,
|
||||
currentStyle,
|
||||
currentContent,
|
||||
onStyleUpdate,
|
||||
onContentUpdate,
|
||||
onStyleChange,
|
||||
onContentChange,
|
||||
config,
|
||||
onConfigChange
|
||||
}) => {
|
||||
// 组件实现...
|
||||
});
|
||||
|
||||
// 使用 useMemo 缓存计算结果
|
||||
const processedPresets = useMemo(() => {
|
||||
return presets.filter(preset => preset.favorite);
|
||||
}, [presets]);
|
||||
|
||||
// 使用 useCallback 缓存回调函数
|
||||
const handleStyleUpdate = useCallback((data) => {
|
||||
onStyleUpdate(data);
|
||||
}, [onStyleUpdate]);
|
||||
```
|
||||
|
||||
### 2. 内存管理
|
||||
|
||||
```typescript
|
||||
// 清理副作用
|
||||
useEffect(() => {
|
||||
const handleKeydown = (event) => {
|
||||
// 处理键盘事件
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeydown);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeydown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
// 自动保存逻辑
|
||||
}, config.autoSaveInterval);
|
||||
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [config.autoSaveInterval]);
|
||||
```
|
||||
|
||||
## 最佳实践
|
||||
|
||||
### 1. 配置管理
|
||||
- 合理设置自动保存间隔,避免过于频繁的保存操作
|
||||
- 为不同用户角色设置不同的默认配置
|
||||
- 定期清理无用的自定义预设
|
||||
|
||||
### 2. 性能优化
|
||||
- 大量预设数据时分页加载
|
||||
- 使用虚拟滚动优化长列表显示
|
||||
- 合理使用防抖和节流
|
||||
|
||||
### 3. 用户体验
|
||||
- 提供清晰的错误提示和恢复机制
|
||||
- 支持快捷键组合,满足熟练用户需求
|
||||
- 保持界面的响应性和直观性
|
||||
|
||||
### 4. 数据安全
|
||||
- 定期备份用户配置
|
||||
- 验证导入数据的格式和安全性
|
||||
- 提供配置恢复功能
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 常见问题
|
||||
|
||||
#### Q: 面板不显示或加载失败
|
||||
**A**: 检查以下项目:
|
||||
1. 确认所有依赖包已正确安装
|
||||
2. 检查网络连接是否正常
|
||||
3. 查看浏览器控制台是否有错误信息
|
||||
4. 验证配置格式是否正确
|
||||
|
||||
#### Q: 自定义预设无法保存
|
||||
**A**: 可能原因:
|
||||
1. LocalStorage 存储已满,尝试清理无用数据
|
||||
2. 预设数据格式不正确,检查数据结构
|
||||
3. 浏览器隐私设置阻止了本地存储
|
||||
|
||||
#### Q: 快捷键不生效
|
||||
**A**: 检查项目:
|
||||
1. 确认键盘事件监听器正确注册
|
||||
2. 检查是否有其他组件占用了相同的快捷键
|
||||
3. 验证快捷键格式是否符合系统要求
|
||||
|
||||
#### Q: 配置导入导出失败
|
||||
**A**: 可能的问题:
|
||||
1. JSON 格式错误,使用在线工具验证
|
||||
2. 文件权限问题,检查文件读写权限
|
||||
3. 数据大小超限,压缩或分批导入
|
||||
|
||||
### 调试技巧
|
||||
|
||||
#### 1. 启用调试模式
|
||||
```typescript
|
||||
const config = {
|
||||
debug: true,
|
||||
// 其他配置...
|
||||
};
|
||||
```
|
||||
|
||||
#### 2. 监控配置变化
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
console.log('Config changed:', config);
|
||||
}, [config]);
|
||||
```
|
||||
|
||||
#### 3. 检查存储状态
|
||||
```typescript
|
||||
const checkStorage = () => {
|
||||
const config = localStorage.getItem('appdev_property_panel_config');
|
||||
const presets = localStorage.getItem('appdev_property_panel_presets');
|
||||
console.log('Stored config:', config);
|
||||
console.log('Stored presets:', presets);
|
||||
};
|
||||
```
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v2.0.0 (当前版本)
|
||||
- ✨ 新增完整的可自定义属性面板
|
||||
- ✨ 支持主题切换和个性化配置
|
||||
- ✨ 新增预设管理系统
|
||||
- ✨ 支持配置导入导出
|
||||
- ✨ 增强键盘快捷键支持
|
||||
- ✨ 改进错误处理和恢复机制
|
||||
|
||||
### v1.0.0
|
||||
- 🎉 初始版本发布
|
||||
- ✨ 基础的样式和内容编辑功能
|
||||
- ✨ 简单的面板配置选项
|
||||
|
||||
## 技术支持
|
||||
|
||||
如果您在使用过程中遇到问题,请通过以下方式获取帮助:
|
||||
|
||||
1. **查看文档**: 详细阅读本文档和使用指南
|
||||
2. **检查示例**: 参考 examples/demo 目录中的示例代码
|
||||
3. **调试模式**: 启用 debug 模式查看详细日志
|
||||
4. **社区支持**: 在 GitHub 上提交 Issue
|
||||
5. **联系支持**: 发送邮件到 support@example.com
|
||||
|
||||
## 贡献指南
|
||||
|
||||
我们欢迎社区贡献!请查看 CONTRIBUTING.md 了解如何参与项目开发。
|
||||
|
||||
### 贡献方式
|
||||
- 🐛 报告 Bug
|
||||
- 💡 提出新功能建议
|
||||
- 📝 完善文档
|
||||
- 💻 提交代码改进
|
||||
- 🧪 编写测试用例
|
||||
|
||||
感谢您对项目的关注和支持!🎉
|
||||
@@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
32
qiming-vite-plugin-design-mode/examples/demo/index.html
Normal file
32
qiming-vite-plugin-design-mode/examples/demo/index.html
Normal file
@@ -0,0 +1,32 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>设计模式演示</title>
|
||||
<!-- DEV-INJECT-START -->
|
||||
<script data-id="dev-inject-monitor">
|
||||
(function() {
|
||||
const remote = "/sdk/dev-monitor.js";
|
||||
const separator = remote.includes('?') ? '&' : '?';
|
||||
const script = document.createElement('script');
|
||||
script.src = remote + separator + 't=' + Date.now();
|
||||
script.dataset.id = 'dev-inject-monitor-script';
|
||||
script.defer = true;
|
||||
// 防止重复注入
|
||||
if (!document.querySelector('[data-id="dev-inject-monitor-script"]')) {
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<!-- DEV-INJECT-END -->
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
2097
qiming-vite-plugin-design-mode/examples/demo/package-lock.json
generated
Normal file
2097
qiming-vite-plugin-design-mode/examples/demo/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
qiming-vite-plugin-design-mode/examples/demo/package.json
Normal file
28
qiming-vite-plugin-design-mode/examples/demo/package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "design-mode-demo",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-dialog": "^1.1.2",
|
||||
"@radix-ui/react-switch": "^1.1.1",
|
||||
"clsx": "^2.1.1",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"tailwind-merge": "^2.5.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.0.0",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "~5.6.2",
|
||||
"vite": "^7.2.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
42
qiming-vite-plugin-design-mode/examples/demo/src/App.css
Normal file
42
qiming-vite-plugin-design-mode/examples/demo/src/App.css
Normal file
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
64
qiming-vite-plugin-design-mode/examples/demo/src/App.tsx
Normal file
64
qiming-vite-plugin-design-mode/examples/demo/src/App.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import React, { useState } from 'react';
|
||||
import HomePage from './pages/HomePage';
|
||||
import FeaturesPage from './pages/FeaturesPage';
|
||||
import IframeDemoPage from './pages/IframeDemoPage';
|
||||
|
||||
function App() {
|
||||
const [currentPage, setCurrentPage] = useState<'home' | 'features' | 'iframe'>('home');
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
|
||||
{/* 导航栏 */}
|
||||
<nav className="bg-white shadow-md">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex justify-between h-16">
|
||||
<div className="flex items-center">
|
||||
<h1 className="text-2xl font-bold text-indigo-600">设计模式演示</h1>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<button
|
||||
onClick={() => setCurrentPage('home')}
|
||||
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
currentPage === 'home'
|
||||
? 'bg-indigo-600 text-white'
|
||||
: 'text-gray-700 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
首页
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setCurrentPage('features')}
|
||||
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
currentPage === 'features'
|
||||
? 'bg-indigo-600 text-white'
|
||||
: 'text-gray-700 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
功能展示
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setCurrentPage('iframe')}
|
||||
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
currentPage === 'iframe'
|
||||
? 'bg-indigo-600 text-white'
|
||||
: 'text-gray-700 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
Iframe 演示
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Page Content */}
|
||||
<main>
|
||||
{currentPage === 'home' && <HomePage />}
|
||||
{currentPage === 'features' && <FeaturesPage />}
|
||||
{currentPage === 'iframe' && <IframeDemoPage />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -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> <{selectedElement.tagName}></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;
|
||||
@@ -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> <{selectedElement.tagName}></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;
|
||||
@@ -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> <{selectedElement.tagName}></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;
|
||||
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
10
qiming-vite-plugin-design-mode/examples/demo/src/main.tsx
Normal file
10
qiming-vite-plugin-design-mode/examples/demo/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App.tsx';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,499 @@
|
||||
import React from '../react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card, Row, Col, Button, Space, Divider, message, Badge } from 'antd';
|
||||
import { ThunderboltOutlined, CodeOutlined, BgColorsOutlined, EditOutlined, EyeOutlined, ReloadOutlined, WarningOutlined, CheckCircleOutlined } from '@ant-design/icons';
|
||||
import type { ElementInfo, SourceInfo } from '../../../../packages/client-shared/src/messages';
|
||||
import PropertyPanel from '../external-panel/PropertyPanel';
|
||||
import type { PropertyPanelConfig } from '../external-panel/PropertyPanel';
|
||||
import { bridge } from '../../../../packages/client-react/src/bridge';
|
||||
|
||||
export default function CustomizableDemoPage() {
|
||||
const [selectedElement, setSelectedElement] = useState<ElementInfo | null>(null);
|
||||
const [currentStyle, setCurrentStyle] = useState<string>('');
|
||||
const [currentContent, setCurrentContent] = useState<string>('');
|
||||
const [demoConfig, setDemoConfig] = useState<PropertyPanelConfig | undefined>();
|
||||
const [bridgeStatus, setBridgeStatus] = useState<'checking' | 'connected' | 'disconnected' | 'error'>('checking');
|
||||
const [bridgeInfo, setBridgeInfo] = useState<any>(null);
|
||||
|
||||
// Bridge状态检查
|
||||
useEffect(() => {
|
||||
const checkBridgeStatus = async () => {
|
||||
try {
|
||||
// 检查环境信息
|
||||
const envInfo = bridge.getEnvironmentInfo();
|
||||
setBridgeInfo(envInfo);
|
||||
|
||||
console.log('[Demo] Bridge environment info:', envInfo);
|
||||
|
||||
if (!envInfo.isIframe) {
|
||||
setBridgeStatus('disconnected');
|
||||
console.log('[Demo] Running in main window, bridge connection not needed');
|
||||
return;
|
||||
}
|
||||
|
||||
// 执行健康检查
|
||||
const health = await bridge.healthCheck();
|
||||
console.log('[Demo] Bridge health check:', health);
|
||||
|
||||
if (health.status === 'healthy') {
|
||||
setBridgeStatus('connected');
|
||||
} else if (health.status === 'degraded') {
|
||||
setBridgeStatus('error');
|
||||
} else {
|
||||
setBridgeStatus('disconnected');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Demo] Bridge health check failed:', error);
|
||||
setBridgeStatus('error');
|
||||
}
|
||||
};
|
||||
|
||||
// 立即检查一次
|
||||
checkBridgeStatus();
|
||||
|
||||
// 定期检查
|
||||
const statusTimer = setInterval(checkBridgeStatus, 10000); // 10秒检查一次
|
||||
|
||||
return () => clearInterval(statusTimer);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 获取Bridge状态显示组件
|
||||
*/
|
||||
const BridgeStatusPanel = () => {
|
||||
const getStatusIcon = () => {
|
||||
switch (bridgeStatus) {
|
||||
case 'connected':
|
||||
return <CheckCircleOutlined className="text-green-500" />;
|
||||
case 'disconnected':
|
||||
return <WarningOutlined className="text-yellow-500" />;
|
||||
case 'error':
|
||||
return <WarningOutlined className="text-red-500" />;
|
||||
default:
|
||||
return <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusText = () => {
|
||||
switch (bridgeStatus) {
|
||||
case 'connected':
|
||||
return 'Bridge已连接';
|
||||
case 'disconnected':
|
||||
return 'Bridge未连接(主窗口模式)';
|
||||
case 'error':
|
||||
return 'Bridge连接错误';
|
||||
case 'checking':
|
||||
return '检查Bridge状态...';
|
||||
default:
|
||||
return '未知状态';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusColor = () => {
|
||||
switch (bridgeStatus) {
|
||||
case 'connected':
|
||||
return 'success';
|
||||
case 'disconnected':
|
||||
return 'warning';
|
||||
case 'error':
|
||||
return 'error';
|
||||
default:
|
||||
return 'processing';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card size="small" title="Bridge状态" className="mb-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{getStatusIcon()}
|
||||
<span className="text-sm">{getStatusText()}</span>
|
||||
</div>
|
||||
<Space>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => {
|
||||
bridge.diagnose();
|
||||
message.info('Bridge诊断信息已输出到控制台');
|
||||
}}
|
||||
>
|
||||
诊断
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{bridgeInfo && (
|
||||
<div className="mt-2 text-xs text-gray-500 space-y-1">
|
||||
<div>环境: {bridgeInfo.isIframe ? 'Iframe' : '主窗口'}</div>
|
||||
<div>位置: {bridgeInfo.location.substring(0, 50)}...</div>
|
||||
<div>来源: {bridgeInfo.origin}</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
// 模拟iframe内容
|
||||
const [iframeSrc] = useState(() => {
|
||||
// 生成一个包含源码映射的演示HTML
|
||||
return `data:text/html;charset=utf-8,${encodeURIComponent(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>设计模式演示</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; margin: 20px; }
|
||||
.container { max-width: 800px; margin: 0 auto; }
|
||||
.hero { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px; border-radius: 12px; text-align: center; margin-bottom: 30px; }
|
||||
.hero h1 { margin: 0 0 10px 0; font-size: 2.5rem; font-weight: bold; }
|
||||
.hero p { margin: 0; font-size: 1.2rem; opacity: 0.9; }
|
||||
.features { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; }
|
||||
.feature-card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border: 1px solid #e5e7eb; }
|
||||
.feature-card h3 { margin: 0 0 10px 0; color: #1f2937; font-size: 1.25rem; }
|
||||
.feature-card p { margin: 0; color: #6b7280; line-height: 1.6; }
|
||||
.cta { text-align: center; background: #f9fafb; padding: 30px; border-radius: 8px; border: 1px solid #e5e7eb; }
|
||||
.cta-button { background: #3b82f6; color: white; padding: 12px 24px; border: none; border-radius: 6px; font-size: 1rem; font-weight: 500; cursor: pointer; transition: background-color 0.2s; }
|
||||
.cta-button:hover { background: #2563eb; }
|
||||
.code-block { background: #1f2937; color: #f9fafb; padding: 20px; border-radius: 8px; font-family: 'Courier New', monospace; margin: 20px 0; overflow-x: auto; }
|
||||
.highlight { background: rgba(59, 130, 246, 0.1); padding: 2px 4px; border-radius: 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="hero">
|
||||
<h1 data-source-file="src/components/Hero.tsx" data-source-line="10" data-source-column="4">设计模式演示</h1>
|
||||
<p data-source-file="src/components/Hero.tsx" data-source-line="11" data-source-column="4">体验强大的可视化开发工具,让设计触手可及</p>
|
||||
</div>
|
||||
|
||||
<div class="features">
|
||||
<div class="feature-card">
|
||||
<h3 data-source-file="src/components/FeatureCard.tsx" data-source-line="5" data-source-column="8">实时预览</h3>
|
||||
<p data-source-file="src/components/FeatureCard.tsx" data-source-line="6" data-source-column="8">即时查看修改效果,所见即所得的开发体验</p>
|
||||
</div>
|
||||
<div class="feature-card">
|
||||
<h3 data-source-file="src/components/FeatureCard.tsx" data-source-line="12" data-source-column="8">智能提示</h3>
|
||||
<p data-source-file="src/components/FeatureCard.tsx" data-source-line="13" data-source-column="8">AI驱动的智能建议,提升开发效率</p>
|
||||
</div>
|
||||
<div class="feature-card">
|
||||
<h3 data-source-file="src/components/FeatureCard.tsx" data-source-line="19" data-source-column="8">一键部署</h3>
|
||||
<p data-source-file="src/components/FeatureCard.tsx" data-source-line="20" data-source-column="8">无缝集成CI/CD流程,快速交付产品</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cta">
|
||||
<h2 data-source-file="src/components/CallToAction.tsx" data-source-line="8" data-source-column="12">准备好开始了吗?</h2>
|
||||
<p data-source-file="src/components/CallToAction.tsx" data-source-line="9" data-source-column="12">立即体验下一代设计开发工具</p>
|
||||
<button class="cta-button" data-source-file="src/components/CallToAction.tsx" data-source-line="15" data-source-column="8">开始使用</button>
|
||||
</div>
|
||||
|
||||
<div class="code-block">
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="5" data-source-column="4">// 简单的使用示例</div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="6" data-source-column="4">import { DesignMode } from '@xagi/design-mode';</div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="7" data-source-column="4"></div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="8" data-source-column="4">const config = {</div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="9" data-source-column="8">enableSelection: true,</div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="10" data-source-column="8">autoSave: true</div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="11" data-source-column="4">};</div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="12" data-source-column="4"></div>
|
||||
<div data-source-file="src/utils/code-example.ts" data-source-line="13" data-source-column="4">DesignMode.init(config);</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 添加点击事件监听
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// 监听所有可编辑元素的点击
|
||||
const editableElements = document.querySelectorAll('[data-source-file]');
|
||||
|
||||
editableElements.forEach(element => {
|
||||
element.style.cursor = 'pointer';
|
||||
element.addEventListener('click', function(e) {
|
||||
e.stopPropagation();
|
||||
|
||||
// 移除之前的高亮
|
||||
document.querySelectorAll('[data-selected="true"]').forEach(el => {
|
||||
el.removeAttribute('data-selected');
|
||||
el.style.outline = '';
|
||||
});
|
||||
|
||||
// 添加高亮
|
||||
this.setAttribute('data-selected', 'true');
|
||||
this.style.outline = '2px solid #3b82f6';
|
||||
this.style.outlineOffset = '2px';
|
||||
|
||||
// 发送选中消息到父窗口
|
||||
// 判断是否为静态文本:检查元素是否有 static-content 属性
|
||||
const isStaticText = this.hasAttribute('data-source-static-content');
|
||||
|
||||
const elementInfo = {
|
||||
tagName: this.tagName.toLowerCase(),
|
||||
className: this.className || '',
|
||||
textContent: this.textContent || '',
|
||||
sourceInfo: {
|
||||
fileName: this.getAttribute('data-source-file'),
|
||||
lineNumber: parseInt(this.getAttribute('data-source-line')),
|
||||
columnNumber: parseInt(this.getAttribute('data-source-column'))
|
||||
},
|
||||
isStaticText: isStaticText || false // 默认为 false
|
||||
};
|
||||
|
||||
window.parent.postMessage({
|
||||
type: 'ELEMENT_SELECTED',
|
||||
payload: { elementInfo }
|
||||
}, '*');
|
||||
|
||||
console.log('Element selected:', elementInfo);
|
||||
});
|
||||
});
|
||||
|
||||
// 点击空白处取消选择
|
||||
document.addEventListener('click', function(e) {
|
||||
if (!e.target.hasAttribute('data-source-file')) {
|
||||
document.querySelectorAll('[data-selected="true"]').forEach(el => {
|
||||
el.removeAttribute('data-selected');
|
||||
el.style.outline = '';
|
||||
});
|
||||
|
||||
window.parent.postMessage({
|
||||
type: 'ELEMENT_DESELECTED'
|
||||
}, '*');
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
`)}`);
|
||||
|
||||
/**
|
||||
* 处理iframe中的元素选择
|
||||
*/
|
||||
useEffect(() => {
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
const { type, payload } = event.data;
|
||||
|
||||
switch (type) {
|
||||
case 'ELEMENT_SELECTED':
|
||||
setSelectedElement(payload.elementInfo);
|
||||
setCurrentStyle(payload.elementInfo.className);
|
||||
setCurrentContent(payload.elementInfo.textContent);
|
||||
console.log('[Parent] Element selected:', payload.elementInfo);
|
||||
break;
|
||||
|
||||
case 'ELEMENT_DESELECTED':
|
||||
setSelectedElement(null);
|
||||
console.log('[Parent] Element deselected');
|
||||
break;
|
||||
|
||||
case 'STYLE_UPDATED':
|
||||
console.log('[Parent] Style updated:', payload);
|
||||
// 更新当前样式
|
||||
if (selectedElement) {
|
||||
setCurrentStyle(payload.newClass);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'CONTENT_UPDATED':
|
||||
console.log('[Parent] Content updated:', payload);
|
||||
// 更新当前内容
|
||||
if (selectedElement) {
|
||||
setCurrentContent(payload.newValue);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [selectedElement]);
|
||||
|
||||
/**
|
||||
* 处理样式更新
|
||||
*/
|
||||
const handleStyleUpdate = (data: { sourceInfo: SourceInfo; newClass: string }) => {
|
||||
// 这里可以发送消息到iframe或者直接调用API
|
||||
console.log('Style update requested:', data);
|
||||
|
||||
// 模拟更新成功
|
||||
message.success('样式更新成功');
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理内容更新
|
||||
*/
|
||||
const handleContentUpdate = (data: { sourceInfo: SourceInfo; newContent: string }) => {
|
||||
// 这里可以发送消息到iframe或者直接调用API
|
||||
console.log('Content update requested:', data);
|
||||
|
||||
// 模拟更新成功
|
||||
message.success('内容更新成功');
|
||||
};
|
||||
|
||||
/**
|
||||
* 配置更改处理
|
||||
*/
|
||||
const handleConfigChange = (config: PropertyPanelConfig) => {
|
||||
setDemoConfig(config);
|
||||
console.log('Panel config changed:', config);
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置演示
|
||||
*/
|
||||
const resetDemo = () => {
|
||||
setSelectedElement(null);
|
||||
setCurrentStyle('');
|
||||
setCurrentContent('');
|
||||
|
||||
// 发送重置消息到iframe
|
||||
const iframe = document.querySelector('iframe') as HTMLIFrameElement;
|
||||
if (iframe && iframe.contentWindow) {
|
||||
iframe.contentWindow.postMessage({ type: 'RESET_DEMO' }, '*');
|
||||
}
|
||||
|
||||
message.info('演示已重置');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* 顶部标题栏 */}
|
||||
<div className="bg-white border-b border-gray-200 px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
|
||||
<ThunderboltOutlined className="text-white text-lg" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">可自定义属性面板演示</h1>
|
||||
<p className="text-sm text-gray-600">体验完整的双向同步设计模式架构</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Space>
|
||||
<Button icon={<CodeOutlined />} onClick={() => window.open('https://github.com/your-repo', '_blank')}>
|
||||
查看源码
|
||||
</Button>
|
||||
<Button icon={<ReloadOutlined />} onClick={resetDemo}>
|
||||
重置演示
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex h-[calc(100vh-88px)]">
|
||||
{/* 左侧:可自定义属性面板 */}
|
||||
<div className="w-96 bg-white border-r border-gray-200 flex flex-col">
|
||||
{/* Bridge状态面板 */}
|
||||
<div className="p-4 border-b border-gray-200">
|
||||
<BridgeStatusPanel />
|
||||
</div>
|
||||
|
||||
{/* 主体面板内容 */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<PropertyPanel
|
||||
selectedElement={selectedElement}
|
||||
currentStyle={currentStyle}
|
||||
currentContent={currentContent}
|
||||
onStyleUpdate={handleStyleUpdate}
|
||||
onContentUpdate={handleContentUpdate}
|
||||
onStyleChange={setCurrentStyle}
|
||||
onContentChange={setCurrentContent}
|
||||
config={demoConfig}
|
||||
onConfigChange={handleConfigChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧:iframe预览 */}
|
||||
<div className="flex-1 bg-white">
|
||||
<div className="h-full flex flex-col">
|
||||
{/* 预览工具栏 */}
|
||||
<div className="border-b border-gray-200 px-6 py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<EyeOutlined className="text-blue-500" />
|
||||
<span className="font-medium text-gray-900">实时预览</span>
|
||||
{selectedElement && (
|
||||
<>
|
||||
<Divider type="vertical" />
|
||||
<span className="text-sm text-gray-600">
|
||||
已选择: <{selectedElement.tagName}>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 bg-green-400 rounded-full"></div>
|
||||
<span className="text-xs text-gray-500">实时同步</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* iframe容器 */}
|
||||
<div className="flex-1 bg-gray-100">
|
||||
<iframe
|
||||
src={iframeSrc}
|
||||
className="w-full h-full border-0"
|
||||
title="可自定义属性面板演示"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部功能说明 */}
|
||||
<div className="border-t border-gray-200 bg-white px-6 py-4">
|
||||
<div className="grid grid-cols-3 gap-6">
|
||||
<Card size="small" className="h-full">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<BgColorsOutlined className="text-blue-500" />
|
||||
<span className="font-medium">样式自定义</span>
|
||||
</div>
|
||||
<ul className="text-sm text-gray-600 space-y-1">
|
||||
<li>• 自定义颜色方案和预设</li>
|
||||
<li>• 保存和加载样式配置</li>
|
||||
<li>• 主题切换(浅色/深色/跟随系统)</li>
|
||||
<li>• 快捷键自定义</li>
|
||||
</ul>
|
||||
</Card>
|
||||
|
||||
<Card size="small" className="h-full">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<EditOutlined className="text-green-500" />
|
||||
<span className="font-medium">内容自定义</span>
|
||||
</div>
|
||||
<ul className="text-sm text-gray-600 space-y-1">
|
||||
<li>• 富文本编辑和格式化</li>
|
||||
<li>• 内容历史记录管理</li>
|
||||
<li>• 模板和占位符自定义</li>
|
||||
<li>• 自动保存配置</li>
|
||||
</ul>
|
||||
</Card>
|
||||
|
||||
<Card size="small" className="h-full">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<ToolOutlined className="text-purple-500" />
|
||||
<span className="font-medium">高级功能</span>
|
||||
</div>
|
||||
<ul className="text-sm text-gray-600 space-y-1">
|
||||
<li>• 批量操作和防抖处理</li>
|
||||
<li>• 配置导入导出</li>
|
||||
<li>• 错误处理和回滚机制</li>
|
||||
<li>• 实时双向同步</li>
|
||||
</ul>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import React from 'react';
|
||||
|
||||
export default function FeaturesPage() {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
|
||||
<h1 className="text-4xl font-bold text-gray-900 mb-8">全部功能</h1>
|
||||
|
||||
{/* 功能 1: 样式编辑 */}
|
||||
<section className="mb-12 bg-white rounded-xl shadow-lg p-8">
|
||||
<h2 className="text-2xl font-bold text-indigo-600 mb-4">1. 样式编辑</h2>
|
||||
<p className="text-gray-700 mb-6">
|
||||
选择任意元素,使用可视化编辑器修改其 Tailwind CSS 类。
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="p-4 bg-slate-100 rounded-md">
|
||||
<p className="text-sm text-slate-600">默认样式</p>
|
||||
</div>
|
||||
<div className="p-4 bg-blue-100 rounded-md">
|
||||
<p className="text-sm text-blue-600">修改后的样式</p>
|
||||
</div>
|
||||
<div className="p-6 bg-red-50 rounded-lg">
|
||||
<p className="text-base text-red-700">大内边距</p>
|
||||
</div>
|
||||
<div className="p-2 bg-green-50 rounded-full">
|
||||
<p className="text-xs text-green-700">小内边距 + 圆角</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 功能 2: 内容编辑 */}
|
||||
<section className="mb-12 bg-white rounded-xl shadow-lg p-8">
|
||||
<h2 className="text-2xl font-bold text-green-600 mb-4">2. 内容编辑</h2>
|
||||
<p className="text-gray-700 mb-6">
|
||||
双击任意文本即可直接编辑。修改会保存到源文件中。
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-gray-50 rounded-md">
|
||||
<h3 className="text-lg font-semibold text-gray-900">可编辑标题</h3>
|
||||
<p className="text-gray-600">双击即可编辑这段文字。</p>
|
||||
</div>
|
||||
<div className="p-4 bg-blue-50 rounded-md">
|
||||
<p className="text-blue-900">试着编辑这段文本!11</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 功能 3: 源码映射 */}
|
||||
<section className="mb-12 bg-white rounded-xl shadow-lg p-8">
|
||||
<h2 className="text-2xl font-bold text-purple-600 mb-4">3. 源码映射</h2>
|
||||
<p className="text-gray-700 mb-6">
|
||||
每个元素都有指向其源文件位置的元数据。
|
||||
</p>
|
||||
|
||||
<div className="bg-gray-900 text-green-400 p-4 rounded-md font-mono text-sm">
|
||||
<div>data-source-file="/src/pages/FeaturesPage.tsx"</div>
|
||||
<div>data-source-line="42"</div>
|
||||
<div>data-source-column="8"</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 功能 4: 实时更新 */}
|
||||
<section className="mb-12 bg-white rounded-xl shadow-lg p-8">
|
||||
<h2 className="text-2xl font-bold text-orange-600 mb-4">4. 实时更新</h2>
|
||||
<p className="text-gray-700 mb-6">
|
||||
所有修改都会立即反映在界面上并保存到磁盘。
|
||||
</p>
|
||||
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex-1 p-4 bg-orange-50 rounded-md text-center">
|
||||
<p className="text-orange-700 font-medium">修改前</p>
|
||||
</div>
|
||||
<svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
|
||||
</svg>
|
||||
<div className="flex-1 p-4 bg-orange-100 rounded-lg text-center">
|
||||
<p className="text-orange-900 font-bold">修改后</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 交互演示 */}
|
||||
<section className="bg-gradient-to-r from-indigo-500 to-purple-600 rounded-xl shadow-xl p-8 text-white">
|
||||
<h2 className="text-3xl font-bold mb-4">交互演示</h2>
|
||||
<p className="text-indigo-100 mb-6">
|
||||
启用设计模式,尝试修改这些元素:
|
||||
</p>
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="bg-white bg-opacity-20 backdrop-blur-sm p-6 rounded-lg">
|
||||
<h3 className="text-xl font-semibold mb-2">卡片 1</h3>
|
||||
<p className="text-indigo-100">修改我的背景!</p>
|
||||
</div>
|
||||
<div className="bg-white bg-opacity-20 backdrop-blur-sm p-6 rounded-lg">
|
||||
<h3 className="text-xl font-semibold mb-2">卡片 2</h3>
|
||||
<p className="text-indigo-100">改变我的文字颜色!</p>
|
||||
</div>
|
||||
<div className="bg-white bg-opacity-20 backdrop-blur-sm p-6 rounded-lg">
|
||||
<h3 className="text-xl font-semibold mb-2">卡片 3</h3>
|
||||
<p className="text-indigo-100">编辑我的内容!</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import React from 'react';
|
||||
|
||||
export default function HomePage() {
|
||||
const title = "欢迎使用设计模式";
|
||||
const content = "体验实时可视化编辑,自动更新源代码。";
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
|
||||
{/* 主标题区域 */}
|
||||
<div className="text-center mb-16">
|
||||
<h1 className="text-5xl font-bold text-gray-900 mb-4">
|
||||
你好,{title}
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 max-w-3xl mx-auto">
|
||||
{content}
|
||||
点击右下角的设计模式开关即可开始!
|
||||
{'--变量测试--'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 功能卡片 */}
|
||||
<div className="grid md:grid-cols-3 gap-8 mb-16">
|
||||
<div className="rounded-lg shadow-lg p-6 bg-green-100">
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mb-4">
|
||||
<svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2 bg-red-100">样式编辑</h3>
|
||||
<p className="text-gray-600 bg-gray-100">
|
||||
点击任意元素,实时修改其 Tailwind CSS 类。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg shadow-lg p-6 bg-green-100">
|
||||
<div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center mb-4">
|
||||
<svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2 bg-green-100">内容编辑12</h3>
|
||||
<p className="text-gray-600 bg-gray-100">
|
||||
双击文本元素直接编辑内容,自动更新源文件。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg shadow-lg p-6">
|
||||
<div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center mb-4">
|
||||
<svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2 bg-blue-100">源码更新</h3>
|
||||
<p className="text-gray-600 bg-gray-100">
|
||||
所有修改都会自动保存到源代码文件中。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-xl shadow-xl p-8">
|
||||
3111
|
||||
<div className="space-y-4">
|
||||
<div className="p-6 bg-blue-50 rounded-lg border-2 border-blue-200">
|
||||
<h3 className="text-xl font-semibold text-blue-900 mb-2">可编辑卡片</h3>
|
||||
<p className="text-blue-700 bg-blue-100 bg-red-100">
|
||||
这是一个可编辑的段落。在设计模式下试着点击它!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-6 bg-green-50 rounded-lg border-2 border-green-200">
|
||||
源码更新 1
|
||||
<p className="text-green-700">
|
||||
你可以修改背景、文字颜色、内边距等等。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-6 bg-purple-50 rounded-lg border-2 border-purple-200">
|
||||
<h3 className="text-xl font-semibold text-purple-900 mb-2">第三个卡片</h3>
|
||||
<p className="text-purple-700 bg-green-100">
|
||||
双击这段文字可以直接编辑!3434341212121212
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* 列表修改测试区域 */}
|
||||
<div className="mt-16">
|
||||
<h2 className="text-3xl font-bold text-gray-900 mb-8 text-center">列表修改测试</h2>
|
||||
<div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3'>
|
||||
{[
|
||||
{ text: "写一篇关于人工智能的文章", icon: (props: any) => <svg {...props} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" /></svg> },
|
||||
{ text: "解释量子计算", icon: (props: any) => <svg {...props} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19.428 15.428a2 2 0 00-1.022-.547l-2.384-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" /></svg> },
|
||||
{ text: "设计一个Logo", icon: (props: any) => <svg {...props} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg> },
|
||||
].slice(0, 6).map((prompt, index) => {
|
||||
const IconComponent = prompt.icon;
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className='cursor-pointer border border-gray-200 hover:border-blue-300 hover:bg-blue-50 transition-all duration-200 bg-white rounded-lg shadow-sm'
|
||||
>
|
||||
<div className='p-3'>
|
||||
<div className='flex items-center gap-2 bg-yellow-100'>
|
||||
<IconComponent className='w-4 h-4 text-blue-600' />
|
||||
<span className='text-sm text-gray-700 truncate'>
|
||||
"{prompt.text}"
|
||||
</span>
|
||||
<p>这量个相同的文本</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
import React from '../react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { ElementInfo } from '@/types/messages';
|
||||
|
||||
|
||||
// 确保React在所有情况下都可用
|
||||
if (typeof React === 'undefined') {
|
||||
throw new Error(
|
||||
'React is not imported. Please ensure React is imported correctly.'
|
||||
);
|
||||
}
|
||||
|
||||
export default function IframeDemoPage() {
|
||||
const [iframeDesignMode, setIframeDesignMode] = useState(false);
|
||||
const [selectedElement, setSelectedElement] = useState<ElementInfo | null>(
|
||||
null
|
||||
);
|
||||
const [editingContent, setEditingContent] = useState('');
|
||||
const [editingClass, setEditingClass] = useState('');
|
||||
const [pendingChanges, setPendingChanges] = useState<
|
||||
Array<{
|
||||
type: 'style' | 'content';
|
||||
sourceInfo: any;
|
||||
newValue: string;
|
||||
originalValue?: string;
|
||||
}>
|
||||
>([]);
|
||||
|
||||
const iframeRef = React.useRef<HTMLIFrameElement>(null);
|
||||
|
||||
// Listen for messages from iframe
|
||||
useEffect(() => {
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
// Debug log for message source
|
||||
if (event.data.type === 'ELEMENT_SELECTED') {
|
||||
console.log('[Parent] Received ELEMENT_SELECTED', {
|
||||
source: event.source,
|
||||
iframeWindow: iframeRef.current?.contentWindow,
|
||||
isMatch: iframeRef.current && event.source === iframeRef.current.contentWindow,
|
||||
data: event.data
|
||||
});
|
||||
}
|
||||
if (event.data.type === 'ADD_TO_CHAT') {
|
||||
return console.log('[Parent] Add to chat:', event.data.payload);
|
||||
}
|
||||
|
||||
if (event.data.type === 'COPY_ELEMENT') {
|
||||
return console.log('[Parent] Copy element:', event.data.payload);
|
||||
}
|
||||
|
||||
// Only accept messages from the iframe
|
||||
if (iframeRef.current && event.source !== iframeRef.current.contentWindow) {
|
||||
if (event.data.type === 'ELEMENT_SELECTED') {
|
||||
console.warn('[Parent] Ignoring message from non-iframe source');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { type, payload } = event.data;
|
||||
|
||||
switch (type) {
|
||||
case 'DESIGN_MODE_CHANGED':
|
||||
setIframeDesignMode(event.data.enabled);
|
||||
break;
|
||||
|
||||
case 'ELEMENT_SELECTED':
|
||||
console.log('[Parent] Processing ELEMENT_SELECTED', payload);
|
||||
|
||||
// 验证 sourceInfo 是否有效
|
||||
if (
|
||||
!payload.elementInfo?.sourceInfo ||
|
||||
!payload.elementInfo.sourceInfo.fileName ||
|
||||
payload.elementInfo.sourceInfo.lineNumber === 0
|
||||
) {
|
||||
console.warn(
|
||||
'[Parent] Invalid sourceInfo received:',
|
||||
payload.elementInfo?.sourceInfo
|
||||
);
|
||||
console.warn('[Parent] This may cause update operations to fail');
|
||||
}
|
||||
|
||||
setSelectedElement(payload.elementInfo);
|
||||
setEditingContent(payload.elementInfo.textContent);
|
||||
setEditingClass(payload.elementInfo.className);
|
||||
break;
|
||||
|
||||
case 'ELEMENT_DESELECTED':
|
||||
setSelectedElement(null);
|
||||
console.log('[Parent] Element deselected');
|
||||
break;
|
||||
|
||||
case 'CONTENT_UPDATED':
|
||||
console.log('[Parent] Content updated:', payload);
|
||||
break;
|
||||
|
||||
case 'STYLE_UPDATED':
|
||||
console.log('[Parent] Style updated:', payload);
|
||||
break;
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, []);
|
||||
|
||||
// Debounce hook
|
||||
const useDebounce = <T,>(value: T, delay: number): T => {
|
||||
const [debouncedValue, setDebouncedValue] = useState(value);
|
||||
useEffect(() => {
|
||||
const handler = setTimeout(() => {
|
||||
setDebouncedValue(value);
|
||||
}, delay);
|
||||
return () => clearTimeout(handler);
|
||||
}, [value, delay]);
|
||||
return debouncedValue;
|
||||
};
|
||||
|
||||
const debouncedContent = useDebounce(editingContent, 300);
|
||||
const debouncedClass = useDebounce(editingClass, 300);
|
||||
|
||||
// Upsert pending change
|
||||
const upsertPendingChange = (
|
||||
type: 'style' | 'content',
|
||||
newValue: string,
|
||||
originalValue?: string
|
||||
) => {
|
||||
if (!selectedElement) return;
|
||||
setPendingChanges(prev => {
|
||||
const existingIndex = prev.findIndex(
|
||||
item =>
|
||||
item.type === type &&
|
||||
item.sourceInfo.fileName === selectedElement.sourceInfo.fileName &&
|
||||
item.sourceInfo.lineNumber === selectedElement.sourceInfo.lineNumber
|
||||
);
|
||||
|
||||
const newChange = {
|
||||
type,
|
||||
sourceInfo: selectedElement.sourceInfo,
|
||||
newValue,
|
||||
originalValue: originalValue || (type === 'style' ? selectedElement.className : selectedElement.textContent),
|
||||
};
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
const newList = [...prev];
|
||||
newList[existingIndex] = newChange;
|
||||
return newList;
|
||||
} else {
|
||||
return [...prev, newChange];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const lastSelectedElementRef = React.useRef(selectedElement);
|
||||
|
||||
// Real-time content update
|
||||
useEffect(() => {
|
||||
if (!selectedElement) return;
|
||||
|
||||
// If selection changed, skip this update cycle
|
||||
if (selectedElement !== lastSelectedElementRef.current) {
|
||||
console.log('[Parent] Skipping content update due to selection change');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[Parent] Content effect triggered', {
|
||||
debouncedContent,
|
||||
currentContent: selectedElement.textContent,
|
||||
shouldUpdate: debouncedContent !== selectedElement.textContent
|
||||
});
|
||||
|
||||
if (debouncedContent === selectedElement.textContent) return;
|
||||
|
||||
console.log('[Parent] Sending UPDATE_CONTENT', debouncedContent);
|
||||
upsertPendingChange('content', debouncedContent);
|
||||
|
||||
const iframe = iframeRef.current;
|
||||
if (iframe && iframe.contentWindow) {
|
||||
iframe.contentWindow.postMessage(
|
||||
{
|
||||
type: 'UPDATE_CONTENT',
|
||||
payload: {
|
||||
sourceInfo: selectedElement.sourceInfo,
|
||||
newContent: debouncedContent,
|
||||
persist: false,
|
||||
},
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
'*'
|
||||
);
|
||||
}
|
||||
}, [debouncedContent, selectedElement]); // Removed upsertPendingChange to fix infinite loop
|
||||
|
||||
// Real-time style update
|
||||
useEffect(() => {
|
||||
if (!selectedElement) return;
|
||||
|
||||
// If selection changed, skip this update cycle
|
||||
if (selectedElement !== lastSelectedElementRef.current) {
|
||||
console.log('[Parent] Skipping style update due to selection change');
|
||||
return;
|
||||
}
|
||||
|
||||
if (debouncedClass === selectedElement.className) return;
|
||||
|
||||
upsertPendingChange('style', debouncedClass);
|
||||
|
||||
const iframe = iframeRef.current;
|
||||
if (iframe && iframe.contentWindow) {
|
||||
iframe.contentWindow.postMessage(
|
||||
{
|
||||
type: 'UPDATE_STYLE',
|
||||
payload: {
|
||||
sourceInfo: selectedElement.sourceInfo,
|
||||
newClass: debouncedClass,
|
||||
persist: false,
|
||||
},
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
'*'
|
||||
);
|
||||
}
|
||||
}, [debouncedClass, selectedElement]); // Removed upsertPendingChange to fix infinite loop
|
||||
|
||||
// Update lastSelectedElementRef AFTER other effects
|
||||
useEffect(() => {
|
||||
lastSelectedElementRef.current = selectedElement;
|
||||
}, [selectedElement]);
|
||||
|
||||
// Style Manager Logic
|
||||
const toggleStyle = (newStyle: string, categoryRegex: RegExp) => {
|
||||
let currentClasses = editingClass.split(' ').filter(c => c.trim());
|
||||
|
||||
// Remove existing class in the same category
|
||||
currentClasses = currentClasses.filter(c => !categoryRegex.test(c));
|
||||
|
||||
// Add new style if it's not empty (allows clearing style)
|
||||
if (newStyle) {
|
||||
currentClasses.push(newStyle);
|
||||
}
|
||||
|
||||
setEditingClass(currentClasses.join(' '));
|
||||
};
|
||||
|
||||
const hasStyle = (style: string) => {
|
||||
return editingClass.split(' ').includes(style);
|
||||
};
|
||||
|
||||
// UI Controls
|
||||
const renderColorPicker = (prefix: string, colors: string[], label: string) => (
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">{label}</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{colors.map(color => {
|
||||
const styleClass = `${prefix}-${color}`;
|
||||
const isActive = hasStyle(styleClass);
|
||||
return (
|
||||
<button
|
||||
key={color}
|
||||
onClick={() => toggleStyle(styleClass, new RegExp(`^${prefix}-[a-z]+(-\\d+)?$`))}
|
||||
className={`w-8 h-8 rounded-full border-2 transition-all ${isActive ? 'border-gray-900 scale-110' : 'border-transparent hover:scale-105'
|
||||
} ${styleClass.replace('text-', 'bg-')}`} // Use bg color for preview
|
||||
title={color}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
onClick={() => toggleStyle('', new RegExp(`^${prefix}-[a-z]+(-\\d+)?$`))}
|
||||
className="px-2 py-1 text-xs text-gray-500 border border-gray-300 rounded hover:bg-gray-100"
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderSelect = (prefix: string, options: { label: string; value: string }[], label: string) => (
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">{label}</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{options.map(opt => {
|
||||
const styleClass = opt.value ? `${prefix}-${opt.value}` : '';
|
||||
const isActive = styleClass ? hasStyle(styleClass) : !options.some(o => o.value && hasStyle(`${prefix}-${o.value}`));
|
||||
return (
|
||||
<button
|
||||
key={opt.label}
|
||||
onClick={() => toggleStyle(styleClass, new RegExp(`^${prefix}(-[a-z0-9]+)?$`))}
|
||||
className={`px-3 py-1 text-sm rounded border transition-all ${isActive
|
||||
? 'bg-blue-600 text-white border-blue-600'
|
||||
: 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Toggle design mode in iframe
|
||||
const toggleIframeDesignMode = () => {
|
||||
const iframe = iframeRef.current;
|
||||
console.log('[Parent] Toggling iframe design mode...', iframe);
|
||||
if (iframe && iframe.contentWindow) {
|
||||
iframe.contentWindow.postMessage(
|
||||
{
|
||||
type: 'TOGGLE_DESIGN_MODE',
|
||||
enabled: !iframeDesignMode,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
'*'
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// 保存所有更改
|
||||
const saveChanges = async () => {
|
||||
if (pendingChanges.length === 0) return;
|
||||
|
||||
console.log('[Parent] Saving changes...', pendingChanges);
|
||||
|
||||
try {
|
||||
const response = await fetch('/__appdev_design_mode/batch-update', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
updates: pendingChanges.map(change => ({
|
||||
filePath: change.sourceInfo.fileName,
|
||||
line: change.sourceInfo.lineNumber,
|
||||
column: change.sourceInfo.columnNumber,
|
||||
newValue: change.newValue,
|
||||
type: change.type,
|
||||
originalValue: change.originalValue,
|
||||
})),
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
console.log('[Parent] Batch update success:', result);
|
||||
alert(`成功保存 ${result.summary.successful} 个更改!`);
|
||||
setPendingChanges([]); // 清空待保存列表
|
||||
} else {
|
||||
const error = await response.json();
|
||||
console.error('[Parent] Batch update failed:', error);
|
||||
alert('保存失败,请查看控制台错误信息。');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Parent] Error saving changes:', error);
|
||||
alert('保存出错,请检查网络连接。');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='min-h-screen bg-gray-100' data-selection-exclude="true">
|
||||
{/* Top Control Bar */}
|
||||
<div className='bg-white border-b border-gray-200 px-6 py-4'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<h1 className='text-2xl font-bold text-gray-900'>
|
||||
Iframe 设计模式演示
|
||||
</h1>
|
||||
<div className='flex gap-4'>
|
||||
{pendingChanges.length > 0 && (
|
||||
<button
|
||||
onClick={saveChanges}
|
||||
className='px-6 py-2 rounded-lg font-semibold bg-blue-600 hover:bg-blue-700 text-white transition-all shadow-md flex items-center gap-2'
|
||||
>
|
||||
<span>保存更改 ({pendingChanges.length})</span>
|
||||
<svg
|
||||
className='w-4 h-4'
|
||||
fill='none'
|
||||
stroke='currentColor'
|
||||
viewBox='0 0 24 24'
|
||||
>
|
||||
<path
|
||||
strokeLinecap='round'
|
||||
strokeLinejoin='round'
|
||||
strokeWidth={2}
|
||||
d='M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4'
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={toggleIframeDesignMode}
|
||||
className={`px-6 py-2 rounded-lg font-semibold transition-all ${iframeDesignMode
|
||||
? 'bg-green-500 hover:bg-green-600 text-white'
|
||||
: 'bg-gray-200 hover:bg-gray-300 text-gray-700'
|
||||
}`}
|
||||
>
|
||||
{iframeDesignMode ? '✓ 设计模式已启用' : '启用设计模式'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='flex h-[calc(100vh-73px)]'>
|
||||
{/* Left: External Property Panel */}
|
||||
<div className='w-80 bg-white border-r border-gray-200 overflow-y-auto'>
|
||||
<div className='p-6'>
|
||||
<h2 className='text-lg font-bold text-gray-900 mb-4'>
|
||||
外部属性面板
|
||||
</h2>
|
||||
|
||||
{selectedElement ? (
|
||||
<div className='space-y-6'>
|
||||
{/* Element Info */}
|
||||
<div className='bg-blue-50 border border-blue-200 rounded-lg p-4'>
|
||||
<h3 className='text-sm font-semibold text-blue-900 mb-2'>
|
||||
选中元素
|
||||
</h3>
|
||||
<div className='text-xs text-blue-700 space-y-1'>
|
||||
<div>
|
||||
<span className='font-medium'>标签:</span>{' '}
|
||||
{selectedElement.tagName}
|
||||
</div>
|
||||
<div className='break-all'>
|
||||
<span className='font-medium'>文件:</span>{' '}
|
||||
{selectedElement.sourceInfo.fileName.split('/').pop()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content Editor - 仅当 isStaticText 为 true 时显示 */}
|
||||
{selectedElement.isStaticText && (
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 mb-2'>
|
||||
内容编辑
|
||||
</label>
|
||||
<textarea
|
||||
value={editingContent}
|
||||
onChange={e => setEditingContent(e.target.value)}
|
||||
className='w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-indigo-500 focus:border-transparent'
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<hr className="border-gray-200" />
|
||||
|
||||
{/* Smart Style Controls */}
|
||||
<div>
|
||||
<h3 className="text-md font-bold text-gray-900 mb-4">样式设置</h3>
|
||||
|
||||
{renderColorPicker('bg', ['white', 'gray-100', 'red-100', 'blue-100', 'green-100', 'yellow-100', 'purple-100'], '背景颜色')}
|
||||
{renderColorPicker('text', ['gray-900', 'gray-500', 'red-600', 'blue-600', 'green-600', 'purple-600', 'white'], '文字颜色')}
|
||||
|
||||
{renderSelect('p', [
|
||||
{ label: '无', value: '0' },
|
||||
{ label: '小', value: '2' },
|
||||
{ label: '中', value: '4' },
|
||||
{ label: '大', value: '8' },
|
||||
{ label: '特大', value: '12' }
|
||||
], '内边距 (Padding)')}
|
||||
|
||||
{renderSelect('rounded', [
|
||||
{ label: '直角', value: 'none' },
|
||||
{ label: '小圆角', value: 'sm' },
|
||||
{ label: '圆角', value: 'md' },
|
||||
{ label: '大圆角', value: 'lg' },
|
||||
{ label: '全圆角', value: 'full' }
|
||||
], '圆角 (Border Radius)')}
|
||||
|
||||
{renderSelect('text', [
|
||||
{ label: '小', value: 'sm' },
|
||||
{ label: '默认', value: 'base' },
|
||||
{ label: '中', value: 'lg' },
|
||||
{ label: '大', value: 'xl' },
|
||||
{ label: '特大', value: '2xl' }
|
||||
], '文字大小 (Font Size)')}
|
||||
</div>
|
||||
|
||||
{/* Raw Style Editor */}
|
||||
<div className="mt-6 pt-6 border-t border-gray-200">
|
||||
<label className='block text-sm font-medium text-gray-500 mb-2'>
|
||||
原始 ClassName (高级)
|
||||
</label>
|
||||
<textarea
|
||||
value={editingClass}
|
||||
onChange={e => setEditingClass(e.target.value)}
|
||||
className='w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-indigo-500 focus:border-transparent font-mono text-xs text-gray-500'
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className='text-center py-12 text-gray-500'>
|
||||
<p className='text-sm'>
|
||||
{iframeDesignMode
|
||||
? '点击 iframe 内的元素开始编辑'
|
||||
: '请先启用设计模式'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Iframe Preview */}
|
||||
<div className='flex-1 bg-gray-50 p-6'>
|
||||
<div className='h-full bg-white rounded-lg shadow-xl overflow-hidden'>
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={window.location.origin}
|
||||
className='w-full h-full'
|
||||
title='设计模式 Iframe 演示'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
10
qiming-vite-plugin-design-mode/examples/demo/src/react.ts
Normal file
10
qiming-vite-plugin-design-mode/examples/demo/src/react.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
// React重新导出,确保在所有情况下都能正确导入
|
||||
export { useState, useEffect, useCallback, useMemo, useRef, useReducer } from 'react';
|
||||
export { createContext, useContext } from 'react';
|
||||
export { createElement, Fragment } from 'react';
|
||||
export type { ReactNode, ReactElement, ComponentType } from 'react';
|
||||
|
||||
// React主对象重新导出(兼容旧版本)
|
||||
import * as ReactModule from 'react';
|
||||
export default ReactModule;
|
||||
export const React = ReactModule;
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": [
|
||||
"ES2022",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"module": "ESNext",
|
||||
"types": [
|
||||
"vite/client"
|
||||
],
|
||||
"skipLibCheck": true,
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"../../packages/plugin/src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
44
qiming-vite-plugin-design-mode/examples/demo/vite.config.ts
Normal file
44
qiming-vite-plugin-design-mode/examples/demo/vite.config.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import path from 'path';
|
||||
import appdevDesignMode from '@xagi/vite-plugin-design-mode';
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
|
||||
// <!-- DEV-INJECT-START -->
|
||||
{
|
||||
name: 'dev-inject',
|
||||
enforce: 'post', // 确保在 HTML 注入阶段最后执行
|
||||
transformIndexHtml(html) {
|
||||
if (!html.includes('data-id="dev-inject-monitor"')) {
|
||||
return html.replace("</head>", `
|
||||
<script data-id="dev-inject-monitor">
|
||||
(function() {
|
||||
const remote = "/sdk/dev-monitor.js";
|
||||
const separator = remote.includes('?') ? '&' : '?';
|
||||
const script = document.createElement('script');
|
||||
script.src = remote + separator + 't=' + Date.now();
|
||||
script.dataset.id = 'dev-inject-monitor-script';
|
||||
script.defer = true;
|
||||
// 防止重复注入
|
||||
if (!document.querySelector('[data-id="dev-inject-monitor-script"]')) {
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
\n</head>`);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
},
|
||||
// <!-- DEV-INJECT-END -->
|
||||
react(),
|
||||
appdevDesignMode()
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src')
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user