Cowart 双模式融合 — 编辑器模式
适用场景
给已有的 React + tldraw 无限画布项目增加「HTML 可视化编辑器」模式,保留原画布模式不变,形成双模式切换架构。
参考实现:~/plugins/cowart/ V3.0.0
架构原则
- 零改动画布模式 — 画布模式所有 tldraw 代码原封不动
- 全局顶栏统一切换 — mode 状态放在 App.jsx 顶层,切换 tab 在两模式共享
- 编辑器组件独立目录 —
src/editor/目录,零耦合
关键组件
| 组件 | 职责 |
|---|---|
ModeToggle.jsx |
画布/编辑器 tab |
EditorMode.jsx |
编辑器容器,组装三栏 + 智能缩放 |
HtmlPreview.jsx |
iframe srcdoc 渲染 + postMessage 桥 + 导入/导出 |
InspectorPanel.jsx |
右侧 260px 属性面板(10 区编辑) |
ViewportSwitch.jsx |
桌面/宽屏/平板/手机 4 档 |
postMessage 协议
iframe → parent:
{ type: 'COWART_SELECT', cowartId, tag, id, className, innerText, styles, attributes }
parent → iframe:
{ type: 'COWART_STYLE', cowartId, styles }
{ type: 'COWART_TEXT', cowartId, innerText }
{ type: 'COWART_ATTR', cowartId, attributes }
关键实现细节
1. Bridge 脚本注入(不动用户 HTML)
// HtmlPreview.jsx — iframe 加载完后注入 bridge
const onIframeLoad = () => {
const doc = iframeRef.current.contentDocument
const script = doc.createElement('script')
script.textContent = BRIDGE_SCRIPT
doc.head.appendChild(script)
}
- ❌ 不要用
html.replace()修改用户 HTML(会破坏 CSS/JS 字符串) - ✅ 通过
contentDocument.createElement('script')注入
2. sendToIframe 父子桥接
- iframe 内部的 bridge 用
window.parent.postMessage(msg, '*')向外发 - 父组件用
iframe.contentWindow.postMessage(msg, '*')向内发 - 接收端校验
e.source === iframeRef.current.contentWindow
3. 智能缩放(解决宽屏溢出)
// EditorMode.jsx
const [scale, setScale] = useState(1)
useEffect(() => {
const sW = (el.clientWidth - 48) / vw
const sH = (el.clientHeight - 48) / 900
setScale(Math.min(1, sW, sH))
}, [viewport])
window.addEventListener('resize', recompute)
- 容器
width: vw * scale, height: 900 * scale - iframe
transform: scale(scale); transformOrigin: top left - 结果:1920 宽屏在 1500 可用宽度下完整缩小可见
4. 数据清理(导出)
const cleaned = htmlContent
.replace(/s+data-cowart-id="[^"]*"/gi, '')
.replace(/s+data-cowart-id='[^']*'/gi, '')
视觉规范(暗色设计工具风格)
| 元素 | 颜色 |
|---|---|
| 画布背景 | #141428 + dot-grid |
| Inspector 面板 | #1e1e30 |
| 顶栏 | #16162a 34px |
| 选中态 | 蓝渐变 #3b82f6 → #2563eb + 阴影 |
- Inspector 260px 固定宽
- micro-text 标题(10px 全大写 + 0.07em 字间距)
- 自定义控件(range/select/checkbox/color swatch)
文件清单(最小化)
src/
App.jsx ← 改:+mode 状态 + 全局顶栏 + 条件渲染
styles.css ← 改:+~83 条 .editor-* 样式
editor/
ModeToggle.jsx ← 新增
EditorMode.jsx ← 新增
HtmlPreview.jsx ← 新增
InspectorPanel.jsx ← 新增
ViewportSwitch.jsx ← 新增
不变清单(保证零回归)
src/main.jsxvite.config.jspublic/存量文件- 画布模式所有 tldraw 代码
- 原有标注工具、API 路由




