Compare commits

..

120 Commits

Author SHA1 Message Date
roymondchen
e5e0da3785 fix(editor): 修正 StyleSetter 字段 prop 取值逻辑
将 `prop ? `${prop}.${name}` : name` 简化为 `prop || name`,
避免嵌套路径拼接导致的表单校验 prop 错误。
2026-07-20 20:02:42 +08:00
roymondchen
ef66e8a598 fix(form,editor): 完善表单校验与样式属性匹配 2026-07-20 19:09:55 +08:00
roymondchen
932974f0fa style: lint-fix 自动修复格式问题 2026-07-20 11:20:15 +08:00
roymondchen
edb44da255 chore: 清理 vue-demi/composition-api 传递依赖,重构 ActionButton 去重并修复 Popconfirm 兼容 2026-07-20 11:18:41 +08:00
roymondchen
7459224009 chore(deps): 升级开发依赖版本并同步 workspace catalog 与 lockfile 2026-07-16 19:48:07 +08:00
roymondchen
d07e48bb10 feat(form,editor): 新增 validateForm 校验能力并接入源码保存校验联动 2026-07-16 19:37:46 +08:00
roymondchen
4a15da2108 fix(editor): 修复 Monaco 编辑器卸载时容器失效与 Canceled 未处理异常 2026-07-16 19:35:43 +08:00
roymondchen
ce43fface8 refactor(editor): 完善内置 typeMatch 校验规则并规范文件名
- 重命名 typeMatchRules.ts 为 type-match-rules.ts
- 为 event-select、display-conds 等字段补充结构校验规则
- advancedTabConfig 的 code-select 字段增加 hookType 校验
- 修复 update 未携带 invalidInfo 时清除对应节点全部来源错误
- 将 code-select/display-conds 字段 typeMatch 触发时机调整为 change
2026-07-14 20:28:03 +08:00
roymondchen
0e4669261f feat(editor): 新增属性配置表单校验联动能力
- 新增 enablePropsFormValidate 开关
- 校验失败时仍更新节点并记录错误
- editorService 增加 invalidNodeIds 状态及错误读写方法
- 新增 invalid-node-change 事件,错误随历史快照还原
- 组件树节点标红并展示错误图标
- playground 保存前拦截校验错误组件
- 补充 API 与进阶指南文档
2026-07-14 19:51:21 +08:00
roymondchen
1c67b5e77b feat(editor): 注册编辑器字段内置 typeMatch 校验规则并补充文档
- 新增 typeMatchRules.ts,为编辑器自定义字段注册内置 typeMatch 校验规则
- 抽取 event.ts 事件工具函数
- form typeMatch 适配 TDesign 校验器签名,错误消息补充实际值
- rules.md 新增「Editor 字段内置规则」章节,16 个字段文档补充校验说明
2026-07-14 17:15:28 +08:00
roymondchen
bbe73aae64 feat(editor): 扩展 customContentMenu 支持 getTarget 获取右键目标
为数据源与代码块面板的右键菜单传入 getTarget 回调,便于业务在自定义菜单 handler 中读取当前节点 id 与原始数据。
2026-07-14 15:55:19 +08:00
roymondchen
734e6a8ee6 feat(form): 支持 rules.typeMatch 按字段 type 校验值类型与选项匹配
新增可扩展的 typeMatch 校验能力,兼容 async-validator 规则体系,并补充文档与单元测试。
2026-07-13 15:52:56 +08:00
roymondchen
f7d737a0c0 docs: 补充新增修改代码测试覆盖率不低于85%的开发约定
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-13 14:43:48 +08:00
roymondchen
42d45bed18 fix(form): radio group disabled不生效 2026-07-10 16:40:42 +08:00
roymondchen
de7a4f73ad style(table): 为 sub-actions 类名添加 tmagic-table 命名空间并迁移样式到主题文件 2026-07-07 19:45:38 +08:00
roymondchen
605f07c8fe feat(editor): 支持自定义历史对比/回滚弹窗内表单组件的尺寸 2026-07-06 17:17:39 +08:00
roymondchen
90492ad3ea fix(adapters): tag 非法 type 回退为默认主题
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-06 16:48:45 +08:00
roymondchen
b183e71f64 feat(table): 抽取 ActionPopconfirm 并优化 sub-actions 展开交互
将 Popconfirm 逻辑抽离为独立组件,ActionButton 内置 tooltip 支持,sub-actions 触发按钮改用箭头图标切换展开状态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-06 16:47:16 +08:00
roymondchen
78a1259665 feat(table): 操作列支持 sub-actions 更多菜单并抽取 ActionButton 组件 2026-07-06 15:08:24 +08:00
roymondchen
4a893d35df fix(editor): 为 FloatingBox 拖拽遮罩添加失焦等兜底清理,避免残留导致编辑器无法点击 2026-07-06 11:34:41 +08:00
roymondchen
3c21f45e88 feat(editor): 支持通过 uiService 配置列布局最小宽度
将左侧、中间、右侧列的最小宽度从硬编码常量改为 UiState 配置项,便于业务侧自定义编辑器布局约束。
2026-07-03 19:44:13 +08:00
roymondchen
aa71fe9ddd fix(core): 在 initNode 前校验 config.items 为数组
避免 config.items 非数组时 forEach 抛出运行时错误。
2026-07-03 11:46:09 +08:00
roymondchen
9e8272b521 feat(table): 为操作列新增 Popconfirm 二次确认能力
支持 popconfirm、confirmText、popconfirmWidth 配置,并扩展 Popconfirm 组件的 width 与 teleported 属性。
2026-07-03 11:39:37 +08:00
roymondchen
9aa251ce57 fix(editor): 延迟 FloatingBox 拖拽遮罩到实际位移时显示,修复关闭按钮点击失效 2026-07-02 20:52:17 +08:00
roymondchen
3b9fb714e5 refactor(editor): 解耦 FloatingBox 的 uiService 依赖并改为 props 传入
- FloatingBox 不再强制依赖 uiService
- frameworkWidth 默认回退到视窗宽度
- 新增 initialStyle prop 支持外部设置初始样式
- 各调用方显式传入 frameworkWidth 以保留右边界收敛行为
2026-07-02 20:22:24 +08:00
roymondchen
284be0d276 fix(editor): 修复 FloatingBox 拖动时鼠标进入 iframe 区域事件丢失
- 拖拽/缩放开始时插入全屏透明遮罩盖住 iframe,结束时移除,避免事件被 iframe 吞掉
- 修正拖拽标题时 z-index 竞态导致遮罩被浮窗盖住的问题
- 将 body 内边距从 scss 抽取为 bodyStyle 透传,复用方按需自定义
2026-07-02 20:01:45 +08:00
roymondchen
c57ef89715 chore: update lockfile v1.8.0-beta.11 2026-06-29 21:27:41 +08:00
roymondchen
1ef3ea9eb9 chore: release v1.8.0-beta.11 2026-06-29 21:26:37 +08:00
roymondchen
83f4e52845 feat(editor): support custom width and initial diff mode for history diff dialog
为历史差异/回滚确认弹窗新增可配置宽度(dialogWidth / width 透传至 TMagicDialog),
并支持通过 payload.mode 指定打开时的初始对比模式,不可用时回退自动推断。
2026-06-29 20:23:19 +08:00
roymondchen
4330738b9f feat(form): add debug mode to submitForm
Allow submitForm to render a visible modal for manual validation and submission during debugging.
2026-06-29 15:49:33 +08:00
roymondchen
e59c3d2dcd chore: update lockfile v1.8.0-beta.10 2026-06-26 19:53:58 +08:00
roymondchen
55135fc063 chore: release v1.8.0-beta.10 2026-06-26 19:52:59 +08:00
roymondchen
af197363cf fix(vue-runtime-help): handle remove when root is not initialized
When root is empty but RemoveData carries app config, update root instead of throwing.
2026-06-26 19:51:44 +08:00
roymondchen
7bbb1f24c0 feat(editor): add unified change events 2026-06-26 19:48:38 +08:00
roymondchen
f7afed66aa feat(editor): refine history diff defaults 2026-06-26 17:08:39 +08:00
roymondchen
fd359e493f feat(form): support useFieldTextInError option
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-26 16:38:40 +08:00
roymondchen
5e661d0958 refactor(editor): 历史对比 services 改为显式传入并可选
CompareForm / HistoryDiffDialog / useHistoryRevert 不再通过 useServices()
默认 inject 获取 services,改为由调用方显式传入并设为可选,避免在
createApp 动态挂载游离弹窗场景下 inject 链不可靠。同步更新调用点、
测试与文档示例签名。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-26 15:00:08 +08:00
roymondchen
5ea992f5f7 chore: update lockfile v1.8.0-beta.9 2026-06-25 18:17:38 +08:00
roymondchen
4c81f22485 chore: release v1.8.0-beta.9 2026-06-25 18:13:58 +08:00
roymondchen
40acb5b34c feat: 导出 componentListService 和 keybindingService 2026-06-25 17:32:52 +08:00
roymondchen
ce65b18dbb feat(editor): 优化历史记录对比与回滚流程 2026-06-25 16:30:01 +08:00
roymondchen
1c936ff439 chore: update deps 2026-06-24 14:43:11 +08:00
roymondchen
e32780b0fb chore: update lockfile v1.8.0-beta.8 2026-06-23 20:21:19 +08:00
roymondchen
7e789aa83a chore: release v1.8.0-beta.8 2026-06-23 20:20:01 +08:00
roymondchen
0f42989ca3 refactor(editor): 统一历史栈结构,支持扩展历史类型
将 pageSteps/codeBlockState/dataSourceState 三套独立历史栈收敛为统一的 steps 结构
(按 stepType 分桶),并新增 registerStepType/setStepName/getStepName 支持自定义
扩展历史类型。同步重构 history 相关服务、组件、工具方法、测试与文档。
2026-06-23 20:14:41 +08:00
roymondchen
bfdaf2b244 fix(playground): 调整初始化时序避免历史恢复被覆盖
将本地 magicDSL 的恢复逻辑移动到 restoreHistory 之后,避免页面初始化时覆盖已恢复的历史状态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-18 17:28:06 +08:00
roymondchen
1ade61d62e feat(editor): 历史记录支持展示操作人
在历史列表分组头部和子步骤中展示 operator 信息,并补充步骤类型字段以承载操作人与扩展数据,同时收敛相关类型定义与插件方法声明,提升历史记录渲染与扩展能力。
2026-06-18 17:24:25 +08:00
roymondchen
9f2fa1a9c8 refactor(editor): 抽离历史记录回滚交互并开放复用入口 2026-06-18 17:04:16 +08:00
roymondchen
38065f013f chore: update lockfile v1.8.0-beta.7 2026-06-17 17:20:52 +08:00
roymondchen
d5c1fab016 chore: release v1.8.0-beta.7 2026-06-17 17:19:49 +08:00
roymondchen
bbf79fd6df fix(editor): 修复历史记录面板分组与展示逻辑
统一历史记录列表在不同维度下的分组与展示行为,避免对比信息与交互状态不一致,并补齐对应单测覆盖。
2026-06-17 17:14:27 +08:00
roymondchen
24b9b34f65 fix(editor): 恢复新增组件在当前视窗中垂直居中
fixNodePosition 不应要求 style 已存在 top 才计算居中位置,否则从组件面板新增时无法写入视窗居中 top。
2026-06-17 14:20:07 +08:00
roymondchen
95769d6ae0 fix(editor): 数据源配置面板默认激活「数据定义」tab
未指定编辑方法或字段路径时,将 tab 容器默认激活到 fields,避免无 active 状态。
2026-06-16 16:34:27 +08:00
roymondchen
8933c46b73 fix(editor): sidebar 侧栏项 key 与 SideItemKey 常量对齐
确保侧栏配置与字段编辑时切换 tab 的 key 一致,避免硬编码字符串不一致。
2026-06-16 14:12:14 +08:00
roymondchen
c811908971 chore: update lockfile v1.8.0-beta.6 2026-06-15 20:47:10 +08:00
roymondchen
0774aa8e59 chore: release v1.8.0-beta.6 2026-06-15 20:46:05 +08:00
roymondchen
2ff7c479c2 test(editor): 补齐 CodeSelectCol 单测 uiService.set mock 2026-06-15 20:45:50 +08:00
roymondchen
4a8289137b fix(playground): 修复历史恢复后加载 DSL 时缺少页面基线记录
初始 set root 时标记各页面历史栈为已保存,并用 dsl.id 恢复 IndexedDB 历史,避免 restore 后再赋值时走 diff 分支导致无 initial 基线。
2026-06-15 20:43:53 +08:00
roymondchen
ffcc734102 feat(editor): 查看/编辑时自动切换 sidebar 并定位到对应配置
点击代码块、数据源字段或方法的选择器编辑/查看按钮时,自动切换到对应 sidebar tab,并打开详情中的目标字段或方法配置。
2026-06-15 17:43:09 +08:00
roymondchen
b35132e93e feat(editor): 边框方向有配置时显示高亮状态 2026-06-15 17:10:55 +08:00
roymondchen
921188d2da refactor(editor): 优化历史记录 IndexedDB 持久化,仅序列化 step diff
避免 serialize-javascript 序列化整份快照,改为结构化克隆写入 IndexedDB;初始历史行展示已保存标记;root-change 事件携带 options。
2026-06-12 17:46:55 +08:00
roymondchen
6960bd50e1 feat(editor): 增强 *AndGetHistoryId 与 revertById 的 historyIds 能力
*AndGetHistoryId 同时返回原操作结果与 historyIds 数组;revertById/revertPageStepById 统一按 uuids 批量回滚。
2026-06-12 16:32:47 +08:00
roymondchen
27fac02e99 fix(editor): 仅在使用 left/top 定位时修正节点位置
避免对使用 right/bottom 定位的绝对定位节点误写 left 或 top。
2026-06-12 15:04:45 +08:00
roymondchen
1298104732 fix(editor): 完善 fixed 与 absolute 定位切换逻辑
EditorNodeInfo 增加 path 复用节点路径,修复 right/bottom 锚定及冲突定位属性的计算问题。
2026-06-11 20:48:47 +08:00
roymondchen
9fe10e274c test: 补充 editor、stage、table 单元测试覆盖 2026-06-11 18:45:42 +08:00
roymondchen
89cef4e9a9 feat(editor): 数据源与代码块历史记录不再合并相邻操作
每条操作独立展示,与页面历史的合并策略区分开。
2026-06-11 17:25:54 +08:00
roymondchen
273d13dd1f chore: update lockfile v1.8.0-beta.5 2026-06-11 17:06:05 +08:00
roymondchen
771880b994 chore: release v1.8.0-beta.5 2026-06-11 17:05:03 +08:00
roymondchen
113af7dd51 feat(editor): 页面删除前增加确认弹窗并支持危险样式按钮 2026-06-11 17:00:10 +08:00
roymondchen
846f05e04d feat(design): popover 支持点击外部关闭
新增 closeOnClickOutside 与 clickOutsideIgnore 配置,
兼容 element-plus / tdesign 衍生浮层。
历史列表面板改用 v-model:visible 配合自动收起。
2026-06-11 16:49:54 +08:00
roymondchen
fd652b0d13 feat(editor): 页面历史记录点击选中对应画布节点
支持在页面历史 tab 点击记录行选中 diff 中的节点,并联动画布与 overlay;清空页面历史改用 clear-page 事件,避免 restore 时重复触发 change。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 16:22:25 +08:00
roymondchen
7d45aa5eec style(editor): 优化历史列表操作区悬停展示与列对齐
将回滚/回到/查看差异收敛为悬停显示的操作区,固定序号列右对齐,并调整「回到」按钮配色。
2026-06-11 15:51:44 +08:00
roymondchen
171d31e207 fix(stage): 复用 TargetShadow 修正闪烁高亮定位
闪烁提示改为通过 TargetShadow 定位,支持 updateDragEl 校准与滚动偏移。
2026-06-11 15:24:50 +08:00
roymondchen
6ba59c0d14 feat(editor): 将侧边栏激活面板状态同步至 uiService 2026-06-11 15:12:56 +08:00
roymondchen
4f284e8d9c feat(editor): 支持页面初始基线与 root 变更历史记录
设置 root 时为各页建立 initial 基线并展示在历史列表底部;编辑期间再次 set root 按页面粒度写入历史,并抽取历史工具函数以支持撤销下限与持久化恢复。
2026-06-11 15:00:11 +08:00
roymondchen
c4ec2c5c72 perf(editor): 优化节点信息查找性能 2026-06-09 14:23:43 +08:00
roymondchen
48519b0155 fix(editor): 优化历史回滚确认流程 2026-06-09 11:05:26 +08:00
roymondchen
a965dfb06e refactor(editor): 优化历史记录列表复用 2026-06-08 20:09:10 +08:00
roymondchen
614f12adf3 feat(editor): 支持历史记录持久化
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 17:04:39 +08:00
roymondchen
bddc6f343c feat(editor): 支持按历史记录 uuid 回滚 2026-06-05 19:25:50 +08:00
roymondchen
be3a900e6a fix(editor): 修复历史对比属性配置上下文缺失 2026-06-05 17:27:20 +08:00
roymondchen
bc555ebdc0 chore: update lockfile v1.8.0-beta.4 2026-06-04 17:15:03 +08:00
roymondchen
b7d1cea7c1 chore: release v1.8.0-beta.4 2026-06-04 17:13:59 +08:00
roymondchen
3bd0eecb42 fix(editor): 修复合并历史记录信息展示
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-04 17:10:54 +08:00
roymondchen
cd19dec790 fix(editor): 修复历史对比样式配置显示
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-04 16:59:08 +08:00
roymondchen
10b70c36bb fix(editor): 禁止缺少变更记录的历史回滚 2026-06-04 16:48:24 +08:00
roymondchen
27b2c2c685 feat(editor): 历史记录支持操作来源 2026-06-04 16:08:52 +08:00
roymondchen
a8a9cf372d chore: update lockfile v1.8.0-beta.3 2026-06-04 14:13:01 +08:00
roymondchen
6253d7ed23 chore: release v1.8.0-beta.3 2026-06-04 14:12:13 +08:00
roymondchen
444d4223a9 feat(stage): 非点击画布选中组件时高亮闪烁选中区域
从图层树、面包屑等外部选中组件时,在画布上对选中区域做一次紫色高亮闪烁,
帮助用户快速定位组件;选中页面不触发。支持通过 editor 的 disabledFlashTip 关闭。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-04 14:02:57 +08:00
roymondchen
a9e9e65f9c feat(editor): 历史记录列表展示时间并优化回滚差异弹窗
为历史步骤自动写入 timestamp 并按当天/跨天格式化展示;回滚确认弹窗区分标题与说明,关闭时清理确认回调。
2026-06-03 18:09:21 +08:00
roymondchen
42162f2e4a feat(editor): 历史记录差异对比弹窗关闭时派发 close 事件
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 19:56:34 +08:00
roymondchen
7a161cab00 refactor(editor): 历史记录数据源/代码块 tab 复用通用 BucketTab 2026-06-02 19:07:38 +08:00
roymondchen
1cd69b33fe feat(editor): 对比表单支持自定义 loadConfig 加载逻辑
将 CompareCategory 等类型抽取到 type.ts,
新增 CompareFormLoadConfig 支持外部接管表单配置加载,
HistoryDiffDialog 透传 loadConfig 并支持 width 配置及对外导出。
2026-06-02 17:03:27 +08:00
roymondchen
12069e0937 feat(form): submitForm 支持返回 changeRecords
新增 returnChangeRecords 选项,开启后 resolve { values, changeRecords },
便于命令式调用时获取表单变更记录,并同步更新文档与单测。
2026-06-02 16:43:07 +08:00
roymondchen
1b66ab1b88 refactor(editor): 抽取 serializeConfig 工具统一序列化配置
将分散在 CodeLink、CodeEditor 及 playground 中重复的 serialize-javascript
序列化逻辑收敛为 @editor/utils/editor 的 serializeConfig 并对外导出复用。
2026-06-02 16:34:23 +08:00
roymondchen
64d35d5363 fix(form): 对比模式下无 name 字段时不展示差异
避免 name 为空时拿整个 model/lastValues 做对比导致误判

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 16:28:08 +08:00
roymondchen
35fc394199 feat(form): fieldset legend 支持函数动态生成标题 2026-06-02 14:24:09 +08:00
roymondchen
8612311db1 feat(editor): 历史记录面板支持自定义扩展 tab 并开放 Bucket/goto 配置
新增 historyListExtraTabs 配置,可在内置页面/数据源/代码块 tab 后追加业务自定义历史 tab。
导出 HistoryListBucket 供复用,GroupRow 支持配置是否允许跳转,Bucket 支持配置是否展示初始项。
2026-06-01 19:21:36 +08:00
roymondchen
818b41f07f chore: update lockfile v1.8.0-beta.2 2026-05-29 18:56:40 +08:00
roymondchen
9b34124805 chore: release v1.8.0-beta.2 2026-05-29 18:55:38 +08:00
roymondchen
7a61a35664 fix(editor): 显式标注 CompareForm 的 defineExpose 类型以修复 DTS 构建报错
defineExpose 同时暴露 MForm 实例 ref 与递归的 FormConfig ref,导致
vue-tsc 生成声明文件时推断类型过大无法序列化(TS7056)。改为显式标注
暴露类型,使其引用具名别名而非展开完整结构。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 18:53:08 +08:00
roymondchen
025cca365c perf(dep): 依赖收集改为单次遍历批量处理多 target
将 collectItems/removeTargetsDep 改为整棵树只遍历一次、在每个属性上检查所有
target,把结构遍历开销从 ×targets 降到 ×1,收集结果保持一致。

同时修正 dataSourceMethodDeps 字段命名并补充到 MApp schema。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 17:55:13 +08:00
roymondchen
a3333e2b4e feat(editor): 新增 hideSidebar 配置支持隐藏左侧面板
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 16:49:10 +08:00
roymondchen
cbc4b25072 feat(editor): 字段对比模式逐项展示差异并补充历史记录面板文档
- CodeSelect/CodeSelectCol/EventSelect/DataSource 等复合字段在对比模式下
  按索引对齐前后值,逐项展示新增/删除/修改高亮,并隐藏写操作按钮
- form 容器/列表/表格支持对比模式只读展示
- 新增「历史记录面板」指南文档,完善表单对比文档及 menu props 说明
- 补充相关单元测试

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 15:51:47 +08:00
roymondchen
b02aa75ddc feat(editor): 历史记录面板支持单步回滚(类 git revert)
将目标历史步骤的修改作为一次新操作反向应用,不破坏原有栈结构,
page/dataSource/codeBlock 三类 service 均提供 revert 能力;
面板新增关闭按钮、步骤编号展示与合并组卡片样式优化。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 14:19:44 +08:00
roymondchen
f0c66427b8 feat: form 新增 showDiff prop 支持自定义对比判断
- form: MForm/Container 新增 showDiff prop,允许调用方自定义

  '是否展示对比内容' 的判断逻辑,并在嵌套 Container 中自动透传;

  不传时沿用默认的 isEqual 行为

- editor: CompareForm 利用该能力处理 code-select 字段中 '' 与

  { hookType: 'code', hookData: [] } 两种语义为空形态被 isEqual 误判为差异的问题

- docs: 补充 form-props.md 中 showDiff 的说明与示例

- test: 补充 Code 字段相关单测
2026-05-28 20:30:05 +08:00
roymondchen
c854dfa8bf feat(editor): vs-code 字段对比模式改用 monaco diff 编辑器
- Container.vue 新增「自接管对比」字段类型白名单(当前含 vs-code),命中时只渲染一次组件并透传 model/lastValues/isCompare,由字段内部展示差异
- Code.vue 在 isCompare 模式下切换到 type='diff',使用 monaco 内置 diff 视图替代两个独立编辑器实例
- CodeEditor.vue 补充对 modifiedValues 的 watch,避免 diff 模式下右侧值停留在初始快照
2026-05-28 20:12:46 +08:00
roymondchen
59f4e0edac feat(editor): 历史记录面板支持差异对比
- 新增 HistoryDiffDialog 历史差异对比弹窗
- 新增 CompareForm 表单对比组件
- 抽取 code-block 工具函数到 utils/code-block.ts
- 历史列表面板支持选择两个版本进行对比
2026-05-28 19:49:03 +08:00
roymondchen
0f8abf7298 fix: 对比模式下关闭 tab-pane 的 lazy,确保差异数能正确统计 2026-05-28 19:32:54 +08:00
roymondchen
62a2ee6693 feat(editor): 历史记录面板支持点击跳转与回到初始状态
- 单步组头部点击跳转到该步骤;合并组头部点击展开/收起,子步行点击跳转到具体步骤
- 列表底部新增「初始」记录项,可一键回到所有修改之前的状态
- editorService/dataSourceService/codeBlockService 新增 goto API;historyService 暴露 cursor 读取器
2026-05-28 18:52:11 +08:00
roymondchen
0446202ba6 feat(editor): 新增历史记录列表面板
- 新增 history-list 模块(面板、Tab、Bucket、GroupRow 与 composables)
- NavMenu 接入历史记录面板入口
- history/editor/codeBlock/dataSource service 配合面板能力调整
- utils/undo-redo 适配新面板
- 扩展 type.ts 相关类型定义
- 新增 history-list-panel.scss 并在 theme.scss 引入
- 补充 history-list 模块完整单元测试
- playground 同步小幅调整
2026-05-28 17:51:52 +08:00
roymondchen
285434ef3e feat(form): 支持自定义 label slot
在 MForm / Container 上新增具名作用域插槽 label,允许使用方自定义表单项标题渲染。
Slot 作用域参数:config、type、text、prop、disabled。
类型 FormLabelSlotProps / FormSlots 提取到 schema.ts 复用。
2026-05-28 16:45:11 +08:00
roymondchen
8dae67769c feat(editor): 数据源与代码块 service 支持 undo/redo
- dataSourceService / codeBlockService 新增 undo / redo / canUndo / canRedo 方法
- undo/redo 内部复用 add / update / remove / setCodeDslByIdSync / deleteCodeDslByIds 写回,
  并强制 doNotPushHistory,借此自动驱动 initService 中的依赖收集链路
  (DepTargetType.DATA_SOURCE / DATA_SOURCE_COND / DATA_SOURCE_METHOD / CODE_BLOCK)
- 更新场景下若 step 带 changeRecords,按 propPath 局部 patch,不冲掉同节点其它无关变更;
  缺省退化为整 schema / 整内容替换
- 补充对应单测与 API 文档
2026-05-28 16:40:49 +08:00
roymondchen
09558fa027 feat(editor): 历史记录接入 changeRecords,undo/redo 按 propPath 局部更新
- 节点 / 数据源 / 代码块的 history step 增加 changeRecords 字段

- editor.update / dataSource.update / codeBlock.setCodeDslById(Sync) 透传 changeRecords 入历史

- applyHistoryOp 的 update 分支:携带 changeRecords 时,按 propPath 从 oldNode/newNode 取值

  构造最小 patch 走 update,不冲掉同节点上其它无关变更;缺省退化为整节点替换

  (覆盖 sort/moveLayer/拖动等纯快照场景)

- editor.update 增加 changeRecordList 形参,多节点场景每个节点单独保留 records;

  use-stage 多选拖动 / 缩放改用 changeRecordList,避免 records 在多节点间共享

- use-code-block-edit.submitCodeBlockHandler 透传 form changeRecords

- 同步更新 editor / dataSource / codeBlock / history service 文档
2026-05-28 16:28:35 +08:00
roymondchen
4c855ba50b feat(editor): 写操作支持 doNotPushHistory 选项以跳过历史记录
- editor/codeBlock/dataSource 的 add/update/delete 等接口新增 doNotPushHistory 选项
- 移除不再使用的 editor-history 工具及其单测
- 修复 layer 节点状态在重建时丢失已有 status 的问题
- 同步更新 service 方法文档,新增 dragto 复现用例
2026-05-28 16:03:29 +08:00
roymondchen
e2c065f90d feat(editor): 代码块与数据源支持按 id 独立的历史记录
- history service 新增 pushCodeBlock/undoCodeBlock/redoCodeBlock
  /canUndoCodeBlock/canRedoCodeBlock 及数据源对称 API
- 按 id 维度各自维护独立 UndoRedo 栈,与页面/节点历史完全解耦
- type 新增 CodeBlockStepValue / DataSourceStepValue 独立类型
- HistoryState 扩展 codeBlockState / dataSourceState 字段
- codeBlockService.setCodeDslByIdSync / deleteCodeDslByIds 自动入历史
- dataSourceService.add / update / remove 自动入历史
- 入栈成功时 emit code-block-history-change / data-source-history-change
- 补充单测共 21 例,更新 history/codeBlock/dataSource 相关文档
2026-05-27 19:50:17 +08:00
roymondchen
a341c7d73e fix(editor): 多选时对多个节点的操作合并入同一条历史记录
- moveToContainer 支持数组形参,多选移动整批只产生一条历史记录

- use-stage 拖动多选元素入容器 / 多选拖动缩放整批合成一次调用

- 右键移动至改走 moveToContainer,避免 remove+add 切成两条历史

- 跳过选中目标节点的分支清理 state.nodes 残留旧引用

- history.push 新增可选 pageId 参数,跨页操作正确落到目标页栈

- pushOpHistory 显式按 step.data.id 入栈,避免跨页操作错配
2026-05-27 19:09:34 +08:00
roymondchen
de94a75803 refactor(editor): 移除 BaseService 废弃的 use/middleware 机制
- 删除已 @deprecated 的 BaseService.use 方法及其 middleware 通道

- 删除 utils/compose.ts 及对应测试(仅服务于 middleware,无其他引用)

- editor.ts 移除 safeOptions/safeParent 兜底,相关方法 options 改用形参默认值

- props.ts fillConfig 的 labelWidth 改为形参默认值,移除 typeof function 兜底

- 同步更新 5 份 service 方法文档,删除 ## use 章节
2026-05-27 18:55:38 +08:00
roymondchen
d01a28ce76 fix(editor): 修复移动到菜单导致节点引用异常的问题 2026-05-27 17:17:43 +08:00
325 changed files with 28897 additions and 5137 deletions

1
.gitignore vendored
View File

@ -20,6 +20,7 @@ pnpm-debug.log*
# Editor directories and files # Editor directories and files
.idea .idea
.vscode .vscode
.codebuddy
*.suo *.suo
*.ntvs* *.ntvs*
*.njsproj *.njsproj

View File

@ -14,12 +14,13 @@ TMagic Editor 是魔方平台的可视化编辑器核心库,提供拖拽式组
## 架构地图 ## 架构地图
关键目录: 关键目录:
- `packages/` — 核心编辑器包202 *.vue, 194 *.ts
- `packages/` — 核心编辑器包
- `runtime/` — Vue/React Runtime 实现 - `runtime/` — Vue/React Runtime 实现
- `vue-components/` — Vue 组件封装 - `vue-components/` — Vue 组件封装
- `react-components/` — React 组件封装 - `react-components/` — React 组件封装
- `playground/` — 演示 playground - `playground/` — 演示 playground
- `docs/` — VitePress 文档100 *.md - `docs/` — VitePress 文档
- `scripts/` — 构建和发布脚本 - `scripts/` — 构建和发布脚本
- `eslint-config/` — 共享 ESLint 配置 - `eslint-config/` — 共享 ESLint 配置
@ -27,10 +28,13 @@ TMagic Editor 是魔方平台的可视化编辑器核心库,提供拖拽式组
**分支策略:** dev=dev, test/prod=master **分支策略:** dev=dev, test/prod=master
**提交规范:** commitlint + husky`type: 描述` **提交规范:** commitlint + husky`type: 描述`
**测试覆盖率:** 新增或修改的代码必须补充单元测试,覆盖率不低于 85%
**禁止事项:** **禁止事项:**
- 禁止在核心包中引入腾讯内部专有依赖(开源项目) - 禁止在核心包中引入腾讯内部专有依赖(开源项目)
- 禁止直接修改 CHANGELOG.md应通过 `pnpm changelog` 生成 - 禁止直接修改 CHANGELOG.md应通过 `pnpm changelog` 生成
- 禁止提交未达 85% 测试覆盖率的新增/修改代码
## 常用命令 ## 常用命令
@ -50,7 +54,7 @@ TMagic Editor 是魔方平台的可视化编辑器核心库,提供拖拽式组
## 深入阅读 ## 深入阅读
| 文档 | 说明 | | 文档 | 说明 |
|------|------| | --------------- | ---------------- |
| docs/ | VitePress 文档站 | | docs/ | VitePress 文档站 |
| CONTRIBUTING.md | 贡献指南 | | CONTRIBUTING.md | 贡献指南 |
| CHANGELOG.md | 变更日志 | | CHANGELOG.md | 变更日志 |

View File

@ -1,3 +1,181 @@
# [1.8.0-beta.11](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.10...v1.8.0-beta.11) (2026-06-29)
### Features
* **editor:** support custom width and initial diff mode for history diff dialog ([83f4e52](https://github.com/Tencent/tmagic-editor/commit/83f4e528450be3971eea25b59dab126e04ac4df4))
* **form:** add debug mode to submitForm ([4330738](https://github.com/Tencent/tmagic-editor/commit/4330738b9f3d91c728826f5a74129cf1febbcf48))
# [1.8.0-beta.10](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.9...v1.8.0-beta.10) (2026-06-26)
### Bug Fixes
* **vue-runtime-help:** handle remove when root is not initialized ([af19736](https://github.com/Tencent/tmagic-editor/commit/af197363cfaa5c555758c19354a0b3a5031b973e))
### Features
* **editor:** add unified change events ([7bbb1f2](https://github.com/Tencent/tmagic-editor/commit/7bbb1f24c0f7180f301f573de1b916bfd0a35152))
* **editor:** refine history diff defaults ([f7afed6](https://github.com/Tencent/tmagic-editor/commit/f7afed66aaa8f57cdde02f0e25cca1dab825e7c0))
* **form:** support useFieldTextInError option ([fd359e4](https://github.com/Tencent/tmagic-editor/commit/fd359e493fdf205126957799a4a228f31267f3c2))
# [1.8.0-beta.9](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.8...v1.8.0-beta.9) (2026-06-25)
### Features
* **editor:** 优化历史记录对比与回滚流程 ([ce65b18](https://github.com/Tencent/tmagic-editor/commit/ce65b18dbb2976db484ab35a98479858b4c426e4))
* 导出 componentListService 和 keybindingService ([40acb5b](https://github.com/Tencent/tmagic-editor/commit/40acb5b34cb3b492bc5234c75bde4fbf8e787be2))
# [1.8.0-beta.8](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.7...v1.8.0-beta.8) (2026-06-23)
### Bug Fixes
* **playground:** 调整初始化时序避免历史恢复被覆盖 ([bfdaf2b](https://github.com/Tencent/tmagic-editor/commit/bfdaf2b244dfe7387cac5b399a84ccd614201e73))
### Features
* **editor:** 历史记录支持展示操作人 ([1ade61d](https://github.com/Tencent/tmagic-editor/commit/1ade61d62e61c86fcff2033a3dd57c533ce4241c))
# [1.8.0-beta.7](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.6...v1.8.0-beta.7) (2026-06-17)
### Bug Fixes
* **editor:** sidebar 侧栏项 key 与 SideItemKey 常量对齐 ([8933c46](https://github.com/Tencent/tmagic-editor/commit/8933c46b73525aa2aeca81aeea88610539a218d9))
* **editor:** 修复历史记录面板分组与展示逻辑 ([bbf79fd](https://github.com/Tencent/tmagic-editor/commit/bbf79fd6df505351bc28d63bea1a5c0cd16a5984))
* **editor:** 恢复新增组件在当前视窗中垂直居中 ([24b9b34](https://github.com/Tencent/tmagic-editor/commit/24b9b34f6569ed671edaf4e9f14622597688d72c))
* **editor:** 数据源配置面板默认激活「数据定义」tab ([95769d6](https://github.com/Tencent/tmagic-editor/commit/95769d6ae05d6171366ad5995f6e8ce79491d5cd))
# [1.8.0-beta.6](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.5...v1.8.0-beta.6) (2026-06-15)
### Bug Fixes
* **editor:** 仅在使用 left/top 定位时修正节点位置 ([27fac02](https://github.com/Tencent/tmagic-editor/commit/27fac02e994b69417622d009cb69037d99eef10a))
* **editor:** 完善 fixed 与 absolute 定位切换逻辑 ([1298104](https://github.com/Tencent/tmagic-editor/commit/1298104732de1074ecc1398777459dd2fcbb74f7))
* **playground:** 修复历史恢复后加载 DSL 时缺少页面基线记录 ([4a82891](https://github.com/Tencent/tmagic-editor/commit/4a8289137b539a6597d1b978418bb9901392e5c3))
### Features
* **editor:** 增强 *AndGetHistoryId 与 revertById 的 historyIds 能力 ([6960bd5](https://github.com/Tencent/tmagic-editor/commit/6960bd50e16fe612e486eb78af7630642f5e6c8f))
* **editor:** 数据源与代码块历史记录不再合并相邻操作 ([89cef4e](https://github.com/Tencent/tmagic-editor/commit/89cef4e9a9b1ffb11ab72c33e8b283bf59377f47))
* **editor:** 查看/编辑时自动切换 sidebar 并定位到对应配置 ([ffcc734](https://github.com/Tencent/tmagic-editor/commit/ffcc7341021da525263819cb6559cf20c2afea6a))
* **editor:** 边框方向有配置时显示高亮状态 ([b35132e](https://github.com/Tencent/tmagic-editor/commit/b35132e93eba6136990ba82912e53887c17c0cc1))
# [1.8.0-beta.5](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.4...v1.8.0-beta.5) (2026-06-11)
### Bug Fixes
* **editor:** 优化历史回滚确认流程 ([48519b0](https://github.com/Tencent/tmagic-editor/commit/48519b0155a7cda8226217fa3bfd97a92410a7a6))
* **editor:** 修复历史对比属性配置上下文缺失 ([be3a900](https://github.com/Tencent/tmagic-editor/commit/be3a900e6a132751f3b1d59c06b850c00604ee15))
* **stage:** 复用 TargetShadow 修正闪烁高亮定位 ([171d31e](https://github.com/Tencent/tmagic-editor/commit/171d31e20797ab0e68ac8b2a4c39740e1f636634))
### Features
* **design:** popover 支持点击外部关闭 ([846f05e](https://github.com/Tencent/tmagic-editor/commit/846f05e04d6d85d37611148185eae93661e9d0da))
* **editor:** 将侧边栏激活面板状态同步至 uiService ([6ba59c0](https://github.com/Tencent/tmagic-editor/commit/6ba59c0d141947727c83bc708c9fb7fc6b71a47f))
* **editor:** 支持历史记录持久化 ([614f12a](https://github.com/Tencent/tmagic-editor/commit/614f12adf3174a4dadac028bda27057d18831a81))
* **editor:** 支持按历史记录 uuid 回滚 ([bddc6f3](https://github.com/Tencent/tmagic-editor/commit/bddc6f343cc97d3034c869c3fc46780759134f7c))
* **editor:** 支持页面初始基线与 root 变更历史记录 ([4f284e8](https://github.com/Tencent/tmagic-editor/commit/4f284e8d9cf6af9af234d345c14a2bf9176e5284))
* **editor:** 页面删除前增加确认弹窗并支持危险样式按钮 ([113af7d](https://github.com/Tencent/tmagic-editor/commit/113af7dd5104f5f49515abd66f12f5e62098f7e2))
* **editor:** 页面历史记录点击选中对应画布节点 ([fd652b0](https://github.com/Tencent/tmagic-editor/commit/fd652b0d13a2bf87db55d03013dc2c9ff01ff45d))
### Performance Improvements
* **editor:** 优化节点信息查找性能 ([c4ec2c5](https://github.com/Tencent/tmagic-editor/commit/c4ec2c5c722963c95141ac2d2ddf94d952d2e47d))
# [1.8.0-beta.4](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.3...v1.8.0-beta.4) (2026-06-04)
### Bug Fixes
* **editor:** 修复历史对比样式配置显示 ([cd19dec](https://github.com/Tencent/tmagic-editor/commit/cd19dec7907cac5cff775f1cbde24cb3f384e87b))
* **editor:** 修复合并历史记录信息展示 ([3bd0eec](https://github.com/Tencent/tmagic-editor/commit/3bd0eecb42d06f06f50cc4736ecc31cc07cc1886))
* **editor:** 禁止缺少变更记录的历史回滚 ([10b70c3](https://github.com/Tencent/tmagic-editor/commit/10b70c36bbace6af48bf6fa63f2df0704c6861af))
### Features
* **editor:** 历史记录支持操作来源 ([27b2c2c](https://github.com/Tencent/tmagic-editor/commit/27b2c2c68598264e97a1e1ecc34121829851c85e))
# [1.8.0-beta.3](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.2...v1.8.0-beta.3) (2026-06-04)
### Bug Fixes
* **form:** 对比模式下无 name 字段时不展示差异 ([64d35d5](https://github.com/Tencent/tmagic-editor/commit/64d35d53631698e8d94362765a1621654bd3d1f6))
### Features
* **editor:** 历史记录列表展示时间并优化回滚差异弹窗 ([a9e9e65](https://github.com/Tencent/tmagic-editor/commit/a9e9e65f9c50e47b22de8eab7184cebd87632bc6))
* **editor:** 历史记录差异对比弹窗关闭时派发 close 事件 ([42162f2](https://github.com/Tencent/tmagic-editor/commit/42162f2e4ac651ad78ff2f5291e00639a658a1ae))
* **editor:** 历史记录面板支持自定义扩展 tab 并开放 Bucket/goto 配置 ([8612311](https://github.com/Tencent/tmagic-editor/commit/8612311db12a22adcc30188ae1ead03729fa6a7a))
* **editor:** 对比表单支持自定义 loadConfig 加载逻辑 ([1cd69b3](https://github.com/Tencent/tmagic-editor/commit/1cd69b33fecd75fe8522d9a261e1c03e806ecf69))
* **form:** fieldset legend 支持函数动态生成标题 ([35fc394](https://github.com/Tencent/tmagic-editor/commit/35fc39419902e14e2d5bdf98f99802f05a4b5934))
* **form:** submitForm 支持返回 changeRecords ([12069e0](https://github.com/Tencent/tmagic-editor/commit/12069e0937589cf9b7684e4bd5ed927e15462513))
* **stage:** 非点击画布选中组件时高亮闪烁选中区域 ([444d422](https://github.com/Tencent/tmagic-editor/commit/444d4223a943d763a33b752ffbbfa704591820ca))
# [1.8.0-beta.2](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.1...v1.8.0-beta.2) (2026-05-29)
### Bug Fixes
* **editor:** 修复移动到菜单导致节点引用异常的问题 ([d01a28c](https://github.com/Tencent/tmagic-editor/commit/d01a28ce76203765f333548b30b4ec2954e68d4c))
* **editor:** 多选时对多个节点的操作合并入同一条历史记录 ([a341c7d](https://github.com/Tencent/tmagic-editor/commit/a341c7d73e78f0727c1adffce767b6806d356beb))
* **editor:** 显式标注 CompareForm 的 defineExpose 类型以修复 DTS 构建报错 ([7a61a35](https://github.com/Tencent/tmagic-editor/commit/7a61a356649838531f4f51c45e2e76ab84474107))
* 对比模式下关闭 tab-pane 的 lazy确保差异数能正确统计 ([0f8abf7](https://github.com/Tencent/tmagic-editor/commit/0f8abf729854f5bfc3fbad98153a77e947ead246))
### Features
* **editor:** vs-code 字段对比模式改用 monaco diff 编辑器 ([c854dfa](https://github.com/Tencent/tmagic-editor/commit/c854dfa8bf80bd501534b98c72fa1b2802076cac))
* **editor:** 代码块与数据源支持按 id 独立的历史记录 ([e2c065f](https://github.com/Tencent/tmagic-editor/commit/e2c065f90d12d1234edd3620430262857a014ee9))
* **editor:** 写操作支持 doNotPushHistory 选项以跳过历史记录 ([4c855ba](https://github.com/Tencent/tmagic-editor/commit/4c855ba50b69a2e0ab73f944171c4d5561d5a06a))
* **editor:** 历史记录接入 changeRecordsundo/redo 按 propPath 局部更新 ([09558fa](https://github.com/Tencent/tmagic-editor/commit/09558fa0273af0b7d25b4338a8ea56810b09bb1c))
* **editor:** 历史记录面板支持单步回滚(类 git revert ([b02aa75](https://github.com/Tencent/tmagic-editor/commit/b02aa75ddc2b37a024a8966ddad96cf8d85317bb))
* **editor:** 历史记录面板支持差异对比 ([59f4e0e](https://github.com/Tencent/tmagic-editor/commit/59f4e0edac47e986a83a3f9b7862cf92650b7fee))
* **editor:** 历史记录面板支持点击跳转与回到初始状态 ([62a2ee6](https://github.com/Tencent/tmagic-editor/commit/62a2ee66931caed51f86bf170c3bce96c7e40dea))
* **editor:** 字段对比模式逐项展示差异并补充历史记录面板文档 ([cbc4b25](https://github.com/Tencent/tmagic-editor/commit/cbc4b25072542d98f19707a11b87be0295157216))
* **editor:** 数据源与代码块 service 支持 undo/redo ([8dae677](https://github.com/Tencent/tmagic-editor/commit/8dae67769c32dbf65413d47ac56ca46e65eaeecf))
* **editor:** 新增 hideSidebar 配置支持隐藏左侧面板 ([a3333e2](https://github.com/Tencent/tmagic-editor/commit/a3333e2b4e0f05b2f83c9dc539466ebd31c04250))
* **editor:** 新增历史记录列表面板 ([0446202](https://github.com/Tencent/tmagic-editor/commit/0446202ba6aaf0c99265b367343c7a4d1a8201e9))
* form 新增 showDiff prop 支持自定义对比判断 ([f0c6642](https://github.com/Tencent/tmagic-editor/commit/f0c66427b8e011252110a11c90a109f5f58d3101))
* **form:** 支持自定义 label slot ([285434e](https://github.com/Tencent/tmagic-editor/commit/285434ef3effd94c51d3ed10198842f6e689046a))
### Performance Improvements
* **dep:** 依赖收集改为单次遍历批量处理多 target ([025cca3](https://github.com/Tencent/tmagic-editor/commit/025cca365c87d755abfc047786ac9a75758019f5))
# [1.8.0-beta.1](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.0...v1.8.0-beta.1) (2026-05-27) # [1.8.0-beta.1](https://github.com/Tencent/tmagic-editor/compare/v1.8.0-beta.0...v1.8.0-beta.1) (2026-05-27)

View File

@ -102,11 +102,19 @@ export default defineConfig({
text: '数据源', text: '数据源',
link: '/guide/advanced/data-source.md' link: '/guide/advanced/data-source.md'
}, },
{
text: '历史记录面板',
link: '/guide/advanced/history-list.md',
},
{ {
text: '@tmagic/form', text: '@tmagic/form',
link: '/guide/advanced/tmagic-form.md', link: '/guide/advanced/tmagic-form.md',
}, },
{
text: '属性配置表单校验联动',
link: '/guide/advanced/prop-form-validate.md',
},
], ],
}, },
{ {
@ -197,8 +205,17 @@ export default defineConfig({
}, },
{ {
text: 'uiService', text: 'uiService',
items: [
{
text: '方法',
link: '/api/editor/uiServiceMethods.md', link: '/api/editor/uiServiceMethods.md',
}, },
{
text: '事件',
link: '/api/editor/uiServiceEvents.md',
},
],
},
{ {
text: 'codeBlockService', text: 'codeBlockService',
link: '/api/editor/codeBlockServiceMethods.md', link: '/api/editor/codeBlockServiceMethods.md',
@ -475,6 +492,15 @@ export default defineConfig({
} }
] ]
}, },
{
text: '表单校验',
items: [
{
text: '表单校验',
link: '/form-config/rules.md',
}
]
},
{ {
text: '表单对比', text: '表单对比',
items: [ items: [

View File

@ -1,5 +1,8 @@
# codeBlockService方法 # codeBlockService方法
写入历史栈的方法([setCodeDslById](#setcodedslbyid)、[setCodeDslByIdSync](#setcodedslbyidsync)、[deleteCodeDslByIds](#deletecodedslbyids) 等)的 `options` 支持
[historyDescription / historySource](./editorServiceMethods.md#历史记录相关-options),会透传到 `historyService.push('codeBlock', step, id)` 入栈记录的 `historyDescription` / `source` 字段。
## setCodeDsl ## setCodeDsl
- **参数:** - **参数:**
@ -48,6 +51,15 @@
- **参数:** - **参数:**
- `{string | number}` id 代码块id - `{string | number}` id 代码块id
- {Partial<`CodeBlockContent`>} codeConfig 代码块内容配置信息 - {Partial<`CodeBlockContent`>} codeConfig 代码块内容配置信息
- `{Object}` options 可选配置
- {`ChangeRecord`[]} changeRecords form 端变更记录,用于历史记录的精细化撤销/重做
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
::: details 查看 ChangeRecord 类型定义
<<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts}
:::
- **返回:** - **返回:**
- `{Promise<void>}` - `{Promise<void>}`
@ -62,6 +74,11 @@
- `{string | number}` id 代码块id - `{string | number}` id 代码块id
- {Partial<`CodeBlockContent`>} codeConfig 代码块内容配置信息 - {Partial<`CodeBlockContent`>} codeConfig 代码块内容配置信息
- `{boolean}` force 是否强制写入,默认 `true`;为 `false` 时若同 id 已存在则跳过 - `{boolean}` force 是否强制写入,默认 `true`;为 `false` 时若同 id 已存在则跳过
- `{Object}` options 可选配置
- {`ChangeRecord`[]} changeRecords form 端变更记录,用于历史记录的精细化撤销/重做
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- **返回:** - **返回:**
- `{void}` - `{void}`
@ -70,6 +87,13 @@
同步版本的 [setCodeDslById](#setcodedslbyid),并会触发 `addOrUpdate` 事件 同步版本的 [setCodeDslById](#setcodedslbyid),并会触发 `addOrUpdate` 事件
::: tip
写入成功时(`force=false` 且同 id 已存在的跳过场景除外)会自动调用 `historyService.push('codeBlock', step, id)`
把本次变更入历史栈,参见 [historyService.push](./historyServiceMethods.md#push)。
传入的 `changeRecords` 会一同写进 step撤销/重做时调用方可据此按 `propPath` 局部回放。
传入 `doNotPushHistory: true` 可跳过写入历史栈,常用于批量导入、外部同步等非用户操作场景。
:::
## getCodeDslByIds ## getCodeDslByIds
- **参数:** - **参数:**
@ -194,6 +218,10 @@
- **参数:** - **参数:**
- `{(string | number)[]}` codeIds 需要删除的代码块id数组 - `{(string | number)[]}` codeIds 需要删除的代码块id数组
- `{Object}` options 可选配置
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- **返回:** - **返回:**
- `{Promise<void>}` - `{Promise<void>}`
@ -202,6 +230,160 @@
在dsl数据源中删除指定id的代码块每删除一个会触发一次 `remove` 事件 在dsl数据源中删除指定id的代码块每删除一个会触发一次 `remove` 事件
::: tip
对每个实际存在并被删除的代码块,会自动调用 `historyService.push('codeBlock', step, id)` 入栈一条
`newSchema=null` 的删除记录;不存在的 id 不会入历史。传入 `doNotPushHistory: true` 也可显式跳过写入历史栈。
:::
## setCodeDslByIdAndGetHistoryId
- **参数:** 同 [setCodeDslById](#setcodedslbyid)
- **返回:**
- {`Promise<`[`DslOpWithHistoryIdsResult<void>`](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)`>`}
- `historyIds`:本次写入历史记录的 uuid 列表;未写入历史(`doNotPushHistory: true` 等)时为 `[]`
- **详情:**
与 [setCodeDslById](#setcodedslbyid) 行为完全一致,并在返回值中额外提供 `historyIds`,可用于精确引用 / 定位该条历史记录。
参见 [editorService 历史记录 uuid 与 \*AndGetHistoryId](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)。
- **示例:**
```js
import { codeBlockService } from "@tmagic/editor";
const { historyIds } = await codeBlockService.setCodeDslByIdAndGetHistoryId("code_1234", {
name: "代码块1",
content: "() => {}",
});
console.log(historyIds); // 本次变更对应的历史记录 uuid 列表,或 []
```
## setCodeDslByIdSyncAndGetHistoryId
- **参数:** 同 [setCodeDslByIdSync](#setcodedslbyidsync)
- **返回:**
- {[`DslOpWithHistoryIdsResult<void>`](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)}
- `historyIds`:本次写入历史记录的 uuid 列表;未写入历史(`doNotPushHistory: true`、或 `force=false` 跳过等)时为 `[]`
- **详情:**
与 [setCodeDslByIdSync](#setcodedslbyidsync) 行为完全一致(同步),并在返回值中额外提供 `historyIds`
## deleteCodeDslByIdsAndGetHistoryId
- **参数:** 同 [deleteCodeDslByIds](#deletecodedslbyids)
- **返回:**
- {`Promise<`[`DslOpWithHistoryIdsResult<void>`](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)`>`}
- `historyIds`:本次写入的全部历史记录 uuid按删除顺序未写入任何历史时为 `[]`
- **详情:**
与 [deleteCodeDslByIds](#deletecodedslbyids) 行为完全一致。由于一次可删除多个代码块、会产生多条历史记录,因此使用 `historyIds` 数组(每条删除记录一个 uuid不存在的 id 不会入历史,也不会出现在 `historyIds` 中。
- **示例:**
```js
import { codeBlockService } from "@tmagic/editor";
const { historyIds } = await codeBlockService.deleteCodeDslByIdsAndGetHistoryId(["code_1", "code_2"]);
console.log(historyIds); // ['xxxx', 'yyyy'],或 []
```
## revertById
- **参数:**
- `{string[]}` uuids 目标历史记录的 uuid 列表(通常由 [setCodeDslByIdAndGetHistoryId](#setcodedslbyidandgethistoryid) 等方法返回的 `historyIds`
- **返回:**
- {`Promise<(`CodeBlockStepValue` | null)[]>`} 与入参同序的回滚结果列表,某项失败时为 `null`
- **详情:**
通过历史记录 uuid「回滚」代码块历史步骤类 git revert 语义),语义同按 `(id, index)` 回滚,
仅无需调用方再传 `codeBlockId``index`。**按数组顺序依次回滚**。
参见 [editorService 历史记录 uuid 与 \*AndGetHistoryId](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)。
- **示例:**
```js
import { codeBlockService } from "@tmagic/editor";
const { historyIds } = await codeBlockService.setCodeDslByIdAndGetHistoryId("code_1234", { name: "代码块1" });
if (historyIds.length) {
await codeBlockService.revertById(historyIds);
}
```
## undo
- **参数:**
- `{Id}` id 代码块id
- **返回:**
- `{Promise<CodeBlockStepValue | null>}` 撤销的 step栈不存在或已无可撤销时返回 `null`
- **详情:**
撤销指定代码块的最近一次变更。内部根据 [historyService](./historyServiceMethods.md) 取出 step 后,
复用 [setCodeDslByIdSync](#setcodedslbyidsync) / [deleteCodeDslByIds](#deletecodedslbyids) 写回,
并自动带上 `doNotPushHistory: true`,确保不会再次入栈。
写回会触发对应的 `addOrUpdate` / `remove` 事件,编辑器内部据此重新维护
`DepTargetType.CODE_BLOCK` 的 dep target无需调用方额外处理。
对于带有 `changeRecords` 的更新 step会按 `propPath` 局部 patch 当前代码块内容;缺省才退化为整内容替换,
避免冲掉同代码块上的其它无关变更。
- **示例:**
```js
import { codeBlockService } from "@tmagic/editor";
if (codeBlockService.canUndo("code_1234")) {
await codeBlockService.undo("code_1234");
}
```
## redo
- **参数:**
- `{Id}` id 代码块id
- **返回:**
- `{Promise<CodeBlockStepValue | null>}` 重做的 step栈不存在或已无可重做时返回 `null`
- **详情:**
重做指定代码块的下一次变更。其它行为同 [undo](#undo)。
## canUndo
- **参数:**
- `{Id}` id 代码块id
- **返回:**
- `{boolean}`
- **详情:**
当前指定代码块是否可撤销,等价于 `historyService.canUndo('codeBlock', id)`
## canRedo
- **参数:**
- `{Id}` id 代码块id
- **返回:**
- `{boolean}`
- **详情:**
当前指定代码块是否可重做,等价于 `historyService.canRedo('codeBlock', id)`
## setParamsColConfig ## setParamsColConfig
- **参数:** - **参数:**
@ -288,15 +470,11 @@
销毁 codeBlockService重置状态并移除所有事件监听和插件 销毁 codeBlockService重置状态并移除所有事件监听和插件
## use
使用中间件的方式扩展方法,上述方法中标记有`扩展支持: 是`的方法都支持使用use扩展
## usePlugin ## usePlugin
- **详情:** - **详情:**
相对于[use](#use), usePlugin支持更加灵活更加细致的扩展, 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展 usePlugin支持灵活细致的扩展, 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展
每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值 每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值

View File

@ -298,6 +298,10 @@ dataSourceService.setFormMethod("http", [
- **参数:** - **参数:**
- {`DataSourceSchema`} config 数据源配置 - {`DataSourceSchema`} config 数据源配置
- `{Object}` options 可选配置
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- **返回:** - **返回:**
- {`DataSourceSchema`} 添加后的数据源配置 - {`DataSourceSchema`} 添加后的数据源配置
@ -306,6 +310,12 @@ dataSourceService.setFormMethod("http", [
添加一个数据源如果配置中没有id或id已存在会自动生成新的id 添加一个数据源如果配置中没有id或id已存在会自动生成新的id
::: tip
添加成功会自动调用 `historyService.push('dataSource', step, id)` 入栈一条 `oldSchema=null` 的新增记录,
参见 [historyService.push](./historyServiceMethods.md#push)。
传入 `doNotPushHistory: true` 可跳过写入历史栈,常用于批量导入、外部同步等非用户操作场景。
:::
- **示例:** - **示例:**
```js ```js
@ -329,6 +339,9 @@ console.log(newDs.id); // 自动生成的id
- {`DataSourceSchema`} config 数据源配置 - {`DataSourceSchema`} config 数据源配置
- `{Object}` options 可选配置 - `{Object}` options 可选配置
- {`ChangeRecord`[]} changeRecords 变更记录 - {`ChangeRecord`[]} changeRecords 变更记录
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
::: details 查看 ChangeRecord 类型定义 ::: details 查看 ChangeRecord 类型定义
<<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts} <<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts}
@ -341,6 +354,12 @@ console.log(newDs.id); // 自动生成的id
更新数据源 更新数据源
::: tip
更新成功会自动调用 `historyService.push('dataSource', step, id)` 入栈一条 `oldSchema` / `newSchema`
均为对应 schema 的更新记录,传入的 `changeRecords` 也会一并写进 step撤销/重做时调用方可据此按
`propPath` 局部回放,缺省才退化为整 schema 替换。传入 `doNotPushHistory: true` 可跳过写入历史栈。
:::
- **示例:** - **示例:**
```js ```js
@ -362,6 +381,10 @@ console.log(updatedDs);
- **参数:** - **参数:**
- `{string}` id 数据源id - `{string}` id 数据源id
- `{Object}` options 可选配置
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
- **返回:** - **返回:**
- `{void}` - `{void}`
@ -370,6 +393,11 @@ console.log(updatedDs);
删除指定id的数据源 删除指定id的数据源
::: tip
对实际存在的数据源会自动调用 `historyService.push('dataSource', step, id)` 入栈一条 `newSchema=null`
的删除记录;不存在的 id 不会入历史。传入 `doNotPushHistory: true` 也可显式跳过写入历史栈。
:::
- **示例:** - **示例:**
```js ```js
@ -378,6 +406,84 @@ import { dataSourceService } from "@tmagic/editor";
dataSourceService.remove("ds_123"); dataSourceService.remove("ds_123");
``` ```
## addAndGetHistoryId
- **参数:** 同 [add](#add)
- **返回:**
- {[`DslOpWithHistoryIdsResult<DataSourceSchema>`](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)}
- `result`:同 [add](#add) 的返回值(新增的数据源配置)
- `historyIds`:本次写入历史记录的 uuid 列表;未写入历史(`doNotPushHistory: true` 等)时为 `[]`
- **详情:**
与 [add](#add) 行为完全一致,并在返回值中额外提供 `historyIds`,可用于精确引用 / 定位该条历史记录。
参见 [editorService 历史记录 uuid 与 \*AndGetHistoryId](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)。
- **示例:**
```js
import { dataSourceService } from "@tmagic/editor";
const { result, historyIds } = dataSourceService.addAndGetHistoryId({
type: "http",
title: "用户信息",
url: "/api/user",
});
console.log(result); // 新增的数据源配置
console.log(historyIds); // 本次新增对应的历史记录 uuid 列表,或 []
```
## updateAndGetHistoryId
- **参数:** 同 [update](#update)
- **返回:**
- {[`DslOpWithHistoryIdsResult<DataSourceSchema>`](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)}
- `result`:同 [update](#update) 的返回值(更新后的数据源配置)
- `historyIds`:本次写入历史记录的 uuid 列表;未写入历史时为 `[]`
- **详情:**
与 [update](#update) 行为完全一致,并在返回值中额外提供 `historyIds`
## removeAndGetHistoryId
- **参数:** 同 [remove](#remove)
- **返回:**
- {[`DslOpWithHistoryIdsResult<void>`](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)}
- `historyIds`:本次写入历史记录的 uuid 列表;删除的 id 不存在或未写入历史时为 `[]`
- **详情:**
与 [remove](#remove) 行为完全一致,并在返回值中额外提供 `historyIds`
## revertById
- **参数:**
- `{string[]}` uuids 目标历史记录的 uuid 列表(通常由 [addAndGetHistoryId](#addandgethistoryid) 等方法返回的 `historyIds`
- **返回:**
- {(`DataSourceStepValue` | null)[]} 与入参同序的回滚结果列表,某项失败时为 `null`
- **详情:**
通过历史记录 uuid「回滚」数据源历史步骤类 git revert 语义),语义同按 `(id, index)` 回滚,
仅无需调用方再传 `dataSourceId``index`。**按数组顺序依次回滚**。
参见 [editorService 历史记录 uuid 与 \*AndGetHistoryId](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)。
- **示例:**
```js
import { dataSourceService } from "@tmagic/editor";
const { historyIds } = dataSourceService.addAndGetHistoryId({ type: "http", title: "用户信息" });
if (historyIds.length) {
dataSourceService.revertById(historyIds);
}
```
## createId ## createId
- **[扩展支持](../../guide/editor-expand#行为扩展)** 是 - **[扩展支持](../../guide/editor-expand#行为扩展)** 是
@ -421,6 +527,72 @@ const ds = dataSourceService.getDataSourceById("ds_123");
console.log(ds); console.log(ds);
``` ```
## undo
- **参数:**
- `{Id}` id 数据源id
- **返回:**
- {`DataSourceStepValue` | null} 撤销的 step栈不存在或已无可撤销时返回 `null`
- **详情:**
撤销指定数据源的最近一次变更。内部根据 [historyService](./historyServiceMethods.md) 取出 step 后,
复用 [add](#add) / [update](#update) / [remove](#remove) 写回,并自动带上 `doNotPushHistory: true`
确保不会再次入栈。
写回会触发对应的 `add` / `update` / `remove` 事件,编辑器内部据此重新维护数据源相关的依赖收集
`DepTargetType.DATA_SOURCE` / `DATA_SOURCE_COND` / `DATA_SOURCE_METHOD`),无需调用方额外处理。
对于带有 `changeRecords` 的更新 step会按 `propPath` 局部 patch 当前数据源;缺省才退化为整 schema 替换,
避免冲掉同节点上的其它无关变更。
- **示例:**
```js
import { dataSourceService } from "@tmagic/editor";
if (dataSourceService.canUndo("ds_123")) {
dataSourceService.undo("ds_123");
}
```
## redo
- **参数:**
- `{Id}` id 数据源id
- **返回:**
- {`DataSourceStepValue` | null} 重做的 step栈不存在或已无可重做时返回 `null`
- **详情:**
重做指定数据源的下一次变更。其它行为同 [undo](#undo)。
## canUndo
- **参数:**
- `{Id}` id 数据源id
- **返回:**
- `{boolean}`
- **详情:**
当前指定数据源是否可撤销,等价于 `historyService.canUndo('dataSource', id)`
## canRedo
- **参数:**
- `{Id}` id 数据源id
- **返回:**
- `{boolean}`
- **详情:**
当前指定数据源是否可重做,等价于 `historyService.canRedo('dataSource', id)`
## copyWithRelated ## copyWithRelated
- **参数:** - **参数:**

View File

@ -87,3 +87,35 @@
- **详情:** 历史记录改变,[editorService.redo()editorService.undo()](./editorServiceMethods.md#undo)后触发 - **详情:** 历史记录改变,[editorService.redo()editorService.undo()](./editorServiceMethods.md#undo)后触发
- **事件回调函数:** `(data: MPage | MPageFragment) => void` - **事件回调函数:** `(data: MPage | MPageFragment) => void`
## change
- **详情:** DSL 发生变更后统一触发,免去分别监听 `add` / `remove` / `update` / `move-layer` / `drag-to`。在 [editorService.add()](./editorServiceMethods.md#add)、[editorService.remove()](./editorServiceMethods.md#remove)、[editorService.update()](./editorServiceMethods.md#update)、[editorService.moveLayer()](./editorServiceMethods.md#movelayer)、[editorService.dragTo()](./editorServiceMethods.md#dragto) 后触发。
回调参数 `event` 通过 `type` 区分操作类型,并携带本次变更的节点列表 `data`,每项包含变更的 `node` 及其所属的 `page`(可能为 `null`)。`move-layer` 额外携带层级偏移 `offset``drag-to` 额外携带目标位置 `targetIndex` / `targetParent`
::: warning 注意
撤销 / 重做(`undo` / `redo`)内部同样会经由 `add` / `remove` / `update` 触发本事件;如需区分「用户操作」与「撤销重做」,请配合 [history-change](#history-change) 事件判断。
:::
- **事件回调函数:** `(event: EditorChangeEvent) => void`
::: details 查看 EditorChangeEvent 类型定义
<<< @/../packages/editor/src/type.ts#EditorChangeEvent{ts}
:::
## invalid-node-change
- **详情:** 节点校验错误状态发生变化时触发(记录 / 清除错误、删除节点、整体替换 root、撤销重做还原错误标记等场景均会触发在 [editorService.setInvalidNode()](./editorServiceMethods.md#setinvalidnode)、[editorService.deleteInvalidNode()](./editorServiceMethods.md#deleteinvalidnode)、[editorService.resetInvalidNodeId()](./editorServiceMethods.md#resetinvalidnodeid) 及 DSL 操作 / 撤销重做内部调用后触发。
携带当前完整的错误 Map供非响应式消费方如自定义工具栏订阅实现组件树标红、保存拦截等。需响应式读取如组件树节点内容请直接读取 `editorService.get('invalidNodeIds')`
- **事件回调函数:** `(invalidNodeIds: Map<Id, NodeInvalidInfo>) => void`
::: details 查看 NodeInvalidInfo 及关联类型定义
<<< @/../packages/editor/src/type.ts#NodeInvalidInfo{ts}
<<< @/../packages/editor/src/type.ts#NodeInvalidSource{ts}
<<< @/../packages/schema/src/index.ts#Id{ts}
:::

View File

@ -1,9 +1,54 @@
# editorService方法 # editorService方法
## 历史记录相关 options
下列 DSL 操作方法([add](#add)、[remove](#remove)、[update](#update) 等)的 `options` / `data` 参数,以及
[codeBlockService](./codeBlockServiceMethods.md) / [dataSourceService](./dataSourceServiceMethods.md)
`options`,在 `doNotPushHistory` 之外还可传入:
- `{string}` **historyDescription**:入栈时附带的人类可读描述,用于历史面板展示;不影响 undo/redo 行为,缺省时面板会自动生成描述
- `{HistoryOpSource}` **historySource**:操作途径,用于历史面板展示与埋点;不影响 undo/redo 行为,缺省时面板视为「未知」
编辑器内置交互(画布、树面板、配置面板、右键菜单、快捷键等)会自动传入对应的 `historySource`
业务侧程序化调用时建议显式传入(如 `api`),便于历史面板区分来源。
## 历史记录 uuid 与 \*AndGetHistoryId
每条历史记录入栈时都会自动生成一个唯一标识 `uuid`(见 [StepValue](#undo)),可用于精确引用 / 定位某一条历史记录(如埋点、回滚、跨端同步等)。
DSL 操作方法(`add` / `remove` / `update` 等)默认返回操作结果(节点 / 节点集合 / void不会返回 `uuid`。若需要同时拿到原操作结果与本次写入历史记录的 `uuid`,可改用对应的 `*AndGetHistoryId` 方法:它们与原方法行为完全一致,返回值类型为 [`DslOpWithHistoryIdsResult<T>`](#历史记录-uuid-与-andgethistoryid)`result` 为原方法返回值,`historyIds` 为本次写入的 uuid 列表)。当本次操作未写入历史(`doNotPushHistory: true`、无实际变更或提前返回)时 `historyIds``[]`;单次操作通常返回含一个 uuid 的数组。
| 原方法 | 取 uuid 的方法 | 返回值 |
| --- | --- | --- |
| [add](#add) | [addAndGetHistoryId](#addandgethistoryid) | `Promise<DslOpWithHistoryIdsResult<MNode \| MNode[]>>` |
| [remove](#remove) | [removeAndGetHistoryId](#removeandgethistoryid) | `Promise<DslOpWithHistoryIdsResult<void>>` |
| [update](#update) | [updateAndGetHistoryId](#updateandgethistoryid) | `Promise<DslOpWithHistoryIdsResult<MNode \| MNode[]>>` |
| [moveLayer](#movelayer) | [moveLayerAndGetHistoryId](#movelayerandgethistoryid) | `Promise<DslOpWithHistoryIdsResult<void>>` |
| [moveToContainer](#movetocontainer) | [moveToContainerAndGetHistoryId](#movetocontainerandgethistoryid) | `Promise<DslOpWithHistoryIdsResult<MNode \| MNode[]>>` |
| [dragTo](#dragto) | [dragToAndGetHistoryId](#dragtoandgethistoryid) | `Promise<DslOpWithHistoryIdsResult<void>>` |
[dataSourceService](./dataSourceServiceMethods.md) / [codeBlockService](./codeBlockServiceMethods.md) 也提供了同名约定的 `*AndGetHistoryId` 方法,返回值约定相同(`result` + `historyIds`)。
拿到 `uuid` 后,可在需要时按 uuid「回滚」对应的历史记录类 git revert 语义,详见[历史记录面板](../../guide/advanced/history-list.md))。相比按 index 回滚uuid 不会随栈内步骤增删而变化,更适合业务侧持有引用后再回滚:
- 页面:[editorService.revertPageStepById(uuids)](#revertpagestepbyid)
- 数据源:[dataSourceService.revertById(uuids)](./dataSourceServiceMethods.md#revertbyid)
- 代码块:[codeBlockService.revertById(uuids)](./codeBlockServiceMethods.md#revertbyid)
::: details 查看 HistoryOpOptions / DslOpOptions / DslOpWithHistoryIdsResult / HistoryOpSource 类型定义
<<< @/../packages/editor/src/type.ts#HistoryOpOptions{ts}
<<< @/../packages/editor/src/type.ts#DslOpOptions{ts}
<<< @/../packages/editor/src/type.ts#DslOpWithHistoryIdsResult{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpSource{ts}
:::
## get ## get
- **参数:** - **参数:**
- `{'root' | 'page' | 'parent' | 'node' | 'highlightNode' | 'nodes' | 'modifiedNodeIds' | 'pageLength' | 'pageFragmentLength' | 'stage' | 'stageLoading' | 'disabledMultiSelect' | 'alwaysMultiSelect'} name` - `{'root' | 'page' | 'parent' | 'node' | 'highlightNode' | 'nodes' | 'modifiedNodeIds' | 'invalidNodeIds' | 'pageLength' | 'pageFragmentLength' | 'stage' | 'stageLoading' | 'disabledMultiSelect' | 'alwaysMultiSelect'} name`
- **返回:** - **返回:**
- `{any} value` - `{any} value`
@ -26,6 +71,8 @@
'modifiedNodeIds': 当前页面所有改动过的节点id 'modifiedNodeIds': 当前页面所有改动过的节点id
'invalidNodeIds': 校验失败的节点错误信息(`Map<Id, NodeInvalidInfo>`),供组件树标红提示与保存拦截读取
'pageLength': 所以页面个数 'pageLength': 所以页面个数
'pageFragmentLength': 页面片个数 'pageFragmentLength': 页面片个数
@ -48,7 +95,7 @@ const node = editorService.get("node");
## set ## set
- `{'root' | 'page' | 'parent' | 'node' | 'highlightNode' | 'nodes' | 'modifiedNodeIds' | 'pageLength' | 'pageFragmentLength' | 'stage' | 'stageLoading' | 'disabledMultiSelect' | 'alwaysMultiSelect'} name` - `{'root' | 'page' | 'parent' | 'node' | 'highlightNode' | 'nodes' | 'modifiedNodeIds' | 'invalidNodeIds' | 'pageLength' | 'pageFragmentLength' | 'stage' | 'stageLoading' | 'disabledMultiSelect' | 'alwaysMultiSelect'} name`
- `{any} value` - `{any} value`
- **详情:** - **详情:**
@ -358,6 +405,9 @@ editorService.highlight("text_123");
- `{Object}` options 可选配置 - `{Object}` options 可选配置
- `{boolean}` doNotSelect 添加后是否不更新当前选中节点(默认 false添加后会选中新增的节点 - `{boolean}` doNotSelect 添加后是否不更新当前选中节点(默认 false添加后会选中新增的节点
- `{boolean}` doNotSwitchPage 添加后是否不切换当前页面(默认 false新增页面 / 跨页新增时为 true 会跳过会引发页面切换的选中操作) - `{boolean}` doNotSwitchPage 添加后是否不切换当前页面(默认 false新增页面 / 跨页新增时为 true 会跳过会引发页面切换的选中操作)
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- {Promise<`MNode` | `MNode`[]>} 新增的组件或组件集合 - {Promise<`MNode` | `MNode`[]>} 新增的组件或组件集合
@ -403,6 +453,9 @@ editorService.highlight("text_123");
- `{Object}` options 可选配置 - `{Object}` options 可选配置
- `{boolean}` doNotSelect 删除后是否不更新当前选中节点(默认 false删除后会选中父节点或首个页面 - `{boolean}` doNotSelect 删除后是否不更新当前选中节点(默认 false删除后会选中父节点或首个页面
- `{boolean}` doNotSwitchPage 删除后是否不切换当前页面(默认 false删除页面 / 页面片段时为 true 会跳过自动切换到首个剩余页面) - `{boolean}` doNotSwitchPage 删除后是否不切换当前页面(默认 false删除页面 / 页面片段时为 true 会跳过自动切换到首个剩余页面)
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- `{Promise<void>}` - `{Promise<void>}`
@ -454,7 +507,19 @@ editorService.highlight("text_123");
- **参数:** - **参数:**
- {`MNode` | `MNode`[]} config 新的节点或节点集合 - {`MNode` | `MNode`[]} config 新的节点或节点集合
- `{Object}` data 可选配置 - `{Object}` data 可选配置
- {`ChangeRecord`[]} changeRecords 变更记录 - {`ChangeRecord`[]} changeRecords 单节点 form 端变更记录(多节点场景下被忽略,使用 `changeRecordList`
- {`ChangeRecord`[][]} changeRecordList 多节点 form 端变更记录列表,按 `config` 数组同序对应每个节点;优先级高于 `changeRecords`
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- `{Object}` invalidInfo 启用 [enablePropsFormValidate](./props.md#enablepropsformvalidate) 时,属性面板提交携带的校验错误信息,在写入历史记录之前落库,使历史快照与本次变更对齐
- `{Id}` id 节点 id
- `{'props' | 'style'}` source 错误来源:属性表单 / 样式表单
- `{string}` error 错误文案(可为含 `<br>` 的 HTML为空时表示清除该来源的错误记录
::: details 查看 ChangeRecord 类型定义
<<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts}
:::
- **返回:** - **返回:**
- {Promise<`MNode` | `MNode`[]>} 新的节点或节点集合 - {Promise<`MNode` | `MNode`[]>} 新的节点或节点集合
@ -471,6 +536,16 @@ editorService.highlight("text_123");
编辑器内部更新组件都是调用update来实现的update除了更新操作外还会记录历史堆还会更新[代码块](../../guide/advanced/code-block.md)关系链。 编辑器内部更新组件都是调用update来实现的update除了更新操作外还会记录历史堆还会更新[代码块](../../guide/advanced/code-block.md)关系链。
::: :::
:::tip
**多节点场景必须使用 `changeRecordList`**:每个节点应保留自己独立的 records不能把多个节点的
records 合并到同一个 `changeRecords` 数组里,否则 `doUpdate` / 依赖收集 / 历史回放都会按错误的
`propPath` 处理。
写入历史时,每个节点的 records 会单独保存到 `updatedItems[i].changeRecords`;撤销/重做时若有
records则仅按 `propPath` 局部更新对应字段,避免整节点替换冲掉同节点上的其它无关变更;缺省
才退化为整节点替换(如内部 `sort` / `moveLayer` / 拖动等纯快照场景)。
:::
## sort ## sort
- **[扩展支持](../../guide/editor-expand#行为扩展)** 是 - **[扩展支持](../../guide/editor-expand#行为扩展)** 是
@ -481,6 +556,8 @@ editorService.highlight("text_123");
- `{Object}` options 可选配置 - `{Object}` options 可选配置
- `{boolean}` doNotSelect 排序后是否不更新当前选中节点(默认 false - `{boolean}` doNotSelect 排序后是否不更新当前选中节点(默认 false
- `{boolean}` doNotSwitchPage 排序后是否不切换当前页面(排序只发生在同一父节点内,方法内为空操作;保留以与其它 DSL 操作 API 一致) - `{boolean}` doNotSwitchPage 排序后是否不切换当前页面(排序只发生在同一父节点内,方法内为空操作;保留以与其它 DSL 操作 API 一致)
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- `{Promise<void>}` - `{Promise<void>}`
@ -548,6 +625,9 @@ editorService.highlight("text_123");
- `{Object}` options 可选配置 - `{Object}` options 可选配置
- `{boolean}` doNotSelect 粘贴后是否不更新当前选中节点(默认 false - `{boolean}` doNotSelect 粘贴后是否不更新当前选中节点(默认 false
- `{boolean}` doNotSwitchPage 粘贴后是否不切换当前页面(默认 false跨页粘贴时为 true 会跳过页面切换) - `{boolean}` doNotSwitchPage 粘贴后是否不切换当前页面(默认 false跨页粘贴时为 true 会跳过页面切换)
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- {Promise<`MNode` | `MNode`[]>} 添加后的组件节点配置 - {Promise<`MNode` | `MNode`[]>} 添加后的组件节点配置
@ -585,6 +665,9 @@ editorService.highlight("text_123");
- `{Object}` options 可选配置 - `{Object}` options 可选配置
- `{boolean}` doNotSelect 居中后是否不更新当前选中节点(默认 false - `{boolean}` doNotSelect 居中后是否不更新当前选中节点(默认 false
- `{boolean}` doNotSwitchPage 居中后是否不切换当前页面(居中只更新节点 style方法内为空操作保留以与其它 DSL 操作 API 一致) - `{boolean}` doNotSwitchPage 居中后是否不切换当前页面(居中只更新节点 style方法内为空操作保留以与其它 DSL 操作 API 一致)
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- {Promise<`MNode` | `MNode`[]>} - {Promise<`MNode` | `MNode`[]>}
@ -605,6 +688,10 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
- **参数:** - **参数:**
- `{number | 'top' | 'bottom'}` offset - `{number | 'top' | 'bottom'}` offset
- `{Object}` options 可选配置
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- `{Promise<void>}` - `{Promise<void>}`
@ -625,6 +712,9 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
- `{Object}` options 可选配置 - `{Object}` options 可选配置
- `{boolean}` doNotSelect 移动后是否不更新当前选中节点(默认 false - `{boolean}` doNotSelect 移动后是否不更新当前选中节点(默认 false
- `{boolean}` doNotSwitchPage 移动后是否不切换当前页面(默认 false目标容器位于其它页面时为 true 会跳过自动选中以避免页面切换) - `{boolean}` doNotSwitchPage 移动后是否不切换当前页面(默认 false目标容器位于其它页面时为 true 会跳过自动选中以避免页面切换)
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- Promise<`MNode` | undefined> - Promise<`MNode` | undefined>
@ -639,6 +729,10 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
- {`MNode` | `MNode`[]} config 需要拖拽的节点或节点集合 - {`MNode` | `MNode`[]} config 需要拖拽的节点或节点集合
- {`MContainer`} targetParent 目标父容器 - {`MContainer`} targetParent 目标父容器
- `{number}` targetIndex 目标位置索引 - `{number}` targetIndex 目标位置索引
- `{Object}` options 可选配置
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- `{Promise<void>}` - `{Promise<void>}`
@ -647,6 +741,123 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
将节点(支持多选)拖拽到目标容器的指定位置,会自动处理跨容器布局切换并记录历史 将节点(支持多选)拖拽到目标容器的指定位置,会自动处理跨容器布局切换并记录历史
## addAndGetHistoryId
- **参数:** 同 [add](#add)
- **返回:**
- {Promise<[`DslOpWithHistoryIdsResult<MNode | MNode[]>`](#历史记录-uuid-与-andgethistoryid)>}
- `result`:同 [add](#add) 的返回值(新增节点 / 节点数组)
- `historyIds`:本次写入历史记录的 [uuid](#历史记录-uuid-与-andgethistoryid) 列表;未写入历史时为 `[]`
- **详情:**
与 [add](#add) 行为完全一致,并在返回值中额外提供 `historyIds`,见[历史记录 uuid 与 \*AndGetHistoryId](#历史记录-uuid-与-andgethistoryid)
- **示例:**
```js
import { editorService } from "@tmagic/editor";
const { result, historyIds } = await editorService.addAndGetHistoryId(
{ type: "text", text: "hello" },
parent,
{ historySource: "api" },
);
console.log(result); // 新增节点
console.log(historyIds); // 本次新增对应的历史记录 uuid 列表,或 []
```
## removeAndGetHistoryId
- **参数:** 同 [remove](#remove)
- **返回:**
- {Promise<[`DslOpWithHistoryIdsResult<void>`](#历史记录-uuid-与-andgethistoryid)>}
- `historyIds`:本次写入历史记录的 [uuid](#历史记录-uuid-与-andgethistoryid) 列表;未写入历史时为 `[]`
- **详情:**
与 [remove](#remove) 行为完全一致,并在返回值中额外提供 `historyIds`
## updateAndGetHistoryId
- **参数:** 同 [update](#update)
- **返回:**
- {Promise<[`DslOpWithHistoryIdsResult<MNode | MNode[]>`](#历史记录-uuid-与-andgethistoryid)>}
- `result`:同 [update](#update) 的返回值(更新后的节点 / 节点数组)
- `historyIds`:本次写入历史记录的 [uuid](#历史记录-uuid-与-andgethistoryid) 列表;未写入历史时为 `[]`
- **详情:**
与 [update](#update) 行为完全一致,并在返回值中额外提供 `historyIds`
## moveLayerAndGetHistoryId
- **参数:** 同 [moveLayer](#movelayer)
- **返回:**
- {Promise<[`DslOpWithHistoryIdsResult<void>`](#历史记录-uuid-与-andgethistoryid)>}
- `historyIds`:本次写入历史记录的 [uuid](#历史记录-uuid-与-andgethistoryid) 列表;未写入历史时为 `[]`
- **详情:**
与 [moveLayer](#movelayer) 行为完全一致,并在返回值中额外提供 `historyIds`
## moveToContainerAndGetHistoryId
- **参数:** 同 [moveToContainer](#movetocontainer)
- **返回:**
- {Promise<[`DslOpWithHistoryIdsResult<MNode | MNode[]>`](#历史记录-uuid-与-andgethistoryid)>}
- `result`:同 [moveToContainer](#movetocontainer) 的返回值(移动后的节点 / 节点数组)
- `historyIds`:本次写入历史记录的 [uuid](#历史记录-uuid-与-andgethistoryid) 列表;未写入历史时为 `[]`
- **详情:**
与 [moveToContainer](#movetocontainer) 行为完全一致,并在返回值中额外提供 `historyIds`
## dragToAndGetHistoryId
- **参数:** 同 [dragTo](#dragto)
- **返回:**
- {Promise<[`DslOpWithHistoryIdsResult<void>`](#历史记录-uuid-与-andgethistoryid)>}
- `historyIds`:本次写入历史记录的 [uuid](#历史记录-uuid-与-andgethistoryid) 列表;未写入历史时为 `[]`
- **详情:**
与 [dragTo](#dragto) 行为完全一致,并在返回值中额外提供 `historyIds`
## revertPageStepById
- **参数:**
- `{string[]}` uuids 目标历史记录的 uuid 列表(通常由 `*AndGetHistoryId` 方法返回的 `historyIds`
- **返回:**
- {Promise<(`StepValue` | null)[]>} 与入参同序的回滚结果列表,某项失败时为 `null`
- **详情:**
通过历史记录 uuid「回滚」当前页面的历史步骤类 git revert 语义):不移动游标、不丢弃任何步骤,而是把目标 step 的修改**反向应用为一条全新的步骤**压入栈顶。**按数组顺序依次回滚**。
::: tip
`opType: 'update'` 的步骤必须携带 `changeRecords` 才支持回滚(否则只能整节点替换,会冲掉后续无关变更);未应用(已被撤销)的步骤无法回滚。
:::
- **示例:**
```js
import { editorService } from "@tmagic/editor";
// 执行操作时拿到本次历史记录 uuid
const { historyIds } = await editorService.addAndGetHistoryId({ type: "text", text: "hello" });
// 之后任意时机按 uuid 回滚(支持单个或整批 historyIds
await editorService.revertPageStepById(historyIds);
```
## undo ## undo
- **[扩展支持](../../guide/editor-expand#行为扩展)** 是 - **[扩展支持](../../guide/editor-expand#行为扩展)** 是
@ -657,8 +868,14 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
::: details 查看 StepValue 及关联类型定义 ::: details 查看 StepValue 及关联类型定义
<<< @/../packages/editor/src/type.ts#StepValue{ts} <<< @/../packages/editor/src/type.ts#StepValue{ts}
<<< @/../packages/editor/src/type.ts#BaseStepValue{ts}
<<< @/../packages/editor/src/type.ts#StepExtra{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpType{ts} <<< @/../packages/editor/src/type.ts#HistoryOpType{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpSource{ts}
<<< @/../packages/schema/src/index.ts#Id{ts} <<< @/../packages/schema/src/index.ts#Id{ts}
::: :::
@ -673,6 +890,20 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
- **返回:** - **返回:**
- {Promise<`StepValue` | null>} - {Promise<`StepValue` | null>}
::: details 查看 StepValue 及关联类型定义
<<< @/../packages/editor/src/type.ts#StepValue{ts}
<<< @/../packages/editor/src/type.ts#BaseStepValue{ts}
<<< @/../packages/editor/src/type.ts#StepExtra{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpType{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpSource{ts}
<<< @/../packages/schema/src/index.ts#Id{ts}
:::
- **详情:** - **详情:**
恢复到下一步 恢复到下一步
@ -684,6 +915,10 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
- **参数:** - **参数:**
- `{number}` left - `{number}` left
- `{number}` top - `{number}` top
- `{Object}` options 可选配置
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
- **返回:** - **返回:**
- `{Promise<void>}` - `{Promise<void>}`
@ -698,6 +933,89 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
重置当前记录的修改过的节点id记录通常用于保存之后 重置当前记录的修改过的节点id记录通常用于保存之后
## setInvalidNode
- **参数:**
- `{Id}` id 节点 id
- `{'props' | 'style'}` source 错误来源:属性表单(`props`/ 样式表单(`style`
- `{string}` message 错误文案(可能为包含 `<br>` 的 HTML
- **详情:**
记录(或覆盖)某个节点在指定来源上的校验错误信息,写入 `invalidNodeIds` 状态并发出 [invalid-node-change](#invalid-node-change) 事件。
属性表单与样式表单是两个独立的 `FormPanel` 且均指向同一节点,故以来源为键分别保存,避免某个面板校验通过时误清另一个面板记录的错误。节点视为存在错误当且仅当任一来源存在非空文本。
- **示例:**
```js
import { editorService } from "@tmagic/editor";
// 标记 text_123 的属性表单校验错误
editorService.setInvalidNode("text_123", "props", "标题不能为空");
```
## deleteInvalidNode
- **参数:**
- `{Id}` id 节点 id
- `{'props' | 'style'}` source 可选;指定来源则仅删除该来源错误,不传则删除该节点全部来源的错误
- **详情:**
删除节点的校验错误记录。仅当该来源被清空且另一来源也无错误时,节点整体错误记录才会被移除;随后发出 [invalid-node-change](#invalid-node-change) 事件。
## getInvalidNodeIds
- **返回:**
- {`Map<Id, NodeInvalidInfo>`} 当前存在校验错误的节点错误 Mapkey 为节点 id
- **详情:**
获取当前存在校验错误的节点错误 Map供组件树标红提示与保存拦截读取。
::: details 查看 NodeInvalidInfo 及关联类型定义
<<< @/../packages/editor/src/type.ts#NodeInvalidInfo{ts}
<<< @/../packages/editor/src/type.ts#NodeInvalidSource{ts}
<<< @/../packages/schema/src/index.ts#Id{ts}
:::
- **示例:**
```js
import { editorService } from "@tmagic/editor";
// 保存前检查是否存在校验错误的组件
const invalidNodeIds = editorService.getInvalidNodeIds();
if (invalidNodeIds.size > 0) {
const names = [...invalidNodeIds.keys()].map((id) => {
const node = editorService.getNodeById(id);
return node?.name ? `${node.name}(${id})` : `${id}`;
});
console.warn(`以下组件存在配置校验错误,请修复后再保存:${names.join("、")}`);
}
```
## getInvalidNodeInfo
- **参数:**
- `{Id}` id 节点 id
- **返回:**
- {`NodeInvalidInfo` | undefined} 指定节点的校验错误信息(含 `props` / `style` 来源的错误文案)
- **详情:**
获取指定节点的校验错误信息。
## resetInvalidNodeId
- **详情:**
清空全部校验错误记录(即 `invalidNodeIds` 状态),随后发出 [invalid-node-change](#invalid-node-change) 事件。
## resetState ## resetState
- **详情:** - **详情:**
@ -712,45 +1030,11 @@ alignCenter可以支持一次水平居中多个组件alignCenter是通过调
移除所有事件监听清空state移除所有插件 移除所有事件监听清空state移除所有插件
## use
使用中间件的方式扩展方法,上述方法中标记有`扩展支持: 是`的方法都支持使用use扩展
- **示例:**
```js
import { editorService, getAddParent } from "@tmagic/editor";
import { ElMessageBox } from "element-plus";
editorService.use({
// 添加是否删除节点确认提示
async remove(node, next) {
await ElMessageBox.confirm("是否删除", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
});
next();
},
add(node, next) {
// text组件只能添加到container中
const parentNode = getAddParent(node);
if (node.type === "text" && parentNode?.type !== "container") {
return;
}
next();
},
});
```
## usePlugin ## usePlugin
- **详情:** - **详情:**
相对于[use](#use), usePlugin支持更加灵活更加细致的扩展, 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展 usePlugin支持灵活细致的扩展 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展
每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值 每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值

View File

@ -1,31 +1,122 @@
# historyService事件 # historyService事件
## page-change
- **详情:** 页面切换
- **事件回调函数:** `(undoRedo: UndoRedo) => void`
::: details 查看 UndoRedo 类定义
<<< @/../packages/editor/src/utils/undo-redo.ts#UndoRedo{ts}
:::
## change ## change
- **详情:** 历史记录发生变化 - **详情:** 页面历史记录发生变化(`page` 类型 `push` / `undo` / `redo` 成功时触发;与 `code-block-history-change` / `data-source-history-change` 同构)
- **事件回调函数:** `(state: StepValue | null) => void` - **事件回调函数:** `(pageId: Id, step: StepValue) => void`
::: details 查看 StepValue 及关联类型定义 ::: details 查看 StepValue 及关联类型定义
<<< @/../packages/editor/src/type.ts#StepValue{ts} <<< @/../packages/editor/src/type.ts#StepValue{ts}
<<< @/../packages/editor/src/type.ts#BaseStepValue{ts}
<<< @/../packages/editor/src/type.ts#StepExtra{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpType{ts} <<< @/../packages/editor/src/type.ts#HistoryOpType{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpSource{ts}
<<< @/../packages/schema/src/index.ts#Id{ts} <<< @/../packages/schema/src/index.ts#Id{ts}
<<< @/../packages/schema/src/index.ts#MNode{ts} <<< @/../packages/schema/src/index.ts#MNode{ts}
::: :::
:::tip :::tip
当游标处于历史栈边界(已经无法继续撤销或重做)时,`UndoRedo.undo()` / `redo()` 返回 `null`,对应 `change` 回调收到的 `state``null` 回调签名已与其它历史类型统一为 `(id, step)`。当游标处于历史栈边界(已无法继续撤销 / 重做)时 `undo` / `redo` 返回 `null`,此时不会触发该事件。
:::
## marker-change
- **详情:** 通过 [`setMarker`](./historyServiceMethods.md#setmarker) 为某个历史栈种入 `initial` 基线时触发(适用于所有类型)
- **事件回调函数:** `(id: Id, marker: StepValue, stepType: HistoryStepType) => void`
## clear
- **详情:** 调用 [`clear`](./historyServiceMethods.md#clear) 清空历史栈时触发(适用于所有类型)
- **事件回调函数:** `(id: Id | undefined, stepType: HistoryStepType) => void`
:::tip
`id` 缺省(清空 `stepType` 下全部栈)时回调的 `id``undefined`
:::
## code-block-history-change
- **详情:** 代码块历史记录发生变化(`push('codeBlock', step, codeBlockId)` / `undo('codeBlock', id)` / `redo('codeBlock', id)` 成功时触发)
- **事件回调函数:** `(codeBlockId: Id, step: CodeBlockStepValue) => void`
::: details 查看 CodeBlockStepValue 及关联类型定义
<<< @/../packages/editor/src/type.ts#CodeBlockStepValue{ts}
<<< @/../packages/editor/src/type.ts#BaseStepValue{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpSource{ts}
<<< @/../packages/schema/src/index.ts#CodeBlockContent{ts}
<<< @/../packages/schema/src/index.ts#Id{ts}
:::
:::tip
- 新增触发的 step 其 diff 项 `oldSchema``null`
- 删除触发的 step 其 diff 项 `newSchema``null`
- `undo` / `redo` 返回 `null`(边界状态)时不会触发该事件
:::
## data-source-history-change
- **详情:** 数据源历史记录发生变化(`push('dataSource', step, dataSourceId)` / `undo('dataSource', id)` / `redo('dataSource', id)` 成功时触发)
- **事件回调函数:** `(dataSourceId: Id, step: DataSourceStepValue) => void`
::: details 查看 DataSourceStepValue 及关联类型定义
<<< @/../packages/editor/src/type.ts#DataSourceStepValue{ts}
<<< @/../packages/editor/src/type.ts#BaseStepValue{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpSource{ts}
<<< @/../packages/schema/src/index.ts#Id{ts}
:::
:::tip
- 新增触发的 step 其 diff 项 `oldSchema``null`
- 删除触发的 step 其 diff 项 `newSchema``null`
- `undo` / `redo` 返回 `null`(边界状态)时不会触发该事件
:::
## mark-saved
- **详情:** 调用 [`markSaved`](./historyServiceMethods.md#marksaved) 标记「已保存」记录时触发
- **事件回调函数:** `(payload: { kind: 'all' | HistoryStepType; id?: Id }) => void`
::: tip
- `markSaved(stepType)`(缺省 id触发时 `kind``all`,无 `id`(此时 `stepType` 不生效)
- `markSaved(stepType, id)` 触发时 `kind` 为对应的 `stepType``page` / `codeBlock` / `dataSource` / 扩展),`id` 为目标栈 id
:::
## save-to-indexed-db
- **详情:** `saveToIndexedDB` 把历史记录写入本地 IndexedDB 成功时触发
- **事件回调函数:** `(snapshot: PersistedHistoryState) => void`
::: details 查看 PersistedHistoryState 类型定义
<<< @/../packages/editor/src/type.ts#PersistedHistoryState{ts}
<<< @/../packages/editor/src/utils/undo-redo.ts#SerializedUndoRedo{ts}
:::
## restore-from-indexed-db
- **详情:** `restoreFromIndexedDB` 从本地 IndexedDB 读取并重建历史记录成功时触发(找不到记录时不触发)
- **事件回调函数:** `(snapshot: PersistedHistoryState) => void`
::: details 查看 PersistedHistoryState 类型定义
<<< @/../packages/editor/src/type.ts#PersistedHistoryState{ts}
::: :::

View File

@ -4,78 +4,286 @@
- **详情:** - **详情:**
重置记录 重置全部历史记录:清空 `state.steps` 下的页面 / 代码块 / 数据源 / 扩展类型全部栈(保留已注册的扩展类型键)。
## resetPage
- **详情:**
重置当前页面的历史记录状态清空当前页面id重置 canRedo/canUndo
## resetState ## resetState
- **详情:** - **详情:**
重置历史记录全部内部状态(清空 pageId、pageSteps、canRedo、canUndo 同 [`reset`](#reset),清空 `state.steps` 下全部栈。
## changePage ::: tip
历史服务不再维护「当前活动页」状态(已移除 `state.pageId` / `state.canUndo` / `state.canRedo`)。
活动页由 `editorService` 维护,撤销 / 重做 / 读取页面历史时请显式传入 pageId。
是否可撤销 / 重做请改用 [`canUndo`](#canundo) / [`canRedo`](#canredo)。
:::
## registerStepType
- **参数:** - **参数:**
- `{MPage | MPageFragment} page` - `{string} stepType` 自定义历史类型标识(勿与内置 `page` / `codeBlock` / `dataSource` 重名)
- `{Object} options` 可选
::: details 查看 MPage / MPageFragment 类型定义 - `{string} event` push / undo / redo 后派发的事件名;缺省为 `${stepType}-history-change`
<<< @/../packages/schema/src/index.ts#MPage{ts} - `{string} name` 历史面板中的展示名称tab / 分组标题等);缺省回退到 stepType 本身
<<< @/../packages/schema/src/index.ts#MPageFragment{ts}
:::
- **详情:** - **详情:**
按页面切换历史堆栈 注册一个扩展历史类型,使其可与内置 `page` / `codeBlock` / `dataSource` 一样走统一的
[`push`](#push) / [`undo`](#undo) / [`redo`](#redo)(按 id 分栈、独立 undo/redo
注册后该类型的栈存放在 `historyService.state.steps[stepType]`,展示名称存放在 `historyService.state.stepNames[stepType]`
## getStepName
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- **返回:**
- `{string}` 该类型的展示名称(用于历史面板 tab / 分组标题等);未登记时回退到 stepType 本身
- **详情:**
读取指定历史类型的展示名称。内置 `page` / `codeBlock` / `dataSource` 默认分别为「页面 / 代码块 / 数据源」。
## setStepName
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{string} name` 展示名称
- **详情:**
设置指定历史类型的展示名称(写入 `historyService.state.stepNames`,历史面板会响应式刷新)。
内置 `page` / `codeBlock` / `dataSource` 也可在此覆盖默认中文名。
## push ## push
- **参数:** - **参数:**
- `{StepValue} state` - `{HistoryStepType} stepType` 历史类型,内置 `'page'` / `'codeBlock'` / `'dataSource'`,并支持通过 [`registerStepType`](#registersteptype) 扩展
- `{StepValue | BaseStepValue} step` 已构造好的历史记录(缺省自动补全 `uuid` / `timestamp`
- `{Id} id` 必填;目标栈 id`page` 为 pageId其余类型为对应资源 id
::: details 查看 StepValue 及关联类型定义 ::: details 查看 StepValue 及关联类型定义
<<< @/../packages/editor/src/type.ts#StepValue{ts} <<< @/../packages/editor/src/type.ts#StepValue{ts}
<<< @/../packages/editor/src/type.ts#BaseStepValue{ts}
<<< @/../packages/editor/src/type.ts#StepExtra{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpType{ts} <<< @/../packages/editor/src/type.ts#HistoryOpType{ts}
<<< @/../packages/editor/src/type.ts#HistoryOpSource{ts}
<<< @/../packages/schema/src/index.ts#Id{ts} <<< @/../packages/schema/src/index.ts#Id{ts}
<<< @/../packages/schema/src/index.ts#MNode{ts} <<< @/../packages/schema/src/index.ts#MNode{ts}
<<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts}
::: :::
- **返回:** - **返回:**
- `{StepValue | null}` - `{StepValue | BaseStepValue | null}` 入栈失败(未传 / 无效 id时返回 `null`
- **详情:** - **详情:**
添加一条历史记录 添加一条历史记录。统一入口,所有类型(`page` / `codeBlock` / `dataSource` / 扩展)行为完全一致:按 `stepType` 选择目标栈类型、按 `id`(必填)选择具体栈,按需建栈后入栈,并派发对应的历史变更事件(`page``change`,其余如 `code-block-history-change` / `data-source-history-change`),回调签名统一为 `(id, step)`
跨页 / 跨资源操作(如把节点搬到其它页)必须显式传入目标 id。`codeBlock` / `dataSource` 的 step 通常由 `createStackStep` 等工具按 `oldValue` / `newValue` 构造后传入。
::: tip
`opType: 'update'` 的每个 diff 项上可携带 `changeRecords`,用于撤销 / 重做时仅按
`propPath` 局部更新对应字段,避免整节点替换冲掉同节点上的其它无关变更;不带
`changeRecords` 时退化为整节点替换(如 `sort` / `moveLayer` / 拖动等纯快照场景)。
`step` 上的 `historyDescription` / `source` 仅用于历史面板展示与埋点,不影响 undo/redo 行为。
入栈时会为每条记录自动生成唯一标识 `uuid`(调用方未指定时),可用于精确引用 / 定位某一条历史记录。
若需要在执行 DSL 操作后拿到本次写入记录的 `uuid`,可使用 editorService / dataSourceService /
codeBlockService 提供的 `*AndGetHistoryId` 方法,参见
[editorService 历史记录 uuid 与 \*AndGetHistoryId](./editorServiceMethods.md#历史记录-uuid-与-andgethistoryid)。
:::
## undo ## undo
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{Id} id` 必填;目标栈 id`page` 为 pageId其余类型为对应资源 id
- **返回:** - **返回:**
- `{StepValue | null}` - `{StepValue | BaseStepValue | null}`
- **详情:** - **详情:**
撤销当前操作 撤销指定历史栈的最近一次变更。所有类型行为一致:按 `stepType` + `id` 定位栈,不会越过 index 0 的 initial 基线(所有类型同等适用,见 [`setMarker`](#setmarker)),仅在确有可撤销 step 时派发对应的历史变更事件(`page``change`,回调签名 `(id, step)`)。
`page` 类型 `opType: 'update'` 时,若 diff 项的 `changeRecords` 存在,会按 `propPath``oldSchema` 取值做局部回滚;否则用 `oldSchema` 整节点替换。`codeBlock` / `dataSource` 拿到 step 后由调用方写回对应 service本方法不会自动回放
## redo ## redo
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{Id} id` 必填;目标栈 id`page` 为 pageId其余类型为对应资源 id
- **返回:** - **返回:**
- `{StepValue | null}` - `{StepValue | BaseStepValue | null}`
- **详情:** - **详情:**
恢复到下一步 恢复指定历史栈到下一步,语义与 [`undo`](#undo) 对称。`page` 类型 `opType: 'update'` 时,若 diff 项的 `changeRecords` 存在,会按 `propPath``newSchema` 取值做局部重做;否则用 `newSchema` 整节点替换。
## canUndo
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{Id} id` 可选;目标栈 id缺省 / 无效时返回 `false`
- **返回:**
- `{boolean}`
- **详情:**
指定历史栈当前是否可撤销(游标高于 index 0 的 initial 基线底线)。适用于所有类型(`page` / `codeBlock` / `dataSource` / 扩展)。
## canRedo
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{Id} id` 可选;目标栈 id缺省 / 无效时返回 `false`
- **返回:**
- `{boolean}`
- **详情:**
指定历史栈当前是否可重做。适用于所有类型(`page` / `codeBlock` / `dataSource` / 扩展)。
## setMarker
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{Id} id` 目标栈 id`page` 为 pageId其余类型为对应资源 id
- `{Object} options` 可选:`name` / `description` / `source`,用于基线的展示信息
- **返回:**
- `{StepValue | null}` 已存在基线时返回原基线;栈非空(无基线)或 id 无效时返回 `null`
- **详情:**
为指定历史栈种入一条 `opType: 'initial'` 的「初始基线」记录,作为该栈 index 0 的固定底线:它是真实入栈并随栈持久化的 step但被钉为撤销 / 回滚的下限,`undo` / `goto` / `revert` 都不会越过它。所有类型(含扩展类型)均可设置基线,仅当目标栈为空时种入。
## getMarker
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{Id} id` 可选;目标栈 id缺省 / 无效时返回 `undefined`
- **返回:**
- `{StepValue | undefined}`
- **详情:**
读取指定历史栈的初始基线 step栈 index 0 且 `opType: 'initial'`),不存在时返回 `undefined`
## markSaved
- **参数:**
- `{HistoryStepType} stepType` 历史类型,内置另有 `'codeBlock'` / `'dataSource'`,并支持扩展(仅在传入 `id` 时生效)
- `{Id} id` 可选;目标栈 id。缺省表示标记全部类型、全部栈
- **详情:**
标记历史记录为「已保存」(把对应栈当前游标所在的记录标记为 `saved = true`)。统一入口:
- **缺省 `id`**:标记「整份 DSL 已保存」——把所有类型、所有栈当前游标所在的记录都标记为已保存(此时 `stepType` 不生效),触发 `mark-saved` 事件且 `{ kind: 'all' }`。通常在 DSL 整体落库成功后调用。
- **传入 `id`**:仅标记 `stepType` 下该 id 对应的栈,触发 `mark-saved` 事件且 `{ kind: stepType, id }`(如 `{ kind: 'page', id }` / `{ kind: 'codeBlock', id }` / `{ kind: 'dataSource', id }`)。
同一栈内任意时刻最多保留一条已保存记录标记前会清除该栈内全部旧标记某个栈处于「全部已撤销」cursor 为 0时不会留下已保存记录从 IndexedDB 恢复时其游标会回到 0。配合 [`restoreFromIndexedDB`](#restorefromindexeddb) 把游标恢复到此处。
## clear
- **参数:**
- `{HistoryStepType} stepType` 历史类型,内置另有 `'codeBlock'` / `'dataSource'`,并支持扩展
- `{Id} id` 可选;目标栈 id。缺省表示清空 `stepType` 下的全部栈
- **详情:**
清空历史记录栈。统一入口所有类型page / codeBlock / dataSource / 扩展)行为一致:
- **传入 `id`**:仅清空 `stepType` 下该 id 对应的栈;
- **缺省 `id`**:清空 `stepType` 下的全部栈。
仅删除撤销/重做记录,不会改动 DSL / 代码块 / 数据源本身。清空时会**保留各栈原有的 initial 基线**(文案 / 来源,见 [`setMarker`](#setmarker)),无基线时清空成空栈。清空后触发 `clear` 事件(签名 `(id, stepType)`)。
## saveToIndexedDB
- **参数:**
- `{HistoryPersistOptions} options` 可选
::: details 查看 HistoryPersistOptions / PersistedHistoryState 类型定义
<<< @/../packages/editor/src/type.ts#HistoryPersistOptions{ts}
<<< @/../packages/editor/src/type.ts#PersistedHistoryState{ts}
<<< @/../packages/editor/src/utils/undo-redo.ts#SerializedUndoRedo{ts}
:::
- **返回:**
- `{Promise<PersistedHistoryState>}` 写入成功的快照对象
- **详情:**
把当前内存中的全部历史栈(页面 / 代码块 / 数据源 / 扩展类型)连同各自游标、容量序列化后写入本地 IndexedDB。
- 最终库名为 `${dbName}-${当前 DSL app id}`,按应用隔离;
- `key` 用于在同一 store 下区分不同记录,缺省为 `default`
- 历史记录里可能包含函数(代码块内容 / 节点事件等),内部使用 `serialize-javascript` 序列化为字符串后写入,恢复时再用 `parseDSL` 还原,因此可安全持久化函数 / `Map` 等;
- 不支持 IndexedDB 的环境(如 SSR会 reject。
写入成功后触发 `save-to-indexed-db` 事件。
::: warning
`beforeunload` / `pagehide` 阶段浏览器不会等待异步 IndexedDB 事务提交,单纯依赖卸载时写入可能丢失最近一次编辑。建议在历史变更时(防抖)即调用本方法持久化,确保刷新后能完整恢复。
:::
## restoreFromIndexedDB
- **参数:**
- `{HistoryPersistOptions} options` 可选
- **返回:**
- `{Promise<PersistedHistoryState | null>}` 找不到记录时返回 `null`
- **详情:**
从本地 IndexedDB 读取此前保存的历史快照并重建全部撤销/重做栈。
- 每个栈都会按 `listMaxSize` 裁剪并还原游标;
- 若某个栈存在已保存记录(见 `markSaved`),其游标会被定位到「最近一条已保存记录」之后,使恢复后的状态与落库的 DSL 对齐;
- 会整体覆盖当前内存中的历史状态(活动页由 `editorService` 维护,不在此恢复);
- 找不到对应记录时返回 `null` 且不改动当前状态;不支持 IndexedDB 的环境会 reject。
成功后触发 `restore-from-indexed-db` 事件。
## findStepLocationByUuid
- **参数:**
- `{HistoryStepType} stepType` 历史类型
- `{string} uuid` 目标历史记录的 uuid
- `{Id} id` 可选;目标栈 id
- **返回:**
- `{ { id: Id; index: number } | null }` 找到时返回所属栈 id 与步骤索引;找不到时返回 `null`
- **详情:**
按历史记录 uuid 在指定历史类型的栈中查找其所属 id 与索引,统一入口。
- **传入 `id`**:仅在该 id 对应的单个栈中查找(如页面历史按活动页查看,传入 pageId
- **缺省 `id`**:遍历该类型下全部栈查找(代码块 / 数据源等按全部资源分桶的场景)。
供「按 uuid 回滚」等需要把 uuid 映射回 `(id, index)` 的场景使用,如 [editorService.revertPageStepById](./editorServiceMethods.md#revertpagestepbyid) / [codeBlockService.revertById](./codeBlockServiceMethods.md#revertbyid) / [dataSourceService.revertById](./dataSourceServiceMethods.md#revertbyid) 内部均通过本方法定位步骤。
## destroy ## destroy
- **详情:** - **详情:**
销毁 销毁

View File

@ -260,7 +260,7 @@ icon使用的是[element-plus icon](https://element-plus.org/zh-CN/component/ico
顶部工具栏 顶部工具栏
系统提供了几个常用功能: `'/' | 'delete' | 'undo' | 'redo' | 'zoom-in' | 'zoom-out' | 'zoom' | 'guides' | 'rule' | 'scale-to-original' | 'scale-to-fit'` 系统提供了几个常用功能: `'/' | 'delete' | 'undo' | 'redo' | 'zoom-in' | 'zoom-out' | 'zoom' | 'guides' | 'rule' | 'scale-to-original' | 'scale-to-fit' | 'history-list'`
'/': 分隔符 '/': 分隔符
@ -284,6 +284,8 @@ icon使用的是[element-plus icon](https://element-plus.org/zh-CN/component/ico
'scale-to-fit': 缩放以适应 'scale-to-fit': 缩放以适应
'history-list': 历史记录面板(按 页面 / 数据源 / 代码块 三个 tab 展示操作历史,相邻同目标修改自动合并,支持点击跳转、回到初始状态、单步回滚及差异对比,详见[历史记录面板](/guide/advanced/history-list.md)
- **默认值:** - **默认值:**
```js ```js
@ -1218,6 +1220,28 @@ const guidesOptions = {
</template> </template>
``` ```
## disabledFlashTip
- **详情:**
禁用「非点击画布选中组件时的高亮闪烁提示」。
当组件不是通过点击画布选中(如从组件树、面包屑等外部方式选中)时,编辑器会在画布上对选中区域做一次高亮闪烁,帮助用户快速定位组件在画布中的位置。设置为 `true` 可关闭该提示。
注:选中页面(`magic-ui-page`)时不会触发闪烁。
- **默认值:** `false`
- **类型:** `boolean`
- **示例:**
```html
<template>
<m-editor :disabled-flash-tip="true"></m-editor>
</template>
```
## disabledStageOverlay ## disabledStageOverlay
- **详情:** - **详情:**
@ -1258,6 +1282,45 @@ const guidesOptions = {
</template> </template>
``` ```
## enablePropsFormValidate
- **详情:**
是否启用「属性配置表单校验」联动能力。
开启后(默认 `false` 关闭),当属性面板(属性表单 / 样式表单)校验失败时,编辑器会**仍按当前表单值更新节点**,并把错误信息集中记录到 `editorService``invalidNodeIds` 状态),用于:
- 组件树(图层)中对出错节点标红并显示错误图标,鼠标悬停可查看错误文案;
- 保存前拦截:业务可通过 `editorService.getInvalidNodeIds()` 读取错误节点,存在校验错误时阻止保存(参考 [playground 菜单保存拦截](../../guide/advanced/prop-form-validate.md#保存拦截))。
关闭时保持原行为:属性 / 样式表单校验失败则丢弃本次改动,不写入节点。
:::tip
校验错误以「来源」为维度分别记录 —— 属性表单来源记为 `props`,样式表单来源记为 `style`;两者指向同一节点,互不覆盖。节点只要任一来源存在错误即视为出错。
错误信息会随 DSL 操作写入历史记录快照,因此「撤销 / 重做」能正确还原校验错误状态(撤销一个「校验失败」的改动后错误消失,重做后错误恢复)。
:::
- **默认值:** `false`
- **类型:** `boolean`
- **示例:**
```html
<template>
<!-- 开启属性配置表单校验联动能力 -->
<m-editor :enable-props-form-validate="true"></m-editor>
</template>
```
- **相关 API**
- `editorService` 错误状态与方法:`get('invalidNodeIds')` / [setInvalidNode](#setinvalidnode) / [deleteInvalidNode](#deleteinvalidnode) / [getInvalidNodeIds](#getinvalidnodeids) / [getInvalidNodeInfo](#getinvalidnodeinfo) / [resetInvalidNodeId](#resetinvalidnodeid)
- 错误状态变化事件:[invalid-node-change](#invalid-node-change)
- 进阶用法见[属性配置表单校验联动](../../guide/advanced/prop-form-validate.md)
## disabledDataSource ## disabledDataSource
- **详情:** - **详情:**
@ -1341,13 +1404,34 @@ const guidesOptions = {
- **详情:** - **详情:**
用于自定义组件树与画布的右键菜单 用于自定义组件树(图层)、画布、数据源、代码块的右键菜单
该函数会在显示右键菜单前被调用,接收默认菜单项作为参数,返回最终显示的菜单项 该函数会在显示右键菜单前被调用,接收默认菜单项与菜单类型作为参数,返回最终显示的菜单项
第二个参数 `type` 用于区分菜单来源:`'layer'`(图层)、`'viewer'`(画布)、`'data-source'`(数据源)、`'code-block'`(代码块)
第三个参数 `getTarget` 仅在**数据源**与**代码块**面板下传入,用于读取当前右键目标(节点 `id` 与原始数据);图层 / 画布不会传入该参数
- **默认值:** `(menus) => menus` - **默认值:** `(menus) => menus`
- **类型:** `(menus: (MenuButton | MenuComponent)[], data: { node?: MNode; page?: MPage; parent?: MContainer; stage?: StageCore }) => (MenuButton | MenuComponent)[]` - **类型:**
```ts
interface ContentMenuTarget {
/** 目标 ID */
id: string;
/** 原始节点数据(树节点等) */
data?: TreeNodeData;
}
type ContentMenuType = 'layer' | 'data-source' | 'viewer' | 'code-block';
type CustomContentMenuFunction = (
menus: (MenuButton | MenuComponent)[],
type: ContentMenuType,
getTarget?: () => ContentMenuTarget | null,
) => (MenuButton | MenuComponent)[];
```
- **示例:** - **示例:**
@ -1357,20 +1441,24 @@ const guidesOptions = {
</template> </template>
<script setup> <script setup>
const customContentMenu = (menus, { node }) => { const customContentMenu = (menus, type, getTarget) => {
// 为特定类型的组件添加自定义菜单 // 为数据源右键菜单追加自定义菜单
if (node?.type === 'container') { if (type === 'data-source') {
menus.push({ menus.push({
type: 'button', type: 'button',
text: '清空容器', text: '查看详情',
handler: () => { handler: () => {
// 清空容器的逻辑 // getTarget 仅在数据源 / 代码块面板下传入
const target = getTarget?.();
if (target) {
console.log(target.id, target.data);
}
}, },
}); });
} }
// 可以过滤掉某些菜单项 // 可以过滤掉某些菜单项
return menus.filter(menu => menu.text !== '删除'); return menus.filter((menu) => menu.text !== '删除');
}; };
</script> </script>
``` ```
@ -1506,6 +1594,55 @@ const extendFormState = async (state) => {
``` ```
::: :::
## historyListExtraTabs
- **详情:**
[历史记录面板](/guide/advanced/history-list.md) 的自定义扩展 tab。
业务方可借此在历史记录面板内置的「页面 / 数据源 / 代码块」三个 tab 之后追加自定义模块的历史 tab例如某个自定义模块维护自己的操作历史时可在面板中增加一个独立的 tab 来展示与回滚。
- **默认值:** `[]`
- **类型:** `HistoryListExtraTab[]`
::: details 查看 HistoryListExtraTab 类型定义
<<< @/../packages/editor/src/type.ts#HistoryListExtraTab{ts}
:::
- **示例:**
```html
<template>
<m-editor :menu="menu" :history-list-extra-tabs="historyListExtraTabs"></m-editor>
</template>
<script setup>
import { markRaw } from 'vue';
import MyModuleHistoryTab from './MyModuleHistoryTab.vue';
const historyListExtraTabs = [
{
name: 'my-module',
// label 支持字符串或函数,函数形式便于展示动态数量
label: () => '我的模块',
component: markRaw(MyModuleHistoryTab),
// 传入内容组件的 props
props: { foo: 'bar' },
// 内容组件的事件监听
listeners: {
goto: (cursor) => console.log(cursor),
},
},
];
</script>
```
::: tip
内容组件内部可自行通过 `useServices()` 获取 `historyService` 等服务来读取与回滚自定义模块的历史。
:::
## pageBarSortOptions ## pageBarSortOptions
- **详情:** - **详情:**

View File

@ -254,15 +254,11 @@
销毁propsService 销毁propsService
## use
使用中间件的方式扩展方法,上述方法中标记有`扩展支持: 是`的方法都支持使用use扩展
## usePlugin ## usePlugin
- **详情:** - **详情:**
相对于[use](#use), usePlugin支持更加灵活更加细致的扩展, 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展 usePlugin支持灵活细致的扩展, 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展
每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值 每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值

View File

@ -231,28 +231,11 @@ import { storageService } from '@tmagic/editor';
storageService.destroy(); storageService.destroy();
``` ```
## use
使用中间件的方式扩展方法,上述方法中标记有`扩展支持: 是`的方法都支持使用use扩展
- **示例:**
```js
import { storageService } from '@tmagic/editor';
storageService.use({
getItem(key, options, next) {
console.log('获取存储项:', key);
return next();
},
});
```
## usePlugin ## usePlugin
- **详情:** - **详情:**
相对于[use](#use), usePlugin支持更加灵活更加细致的扩展, 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展 usePlugin支持灵活细致的扩展 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展
每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值 每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值

View File

@ -0,0 +1,28 @@
# uiService事件
## state-change
- **详情:** UI 状态发生变化时触发,[uiService.set()](./uiServiceMethods.md#set) 在写入的新值与旧值不同时触发
- **事件回调函数:** `(name: keyof UiState, value: UiState[typeof name], preValue: UiState[typeof name]) => void`
::: details 查看 UiState 类型定义
<<< @/../packages/editor/src/type.ts#UiState{ts}
:::
- **示例:**
```js
import { uiService } from '@tmagic/editor';
uiService.on('state-change', (name, value, preValue) => {
console.log(`${name} 从`, preValue, '变为', value);
});
uiService.set('zoom', 1.5);
```
:::tip
- 新值与旧值相同时不会触发该事件
- 通过 `set('stageRect', value)` 修改画布尺寸时,内部会走 `setStageRect` 逻辑并可能联动更新 `zoom`,但不会触发 `state-change` 事件
:::

View File

@ -13,7 +13,7 @@
- **详情:** - **详情:**
设置UI服务的状态 设置UI服务的状态。新值与旧值不同时会触发 [`state-change`](./uiServiceEvents.md#state-change) 事件
可用的状态键: 可用的状态键:
- `uiSelectMode`: UI选择模式 - `uiSelectMode`: UI选择模式
@ -31,6 +31,7 @@
- `showPageListButton`: 是否显示页面列表按钮 - `showPageListButton`: 是否显示页面列表按钮
- `hideSlideBar`: 是否隐藏侧边栏 - `hideSlideBar`: 是否隐藏侧边栏
- `sideBarItems`: 侧边栏项目 - `sideBarItems`: 侧边栏项目
- `sideBarActiveTabName`: 当前激活的侧边栏面板
- `navMenuRect`: 导航菜单尺寸 - `navMenuRect`: 导航菜单尺寸
- `frameworkRect`: 框架尺寸 - `frameworkRect`: 框架尺寸
@ -179,29 +180,11 @@ import { uiService } from '@tmagic/editor';
uiService.destroy(); uiService.destroy();
``` ```
## use
使用中间件的方式扩展方法,上述方法中标记有`扩展支持: 是`的方法都支持使用use扩展
- **示例:**
```js
import { uiService } from '@tmagic/editor';
uiService.use({
async zoom(value, next) {
console.log('缩放前:', uiService.get('zoom'));
await next();
console.log('缩放后:', uiService.get('zoom'));
},
});
```
## usePlugin ## usePlugin
- **详情:** - **详情:**
相对于[use](#use), usePlugin支持更加灵活更加细致的扩展, 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展 usePlugin支持灵活细致的扩展 上述方法中标记有`扩展支持: 是`的方法都支持使用usePlugin扩展
每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值 每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为before可以用于修改传入参数after可以用于修改返回的值

View File

@ -150,6 +150,14 @@
- **类型:** `boolean` - **类型:** `boolean`
## useFieldTextInError
- **详情:** 透传给内部 `Form`,控制表单校验失败时错误提示前缀是否使用字段的 `text` 文案。`false` 时直接使用字段 `name`
- **默认值:** `true`
- **类型:** `boolean`
## closeOnClickModal ## closeOnClickModal
- **详情:** 是否可以通过点击 modal 关闭 Dialog - **详情:** 是否可以通过点击 modal 关闭 Dialog

View File

@ -40,6 +40,8 @@
- **详情:** 通过 `name` 从表单 `config` 中查找对应表单项的 `text` - **详情:** 通过 `name` 从表单 `config` 中查找对应表单项的 `text`
- **相关:** 表单校验失败时是否使用该方法生成错误提示前缀,由 [`useFieldTextInError`](./form-props.md#usefieldtextinerror) prop 控制(默认 `true`
## values ## values
- **类型:** `Ref<FormValue>` - **类型:** `Ref<FormValue>`

View File

@ -85,6 +85,44 @@
- **类型:** `boolean` - **类型:** `boolean`
## showDiff
- **详情:**
自定义“是否展示对比内容”的判断函数(仅在 `isCompare === true` 时生效)。
- 不传:使用默认逻辑 `!isEqual(curValue, lastValue)`(基于 lodash `isEqual`
- 传函数:完全以函数返回值为准,返回 `true` 才展示前后两份对比内容。
该 prop 通过 `formState` 透传到所有层级的 Container 中,调用方只需在 MForm 这一层传一次即可对整棵表单生效。
典型场景:某些字段语义上相等但结构不同(例如 `code-select` 字段中 `''``{ hookType: 'code', hookData: [] }` 应视为相等),调用方在此处显式声明,避免被 `isEqual` 误判为差异。
- **类型:** `(data: { curValue: any; lastValue: any; config: FormItemConfig }) => boolean`
- **示例:**
```html
<template>
<m-form :config="config" :is-compare="true" :last-values="lastValues" :show-diff="showDiff"></m-form>
</template>
<script setup>
import { isEqual } from 'lodash-es';
const showDiff = ({ curValue, lastValue, config }) => {
if (config?.type === 'code-select') {
// 业务侧自定义:双方都是“空形态”视为相等,不展示对比
const isEmpty = (v) =>
v === '' || v === undefined || v === null ||
(typeof v === 'object' && v.hookType === 'code' && Array.isArray(v.hookData) && v.hookData.length === 0);
if (isEmpty(curValue) && isEmpty(lastValue)) return false;
}
return !isEqual(curValue, lastValue);
};
</script>
```
## parentValues ## parentValues
- **详情:** 父级表单值 - **详情:** 父级表单值
@ -168,6 +206,19 @@
- **类型:** `boolean` - **类型:** `boolean`
## useFieldTextInError
- **详情:**
表单校验失败时,错误提示前缀是否使用字段的 `text` 文案(通过 `getTextByName``config` 中查找)。
- `true`(默认):错误提示形如 `字段文案 -> 错误信息`,找不到 `text` 时回退为字段 `name`
- `false`:跳过查找,直接使用字段 `name` 作为错误提示前缀(形如 `字段name -> 错误信息`)。
- **默认值:** `true`
- **类型:** `boolean`
## extendState ## extendState
- **详情:** 扩展 formState 的钩子函数,返回的对象会被合并到 formState 上 - **详情:** 扩展 formState 的钩子函数,返回的对象会被合并到 formState 上

View File

@ -18,7 +18,7 @@ function submitForm(options: SubmitFormOptions): Promise<any>;
## 参数 ## 参数
`options``MForm` 组件的 props 基本对齐,额外提供了 `native``appContext`、`timeout` 三个参数。 `options``MForm` 组件的 props 基本对齐,额外提供了 `native``returnChangeRecords`、`appContext``timeout`参数。
| 名称 | 类型 | 默认值 | 说明 | | 名称 | 类型 | 默认值 | 说明 |
| ---------------------- | ------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------- | | ---------------------- | ------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------- |
@ -37,19 +37,25 @@ function submitForm(options: SubmitFormOptions): Promise<any>;
| `keyProp` | `string` | `'__key'` | 配置项的唯一 key | | `keyProp` | `string` | `'__key'` | 配置项的唯一 key |
| `popperClass` | `string` | — | 弹层 className | | `popperClass` | `string` | — | 弹层 className |
| `preventSubmitDefault` | `boolean` | — | 是否阻止表单原生 submit | | `preventSubmitDefault` | `boolean` | — | 是否阻止表单原生 submit |
| `useFieldTextInError` | `boolean` | `true` | 校验失败时错误提示前缀是否使用字段的 `text` 文案;`false` 时直接使用字段 `name` |
| `extendState` | `(state: FormState) => Record<string, any> \| Promise<Record<string, any>>` | — | 扩展 `formState` | | `extendState` | `(state: FormState) => Record<string, any> \| Promise<Record<string, any>>` | — | 扩展 `formState` |
| `native` | `boolean` | `false` | 透传给 `Form.submitForm``true` 时返回内部响应式 `values`,否则返回 `cloneDeep(toRaw(values))` | | `native` | `boolean` | `false` | 透传给 `Form.submitForm``true` 时返回内部响应式 `values`,否则返回 `cloneDeep(toRaw(values))` |
| `returnChangeRecords` | `boolean` | `false` | `true` 时 resolve 结果为 `{ values, changeRecords }`,携带表单变更记录;否则仅 resolve `values` |
| `appContext` | `AppContext \| null` | `null` | 父级 Vue 应用上下文。需要继承全局组件、指令、provide 等时传入,常通过 `app._context``getCurrentInstance()?.appContext` 获取 | | `appContext` | `AppContext \| null` | `null` | 父级 Vue 应用上下文。需要继承全局组件、指令、provide 等时传入,常通过 `app._context``getCurrentInstance()?.appContext` 获取 |
| `timeout` | `number` | `10000` | 等待表单初始化的最长时间(毫秒)。超时将以错误 reject。设为 `<= 0` 时关闭超时兜底 | | `timeout` | `number` | `10000` | 等待表单初始化的最长时间(毫秒)。超时将以错误 reject。设为 `<= 0` 时关闭超时兜底 |
## 返回值 ## 返回值
- `校验通过``Promise<any>` resolve 当前表单值(`native` 决定是否克隆) - `校验通过``Promise<any>` resolve 当前表单值(`native` 决定是否克隆);当 `returnChangeRecords``true`resolve `{ values, changeRecords }`
- `校验失败``Promise<any>` reject 一个 `Error``message` 中包含逐条字段错误信息(格式 `${text} -> ${message}`,多条用 `<br>` 分隔) - `校验失败``Promise<any>` reject 一个 `Error``message` 中包含逐条字段错误信息(格式 `${text} -> ${message}`,多条用 `<br>` 分隔)
- `初始化超时``Promise<any>` reject `Error('submitForm timeout after ${timeout}ms: form is not initialized.')` - `初始化超时``Promise<any>` reject `Error('submitForm timeout after ${timeout}ms: form is not initialized.')`
无论成功或失败,函数都会在最后自动 `unmount` 内部 app 并移除挂载用的 DOM 容器,无需调用方手动清理。 无论成功或失败,函数都会在最后自动 `unmount` 内部 app 并移除挂载用的 DOM 容器,无需调用方手动清理。
::: tip 关于 changeRecords
`changeRecords` 记录的是表单挂载后发生的字段变更(由各字段的 `change` 事件累积而来)。在 `submitForm` 这种命令式、无用户交互的场景下,通常为空数组;只有在 `extendState` 或字段联动等逻辑中触发了变更时才会有内容。`MForm` 内部的 `submitForm` 在校验通过后会清空变更记录,因此本函数会在调用前先对其做快照再返回。
:::
## 基础用法 ## 基础用法
```ts ```ts
@ -62,7 +68,10 @@ try {
type: 'text', type: 'text',
name: 'username', name: 'username',
text: '用户名', text: '用户名',
rules: [{ required: true, message: '请输入用户名' }], rules: [
{ required: true, message: '请输入用户名' },
{ typeMatch: true, message: '用户名类型不合法' },
],
}, },
], ],
initValues: { username: '' }, initValues: { username: '' },
@ -73,6 +82,23 @@ try {
} }
``` ```
## 同时获取变更记录changeRecords
设置 `returnChangeRecords: true`resolve 的结果会从单纯的 `values` 变为 `{ values, changeRecords }`
```ts
import { submitForm } from '@tmagic/form';
const { values, changeRecords } = await submitForm({
config: [{ type: 'text', name: 'username', text: '用户名' }],
initValues: { username: 'foo' },
returnChangeRecords: true,
});
console.log(values); // { username: 'foo' }
console.log(changeRecords); // ChangeRecord[]
```
## 在组件中继承父级应用上下文 ## 在组件中继承父级应用上下文
`MForm` 内部使用 `@tmagic/design` 的组件(背后可能是 `element-plus``tdesign`),需要宿主应用先完成相应的 `app.use(...)` 安装。在 `submitForm` 这种脱离常规组件树的命令式调用中,可通过 `appContext` 把父级应用上下文带过去: `MForm` 内部使用 `@tmagic/design` 的组件(背后可能是 `element-plus``tdesign`),需要宿主应用先完成相应的 `app.use(...)` 安装。在 `submitForm` 这种脱离常规组件树的命令式调用中,可通过 `appContext` 把父级应用上下文带过去:
@ -190,3 +216,7 @@ console.log(values);
::: details 查看 `SubmitFormOptions` 类型定义 ::: details 查看 `SubmitFormOptions` 类型定义
<<< @/../packages/form/src/submitForm.ts#SubmitFormOptions{ts} <<< @/../packages/form/src/submitForm.ts#SubmitFormOptions{ts}
::: :::
::: details 查看 `SubmitFormResult` 类型定义
<<< @/../packages/form/src/submitForm.ts#SubmitFormResult{ts}
:::

View File

@ -1,7 +1,30 @@
# 表单对比 # 表单对比
tmagic-form可以支持两个版本的表单值对比如果有容器嵌套将在tab标签页展示对应tab下存在的差异数便于在复杂嵌套表单场景下直观的看到差异情况 tmagic-form可以支持两个版本的表单值对比如果有容器嵌套将在tab标签页展示对应tab下存在的差异数便于在复杂嵌套表单场景下直观的看到差异情况
## 使用方法 ## 使用方法
在初始化表单时,需要传入当前版本的表单值,上一版本的表单值,以及表单配置,具体可参见[Form Playground](https://tencent.github.io/tmagic-editor/playground/index.html#/form)的demo演示 在初始化表单时,开启对比模式 `is-compare`,并传入当前版本的表单值(`init-values`)、上一版本的表单值(`last-values`)以及表单配置,具体可参见[Form Playground](https://tencent.github.io/tmagic-editor/playground/index.html#/form)的demo演示。
```html
<m-form
:config="config"
:is-compare="true"
:init-values="curValues"
:last-values="lastValues"
></m-form>
```
相关属性详见 Form 组件 props
- [`isCompare`](/api/form/form-props.html#iscompare):是否开启对比模式;
- [`lastValues`](/api/form/form-props.html#lastvalues):需对比的上一版本表单值;
- [`showDiff`](/api/form/form-props.html#showdiff):自定义「是否展示对比内容」的判断函数,用于规避语义相等但结构不同导致的误判。
## 对比模式下的字段行为
对比模式下,表单仅做只读展示:增删、复制、排序、导入、编辑等写操作按钮会被隐藏。对于由列表或嵌套子表单组成的复合字段(如 `event-select``code-select``code-select-col`),表单会按索引对齐前后值,逐项展示新增 / 删除 / 修改的高亮差异,而不会渲染出两套独立组件。
## 应用场景
编辑器的[历史记录面板](/guide/advanced/history-list.md)即基于该能力,对历史步骤的前后值做表单形式的差异对比。
## 效果展示 ## 效果展示
<img src="https://vip.image.video.qpic.cn/vupload/20230301/c626071677661813135.png" alt="表单对比"/> <img src="https://vip.image.video.qpic.cn/vupload/20230301/c626071677661813135.png" alt="表单对比"/>

View File

@ -27,6 +27,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:要求 `string`,有代码块 DSL 时须为已有 codeId。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -24,6 +24,10 @@ CodeSelect 组件支持:
- 选择数据源方法 - 选择数据源方法
- 配置代码块参数 - 配置代码块参数
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:做 `{ hookType: 'code', hookData }` 的浅层结构校验,`codeId` / 数据源方法存在性由内部单元格各自校验。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -41,6 +41,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:默认要求 `string``parse: true` 时跳过校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -27,6 +27,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为已知算子,能解析字段类型时按类型收窄。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -49,6 +49,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为数据源路径 `string[]`,有 `fieldConfig` 且非路径值时跳过。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -16,6 +16,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为数组并做 `name`/`type` 等浅层结构校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -16,6 +16,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:要求 `string``${...}` 绑定须指向已有数据源 / 字段。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -27,6 +27,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为 `[dsId, methodName]`,方法须在该数据源可选方法集中。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -16,6 +16,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为数组并做 `content`/`params` 等浅层结构校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -16,6 +16,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为数组并做 `title`/`enable`/`data` 等浅层结构校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -38,6 +38,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:`value: 'id'` 时须为已有 ds id否则为含 `isBindDataSource` + `dataSourceId` 的对象。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -27,6 +27,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为数组并做 `cond[].field`/`op` 浅层结构校验,算子合法性 / 字段路径存在性由内部单元格各自校验。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -28,6 +28,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为数组并做兼容新旧格式的浅层结构校验,事件名 / 联动动作是否属于可选项由内部单元格各自校验。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -29,6 +29,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为普通对象,`advanced` 且值为 `function` 时放行。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -16,6 +16,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为 `string``number`,有节点树时须为已有页面片 id。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -16,6 +16,10 @@
} }
``` ```
## 值校验
安装 `@tmagic/editor` 后该字段会自动注册内置 `typeMatch` 校验规则:须为 `string``number`,有节点树时须为已有组件 id。服务数据未就绪时仅做基础形态校验。详见[表单校验 - Editor 字段内置规则](/form-config/rules.md#editor-字段内置规则)。
## Attributes ## Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 | | 参数 | 说明 | 类型 | 可选值 | 默认值 |

View File

@ -24,6 +24,26 @@ type为'select'
</template> </template>
</demo-block> </demo-block>
## 选项值校验
可在 `rules` 中开启 `typeMatch`,校验当前值是否落在 `options` 中(`multiple` 时校验数组元素)。详见[表单校验](/form-config/rules.md)。
```ts
{
type: 'select',
name: 'status',
text: '状态',
options: [
{ text: '启用', value: 1 },
{ text: '禁用', value: 0 },
],
rules: [
{ required: true, message: '请选择状态' },
{ typeMatch: true, message: '状态值不合法' },
],
}
```
## 有禁用选项 ## 有禁用选项
<demo-block type="form" :config="[{ <demo-block type="form" :config="[{

View File

@ -82,6 +82,21 @@ Input输入框的type为'text', 是type的默认值所以可以不配置
</template> </template>
</demo-block> </demo-block>
## 表单校验
可通过 `rules` 配置校验规则。其中 `typeMatch: true` 会按字段 type以及 `filter` / `valueFormat` 等)校验值是否合法,详见[表单校验](/form-config/rules.md)。
```ts
{
name: 'text',
text: '输入框',
rules: [
{ required: true, message: '请输入' },
{ typeMatch: true, message: '值类型不合法' },
],
}
```
## 去掉首尾空格 ## 去掉首尾空格
<demo-block type="form" :config="[{ <demo-block type="form" :config="[{
@ -124,6 +139,7 @@ Input输入框的type为'text', 是type的默认值所以可以不配置
| tooltip | 输入时显示内容 | string / `ToolTipConfigType` | — | — | | tooltip | 输入时显示内容 | string / `ToolTipConfigType` | — | — |
| trim | 是否去掉首尾空格 | boolean | — | false | | trim | 是否去掉首尾空格 | boolean | — | false |
| filter | 过滤值 | string / Function | number | - | | filter | 过滤值 | string / Function | number | - |
| rules | 表单验证规则 | `Rule[]` | — | — |
| prepend | 前置内容 | string | — | - | | prepend | 前置内容 | string | — | - |
| append | 后置内容 | string / Object | — | - | | append | 后置内容 | string / Object | — | - |
| onChange | 值变化时触发的函数 | `OnChangeHandler` | — | - | | onChange | 值变化时触发的函数 | `OnChangeHandler` | — | - |
@ -140,6 +156,8 @@ Input输入框的type为'text', 是type的默认值所以可以不配置
<<< @/../packages/form-schema/src/base.ts#FormValue{ts} <<< @/../packages/form-schema/src/base.ts#FormValue{ts}
<<< @/../packages/form-schema/src/base.ts#ToolTipConfigType{ts} <<< @/../packages/form-schema/src/base.ts#ToolTipConfigType{ts}
<<< @/../packages/form-schema/src/base.ts#Rule{ts}
::: :::

View File

@ -135,6 +135,18 @@
}] }]
}]"></demo-block> }]"></demo-block>
`legend` 除了支持字符串,也支持函数,函数返回值作为标题展示,可根据表单数据动态生成:
<demo-block type="form" :config="[{
type: 'fieldset',
labelWidth: '100px',
legend: (mForm, { formValue }) => `当前值:${formValue.text || '空'}`,
items: [{
name: 'text',
text: '配置1',
}]
}]"></demo-block>
### panel ### panel
<demo-block type="form" :config="[{ <demo-block type="form" :config="[{

206
docs/form-config/rules.md Normal file
View File

@ -0,0 +1,206 @@
# 表单校验
`@tmagic/form` 字段可通过 `rules` 配置校验规则,兼容 [async-validator](https://github.com/yiminghe/async-validator)Element Plus 内部使用)的常见能力,并额外支持按字段 `type` 做值类型 / 选项匹配校验(`typeMatch`)。
## 基础用法
```ts
{
name: 'title',
text: '名称',
rules: [
{ required: true, message: '请输入名称' },
{ typeMatch: true, message: '名称类型不合法' },
],
}
```
`rules` 类型见下方 [`Rule`](#类型定义)。未配置 `typeMatch` 时,现有表单行为不变。
## typeMatch
开启 `typeMatch: true` 后,表单会按字段 `config.type`(及关联配置)校验当前值是否合法。空值(`undefined` / `null` / `''`,多选类空数组 `[]`)直接通过,必填请继续使用 `required`
### 内置映射
| 字段 type | 期望值 |
| --- | --- |
| `text` / `textarea` / `color-picker` / `html` / 默认无 type | `string`;若 `filter: 'number'` 则为 `number``filter` 为自定义函数时跳过内置类型校验 |
| `display` / `hidden` | 不校验 |
| `number` | `number`(非 NaN |
| `number-range` | 长度为 2 的数字数组 |
| `date` / `datetime` / `time` | 按 `valueFormat` 校验;`x` / `timestamp` 期望 `number`,其余按 [Day.js format](https://day.js.org/docs/en/display/format) 严格解析字符串 |
| `daterange` / `timerange` | 无 `names` 时为长度为 2 的数组,元素按 `valueFormat` 校验;有 `names` 时跳过 |
| `switch` / `checkbox` | 值必须是解析后的 `activeValue` / `inactiveValue` 之一(显式配置优先;未配置且 `filter === 'number'` 时为 `1`/`0`;否则为 `true`/`false` |
| `select` | 单选:值 ∈ options`multiple`:数组且每项 ∈ options`allowCreate` / `remote`:只校验基础形态,不做 options 枚举 |
| `radio-group` / `radioGroup` | 值 ∈ options |
| `checkbox-group` / `checkboxGroup` | 数组且每项 ∈ options |
| `cascader` | 有 `valueSeparator` 时可为 `string``array`;默认 `emitPath` 为路径数组;`emitPath: false` 为叶子值;`multiple` 为数组;静态 options 校验路径/叶子;`remote` 只做形态校验 |
| `table` / `group-list` / `groupList` | `array` |
| 容器类(`row` / `tab` / `fieldset` / `panel` / `step` / `flex-layout` / `link` / `component` / `dynamic-field` 等) | 不校验 |
日期类默认 `valueFormat` 与字段组件一致:
- `date``YYYY/MM/DD`
- `datetime` / `daterange``YYYY/MM/DD HH:mm:ss`
- `time` / `timerange``HH:mm:ss`
### 与自定义 validator 共存
同一条 rule 同时配置了 `typeMatch``validator` 时,会先做类型匹配校验,通过后再执行自定义 `validator`
```ts
{
name: 'age',
type: 'number',
rules: [
{
typeMatch: true,
message: '年龄必须是数字',
validator: ({ value, callback }) => {
if (value < 0) {
callback(new Error('年龄不能小于 0'));
return;
}
callback();
},
},
],
}
```
## 扩展自定义 type 规则
业务可覆盖内置规则,或为自定义字段 type 注册校验。自定义规则优先于内置规则。
### 运行时注册
```ts
import {
registerTypeMatchRule,
registerTypeMatchRules,
deleteTypeMatchRule,
clearTypeMatchRules,
} from '@tmagic/form';
// 覆盖内置 text
registerTypeMatchRule('text', (value, { message }) => {
if (typeof value !== 'string') {
return message || '值类型应为字符串';
}
});
// 扩展业务字段
registerTypeMatchRule('vs-code', (value, { message }) => {
if (typeof value !== 'string') {
return message || '代码字段应为字符串';
}
});
// 批量注册
registerTypeMatchRules({
foo: (value) => (Array.isArray(value) ? undefined : '应为数组'),
});
// 删除 / 清空
deleteTypeMatchRule('foo');
clearTypeMatchRules();
```
自定义校验器签名:`(value, context) => string | undefined`。返回错误文案表示失败,返回 `undefined` 表示通过。`context` 包含 `fieldType``mForm``props``message`
### 安装时注册
```ts
import MagicForm from '@tmagic/form';
app.use(MagicForm, {
typeMatchRules: {
'my-field': (value, { message }) => {
if (typeof value !== 'string') {
return message || 'my-field 应为字符串';
}
},
},
});
```
### Editor 字段内置规则
安装 `@tmagic/editor` 时会自动 `registerTypeMatchRules` 注册编辑器自定义字段规则。服务数据(数据源 / 代码块 / 节点树)未就绪时,只做基础形态校验,不做枚举或存在性失败。
| 字段 type | 期望值 |
| --- | --- |
| `key-value` / `style-setter` | 普通对象;`key-value` + `advanced` 且值为 `function` 时放行 |
| `cond-op-select` | 已知算子;能解析字段类型时按类型收窄 |
| `code-select-col` | `string`;有代码块 DSL 时须为已有 codeId |
| `page-fragment-select` / `ui-select` | `string \| number`;有节点树时须为已有页面片 / 组件 id |
| `data-source-input` | `string``${...}` 绑定须指向已有数据源/字段 |
| `data-source-method-select` | `[dsId, methodName]`,方法须在该数据源可选方法集中 |
| `data-source-field-select` | 数据源路径 `string[]`;有 `fieldConfig` 且非路径值时跳过 |
| `data-source-select` | `value: 'id'` 为已有 ds id否则为含 `isBindDataSource` + `dataSourceId` 的对象 |
| `code-select` | `{ hookType: 'code', hookData }` 的浅层结构校验(`codeId` 存在性 / 数据源方法存在性由内部 `code-select-col``data-source-method-select` 单元格各自校验,只标红出错单元格) |
| `data-source-fields` / `data-source-mocks` / `data-source-methods` | 数组 + 浅层结构(`name`/`type``title`/`enable`/`data``content`/`params` 等) |
| `event-select` | 数组;兼容新旧格式的浅层结构校验(`name` / 联动组件 `method` 是否 ∈ 可选项由字段内 `eventNameConfig.rules``compActionConfig.rules` 单独校验,只标红对应 select |
| `display-conds` | 数组 + `cond[].field`/`op` 浅层结构校验(`op` 是否为已知算子、字段路径是否存在由内部 `cond-op-select``field` 单元格各自校验,只标红出错单元格) |
> 容器类字段(`event-select` / `code-select` / `display-conds`)遵循同一约定:容器级 typeMatch 只做结构校验,「枚举 / 存在性」下沉到内部单元格各自的 typeMatch/rules避免单个子项非法导致整块表单标红。
业务仍可用 `registerTypeMatchRule` 覆盖上述任一 type。
## 示例
### select 选项匹配
```ts
{
name: 'status',
type: 'select',
options: [
{ text: '启用', value: 1 },
{ text: '禁用', value: 0 },
],
rules: [
{ required: true, message: '请选择状态' },
{ typeMatch: true, message: '状态值不合法' },
],
}
```
### date 按 valueFormat 校验
```ts
{
name: 'birthday',
type: 'date',
valueFormat: 'YYYY-MM-DD',
rules: [{ typeMatch: true, message: '日期格式不正确' }],
}
```
### text + filter: number
```ts
{
name: 'width',
type: 'text',
filter: 'number',
rules: [{ typeMatch: true, message: '宽度应为数字' }],
}
```
## 类型定义
::: details 查看 Rule 类型定义
<<< @/../packages/form-schema/src/base.ts#Rule{ts}
:::
::: details 查看 TypeMatchValidator / TypeMatchValidateContext 类型定义
<<< @/../packages/form/src/utils/typeMatch.ts#TypeMatchValidator{ts}
<<< @/../packages/form/src/utils/typeMatch.ts#TypeMatchValidateContext{ts}
:::
::: details 查看 FormInstallOptions 类型定义
<<< @/../packages/form/src/plugin.ts#FormInstallOptions{ts}
:::

View File

@ -0,0 +1,173 @@
# 历史记录面板
编辑器内置了一个可视化的「历史记录面板」,用于查看与回溯编辑过程中产生的所有操作。相比顶部菜单栏只能「撤销 / 重做」相邻一步,历史记录面板提供了对整条历史栈的全局视角:可以按页面、数据源、代码块分类浏览,点击任意一步直接跳转,查看每一步的前后差异,甚至像 `git revert` 一样单独回滚某一步而不破坏后续操作。
## 开启面板
历史记录面板以一个内置菜单项 `'history-list'` 的形式提供,将它加入 [`menu`](/api/editor/props.html#menu) 配置即可在顶部工具栏出现一个时钟图标,点击展开面板:
```html
<template>
<m-editor :menu="menu"></m-editor>
</template>
<script setup>
import { ref } from 'vue';
const menu = ref({
left: [],
center: ['delete', 'undo', 'redo', '/', 'history-list'],
right: [],
});
</script>
```
## 面板结构
面板分为三个 tab分别对应三类可被历史记录追踪的对象tab 标题后的数字为各自的分组数量:
| Tab | 内容 | 跳转 API |
| --- | --- | --- |
| 页面 | 当前活动页面的节点操作历史 | `editorService.gotoPageStep(cursor)` |
| 数据源 | 按 `dataSource.id` 分组的数据源变更历史 | `dataSourceService.goto(id, cursor)` |
| 代码块 | 按 `codeBlock.id` 分组的代码块变更历史 | `codeBlockService.goto(id, cursor)` |
### 相邻同目标自动合并
为了避免「连续微调同一个节点 / 数据源 / 代码块」时产生大量碎片化记录,面板会把**相邻的、针对同一目标的连续 `update`** 自动合并成一个分组:
- 页面 tab连续修改同一节点按节点 id 判定)的多步合并为一组,点击组头部可展开查看每一子步;
- 数据源 / 代码块 tab相邻的连续 `update` 按目标 id 合并;`add` / `remove` 始终独立成组(语义上是一次性事件)。
> 合并仅作用于展示与交互,不改变底层 undo/redo 栈的真实结构。
## 交互能力
每个分组 / 步骤支持以下操作:
### 1. 点击跳转
点击任意一条记录编辑器会跳转到「应用至该步完成」的状态。其本质是把对应栈的游标cursor移动到 `step.index + 1`,由 service 层的 undo/redo 链路完成中间步骤的批量正向 / 反向应用。
### 2. 回到初始状态
每个 tab 列表底部提供「回到初始状态」入口,等价于把对应栈游标移到 `0`(所有真实步骤全部撤销)。
### 3. 单步回滚(类 git revert
对于历史中间的某一步,可以单独「回滚」它,而保留它之后的所有操作。该行为不会倒带游标,而是把目标步骤的修改**反向应用为一次全新的操作**并压入栈顶,因此不会破坏既有历史结构:
- 页面:`editorService.revertPageStep(index)`
- 数据源:`dataSourceService.revert(id, index)`
- 代码块:`codeBlockService.revert(id, index)`
如果业务侧在执行操作时已通过 `*AndGetHistoryId` 拿到了该条记录的 uuid见 [uuid 与 *AndGetHistoryId](/api/editor/editorServiceMethods.md#历史记录-uuid-与-andgethistoryid) 返回的 `historyIds`),也可以直接按 uuid 回滚(无需再关心 index / id且 uuid 不会随栈内步骤增删而变化):
- 页面:`editorService.revertPageStepById(uuids)`
- 数据源:`dataSourceService.revertById(uuids)`
- 代码块:`codeBlockService.revertById(uuids)`
#### 复用面板的「交互式回滚 / 查看差异」流程
上面的 `revert*` 方法是**静默**的:它们直接执行反向应用,不做任何校验与二次确认。如果业务方想在自己的入口(自定义按钮、右键菜单等)里复用历史面板那一套**完整交互流程**——即「目标数据已删除的前置校验 + 失败提示」「可差异步骤弹差异确认弹窗 / 其余步骤弹普通二次确认框」「用户确认后才回滚」,以及「查看差异」弹窗——可以直接 import `useHistoryRevert`
```ts
import { useHistoryRevert } from '@tmagic/editor';
// editorRef 为 <m-editor> 组件实例,其 expose 出的即各 service 集合Services
const {
onPageRevert,
onDataSourceRevert,
onCodeBlockRevert,
onPageDiff,
onDataSourceDiff,
onCodeBlockDiff,
} = useHistoryRevert({}, editorRef.value);
// 回滚:可差异步骤弹出差异确认弹窗、其余步骤弹普通二次确认框;用户点「确定」后回滚第 index 步,
// 命中前置校验或用户取消时不执行,返回 null
await onPageRevert(index);
await onDataSourceRevert(id, index);
await onCodeBlockRevert(id, index);
// 查看差异:可差异步骤弹出只读差异弹窗展示前后值差异,无可对比内容时不弹窗
onPageDiff(index);
onDataSourceDiff(id, index);
onCodeBlockDiff(id, index);
```
回滚确认弹窗与查看差异弹窗均由 `useHistoryRevert` 内部**按需动态挂载** `HistoryDiffDialog` 实现,业务方无需自行挂载任何弹窗组件。第二个参数 `options` 可选:
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `appContext` | 否 | 父级应用上下文,用于让动态挂载的差异确认弹窗继承全局组件 / 指令 / provide / 插件Element Plus、`@tmagic/form` 字段组件等)。在组件 `setup` 中调用时会自动取当前组件的 `appContext`,无需手动传;仅当在组件 setup 之外调用时才需显式传入(如 `editorApp._context`)。 |
| `extendState` | 否 | 透传给差异确认弹窗的 `extendState`(同 Editor 的 [`extendFormState`](#自定义对比判断)),使对比表单中依赖业务上下文的 `display` / `disabled``filterFunction` 正常工作。 |
| `dialogWidth` | 否 | 内置页面 / 数据源 / 代码块的差异 / 回滚确认弹窗默认宽度(透传给 `TMagicDialog``width`),如 `'1200px'` / `'80%'`。缺省时使用弹窗内置默认宽度(`900px`)。业务自有历史可在 `viewDiff` / `confirmAndRevert` 调用时通过各自入参的 `width` 单独覆盖。 |
> 若只需要无确认、无校验的静默回滚,直接用上面的 `editorService.revertPageStep` 等即可,无需 `useHistoryRevert`
### 4. 差异对比
在前后值都存在的 `update` 步骤上提供「查看差异」入口,点击后弹出差异对话框。对话框支持两个维度的切换:
- **对比对象**
- `与修改前对比`:该步骤修改前 vs 修改后(默认,体现这一步带来的变化);
- `与当前对比`:该步骤修改后 vs 编辑器中的最新值(用于确认「这一步之后是否又被改动过」,当前值缺失时禁用)。
- **展示形态**
- `表单对比`:以属性表单形式逐字段对比,可读性更好(基于 [表单对比](/form-config/compare.md) 能力);
- `源码对比`:以 JSON 源码做整体 diff基于 monaco diff 编辑器),可以看到表单未覆盖到的字段。
::: tip
表单对比依赖 `@tmagic/form` 的对比模式(`isCompare` / `lastValues`)。对于 `event-select``code-select``code-select-col` 等由列表或嵌套子表单组成的复合字段,表单会逐项展示新增 / 删除 / 修改的高亮差异,并在对比模式下隐藏「添加 / 删除 / 编辑」等写操作按钮,仅保留只读展示。
:::
## 扩展自定义 tab
内置的三个 tab 之外,业务方可以通过 Editor 的 [`historyListExtraTabs`](/api/editor/props.html#historylistextratabs) 在面板中追加自定义的历史 tab追加在「页面 / 数据源 / 代码块」之后。适用于某个自定义模块维护自己的操作历史,需要在历史记录面板中独立展示与回滚的场景。
```html
<template>
<m-editor :menu="menu" :history-list-extra-tabs="historyListExtraTabs"></m-editor>
</template>
<script setup>
import { markRaw } from 'vue';
import MyModuleHistoryTab from './MyModuleHistoryTab.vue';
const historyListExtraTabs = [
{
name: 'my-module',
// label 支持字符串或函数,函数形式便于展示动态数量
label: () => `我的模块 (${getMyModuleHistory().length})`,
component: markRaw(MyModuleHistoryTab),
props: { foo: 'bar' },
listeners: {
goto: (cursor) => console.log(cursor),
},
},
];
</script>
```
每个扩展 tab 的字段说明:
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `name` | 是 | tab 唯一标识,作为内部 `TMagicTabs``name` |
| `label` | 是 | tab 显示文案,支持字符串或返回字符串的函数(便于展示动态数量) |
| `component` | 是 | tab 内容区渲染的组件 |
| `props` | 否 | 传入内容组件的 props |
| `listeners` | 否 | 内容组件的事件监听 |
> 内容组件内部可自行通过 `useServices()` 拿到 `historyService` 等服务,读取并回滚自定义模块自己维护的历史。
## 自定义对比判断
差异对话框中的「表单对比」最终透传到 `MForm`,你可以通过 Editor 顶层注入的 `extendFormState` 让对比表单拿到完整业务上下文,从而让依赖上下文的 `display` / `disabled``filterFunction` 正常工作。
若某些字段语义上相等但结构不同(例如 `code-select` 字段中 `''``{ hookType: 'code', hookData: [] }` 应视为相等),可借助 `@tmagic/form` 的 [`showDiff`](/api/form/form-props.html#showdiff) 自定义判断函数避免被误判为差异。
## 相关 API
历史面板的数据均来自 `historyService` 暴露的聚合方法,详见 [historyService 方法](/api/editor/historyServiceMethods.md)。

View File

@ -0,0 +1,121 @@
# 属性配置表单校验联动
编辑器在属性面板(属性表单 / 样式表单)中已支持 [表单校验](../../form-config/rules.md)。默认情况下,表单校验失败时本次改动会被丢弃,不会写入节点。
「属性配置表单校验联动」能力(`enablePropsFormValidate`)允许在**校验失败时仍按当前表单值更新节点**,并把错误信息集中记录到 `editorService`,从而实现:
- 组件树(图层)中对出错节点**标红并显示错误图标**,悬停可查看错误文案;
- 业务在**保存前拦截**存在校验错误的组件(见 [保存拦截](#保存拦截)
- 校验错误随 DSL 操作写入历史快照,**撤销 / 重做能正确还原**错误状态。
> 该能力默认关闭,需通过 `<m-editor :enable-props-form-validate="true">` 显式开启。
## 工作原理
### 错误来源维度
属性面板分「属性」与「样式」两个独立的 `FormPanel`,它们指向同一节点。为避免某个面板校验通过时误清另一个面板记录的错误,错误信息**以来源(`source`)为键分别保存**
- `'props'`:属性表单校验错误
- `'style'`:样式表单校验错误
节点只要**任一来源存在非空错误文案**即视为出错。
内部类型定义见 `NodeInvalidInfo`
```ts
interface NodeInvalidInfo {
/** 属性表单校验错误文案(可能为包含 <br> 的 HTML */
props?: string;
/** 样式表单校验错误文案(可能为包含 <br> 的 HTML */
style?: string;
}
```
### 数据流
1. 表单校验失败时(开启了 `enablePropsFormValidate``FormPanel` 仍以当前表单值提交,并把错误随提交事件一并抛出;
2. `PropsPanel` 在调用 `editorService.update()` 时,把 `invalidInfo: { id, source, error }` 一并传入;
3. `editorService` 在**写入历史记录之前**落库错误标记(`applyInvalidInfo`),使历史快照与本次变更对齐;
4. 错误被记录到 `invalidNodeIds` 状态,并触发 `invalid-node-change` 事件;
5. 组件树节点通过读取 `invalidNodeIds` 响应式地展示标红与错误图标。
校验成功时(或源码编辑器保存时)不携带 `invalidInfo`,保持已有错误状态不变(即不会清除错误)——只有对应来源的表单再次校验通过才会清除该来源的错误。
## 快速开始
```html
<template>
<m-editor :enable-props-form-validate="true"></m-editor>
</template>
```
开启后无需其它配置,属性 / 样式表单校验失败即会自动记录错误并标红组件树节点。
## 读取与清除错误
业务侧可通过 `editorService` 读取或清除错误标记:
```js
import { editorService } from "@tmagic/editor";
// 读取全部错误节点Map<Id, NodeInvalidInfo>
const invalidNodeIds = editorService.getInvalidNodeIds();
// 读取单个节点的错误
const info = editorService.getInvalidNodeInfo("text_123");
// 手动记录 / 清除错误(一般无需手动调用,属性面板已自动维护)
editorService.setInvalidNode("text_123", "props", "标题不能为空");
editorService.deleteInvalidNode("text_123", "props"); // 仅清除属性表单错误
editorService.resetInvalidNodeId(); // 清空全部错误
```
订阅错误状态变化(非响应式消费方,如自定义工具栏):
```js
editorService.on("invalid-node-change", (invalidNodeIds) => {
console.log("校验错误节点数:", invalidNodeIds.size);
});
```
> 响应式读取(如自定义组件树节点内容)请直接读取 `editorService.get('invalidNodeIds')`,其变化会触发 Vue 响应式更新。
## 保存拦截
开启校验联动后,业务可读取 `invalidNodeIds`,在存在校验错误时阻止保存并提示:
```js
import { editorService } from "@tmagic/editor";
import { tMagicMessage } from "@tmagic/design";
const checkInvalidNodes = (services) => {
const invalidNodeIds = services?.editorService.getInvalidNodeIds?.();
if (!invalidNodeIds || invalidNodeIds.size === 0) {
return true;
}
const names = [...invalidNodeIds.keys()].map((id) => {
const node = services?.editorService.getNodeById(id);
return node?.name ? `${node.name}(${id})` : `${id}`;
});
tMagicMessage.error(`以下组件存在配置校验错误,请修复后再保存:${names.join("、")}`);
return false;
};
// 在菜单保存按钮 / 预览保存的 handler 中:
if (!checkInvalidNodes(services)) return;
save();
```
playground 已内置该拦截逻辑,参见 `playground/src/pages/composables/use-editor-menu.ts`
## 与历史记录的关系
错误标记会随 DSL 操作(`add` / `update` 等)一并写入历史快照。编辑器内部在「操作前」与「操作后」分别留存错误状态快照:
- **撤销undo**:还原到操作前的错误状态(撤销一个「校验失败」的改动后错误消失);
- **重做redo**:还原到操作后的错误状态(重做后错误恢复)。
整体替换 `root`(如加载新 DSL后会自动清理不存在于新 DSL 中的失效节点错误记录,避免残留误报;删除节点时也会同步清理其子树相关的错误记录。

View File

@ -2,7 +2,7 @@
tmagic-editor的表单配置核心就是使用了 @tmagic/form 来作为渲染器。@tmagic/form 是一个 npm 包,可以安装它,在你想使用的地方单独使用。 tmagic-editor的表单配置核心就是使用了 @tmagic/form 来作为渲染器。@tmagic/form 是一个 npm 包,可以安装它,在你想使用的地方单独使用。
@tmagic/form 接受一个表单配置,详细配置可参考[表单 api](../../api/form/form-props.md)。 @tmagic/form 接受一个表单配置,详细配置可参考[表单 api](../../api/form/form-props.md)。字段校验(含 `typeMatch` 类型匹配)见[表单校验](../../form-config/rules.md)。
## 安装 ## 安装
@ -45,6 +45,20 @@ app.use(MagicForm);
app.mount("#app"); app.mount("#app");
``` ```
也可在安装时传入自定义 `typeMatch` 规则,详见[表单校验 - 扩展自定义 type 规则](../../form-config/rules.md#扩展自定义-type-规则)
```javascript
app.use(MagicForm, {
typeMatchRules: {
'my-field': (value, { message }) => {
if (typeof value !== 'string') {
return message || 'my-field 应为字符串';
}
},
},
});
```
以上代码便完成了 @tmagic/form 的引入。需要注意的是Element Plus 的样式文件需要单独引入。 以上代码便完成了 @tmagic/form 的引入。需要注意的是Element Plus 的样式文件需要单独引入。

View File

@ -1,5 +1,5 @@
{ {
"version": "1.8.0-beta.1", "version": "1.8.0-beta.11",
"name": "tmagic", "name": "tmagic",
"private": true, "private": true,
"type": "module", "type": "module",
@ -40,44 +40,44 @@
"url": "https://github.com/Tencent/tmagic-editor.git" "url": "https://github.com/Tencent/tmagic-editor.git"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^20.1.0", "@commitlint/cli": "^20.5.3",
"@commitlint/config-conventional": "^20.0.0", "@commitlint/config-conventional": "^20.5.3",
"@tmagic/eslint-config": "workspace:*", "@tmagic/eslint-config": "workspace:*",
"@types/node": "24.0.10", "@types/node": "24.0.10",
"@vitejs/plugin-vue": "^6.0.6", "@vitejs/plugin-vue": "^6.0.8",
"@vitest/coverage-v8": "^4.1.5", "@vitest/coverage-v8": "^4.1.10",
"@vue/compiler-sfc": "catalog:", "@vue/compiler-sfc": "catalog:",
"c8": "^10.1.3", "c8": "^10.1.3",
"commitizen": "^4.3.1", "commitizen": "^4.3.2",
"conventional-changelog-cli": "^5.0.0", "conventional-changelog-cli": "^5.0.0",
"cosmiconfig": "^ 9.0.0 ", "cosmiconfig": "^9.0.2",
"cz-conventional-changelog": "^3.3.0", "cz-conventional-changelog": "^3.3.0",
"element-plus": "^2.11.8", "element-plus": "^2.14.3",
"enquirer": "^2.4.1", "enquirer": "^2.4.1",
"eslint": "^10.3.0", "eslint": "^10.7.0",
"execa": "^9.6.0", "execa": "^9.6.1",
"happy-dom": "^20.9.0", "happy-dom": "^20.10.6",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"husky": "^9.1.7", "husky": "^9.1.7",
"jsdom": "^27.2.0", "jsdom": "^27.4.0",
"lint-staged": "^16.2.7", "lint-staged": "^16.4.0",
"minimist": "^1.2.8", "minimist": "^1.2.8",
"picocolors": "^1.1.1", "picocolors": "^1.1.1",
"prettier": "^3.8.3", "prettier": "^3.9.5",
"recast": "^0.23.11", "recast": "^0.23.12",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"rolldown": "^1.0.1", "rolldown": "^1.2.0",
"rolldown-plugin-dts": "^0.25.1", "rolldown-plugin-dts": "^0.26.0",
"sass-embedded": "^1.99.0", "sass-embedded": "^1.100.0",
"semver": "^7.7.3", "semver": "^7.8.5",
"serialize-javascript": "^7.0.0", "serialize-javascript": "^7.0.7",
"shx": "^0.3.4", "shx": "^0.3.4",
"typescript": "catalog:", "typescript": "catalog:",
"vite": "catalog:", "vite": "catalog:",
"vitepress": "^2.0.0-alpha.17", "vitepress": "2.0.0-alpha.18",
"vitest": "^4.1.6", "vitest": "^4.1.10",
"vue": "catalog:", "vue": "catalog:",
"vue-tsc": "^3.2.9" "vue-tsc": "^3.3.7"
}, },
"config": { "config": {
"commitizen": { "commitizen": {

View File

@ -1,5 +1,5 @@
{ {
"version": "1.8.0-beta.1", "version": "1.8.0-beta.11",
"name": "@tmagic/cli", "name": "@tmagic/cli",
"main": "lib/index.js", "main": "lib/index.js",
"types": "lib/index.d.ts", "types": "lib/index.d.ts",

View File

@ -1,5 +1,5 @@
{ {
"version": "1.8.0-beta.1", "version": "1.8.0-beta.11",
"name": "@tmagic/core", "name": "@tmagic/core",
"type": "module", "type": "module",
"sideEffects": false, "sideEffects": false,

View File

@ -76,10 +76,12 @@ class IteratorContainer extends Node {
} }
} }
if (Array.isArray(config.items)) {
config.items?.forEach((element: MNode) => { config.items?.forEach((element: MNode) => {
this.initNode(element, node, map); this.initNode(element, node, map);
}); });
} }
}
public setNodes(nodes: MNode[], index: number) { public setNodes(nodes: MNode[], index: number) {
const map = this.nodes[index] || new Map(); const map = this.nodes[index] || new Map();

View File

@ -79,10 +79,12 @@ class Page extends Node {
} }
} }
if (Array.isArray(config.items)) {
config.items?.forEach((element: MComponent | MContainer) => { config.items?.forEach((element: MComponent | MContainer) => {
this.initNode(element, node); this.initNode(element, node);
}); });
} }
}
public getNode<T extends TMagicNode = TMagicNode>( public getNode<T extends TMagicNode = TMagicNode>(
id: Id, id: Id,

View File

@ -1,5 +1,5 @@
{ {
"version": "1.8.0-beta.1", "version": "1.8.0-beta.11",
"name": "@tmagic/data-source", "name": "@tmagic/data-source",
"type": "module", "type": "module",
"sideEffects": false, "sideEffects": false,

View File

@ -38,8 +38,7 @@ export interface HttpDataSourceSchema extends DataSourceSchema {
}; };
autoFetch?: boolean; autoFetch?: boolean;
beforeRequest: beforeRequest:
| string string | ((options: HttpOptions, content: { app: TMagicApp; dataSource: HttpDataSource }) => HttpOptions);
| ((options: HttpOptions, content: { app: TMagicApp; dataSource: HttpDataSource }) => HttpOptions);
afterResponse: afterResponse:
| string | string
| ((response: any, content: { app: TMagicApp; dataSource: HttpDataSource; options: Partial<HttpOptions> }) => any); | ((response: any, content: { app: TMagicApp; dataSource: HttpDataSource; options: Partial<HttpOptions> }) => any);

View File

@ -241,7 +241,7 @@ export const registerDataSourceOnDemand = async (
dsl: MApp, dsl: MApp,
dataSourceModules: Record<string, () => Promise<AsyncDataSourceResolveResult>>, dataSourceModules: Record<string, () => Promise<AsyncDataSourceResolveResult>>,
) => { ) => {
const { dataSourceMethodsDeps = {}, dataSourceCondDeps = {}, dataSourceDeps = {}, dataSources = [] } = dsl; const { dataSourceMethodDeps = {}, dataSourceCondDeps = {}, dataSourceDeps = {}, dataSources = [] } = dsl;
const dsModuleMap: Record<string, () => Promise<AsyncDataSourceResolveResult>> = {}; const dsModuleMap: Record<string, () => Promise<AsyncDataSourceResolveResult>> = {};
@ -253,7 +253,7 @@ export const registerDataSourceOnDemand = async (
} }
if (!Object.keys(dep).length) { if (!Object.keys(dep).length) {
dep = dataSourceMethodsDeps[ds.id] || {}; dep = dataSourceMethodDeps[ds.id] || {};
} }
if (Object.keys(dep).length && dataSourceModules[ds.type]) { if (Object.keys(dep).length && dataSourceModules[ds.type]) {

View File

@ -377,7 +377,7 @@ describe('registerDataSourceOnDemand', () => {
], ],
dataSourceDeps: { a: { node1: { name: 'n', keys: ['x'] } } }, dataSourceDeps: { a: { node1: { name: 'n', keys: ['x'] } } },
dataSourceCondDeps: { c: { node2: { name: 'n', keys: ['y'] } } }, dataSourceCondDeps: { c: { node2: { name: 'n', keys: ['y'] } } },
dataSourceMethodsDeps: {}, dataSourceMethodDeps: {},
}; };
const httpModule = { default: class HttpDS {} }; const httpModule = { default: class HttpDS {} };
const mockModule = { default: class MockDS {} }; const mockModule = { default: class MockDS {} };

View File

@ -1,5 +1,5 @@
{ {
"version": "1.8.0-beta.1", "version": "1.8.0-beta.11",
"name": "@tmagic/dep", "name": "@tmagic/dep",
"type": "module", "type": "module",
"sideEffects": false, "sideEffects": false,

View File

@ -127,10 +127,38 @@ export default class Watcher {
deep = false, deep = false,
type?: DepTargetType | string, type?: DepTargetType | string,
) { ) {
this.collectByCallback(nodes, type, ({ node, target }) => { const targets = this.getCollectableTargets(type);
this.removeTargetDep(target, node);
this.collectItem(node, target, depExtendedData, deep); if (!targets.length) {
}); return;
}
// 整棵树只遍历一次、在每个属性上检查所有 target把结构遍历开销从 ×targets 降到 ×1详见 collectItems
for (const node of nodes) {
this.removeTargetsDep(targets, node);
this.collectItems(node, targets, depExtendedData, deep);
}
}
/**
* target collectByCallback
*
* editor dep service / worker public
* @param type
*/
public getCollectableTargets(type?: DepTargetType | string): Target[] {
const targets: Target[] = [];
traverseTarget(
this.targetsList,
(target) => {
if (!type && !target.isCollectByDefault) {
return;
}
targets.push(target);
},
type,
);
return targets;
} }
public collectByCallback( public collectByCallback(
@ -195,53 +223,11 @@ export default class Watcher {
this.clear(nodes, type); this.clear(nodes, type);
} }
/**
* target collectItems(node, [target], ...)
*/
public collectItem(node: TargetNode, target: Target, depExtendedData: DepExtendedData = {}, deep = false) { public collectItem(node: TargetNode, target: Target, depExtendedData: DepExtendedData = {}, deep = false) {
if (node[NODE_DISABLE_DATA_SOURCE_KEY] && DATA_SOURCE_TARGET_TYPES.has(target.type)) { this.collectItems(node, [target], depExtendedData, deep);
return;
}
if (node[NODE_DISABLE_CODE_BLOCK_KEY] && target.type === DepTargetType.CODE_BLOCK) {
return;
}
const collectTarget = (config: Record<string | number, any>, prop = '') => {
const doCollect = (key: string, value: any) => {
const keyIsItems = key === this.childrenProp;
const fullKey = prop ? `${prop}.${key}` : key;
if (target.isTarget(fullKey, value)) {
target.updateDep({
id: node[this.idProp],
name: `${node[this.nameProp] || node[this.idProp]}`,
data: depExtendedData,
key: fullKey,
});
} else if (!keyIsItems && Array.isArray(value)) {
for (let i = 0, l = value.length; i < l; i++) {
const item = value[i];
if (isObject(item)) {
collectTarget(item, `${fullKey}[${i}]`);
}
}
} else if (isObject(value)) {
collectTarget(value, fullKey);
}
if (keyIsItems && deep && Array.isArray(value)) {
for (const child of value) {
this.collectItem(child, target, depExtendedData, deep);
}
}
};
for (const [key, value] of Object.entries(config)) {
if (typeof value === 'undefined' || value === '') continue;
doCollect(key, value);
}
};
collectTarget(node);
} }
public removeTargetDep(target: Target, node: TargetNode, key?: string | number) { public removeTargetDep(target: Target, node: TargetNode, key?: string | number) {
@ -252,4 +238,117 @@ export default class Watcher {
} }
} }
} }
/**
* removeTargetDep target
* ×targets ×1
*
* editor dep service public
*/
public removeTargetsDep(targets: Target[], node: TargetNode, key?: string | number) {
const id = node[this.idProp];
for (const target of targets) {
target.removeDep(id, key);
}
if (typeof key === 'undefined' && Array.isArray(node[this.childrenProp]) && node[this.childrenProp].length) {
for (const item of node[this.childrenProp] as TargetNode[]) {
this.removeTargetsDep(targets, item, key);
}
}
}
/**
* collectItem target
*
* target O(targets × ) +
* Object.entries / / fullKey targets
* target ×targets ×1isTarget
*
* editor dep service / worker public
*/
public collectItems(node: TargetNode, targets: Target[], depExtendedData: DepExtendedData = {}, deep = false) {
// 对应 collectItem 开头的 NODE_DISABLE_* 判断:被禁用的 target 在该节点及其子树都不收集
const activeTargets = this.filterTargetsByNode(node, targets);
if (!activeTargets.length) {
return;
}
this.collectTargetForTargets(node, node, '', activeTargets, depExtendedData, deep);
}
private filterTargetsByNode(node: TargetNode, targets: Target[]): Target[] {
const disableDataSource = Boolean(node[NODE_DISABLE_DATA_SOURCE_KEY]);
const disableCodeBlock = Boolean(node[NODE_DISABLE_CODE_BLOCK_KEY]);
if (!disableDataSource && !disableCodeBlock) {
return targets;
}
return targets.filter((target) => {
if (disableDataSource && DATA_SOURCE_TARGET_TYPES.has(target.type)) {
return false;
}
if (disableCodeBlock && target.type === DepTargetType.CODE_BLOCK) {
return false;
}
return true;
});
}
private collectTargetForTargets(
node: TargetNode,
config: Record<string | number, any>,
prop: string,
targets: Target[],
depExtendedData: DepExtendedData,
deep: boolean,
) {
const id = node[this.idProp];
const name = `${node[this.nameProp] || node[this.idProp]}`;
for (const [key, value] of Object.entries(config)) {
if (typeof value === 'undefined' || value === '') continue;
const keyIsItems = key === this.childrenProp;
const fullKey = prop ? `${prop}.${key}` : key;
// 在该属性上检查所有 target命中的更新依赖未命中的留待递归到更深层
let notMatched: Target[] | null = null;
for (let i = 0, l = targets.length; i < l; i++) {
const target = targets[i];
if (target.isTarget(fullKey, value, config)) {
target.updateDep({
id,
name,
data: depExtendedData,
key: fullKey,
});
} else {
(notMatched || (notMatched = [])).push(target);
}
}
// 对应原 doCollect 的 else-if 分支:仅未命中的 target 才继续往 value 内部递归
if (notMatched) {
if (!keyIsItems && Array.isArray(value)) {
for (let i = 0, l = value.length; i < l; i++) {
const item = value[i];
if (isObject(item)) {
this.collectTargetForTargets(node, item, `${fullKey}[${i}]`, notMatched, depExtendedData, deep);
}
}
} else if (isObject(value)) {
this.collectTargetForTargets(node, value, fullKey, notMatched, depExtendedData, deep);
}
}
// 对应原 doCollect 末尾的无条件子节点递归
if (keyIsItems && deep && Array.isArray(value)) {
for (const child of value) {
this.collectItems(child, targets, depExtendedData, deep);
}
}
}
}
} }

View File

@ -15,7 +15,7 @@ export enum DepTargetType {
DATA_SOURCE_COND = 'data-source-cond', DATA_SOURCE_COND = 'data-source-cond',
} }
export type IsTarget = (key: string | number, value: any) => boolean; export type IsTarget = (key: string | number, value: any, data?: Record<string, any>) => boolean;
export interface TargetOptions { export interface TargetOptions {
isTarget: IsTarget; isTarget: IsTarget;

View File

@ -1,5 +1,5 @@
{ {
"version": "1.8.0-beta.1", "version": "1.8.0-beta.11",
"name": "@tmagic/design", "name": "@tmagic/design",
"type": "module", "type": "module",
"sideEffects": [ "sideEffects": [

View File

@ -35,6 +35,16 @@ defineExpose({
return form.value?.validate(); return form.value?.validate();
}, },
clearValidate(props?: string | string[]) {
if (typeof form.value?.clearValidate === 'function') {
return form.value?.clearValidate(props);
}
// tdesign 使 clearValidateelement-plus clearValidate
if (typeof form.value?.clearValidateState === 'function') {
return form.value?.clearValidateState();
}
},
resetFields() { resetFields() {
if (typeof form.value?.resetFields === 'function') { if (typeof form.value?.resetFields === 'function') {
return form.value?.resetFields(); return form.value?.resetFields();

View File

@ -8,6 +8,10 @@
<slot></slot> <slot></slot>
<div v-if="adapterType === 'element-plus' && extra" v-html="extra" class="m-form-tip"></div> <div v-if="adapterType === 'element-plus' && extra" v-html="extra" class="m-form-tip"></div>
</template> </template>
<template v-if="adapterType === 'element-plus'" #error="{ error }">
<div class="el-form-item__error">{{ resolveErrorText(error) }}</div>
</template>
</component> </component>
</template> </template>
@ -15,6 +19,7 @@
import { computed } from 'vue'; import { computed } from 'vue';
import { getDesignConfig } from './config'; import { getDesignConfig } from './config';
import { stripValidateSuggestion } from './formValidateMessage';
import type { FormItemProps } from './types'; import type { FormItemProps } from './types';
defineOptions({ defineOptions({
@ -33,4 +38,10 @@ const uiProps = computed<FormItemProps>(() => {
const { extra, ...rest } = ui?.props(props) || props; const { extra, ...rest } = ui?.props(props) || props;
return rest; return rest;
}); });
/**
* 校验错误文案中修改建议仅用于错误汇总展示
* form-item 行内错误只展示主错误描述不展示修改建议
*/
const resolveErrorText = (error?: string) => stripValidateSuggestion(error);
</script> </script>

View File

@ -43,8 +43,16 @@ const props = withDefaults(defineProps<PopoverProps>(), {
visible: undefined, visible: undefined,
tabindex: 0, tabindex: 0,
destroyOnClose: false, destroyOnClose: false,
closeOnClickOutside: true,
}); });
const emit = defineEmits<{
/** 受控模式(传入了 visible下点击外部收起时触发便于配合 v-model:visible。 */
'update:visible': [_visible: boolean];
/** 点击 popover 及其衍生浮层以外的区域时触发。 */
clickoutside: [_event: MouseEvent];
}>();
const popoverVisible = ref(false); const popoverVisible = ref(false);
const visibleWatch = watch( const visibleWatch = watch(
@ -179,6 +187,70 @@ if (props.trigger === 'hover' && typeof props.visible === 'undefined') {
}); });
} }
/**
* popover 内部触发却挂载到 body popper 之外的浮层弹窗二次确认框tooltip
* 下拉 / 日期选择等点击它们属于 popover 内部交互不应顺带把 popover 关闭
*
* 由于 @tmagic/design 通过适配器支持 element-plustdesign 等多套 UI 这里同时列出
* 两套库的浮层 classclass 名互不冲突未命中的选择器无副作用避免切换适配器后失效
*/
const DEFAULT_CLICK_OUTSIDE_IGNORE = [
// @tmagic/design
'.tmagic-design-dialog',
// element-plus
'.el-overlay',
'.el-message-box',
'.el-popper',
'.el-select-dropdown',
'.el-picker__popper',
'.el-dropdown__popper',
'.el-cascader__dropdown',
// tdesign / DialogPlugin / MessagePlugintooltip / select / dropdown / .t-popup
'.t-dialog__ctx',
'.t-dialog',
'.t-message',
'.t-popup',
].join(',');
const clickOutsideIgnoreSelector = computed(() =>
[DEFAULT_CLICK_OUTSIDE_IGNORE, props.clickOutsideIgnore].filter(Boolean).join(','),
);
const handleClickOutside = (e: MouseEvent) => {
if (props.disabled) return;
const target = e.target as HTMLElement | null;
if (!target) return;
// referencepopper
if (referenceElementRef.value?.contains(target)) return;
if (popperElementRef.value?.contains(target)) return;
if (target.closest(clickOutsideIgnoreSelector.value)) return;
emit('clickoutside', e);
// update:visible v-model:visible
if (typeof props.visible === 'undefined') {
popoverVisible.value = false;
} else {
emit('update:visible', false);
}
};
const bindClickOutside = () => globalThis.document?.addEventListener('click', handleClickOutside);
const unbindClickOutside = () => globalThis.document?.removeEventListener('click', handleClickOutside);
watch(popoverVisible, (visible) => {
if (!props.closeOnClickOutside) return;
if (visible) {
// popover
nextTick(bindClickOutside);
} else {
unbindClickOutside();
}
});
const destroy = () => { const destroy = () => {
if (!instanceRef.value) return; if (!instanceRef.value) return;
@ -188,5 +260,6 @@ const destroy = () => {
onBeforeUnmount(() => { onBeforeUnmount(() => {
destroy(); destroy();
unbindClickOutside();
}); });
</script> </script>

View File

@ -0,0 +1,47 @@
/*
* Tencent is pleased to support the open source community by making TMagicEditor available.
*
* Copyright (C) 2025 Tencent. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*
* typeMatch
* `主错误描述${VALIDATE_SUGGESTION_SEPARATOR}修改建议`
* - form-item tooltip
* -
*
* /
* / helper
*/
export const VALIDATE_SUGGESTION_SEPARATOR = '\n\n';
/**
*
*
* @param message
* @param suggestion
*/
export const appendValidateSuggestion = (message: string, suggestion?: string): string =>
suggestion ? `${message}${VALIDATE_SUGGESTION_SEPARATOR}${suggestion}` : message;
/**
*
*
* @param text `主错误描述\n\n修改建议`
*/
export const stripValidateSuggestion = (text?: string): string =>
String(text ?? '').split(VALIDATE_SUGGESTION_SEPARATOR)[0];

View File

@ -8,6 +8,7 @@ import './theme/index.scss';
export * from './types'; export * from './types';
export * from './config'; export * from './config';
export * from './formValidateMessage';
export { default as TMagicAutocomplete } from './Autocomplete.vue'; export { default as TMagicAutocomplete } from './Autocomplete.vue';
export { default as TMagicBadge } from './Badge.vue'; export { default as TMagicBadge } from './Badge.vue';

View File

@ -234,6 +234,9 @@ export interface PaginationProps {
export interface PopconfirmProps { export interface PopconfirmProps {
title?: string; title?: string;
width?: string | number;
/** 浮层是否插入到 body默认 true。设为 false 时浮层内联渲染,便于嵌套在 hover 浮层中避免父级因 mouseleave 收起。 */
teleported?: boolean;
placement?: placement?:
| 'top' | 'top'
| 'left' | 'left'
@ -258,6 +261,13 @@ export interface PopoverProps {
popperClass?: string; popperClass?: string;
tabindex?: number; tabindex?: number;
destroyOnClose?: boolean; destroyOnClose?: boolean;
/** 点击 popover 及其衍生浮层以外的区域时收起,默认开启。 */
closeOnClickOutside?: boolean;
/**
* / /
* popover body popover
*/
clickOutsideIgnore?: string;
} }
export interface RadioProps { export interface RadioProps {

View File

@ -1,5 +1,5 @@
{ {
"version": "1.8.0-beta.1", "version": "1.8.0-beta.11",
"name": "@tmagic/editor", "name": "@tmagic/editor",
"type": "module", "type": "module",
"sideEffects": [ "sideEffects": [

View File

@ -3,6 +3,7 @@
:disabled-page-fragment="disabledPageFragment" :disabled-page-fragment="disabledPageFragment"
:page-bar-sort-options="pageBarSortOptions" :page-bar-sort-options="pageBarSortOptions"
:page-filter-function="pageFilterFunction" :page-filter-function="pageFilterFunction"
:hide-sidebar="hideSidebar"
> >
<template #header> <template #header>
<slot name="header"></slot> <slot name="header"></slot>
@ -134,7 +135,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { provide } from 'vue'; import { provide, ref } from 'vue';
import type { MApp } from '@tmagic/core'; import type { MApp } from '@tmagic/core';
@ -157,7 +158,7 @@ import stageOverlayService from './services/stageOverlay';
import storageService from './services/storage'; import storageService from './services/storage';
import uiService from './services/ui'; import uiService from './services/ui';
import keybindingConfig from './utils/keybinding-config'; import keybindingConfig from './utils/keybinding-config';
import { defaultEditorProps, EditorProps } from './editorProps'; import { defaultEditorProps, EditorProps, ENABLE_PROPS_FORM_VALIDATE } from './editorProps';
import { initServiceEvents, initServiceState } from './initService'; import { initServiceEvents, initServiceState } from './initService';
import type { TreeNodeData } from './type'; import type { TreeNodeData } from './type';
import type { EditorSlots, EventBus, Services, StageOptions } from './type'; import type { EditorSlots, EventBus, Services, StageOptions } from './type';
@ -220,22 +221,47 @@ const stageOptions: StageOptions = {
guidesOptions: props.guidesOptions, guidesOptions: props.guidesOptions,
disabledMultiSelect: props.disabledMultiSelect, disabledMultiSelect: props.disabledMultiSelect,
alwaysMultiSelect: props.alwaysMultiSelect, alwaysMultiSelect: props.alwaysMultiSelect,
disabledFlashTip: props.disabledFlashTip,
beforeDblclick: props.beforeDblclick, beforeDblclick: props.beforeDblclick,
}; };
stageOverlayService.set('stageOptions', stageOptions); stageOverlayService.set('stageOptions', stageOptions);
const propsPanelRef = ref<InstanceType<typeof FormPanel> | null>(null);
provide('services', services); provide('services', services);
provide('codeOptions', props.codeOptions); provide('codeOptions', props.codeOptions);
provide('stageOptions', stageOptions); provide('stageOptions', stageOptions);
/** 是否启用「属性配置表单校验」联动能力,供 PropsPanel / FormPanel 判断校验失败时是否仍更新节点并记录错误 */
provide(ENABLE_PROPS_FORM_VALIDATE, props.enablePropsFormValidate ?? false);
/**
* 把顶层 `extendFormState` 提供给非 PropsPanel 链路上的组件使用例如历史差异对话框 HistoryDiffDialog
* 内部的 CompareForm这样所有依赖业务上下文的表单 filterFunction 都能拿到一致的扩展状态
* PropsPanel 通过 `:extend-state` 显式传入的方式保持等价
*/
provide('extendFormState', props.extendFormState);
/**
* 提供 PropsPanel 主属性表单的 formState getter供历史差异弹窗复用
* CompareForm PropsPanel filterFunction 上下文保持一致
*/
provide('getPropsPanelFormState', () => propsPanelRef.value?.configForm?.formState);
/**
* 把历史记录面板的自定义扩展 tab 提供给深层的 HistoryListPanel它挂在 NavMenu
* markRaw component 形式渲染无法直接通过 props 透传业务方可借此在历史记录
* 面板内追加自定义模块的历史 tab
*/
provide('historyListExtraTabs', props.historyListExtraTabs);
provide<EventBus>('eventBus', new EventEmitter()); provide<EventBus>('eventBus', new EventEmitter());
const propsPanelMountedHandler = (e: InstanceType<typeof FormPanel>) => { const propsPanelMountedHandler = (e: InstanceType<typeof FormPanel>) => {
propsPanelRef.value = e;
emit('props-panel-mounted', e); emit('props-panel-mounted', e);
}; };
const propsPanelUnmountedHandler = () => { const propsPanelUnmountedHandler = () => {
propsPanelRef.value = null;
emit('props-panel-unmounted'); emit('props-panel-unmounted');
}; };

View File

@ -4,7 +4,9 @@
v-model:visible="boxVisible" v-model:visible="boxVisible"
v-model:width="width" v-model:width="width"
v-model:height="codeBlockEditorHeight" v-model:height="codeBlockEditorHeight"
:body-style="{ padding: '0 16px' }"
:title="content.name ? `${disabled ? '查看' : '编辑'}${content.name}` : '新增代码'" :title="content.name ? `${disabled ? '查看' : '编辑'}${content.name}` : '新增代码'"
:framework-width="frameworkWidth"
:position="boxPosition" :position="boxPosition"
:before-close="beforeClose" :before-close="beforeClose"
> >
@ -34,7 +36,7 @@
<Teleport to="body"> <Teleport to="body">
<TMagicDialog title="查看修改" v-model="difVisible" fullscreen destroy-on-close> <TMagicDialog title="查看修改" v-model="difVisible" fullscreen destroy-on-close>
<div style="display: flex; margin-bottom: 10px"> <div style="display: flex; margin-bottom: 10px">
<div style="flex: 1"><TMagicTag size="small" type="info">修改前</TMagicTag></div> <div style="flex: 1"><TMagicTag size="small" type="danger">修改前</TMagicTag></div>
<div style="flex: 1"><TMagicTag size="small" type="success">修改后</TMagicTag></div> <div style="flex: 1"><TMagicTag size="small" type="success">修改后</TMagicTag></div>
</div> </div>
@ -63,14 +65,7 @@ import { computed, inject, nextTick, Ref, ref, useTemplateRef, watch } from 'vue
import type { CodeBlockContent } from '@tmagic/core'; import type { CodeBlockContent } from '@tmagic/core';
import { TMagicButton, TMagicDialog, tMagicMessage, tMagicMessageBox, TMagicTag } from '@tmagic/design'; import { TMagicButton, TMagicDialog, tMagicMessage, tMagicMessageBox, TMagicTag } from '@tmagic/design';
import { import { type ContainerChangeEventData, type FormConfig, MFormBox } from '@tmagic/form';
type ContainerChangeEventData,
defineFormConfig,
defineFormItem,
type FormConfig,
MFormBox,
type TableColumnConfig,
} from '@tmagic/form';
import FloatingBox from '@editor/components/FloatingBox.vue'; import FloatingBox from '@editor/components/FloatingBox.vue';
import { useEditorContentHeight } from '@editor/hooks/use-editor-content-height'; import { useEditorContentHeight } from '@editor/hooks/use-editor-content-height';
@ -78,6 +73,7 @@ import { useNextFloatBoxPosition } from '@editor/hooks/use-next-float-box-positi
import { useServices } from '@editor/hooks/use-services'; import { useServices } from '@editor/hooks/use-services';
import { useWindowRect } from '@editor/hooks/use-window-rect'; import { useWindowRect } from '@editor/hooks/use-window-rect';
import CodeEditor from '@editor/layouts/CodeEditor.vue'; import CodeEditor from '@editor/layouts/CodeEditor.vue';
import { getCodeBlockFormConfig } from '@editor/utils/code-block';
import { getEditorConfig } from '@editor/utils/config'; import { getEditorConfig } from '@editor/utils/config';
defineOptions({ defineOptions({
@ -119,106 +115,23 @@ const diffChange = () => {
difVisible.value = false; difVisible.value = false;
}; };
const defaultParamColConfig = defineFormItem<TableColumnConfig>({ const codeOptions = inject<Record<string, any>>('codeOptions', {});
type: 'row',
label: '参数类型',
items: [
{
text: '参数类型',
labelWidth: '70px',
type: 'select',
name: 'type',
options: [
{
text: '数字',
label: '数字',
value: 'number',
},
{
text: '字符串',
label: '字符串',
value: 'text',
},
{
text: '组件',
label: '组件',
value: 'ui-select',
},
],
},
],
});
const functionConfig = computed( /**
() => * 代码块编辑表单配置统一委托到 utils/code-block `getCodeBlockFormConfig`
defineFormConfig([ * CompareForm 等其它使用方共享同一份 schema避免双份维护
{ *
text: '名称', * 这里以 computed 包裹是为了让 `props.isDataSource` / `props.dataSourceType` 变化时
name: 'name', * "执行时机"字段的可见性与可选项实时刷新
rules: [{ required: true, message: '请输入名称', trigger: 'blur' }], */
}, const functionConfig = computed<FormConfig>(() =>
{ getCodeBlockFormConfig({
text: '描述', paramColConfig: codeBlockService.getParamsColConfig(),
name: 'desc', isDataSource: () => Boolean(props.isDataSource),
}, dataSourceType: () => props.dataSourceType,
{ codeOptions,
text: '执行时机', editable: true,
name: 'timing', }),
type: 'select',
options: () => {
const options = [
{ text: '初始化前', value: 'beforeInit' },
{ text: '初始化后', value: 'afterInit' },
];
if (props.dataSourceType !== 'base') {
options.push({ text: '请求前', value: 'beforeRequest' });
options.push({ text: '请求后', value: 'afterRequest' });
}
return options;
},
display: () => props.isDataSource,
},
{
type: 'table',
border: true,
text: '参数',
enableFullscreen: false,
enableToggleMode: false,
name: 'params',
dropSort: false,
items: [
{
type: 'text',
label: '参数名',
name: 'name',
},
{
type: 'text',
label: '描述',
name: 'extra',
},
codeBlockService.getParamsColConfig() || defaultParamColConfig,
],
},
{
name: 'content',
type: 'vs-code',
options: inject('codeOptions', {}),
autosize: { minRows: 10, maxRows: 30 },
onChange: (_formState, code: string) => {
try {
// js
getEditorConfig('parseDSL')(code);
return code;
} catch (error: any) {
tMagicMessage.error(error.message);
throw error;
}
},
},
]) as FormConfig,
); );
const parseContent = (content: any) => { const parseContent = (content: any) => {
@ -295,6 +208,7 @@ const closedHandler = () => {
const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null)); const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null));
const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating); const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating);
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
watch(boxVisible, (visible) => { watch(boxVisible, (visible) => {
nextTick(() => { nextTick(() => {

View File

@ -3,6 +3,8 @@
ref="form" ref="form"
:config="codeParamsConfig" :config="codeParamsConfig"
:init-values="model" :init-values="model"
:last-values="lastValues"
:is-compare="isCompare"
:disabled="disabled" :disabled="disabled"
:size="size" :size="size"
:watch-props="false" :watch-props="false"
@ -24,6 +26,10 @@ defineOptions({
const props = defineProps<{ const props = defineProps<{
model: any; model: any;
/** 对比模式下的历史值,透传给内部 MForm 用于逐项展示参数差异 */
lastValues?: any;
/** 是否开启对比模式 */
isCompare?: boolean;
size?: 'small' | 'default' | 'large'; size?: 'small' | 'default' | 'large';
disabled?: boolean; disabled?: boolean;
name: string; name: string;

View File

@ -0,0 +1,284 @@
<template>
<div class="m-editor-compare-form-wrapper" :style="wrapperStyle">
<MForm
v-if="config.length"
ref="form"
class="m-editor-compare-form"
:config="config"
:init-values="currentValues"
:last-values="lastValuesProcessed"
:is-compare="true"
:disabled="true"
:label-width="labelWidth"
:extend-state="mergedExtendState"
:show-diff="showDiff"
:self-diff-field-types="selfDiffFieldTypes"
:size="size"
></MForm>
</div>
</template>
<script lang="ts" setup>
import { computed, inject, provide, type Ref, ref, type ShallowRef, useTemplateRef, watch, watchEffect } from 'vue';
import { isEqual } from 'lodash-es';
import { type CodeBlockContent, type DataSourceSchema, HookType, type MNode } from '@tmagic/core';
import { type FieldSize } from '@tmagic/design';
import { type FormConfig, type FormState, type FormValue, MForm } from '@tmagic/form';
import type { CompareCategory, CompareFormLoadConfig, Services } from '@editor/type';
import { getCodeBlockFormConfig } from '@editor/utils/code-block';
defineOptions({
name: 'MEditorCompareForm',
});
const props = withDefaults(
defineProps<{
/** 当前值(修改后的值) */
value: Partial<MNode> | Partial<DataSourceSchema> | Partial<CodeBlockContent> | Record<string, any>;
/** 用于对比的旧值(修改前的值) */
lastValue?: Partial<MNode> | Partial<DataSourceSchema> | Partial<CodeBlockContent> | Record<string, any>;
/**
* 类型说明
* - `category` `node` `type` 为节点组件的类型例如 'text''button''page''container'
* - `category` `data-source` `type` 为数据源类型例如 'base''http'
* - `category` `code-block` `type` 可不传
*/
type?: string;
/** 表单配置类别,决定从哪里取 FormConfig */
category?: CompareCategory;
/** 数据源代码块场景下的数据源类型base/http用于代码块表单中"执行时机"展示 */
dataSourceType?: string;
labelWidth?: string;
/**
* 外层容器高度设置后表单内容超出时会在 CompareForm 内部出现滚动条
* 避免 dialog / 面板使用方需要自行处理滚动可传任意 CSS 长度例如 `60vh` / `400px` / `100%`
*/
height?: string;
/**
* 用户自定义注入到 MForm.formState 的扩展字段 Editor 顶层的 `extendFormState`
* PropsPanel `extend-state` 语义一致表单 item `display` / `disabled`
* filterFunction 经常依赖这里注入的字段 stage自定义业务上下文等
* 因此在差异对比场景下也需要透传避免出现 `formState.xxx is undefined` 的运行时错误
*/
extendState?: (_state: FormState) => Record<string, any> | Promise<Record<string, any>>;
/**
* 外部透传的基础 formState通常来自 PropsPanel 主属性表单
* CompareForm 会提取其中的扩展字段覆盖到自己的 formState保证 filterFunction 上下文一致
*/
baseFormState?: FormState;
/** 需要走 self diff 的字段类型(例如 mod-cond。 */
selfDiffFieldTypes?: string[];
/**
* 表单内组件的尺寸透传给 MForm `size`可选 'large' | 'default' | 'small'
* 缺省时使用 MForm 内置默认尺寸
*/
size?: FieldSize;
/**
* 自定义 FormConfig 加载逻辑传入后将接管内置的按 `category`(node/data-source/code-block)
* 取配置逻辑调用方可根据业务自行返回或异步返回表单配置可通过
* `ctx.defaultLoadConfig()` 复用默认结果再做二次加工返回的 config 直接用于对比展示
*/
loadConfig?: CompareFormLoadConfig;
/** 编辑器服务集合,由调用方传入(不再通过 inject('services') 获取)。 */
services?: Services;
}>(),
{
category: 'node',
labelWidth: '120px',
extendState: (state: FormState) => state,
},
);
provide('services', props.services);
const config = ref<FormConfig>([]);
/** vs-code 编辑器的 monaco 配置项,沿用 Editor 顶层 provide('codeOptions', ...) 的注入。 */
const codeOptions = inject<Record<string, any>>('codeOptions', {});
/** 将代码块的 content 字段统一成字符串,便于在表单/对比中展示 */
const normalizeCodeBlockValue = (
v: Partial<CodeBlockContent> | Record<string, any> | undefined,
): Record<string, any> => {
if (!v) return {};
const next: Record<string, any> = { ...v };
if (next.content && typeof next.content !== 'string') {
try {
next.content = next.content.toString();
} catch {
next.content = '';
}
}
return next;
};
const currentValues = computed<FormValue>(() => {
if (props.category === 'code-block') {
return normalizeCodeBlockValue(props.value as Partial<CodeBlockContent>);
}
return (props.value || {}) as FormValue;
});
const lastValuesProcessed = computed<FormValue>(() => {
if (props.category === 'code-block') {
return normalizeCodeBlockValue(props.lastValue as Partial<CodeBlockContent>);
}
return (props.lastValue || {}) as FormValue;
});
/**
* 外层包裹层的样式当传入 `height` 时启用固定高度 + 内部滚动
* 这样滚动条会出现在 CompareForm 内部避免父容器 Dialog自身也产生滚动
*/
const wrapperStyle = computed(() => {
if (!props.height) return undefined;
return {
height: props.height,
overflow: 'auto',
} as Record<string, string>;
});
/**
* `code-select` 字段在历史数据中存在两种"语义为空"的形态
* - 字符串 `''`旧数据 / 用户从未配置过钩子
* - `{ hookType: HookType.CODE, hookData: [] }`CodeSelect.vue 在挂载时
* 写入的默认结构参见 packages/editor/src/fields/CodeSelect.vue
* `props.model[props.name] = { hookType: HookType.CODE, hookData: [] }`
*
* 直接 `isEqual` 会把两者判为不等从而在历史对比里对每个未配置过钩子的组件
* 都展示一份"差异"体验很糟糕这里把它们视为相等跳过对比
*
* 其它类型字段沿用 MForm/Container 的默认 `!isEqual` 判断逻辑
*/
const isEmptyCodeSelectValue = (v: any): boolean => {
if (v === '' || v === undefined || v === null) return true;
if (Array.isArray(v) && v.length === 0) return true;
return typeof v === 'object' && v.hookType === HookType.CODE && Array.isArray(v.hookData) && v.hookData.length === 0;
};
const showDiff = ({ curValue, lastValue, config }: { curValue: any; lastValue: any; config: any }) => {
if (config?.type === 'code-select') {
// ""
if (isEmptyCodeSelectValue(curValue) && isEmptyCodeSelectValue(lastValue)) {
return false;
}
}
return !isEqual(curValue, lastValue);
};
const removeStyleDisplayConfig = (formConfig: FormConfig): FormConfig =>
formConfig.map((item) => {
if (!('type' in item)) return item;
if (item?.type !== 'tab' || !Array.isArray(item.items)) return item;
return {
...item,
items: item.items.map((tabPane) => {
if (tabPane?.title !== '样式' || !Array.isArray(tabPane.items)) return tabPane;
return {
...tabPane,
display: true,
};
}),
};
});
const mergedExtendState = (state: FormState) => {
return props.extendState(props.baseFormState || state);
};
/**
* 内置的默认 FormConfig 加载逻辑 `category` 从对应 service / 工具取配置
* 作为 ctx.defaultLoadConfig 透传给自定义 `loadConfig`方便复用与二次加工
*/
const defaultLoadConfig = async (): Promise<FormConfig> => {
if (!props.services) {
return [];
}
switch (props.category) {
case 'node': {
if (!props.type) {
return [];
}
return removeStyleDisplayConfig(
await props.services.propsService.getPropsConfig(props.type, { node: props.value as unknown as MNode }),
);
}
case 'data-source': {
const config = props.services.dataSourceService.getFormConfig(props.type || 'base');
// tab status 'fields'tab-pane name 'fields'
// active Tabs '0' 'fields'
// DataSourceConfigPanel tab
return config.map((item) => ('type' in item && item.type === 'tab' ? { ...item, active: 'fields' } : item));
}
case 'code-block': {
return getCodeBlockFormConfig({
paramColConfig: props.services.codeBlockService.getParamsColConfig(),
// dataSourceType "" props.dataSourceType
// step
isDataSource: () => Boolean(props.dataSourceType),
dataSourceType: () => props.dataSourceType,
codeOptions,
// /
editable: false,
});
}
default:
return [];
}
};
const loadConfig = async () => {
if (props.loadConfig) {
config.value = await props.loadConfig({
category: props.category,
type: props.type,
dataSourceType: props.dataSourceType,
defaultLoadConfig,
});
return;
}
config.value = await defaultLoadConfig();
};
watch(
[() => props.category, () => props.type, () => props.dataSourceType, () => props.loadConfig],
() => {
loadConfig();
},
{ immediate: true },
);
const formRef = useTemplateRef<InstanceType<typeof MForm>>('form');
/**
* services / stage 注入 MForm formState避免 propsService 注入的表单配置中
* 形如 `display: ({ services }) => services.uiService.get(...)` filterFunction
* 在执行时拿不到 `formState.services` 而报错
*
* props-panel/FormPanel.vue 中的注入方式保持一致
* - services整个 useServices() 返回的服务集合
* - stage当前 editorService.get('stage') 的最新值
*/
watchEffect(() => {
if (formRef.value && props.services) {
formRef.value.formState.stage = props.services.editorService.get('stage');
formRef.value.formState.services = props.services;
}
});
defineExpose<{
form: ShallowRef<InstanceType<typeof MForm> | null>;
config: Ref<FormConfig>;
reload: () => Promise<void>;
}>({
form: formRef,
config,
reload: loadConfig,
});
</script>

View File

@ -1,6 +1,12 @@
<template> <template>
<Teleport to="body" v-if="visible"> <Teleport to="body" v-if="visible">
<div ref="target" class="m-editor-float-box" :style="{ ...style, zIndex: curZIndex }" @mousedown="nextZIndex"> <div
ref="target"
class="m-editor-float-box"
v-bind="$attrs"
:style="{ ...style, zIndex: curZIndex }"
@mousedown="nextZIndex"
>
<div ref="title" class="m-editor-float-box-title"> <div ref="title" class="m-editor-float-box-title">
<slot name="title"> <slot name="title">
<span>{{ title }}</span> <span>{{ title }}</span>
@ -9,7 +15,7 @@
<TMagicButton link size="small" @click="closeHandler"><MIcon :icon="Close"></MIcon></TMagicButton> <TMagicButton link size="small" @click="closeHandler"><MIcon :icon="Close"></MIcon></TMagicButton>
</div> </div>
</div> </div>
<div class="m-editor-float-box-body" :style="{ height: `${bodyHeight}px` }"> <div class="m-editor-float-box-body" :style="{ height: `${bodyHeight}px`, ...bodyStyle }">
<slot name="body"></slot> <slot name="body"></slot>
</div> </div>
</div> </div>
@ -17,14 +23,13 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, provide, ref, useTemplateRef, watch } from 'vue'; import { computed, type CSSProperties, nextTick, onBeforeUnmount, provide, ref, useTemplateRef, watch } from 'vue';
import { Close } from '@element-plus/icons-vue'; import { Close } from '@element-plus/icons-vue';
import VanillaMoveable from 'moveable'; import VanillaMoveable from 'moveable';
import { TMagicButton, useZIndex } from '@tmagic/design'; import { TMagicButton, useZIndex } from '@tmagic/design';
import MIcon from '@editor/components/Icon.vue'; import MIcon from '@editor/components/Icon.vue';
import { useServices } from '@editor/hooks/use-services';
interface Position { interface Position {
left: number; left: number;
@ -39,11 +44,18 @@ const props = withDefaults(
defineProps<{ defineProps<{
position?: Position; position?: Position;
title?: string; title?: string;
bodyStyle?: CSSProperties;
/** 浮窗初始样式,会与内部计算样式合并,外部传入优先 */
initialStyle?: CSSProperties;
/** 用于约束浮窗 left 的容器宽度,传入时按宽度收敛 left避免超出右边界默认取视窗宽度 */
frameworkWidth?: number;
beforeClose?: (_done: (_cancel?: boolean) => void) => void; beforeClose?: (_done: (_cancel?: boolean) => void) => void;
}>(), }>(),
{ {
title: '', title: '',
position: () => ({ left: 0, top: 0 }), position: () => ({ left: 0, top: 0 }),
initialStyle: () => ({}),
frameworkWidth: 0,
}, },
); );
@ -66,12 +78,11 @@ const bodyHeight = computed(() => {
return 'auto'; return 'auto';
}); });
const { uiService } = useServices();
const frameworkWidth = computed(() => uiService.get('frameworkRect').width || 0);
const style = computed(() => { const style = computed(() => {
let { left } = props.position; let { left } = props.position;
if (width.value) { const frameworkWidth = props.frameworkWidth || globalThis.window?.innerWidth || 0;
left = left + width.value > frameworkWidth.value ? frameworkWidth.value - width.value : left; if (width.value && frameworkWidth) {
left = left + width.value > frameworkWidth ? frameworkWidth - width.value : left;
} }
return { return {
@ -79,11 +90,60 @@ const style = computed(() => {
top: `${props.position.top}px`, top: `${props.position.top}px`,
width: width.value ? `${width.value}px` : 'auto', width: width.value ? `${width.value}px` : 'auto',
height: height.value ? `${height.value}px` : 'auto', height: height.value ? `${height.value}px` : 'auto',
...props.initialStyle,
}; };
}); });
let moveable: VanillaMoveable | null = null; let moveable: VanillaMoveable | null = null;
// / iframe iframe iframe
let dragMask: HTMLDivElement | null = null;
let dragMaskVisible = false;
// moveable dragEnd/resizeEnd
// alt-tab
// pointerup/blur/visibilitychange
const bindDragMaskSafety = () => {
globalThis.window?.addEventListener('pointerup', hideDragMask, true);
globalThis.window?.addEventListener('blur', hideDragMask);
globalThis.document?.addEventListener('visibilitychange', hideDragMask);
};
const unbindDragMaskSafety = () => {
globalThis.window?.removeEventListener('pointerup', hideDragMask, true);
globalThis.window?.removeEventListener('blur', hideDragMask);
globalThis.document?.removeEventListener('visibilitychange', hideDragMask);
};
const showDragMask = () => {
if (dragMaskVisible) {
return;
}
if (!dragMask) {
dragMask = globalThis.document.createElement('div');
dragMask.className = 'm-editor-float-box-drag-mask';
}
globalThis.document.body.appendChild(dragMask);
dragMaskVisible = true;
bindDragMaskSafety();
// root @mousedown="nextZIndex" z-index
// iframe nextTick z-index
const setMaskZIndex = () => {
if (dragMask) {
dragMask.style.zIndex = `${curZIndex.value + 1}`;
}
};
setMaskZIndex();
nextTick(setMaskZIndex);
};
const hideDragMask = () => {
unbindDragMaskSafety();
dragMask?.parentNode?.removeChild(dragMask);
dragMaskVisible = false;
};
const initMoveable = () => { const initMoveable = () => {
moveable = new VanillaMoveable(globalThis.document.body, { moveable = new VanillaMoveable(globalThis.document.body, {
className: 'm-editor-floating-box-moveable', className: 'm-editor-floating-box-moveable',
@ -101,6 +161,14 @@ const initMoveable = () => {
bounds: { left: 0, top: 0, right: 0, bottom: 0, position: 'css' }, bounds: { left: 0, top: 0, right: 0, bottom: 0, position: 'css' },
}); });
// /moveable dragStart/resizeStart mousedown
// mouseup click
// drag/resize
moveable.on('drag', showDragMask);
moveable.on('resize', showDragMask);
moveable.on('dragEnd', hideDragMask);
moveable.on('resizeEnd', hideDragMask);
moveable.on('drag', (e) => { moveable.on('drag', (e) => {
e.target.style.transform = e.transform; e.target.style.transform = e.transform;
}); });
@ -115,6 +183,7 @@ const initMoveable = () => {
}; };
const destroyMoveable = () => { const destroyMoveable = () => {
hideDragMask();
moveable?.destroy(); moveable?.destroy();
moveable = null; moveable = null;
}; };

View File

@ -87,70 +87,3 @@ const scrollBy = (delta: number) => {
} }
}; };
</script> </script>
<style lang="scss">
.m-editor-scroll-bar {
position: absolute;
background-color: transparent;
opacity: 0.3;
transition:
background-color 0.2s linear,
opacity 0.2s linear;
.m-editor-scroll-bar-thumb {
background-color: #aaa;
border-radius: 6px;
position: absolute;
}
&.horizontal {
width: 100%;
height: 15px;
bottom: 0;
.m-editor-scroll-bar-thumb {
height: 6px;
transition:
background-color 0.2s linear,
height 0.2s ease-in-out;
bottom: 2px;
}
}
&.vertical {
height: 100%;
width: 15px;
right: 5px;
.m-editor-scroll-bar-thumb {
width: 6px;
transition:
background-color 0.2s linear,
width 0.2s ease-in-out;
right: 2px;
}
}
&:hover,
&:focus {
background-color: #eee;
opacity: 0.9;
.m-editor-scroll-bar-thumb {
background-color: #999;
}
&.horizontal {
.m-editor-scroll-bar-thumb {
height: 11px;
}
}
&.vertical {
.m-editor-scroll-bar-thumb {
width: 11px;
}
}
}
}
</style>

View File

@ -13,7 +13,7 @@
<template v-else-if="data.type === 'button'"> <template v-else-if="data.type === 'button'">
<TMagicTooltip v-if="data.tooltip" effect="dark" placement="bottom-start" :content="data.tooltip"> <TMagicTooltip v-if="data.tooltip" effect="dark" placement="bottom-start" :content="data.tooltip">
<TMagicButton size="small" link :disabled="disabled"> <TMagicButton size="small" link :disabled="disabled" v-bind="data.buttonProps || {}">
<template #icon v-if="data.icon"> <template #icon v-if="data.icon">
<MIcon :icon="data.icon"></MIcon> <MIcon :icon="data.icon"></MIcon>
</template> </template>
@ -21,7 +21,7 @@
</TMagicButton> </TMagicButton>
</TMagicTooltip> </TMagicTooltip>
<TMagicButton v-else size="small" link :disabled="disabled" :title="data.text"> <TMagicButton v-else size="small" link :disabled="disabled" :title="data.text" v-bind="data.buttonProps || {}">
<template #icon v-if="data.icon"> <template #icon v-if="data.icon">
<MIcon :icon="data.icon"></MIcon> <MIcon :icon="data.icon"></MIcon>
</template> </template>

View File

@ -1,3 +1,5 @@
import type { InjectionKey } from 'vue';
import type { DataSourceSchema, EventOption, Id, MApp, MNode, MPage, MPageFragment } from '@tmagic/core'; import type { DataSourceSchema, EventOption, Id, MApp, MNode, MPage, MPageFragment } from '@tmagic/core';
import type { FormConfig, FormState } from '@tmagic/form'; import type { FormConfig, FormState } from '@tmagic/form';
import StageCore, { import StageCore, {
@ -15,6 +17,7 @@ import type {
ComponentGroup, ComponentGroup,
CustomContentMenuFunction, CustomContentMenuFunction,
DatasourceTypeOption, DatasourceTypeOption,
HistoryListExtraTab,
IsExpandableFunction, IsExpandableFunction,
MenuBarData, MenuBarData,
MenuButton, MenuButton,
@ -25,6 +28,12 @@ import type {
TreeNodeData, TreeNodeData,
} from './type'; } from './type';
/**
* provide/inject
* 使 Symbol PropsPanel / FormPanel
*/
export const ENABLE_PROPS_FORM_VALIDATE: InjectionKey<boolean> = Symbol('enablePropsFormValidate');
export interface EditorProps { export interface EditorProps {
/** 页面初始值 */ /** 页面初始值 */
modelValue?: MApp; modelValue?: MApp;
@ -34,6 +43,8 @@ export interface EditorProps {
datasourceList?: DatasourceTypeOption[]; datasourceList?: DatasourceTypeOption[];
/** 左侧面板配置 */ /** 左侧面板配置 */
sidebar?: SideBarData; sidebar?: SideBarData;
/** 是否隐藏左侧面板 */
hideSidebar?: boolean;
/** 顶部工具栏配置 */ /** 顶部工具栏配置 */
menu?: MenuBarData; menu?: MenuBarData;
/** 组件树右键菜单 */ /** 组件树右键菜单 */
@ -84,8 +95,15 @@ export interface EditorProps {
alwaysMultiSelect?: boolean; alwaysMultiSelect?: boolean;
/** 禁用页面片 */ /** 禁用页面片 */
disabledPageFragment?: boolean; disabledPageFragment?: boolean;
/** 禁用「非点击画布选中组件时(如从图层树、面包屑等外部选中),对选中区域做高亮闪烁提示」,默认 false即默认开启闪烁 */
disabledFlashTip?: boolean;
/** 禁用双击在浮层中单独编辑选中组件 */ /** 禁用双击在浮层中单独编辑选中组件 */
disabledStageOverlay?: boolean; disabledStageOverlay?: boolean;
/**
* /
* editorService false
*/
enablePropsFormValidate?: boolean;
/** 禁用属性配置面板右下角显示源码的按钮 */ /** 禁用属性配置面板右下角显示源码的按钮 */
disabledShowSrc?: boolean; disabledShowSrc?: boolean;
/** 禁用数据源 */ /** 禁用数据源 */
@ -123,6 +141,8 @@ export interface EditorProps {
/** 组件树节点双击前的钩子函数,返回 false 则阻止默认的双击行为 */ /** 组件树节点双击前的钩子函数,返回 false 则阻止默认的双击行为 */
beforeLayerNodeDblclick?: (event: MouseEvent, data: TreeNodeData) => Promise<boolean | void> | boolean | void; beforeLayerNodeDblclick?: (event: MouseEvent, data: TreeNodeData) => Promise<boolean | void> | boolean | void;
extendFormState?: (state: FormState) => Record<string, any> | Promise<Record<string, any>>; extendFormState?: (state: FormState) => Record<string, any> | Promise<Record<string, any>>;
/** 历史记录面板的自定义扩展 tab追加在内置的页面/数据源/代码块 tab 之后 */
historyListExtraTabs?: HistoryListExtraTab[];
/** 页面顺序拖拽配置参数 */ /** 页面顺序拖拽配置参数 */
pageBarSortOptions?: PageBarSortOptions; pageBarSortOptions?: PageBarSortOptions;
/** 页面搜索函数 */ /** 页面搜索函数 */
@ -134,6 +154,7 @@ export const defaultEditorProps = {
disabledMultiSelect: false, disabledMultiSelect: false,
alwaysMultiSelect: false, alwaysMultiSelect: false,
disabledPageFragment: false, disabledPageFragment: false,
disabledFlashTip: false,
disabledStageOverlay: false, disabledStageOverlay: false,
containerHighlightClassName: CONTAINER_HIGHLIGHT_CLASS_NAME, containerHighlightClassName: CONTAINER_HIGHLIGHT_CLASS_NAME,
containerHighlightDuration: 800, containerHighlightDuration: 800,
@ -143,6 +164,7 @@ export const defaultEditorProps = {
disabledCodeBlock: false, disabledCodeBlock: false,
componentGroupList: () => [], componentGroupList: () => [],
datasourceList: () => [], datasourceList: () => [],
historyListExtraTabs: () => [],
menu: () => ({ left: [], right: [] }), menu: () => ({ left: [], right: [] }),
layerContentMenu: () => [], layerContentMenu: () => [],
stageContentMenu: () => [], stageContentMenu: () => [],

View File

@ -1,11 +1,13 @@
<template> <template>
<MagicCodeEditor <MagicCodeEditor
:height="config.height" :height="config.height"
:init-values="model[name]" :type="diffMode ? 'diff' : undefined"
:init-values="diffMode ? (lastValues || {})[name] : model[name]"
:modified-values="diffMode ? model[name] : undefined"
:language="config.language" :language="config.language"
:options="{ :options="{
...config.options, ...config.options,
readOnly: disabled, readOnly: diffMode ? true : disabled,
}" }"
:autosize="config.autosize" :autosize="config.autosize"
:parse="config.parse" :parse="config.parse"
@ -15,6 +17,8 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from 'vue';
import type { CodeConfig, FieldProps } from '@tmagic/form'; import type { CodeConfig, FieldProps } from '@tmagic/form';
import MagicCodeEditor from '@editor/layouts/CodeEditor.vue'; import MagicCodeEditor from '@editor/layouts/CodeEditor.vue';
@ -27,10 +31,22 @@ const emit = defineEmits<{
change: [value: string | any]; change: [value: string | any];
}>(); }>();
withDefaults(defineProps<FieldProps<CodeConfig>>(), { const props = withDefaults(defineProps<FieldProps<CodeConfig>>(), {
disabled: false, disabled: false,
}); });
/**
* 对比模式判定
*
* - `isCompare === true` 由父级 `MFormContainer` 统一渲染一次本字段不再渲染前后两份独立组件
* 并把 `model`当前值 `lastValues`历史值一并传入
* - 此时本字段切换到 monaco 自带的 diff 编辑器左侧旧右侧新相比"两个独立 monaco 实例"更直观
* 也避免了同一表单内重复实例化重型编辑器带来的开销
*
* 仅当存在历史值lastValues且开启了对比模式时启用 diff避免在 lastValues 缺失时退化为空对比
*/
const diffMode = computed(() => Boolean(props.isCompare && props.lastValues));
const save = (v: string | any) => { const save = (v: string | any) => {
emit('change', v); emit('change', v);
}; };

View File

@ -4,11 +4,11 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, reactive, watch } from 'vue'; import { computed, reactive, watch } from 'vue';
import serialize from 'serialize-javascript';
import type { CodeLinkConfig, FieldProps, MLink } from '@tmagic/form'; import type { CodeLinkConfig, FieldProps, MLink } from '@tmagic/form';
import { getEditorConfig } from '@editor/utils/config'; import { getEditorConfig } from '@editor/utils/config';
import { serializeConfig } from '@editor/utils/editor';
defineOptions({ defineOptions({
name: 'MFieldsCodeLink', name: 'MFieldsCodeLink',
@ -47,10 +47,7 @@ watch(
() => props.model[props.name], () => props.model[props.name],
(value) => { (value) => {
modelValue.form = { modelValue.form = {
[props.name]: serialize(value, { [props.name]: serializeConfig(value),
space: 2,
unsafe: true,
}).replace(/"(\w+)":\s/g, '$1: '),
}; };
}, },
{ {

View File

@ -6,7 +6,8 @@
:size="size" :size="size"
:prop="prop" :prop="prop"
:disabled="disabled" :disabled="disabled"
:lastValues="lastValues" :is-compare="isCompareMode"
:last-values="lastValues?.[name]"
:model="model[name]" :model="model[name]"
@change="changeHandler" @change="changeHandler"
> >
@ -38,6 +39,21 @@ const { dataSourceService, codeBlockService } = useServices();
const props = withDefaults(defineProps<FieldProps<CodeSelectConfig>>(), {}); const props = withDefaults(defineProps<FieldProps<CodeSelectConfig>>(), {});
/**
* 对比模式判定
*
* code-select 仅是对内部钩子列表group-list 的包裹本身不渲染叶子字段父级 `MFormContainer`
* 已将其归入自接管对比字段 Container.vue `SELF_DIFF_FIELD_TYPES`即对比时只渲染一次
* 本组件并把当前值 `model` 与历史值 `lastValues` 一并传入由本组件把 `is-compare`/`lastValues`
* 透传给内部 MContainer再由 group-list / code-select-col 等子级逐项展示前后差异
*
* 注意`model` 传入的是 `model[name]`钩子值本身因此 `lastValues` 也必须同层取 `lastValues[name]`
* 否则前后值的嵌套层级不一致会导致对比错位
*
* 仅当存在历史值时才启用对比避免 lastValues 缺失时退化为全部新增的空对比
*/
const isCompareMode = computed(() => Boolean(props.isCompare && props.lastValues));
const codeConfig = computed<GroupListConfig>(() => ({ const codeConfig = computed<GroupListConfig>(() => ({
type: 'group-list', type: 'group-list',
name: 'hookData', name: 'hookData',
@ -77,7 +93,8 @@ const codeConfig = computed<GroupListConfig>(() => ({
{ value: HookCodeType.CODE, text: '代码块' }, { value: HookCodeType.CODE, text: '代码块' },
{ value: HookCodeType.DATA_SOURCE_METHOD, text: '数据源方法' }, { value: HookCodeType.DATA_SOURCE_METHOD, text: '数据源方法' },
], ],
defaultValue: 'code', rules: [{ typeMatch: true, trigger: 'change' }],
defaultValue: HookCodeType.CODE,
onChange: (_mForm, v: HookCodeType, { setModel }) => { onChange: (_mForm, v: HookCodeType, { setModel }) => {
if (v === HookCodeType.DATA_SOURCE_METHOD) { if (v === HookCodeType.DATA_SOURCE_METHOD) {
setModel('codeId', []); setModel('codeId', []);
@ -95,6 +112,7 @@ const codeConfig = computed<GroupListConfig>(() => ({
labelWidth: 0, labelWidth: 0,
display: (_mForm, { model }) => model.codeType !== HookCodeType.DATA_SOURCE_METHOD, display: (_mForm, { model }) => model.codeType !== HookCodeType.DATA_SOURCE_METHOD,
notEditable: () => !codeBlockService.getEditStatus(), notEditable: () => !codeBlockService.getEditStatus(),
rules: [{ typeMatch: true, trigger: 'change' }],
}, },
{ {
type: 'data-source-method-select', type: 'data-source-method-select',
@ -103,6 +121,7 @@ const codeConfig = computed<GroupListConfig>(() => ({
labelWidth: 0, labelWidth: 0,
display: (_mForm, { model }) => model.codeType === HookCodeType.DATA_SOURCE_METHOD, display: (_mForm, { model }) => model.codeType === HookCodeType.DATA_SOURCE_METHOD,
notEditable: () => !dataSourceService.get('editable'), notEditable: () => !dataSourceService.get('editable'),
rules: [{ typeMatch: true, trigger: 'change' }],
}, },
], ],
}, },

View File

@ -2,7 +2,20 @@
<div class="m-fields-code-select-col"> <div class="m-fields-code-select-col">
<div class="code-select-container"> <div class="code-select-container">
<!-- 代码块下拉框 --> <!-- 代码块下拉框 -->
<!-- 对比模式下交由 MFormContainer 展示下拉框的前后差异codeId 变化时高亮新旧代码块名
普通模式仍直接渲染 MSelect 以保留选择 / 写值逻辑 -->
<MFormContainer
v-if="isCompareMode"
class="select"
:config="selectConfig"
:model="model"
:last-values="lastValues"
:is-compare="true"
:size="size"
:prop="prop"
></MFormContainer>
<MSelect <MSelect
v-else
class="select" class="select"
:config="selectConfig" :config="selectConfig"
:name="name" :name="name"
@ -12,9 +25,9 @@
@change="onCodeIdChangeHandler" @change="onCodeIdChangeHandler"
></MSelect> ></MSelect>
<!-- 查看/编辑按钮 --> <!-- 查看/编辑按钮对比模式为只读不展示 -->
<TMagicButton <TMagicButton
v-if="model[name] && hasCodeBlockSidePanel" v-if="!isCompareMode && model[name] && hasCodeBlockSidePanel"
class="m-fields-select-action-button" class="m-fields-select-action-button"
:size="size" :size="size"
@click="editCode(model[name])" @click="editCode(model[name])"
@ -29,6 +42,8 @@
name="params" name="params"
:key="model[name]" :key="model[name]"
:model="model" :model="model"
:last-values="lastValues"
:is-compare="isCompareMode"
:size="size" :size="size"
:disabled="disabled" :disabled="disabled"
:params-config="paramsConfig" :params-config="paramsConfig"
@ -52,6 +67,7 @@ import {
filterFunction, filterFunction,
type FormItemConfig, type FormItemConfig,
type FormState, type FormState,
MContainer as MFormContainer,
MSelect, MSelect,
type SelectConfig, type SelectConfig,
} from '@tmagic/form'; } from '@tmagic/form';
@ -77,12 +93,26 @@ const props = withDefaults(defineProps<FieldProps<CodeSelectColConfig>>(), {
disabled: false, disabled: false,
}); });
/**
* 对比模式判定
*
* code-select-col 代码块下拉框 + 参数子表单组成属于复合字段父级 `MFormContainer` 已将其
* 归入自接管对比字段 Container.vue `SELF_DIFF_FIELD_TYPES`即对比时只渲染一次本组件
* 并把当前值 `model` 与历史值 `lastValues` 一并传入由本组件把 `is-compare`/`lastValues` 透传给
* 内部的下拉框MFormContainer与参数表单CodeParams逐项展示前后差异
*
* 仅当存在历史值时才启用对比避免 lastValues 缺失时退化为全部新增的空对比
*/
const isCompareMode = computed(() => Boolean(props.isCompare && props.lastValues));
const notEditable = computed(() => filterFunction(mForm, props.config.notEditable, props)); const notEditable = computed(() => filterFunction(mForm, props.config.notEditable, props));
const hasCodeBlockSidePanel = computed(() => const codeBlockSidePanel = computed(() =>
(uiService.get('sideBarItems') || []).find((item) => item.$key === SideItemKey.CODE_BLOCK), (uiService.get('sideBarItems') || []).find((item) => item.$key === SideItemKey.CODE_BLOCK),
); );
const hasCodeBlockSidePanel = computed(() => codeBlockSidePanel.value);
/** /**
* 根据代码块id获取代码块参数配置 * 根据代码块id获取代码块参数配置
* @param codeId 代码块ID * @param codeId 代码块ID
@ -163,6 +193,10 @@ const onParamsChangeHandler = (value: any, eventData: ContainerChangeEventData)
}; };
const editCode = (id: string) => { const editCode = (id: string) => {
const sideBarItem = codeBlockSidePanel.value;
if (sideBarItem) {
uiService.set('sideBarActiveTabName', sideBarItem.text || sideBarItem.$key || SideItemKey.CODE_BLOCK);
}
eventBus?.emit('edit-code', id); eventBus?.emit('edit-code', id);
}; };
</script> </script>

View File

@ -33,7 +33,7 @@ import { getDesignConfig, TMagicSelect } from '@tmagic/design';
import type { CondOpSelectConfig, FieldProps } from '@tmagic/form'; import type { CondOpSelectConfig, FieldProps } from '@tmagic/form';
import { useServices } from '@editor/hooks/use-services'; import { useServices } from '@editor/hooks/use-services';
import { arrayOptions, eqOptions, getFieldType, numberOptions } from '@editor/utils'; import { getCondOpOptionsByFieldType, getFieldType } from '@editor/utils';
defineOptions({ defineOptions({
name: 'MFieldsCondOpSelect', name: 'MFieldsCondOpSelect',
@ -51,31 +51,9 @@ const optionComponent = getDesignConfig('components')?.option;
const options = computed(() => { const options = computed(() => {
const [id, ...fieldNames] = [...(props.config.parentFields || []), ...props.model.field]; const [id, ...fieldNames] = [...(props.config.parentFields || []), ...props.model.field];
const ds = dataSourceService.getDataSourceById(id); const ds = dataSourceService.getDataSourceById(id);
const type = getFieldType(ds, fieldNames); const type = getFieldType(ds, fieldNames);
return getCondOpOptionsByFieldType(type);
if (type === 'array') {
return arrayOptions;
}
if (type === 'boolean' || type === 'null') {
return [
{ text: '是', value: 'is' },
{ text: '不是', value: 'not' },
];
}
if (type === 'number') {
return [...eqOptions, ...numberOptions];
}
if (type === 'string') {
return [...arrayOptions, ...eqOptions];
}
return [...arrayOptions, ...eqOptions, ...numberOptions];
}); });
const fieldChangeHandler = (v: string) => { const fieldChangeHandler = (v: string) => {

View File

@ -72,7 +72,10 @@
@change="onChangeHandler" @change="onChangeHandler"
></TMagicCascader> ></TMagicCascader>
<TMagicTooltip v-if="selectDataSourceId && hasDataSourceSidePanel" :content="notEditable ? '查看' : '编辑'"> <TMagicTooltip
v-if="selectDataSourceId && hasDataSourceSidePanel && !isCompare"
:content="notEditable ? '查看' : '编辑'"
>
<TMagicButton class="m-fields-select-action-button" :size="size" @click="editHandler(selectDataSourceId)" <TMagicButton class="m-fields-select-action-button" :size="size" @click="editHandler(selectDataSourceId)"
><MIcon :icon="!notEditable ? Edit : View"></MIcon ><MIcon :icon="!notEditable ? Edit : View"></MIcon
></TMagicButton> ></TMagicButton>
@ -133,6 +136,9 @@ const dataSources = computed(() => {
const valueIsKey = computed(() => props.value === 'key'); const valueIsKey = computed(() => props.value === 'key');
const notEditable = computed(() => filterFunction(mForm, props.notEditable, props)); const notEditable = computed(() => filterFunction(mForm, props.notEditable, props));
/** 对比模式下隐藏查看/编辑操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const dataSourcesOptions = computed<SelectOption[]>(() => const dataSourcesOptions = computed<SelectOption[]>(() =>
dataSources.value.map((ds) => ({ dataSources.value.map((ds) => ({
text: ds.title || ds.id, text: ds.title || ds.id,
@ -205,11 +211,25 @@ const onChangeHandler = (v: string[] = []) => {
emit('change', v); emit('change', v);
}; };
const hasDataSourceSidePanel = computed(() => const dataSourceSidePanel = computed(() =>
uiService.get('sideBarItems').find((item) => item.$key === SideItemKey.DATA_SOURCE), uiService.get('sideBarItems').find((item) => item.$key === SideItemKey.DATA_SOURCE),
); );
const hasDataSourceSidePanel = computed(() => dataSourceSidePanel.value);
const editHandler = (id: string) => { const editHandler = (id: string) => {
eventBus?.emit('edit-data-source', removeDataSourceFieldPrefix(id)); const sideBarItem = dataSourceSidePanel.value;
if (sideBarItem) {
uiService.set('sideBarActiveTabName', sideBarItem.text || sideBarItem.$key || SideItemKey.DATA_SOURCE);
}
const dataSourceId = removeDataSourceFieldPrefix(id);
const fieldPath = selectFieldsId.value;
if (fieldPath.length) {
eventBus?.emit('edit-data-source-field', dataSourceId, [...fieldPath]);
} else {
eventBus?.emit('edit-data-source', dataSourceId);
}
}; };
</script> </script>

View File

@ -28,14 +28,14 @@
></component> ></component>
<TMagicTooltip <TMagicTooltip
v-if="config.fieldConfig && !disabledDataSource" v-if="config.fieldConfig && !disabledDataSource && !mForm?.isCompare"
:disabled="showDataSourceFieldSelect" :disabled="showDataSourceFieldSelect"
content="选择数据源" content="选择数据源"
> >
<TMagicButton <TMagicButton
:type="showDataSourceFieldSelect ? 'primary' : 'default'" :type="showDataSourceFieldSelect ? 'primary' : 'default'"
:size="size" :size="size"
:disabled="disabled || mForm?.isCompare" :disabled="disabled"
@click="onToggleDataSourceFieldSelectHandler" @click="onToggleDataSourceFieldSelectHandler"
><MIcon :icon="Coin"></MIcon ><MIcon :icon="Coin"></MIcon
></TMagicButton> ></TMagicButton>

View File

@ -1,17 +1,19 @@
<template> <template>
<div class="m-editor-data-source-fields"> <div class="m-editor-data-source-fields">
<MagicTable :data="model[name]" :columns="fieldColumns" :border="true"></MagicTable> <MagicTable :data="model[name]" :columns="displayColumns" :border="true"></MagicTable>
<div class="m-editor-data-source-fields-footer"> <div v-if="!isCompare" class="m-editor-data-source-fields-footer">
<TMagicButton size="small" :disabled="disabled" plain @click="newFromJsonHandler()">快速添加</TMagicButton> <TMagicButton size="small" :disabled="disabled" plain @click="newFromJsonHandler()">快速添加</TMagicButton>
<TMagicButton size="small" type="primary" :disabled="disabled" plain @click="newHandler()">添加</TMagicButton> <TMagicButton size="small" type="primary" :disabled="disabled" plain @click="newHandler()">添加</TMagicButton>
</div> </div>
<FloatingBox <FloatingBox
:body-style="{ padding: '0 16px' }"
v-model:visible="addDialogVisible" v-model:visible="addDialogVisible"
v-model:width="width" v-model:width="width"
v-model:height="editorHeight" v-model:height="editorHeight"
:title="fieldTitle" :title="fieldTitle"
:framework-width="frameworkWidth"
:position="boxPosition" :position="boxPosition"
> >
<template #body> <template #body>
@ -28,10 +30,12 @@
</FloatingBox> </FloatingBox>
<FloatingBox <FloatingBox
:body-style="{ padding: '0 16px' }"
v-model:visible="addFromJsonDialogVisible" v-model:visible="addFromJsonDialogVisible"
v-model:width="width" v-model:width="width"
v-model:height="editorHeight" v-model:height="editorHeight"
title="快速添加数据定义" title="快速添加数据定义"
:framework-width="frameworkWidth"
:position="boxPosition" :position="boxPosition"
> >
<template #body> <template #body>
@ -47,7 +51,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { inject, Ref, ref } from 'vue'; import { computed, type ComputedRef, inject, onMounted, provide, Ref, ref } from 'vue';
import type { DataSchema } from '@tmagic/core'; import type { DataSchema } from '@tmagic/core';
import { TMagicButton, tMagicMessage, tMagicMessageBox } from '@tmagic/design'; import { TMagicButton, tMagicMessage, tMagicMessageBox } from '@tmagic/design';
@ -84,6 +88,10 @@ const emit = defineEmits<{
}>(); }>();
const { uiService } = useServices(); const { uiService } = useServices();
const mForm = inject<FormState | undefined>('mForm');
/** 对比模式下隐藏新增/编辑/删除等操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const fieldValues = ref<Record<string, any>>({}); const fieldValues = ref<Record<string, any>>({});
const fieldTitle = ref(''); const fieldTitle = ref('');
@ -97,6 +105,16 @@ const newHandler = () => {
addDialogVisible.value = true; addDialogVisible.value = true;
}; };
const editField = (row: Record<string, any>, index: number) => {
fieldValues.value = {
...row,
index,
};
fieldTitle.value = `编辑${row.title}`;
calcBoxPosition();
addDialogVisible.value = true;
};
const fieldChange = ({ index, ...value }: Record<string, any>, data: ContainerChangeEventData) => { const fieldChange = ({ index, ...value }: Record<string, any>, data: ContainerChangeEventData) => {
addDialogVisible.value = false; addDialogVisible.value = false;
@ -154,13 +172,7 @@ const fieldColumns: ColumnConfig[] = [
{ {
text: '编辑', text: '编辑',
handler: (row: Record<string, any>, index: number) => { handler: (row: Record<string, any>, index: number) => {
fieldValues.value = { editField(row, index);
...row,
index,
};
fieldTitle.value = `编辑${row.title}`;
calcBoxPosition();
addDialogVisible.value = true;
}, },
}, },
{ {
@ -176,6 +188,11 @@ const fieldColumns: ColumnConfig[] = [
}, },
]; ];
/** 对比模式下移除「操作」列(编辑/删除按钮),仅保留只读列。 */
const displayColumns = computed<ColumnConfig[]>(() =>
isCompare.value ? fieldColumns.filter((col) => !col.actions) : fieldColumns,
);
const dataSourceFieldsConfig: FormConfig = [ const dataSourceFieldsConfig: FormConfig = [
{ name: 'index', type: 'hidden', filter: 'number', defaultValue: -1 }, { name: 'index', type: 'hidden', filter: 'number', defaultValue: -1 },
{ {
@ -345,4 +362,30 @@ const { height: editorHeight } = useEditorContentHeight();
const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null)); const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null));
const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating); const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating);
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
/**
* DataSourceConfigPanel 注入打开数据源详情后需要直接打开的字段路径字段名数组
* 当前层消费 path[0]并把剩余路径下发给嵌套字段实现逐层打开
*/
const editingFieldPath = inject<ComputedRef<string[]>>(
'editingDataSourceFieldPath',
computed(() => []),
);
provide(
'editingDataSourceFieldPath',
computed(() => editingFieldPath.value.slice(1)),
);
onMounted(() => {
const path = editingFieldPath.value;
if (!path.length) return;
const fields: Record<string, any>[] = props.model[props.name] || [];
const index = fields.findIndex((field) => field.name === path[0]);
if (index === -1) return;
editField(fields[index], index);
});
</script> </script>

View File

@ -30,10 +30,10 @@
<template #suffix> <template #suffix>
<Icon :icon="Coin" /> <Icon :icon="Coin" />
</template> </template>
<template #default="{ item }"> <template #default="slotProps">
<div style="display: flex; flex-direction: column; line-height: 1.2em"> <div style="display: flex; flex-direction: column; line-height: 1.2em">
<div>{{ item.text }}</div> <div>{{ slotProps?.item?.text || '' }}</div>
<span style="font-size: 10px; color: rgba(0, 0, 0, 0.6)">{{ item.value }}</span> <span style="font-size: 10px; color: rgba(0, 0, 0, 0.6)">{{ slotProps?.item?.value || '' }}</span>
</div> </div>
</template> </template>
</component> </component>
@ -79,11 +79,11 @@ import { Coin } from '@element-plus/icons-vue';
import type { DataSchema, DataSourceSchema } from '@tmagic/core'; import type { DataSchema, DataSourceSchema } from '@tmagic/core';
import { getDesignConfig, TMagicAutocomplete, TMagicInput, TMagicTag } from '@tmagic/design'; import { getDesignConfig, TMagicAutocomplete, TMagicInput, TMagicTag } from '@tmagic/design';
import type { DataSourceInputConfig, FieldProps } from '@tmagic/form'; import type { DataSourceInputConfig, FieldProps } from '@tmagic/form';
import { getKeysArray, isNumber } from '@tmagic/utils'; import { getKeysArray } from '@tmagic/utils';
import Icon from '@editor/components/Icon.vue'; import Icon from '@editor/components/Icon.vue';
import { useServices } from '@editor/hooks/use-services'; import { useServices } from '@editor/hooks/use-services';
import { getDisplayField } from '@editor/utils/data-source'; import { getDisplayField, resolveFieldByPath } from '@editor/utils/data-source';
defineOptions({ defineOptions({
name: 'MFieldsDataSourceInput', name: 'MFieldsDataSourceInput',
@ -251,34 +251,16 @@ const fieldQuerySearch = (
return; return;
} }
let fields = ds.fields || []; const { fields } = resolveFieldByPath(ds.fields, keys, { skipNumberIndices: true });
//
let key = keys.shift();
while (key) {
if (isNumber(key)) {
key = keys.shift();
continue;
}
for (const field of fields) {
if (field.name === key) {
fields = field.fields || [];
key = keys.shift();
break;
}
}
}
if (curCharIsDot(dotIndex)) { if (curCharIsDot(dotIndex)) {
// . // .
result = fields || []; result = fields;
} else if (dotIndex > -1) { } else if (dotIndex > -1) {
const queryName = queryString.substring(dotIndex + 1).toLowerCase(); const queryName = queryString.substring(dotIndex + 1).toLowerCase();
result = result = fields.filter(
fields.filter(
(field) => field.name?.toLowerCase().includes(queryName) || field.title?.toLowerCase().includes(queryName), (field) => field.name?.toLowerCase().includes(queryName) || field.title?.toLowerCase().includes(queryName),
) || []; );
} }
cb( cb(

View File

@ -13,7 +13,7 @@
></MCascader> ></MCascader>
<TMagicTooltip <TMagicTooltip
v-if="model[name] && isCustomMethod && hasDataSourceSidePanel" v-if="model[name] && isCustomMethod && dataSourceSidePanel && !isCompare"
:content="notEditable ? '查看' : '编辑'" :content="notEditable ? '查看' : '编辑'"
> >
<TMagicButton class="m-fields-select-action-button" :size="size" @click="editCodeHandler"> <TMagicButton class="m-fields-select-action-button" :size="size" @click="editCodeHandler">
@ -75,12 +75,15 @@ const props = withDefaults(defineProps<FieldProps<DataSourceMethodSelectConfig>>
disabled: false, disabled: false,
}); });
const hasDataSourceSidePanel = computed(() => const dataSourceSidePanel = computed(() =>
(uiService.get('sideBarItems') || []).find((item) => item.$key === SideItemKey.DATA_SOURCE), (uiService.get('sideBarItems') || []).find((item) => item.$key === SideItemKey.DATA_SOURCE),
); );
const notEditable = computed(() => filterFunction(mForm, props.config.notEditable, props)); const notEditable = computed(() => filterFunction(mForm, props.config.notEditable, props));
/** 对比模式下隐藏查看/编辑操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const dataSources = computed(() => dataSourceService.get('dataSources')); const dataSources = computed(() => dataSourceService.get('dataSources'));
const isCustomMethod = computed(() => { const isCustomMethod = computed(() => {
@ -205,12 +208,17 @@ const onParamsChangeHandler = (value: any, eventData: ContainerChangeEventData)
}; };
const editCodeHandler = () => { const editCodeHandler = () => {
const [id] = props.model[props.name]; const [id, methodName] = props.model[props.name];
const dataSource = dataSourceService.getDataSourceById(id); const dataSource = dataSourceService.getDataSourceById(id);
if (!dataSource) return; if (!dataSource) return;
eventBus?.emit('edit-data-source', id); const sideBarItem = dataSourceSidePanel.value;
if (sideBarItem) {
uiService.set('sideBarActiveTabName', sideBarItem.text || sideBarItem.$key || SideItemKey.DATA_SOURCE);
}
eventBus?.emit('edit-data-source-method', id, methodName);
}; };
</script> </script>

View File

@ -1,8 +1,8 @@
<template> <template>
<div class="m-editor-data-source-methods"> <div class="m-editor-data-source-methods">
<MagicTable :data="model[name]" :columns="methodColumns" :border="true"></MagicTable> <MagicTable :data="model[name]" :columns="displayColumns" :border="true"></MagicTable>
<div class="m-editor-data-source-methods-footer"> <div v-if="!isCompare" class="m-editor-data-source-methods-footer">
<TMagicButton size="small" type="primary" :disabled="disabled" plain @click="createCodeHandler" <TMagicButton size="small" type="primary" :disabled="disabled" plain @click="createCodeHandler"
>添加</TMagicButton >添加</TMagicButton
> >
@ -21,12 +21,12 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, ref, useTemplateRef } from 'vue'; import { computed, type ComputedRef, inject, nextTick, onMounted, ref, useTemplateRef } from 'vue';
import { cloneDeep } from 'lodash-es'; import { cloneDeep } from 'lodash-es';
import type { CodeBlockContent } from '@tmagic/core'; import type { CodeBlockContent } from '@tmagic/core';
import { TMagicButton, tMagicMessageBox } from '@tmagic/design'; import { TMagicButton, tMagicMessageBox } from '@tmagic/design';
import type { ContainerChangeEventData, DataSourceMethodsConfig, FieldProps } from '@tmagic/form'; import type { ContainerChangeEventData, DataSourceMethodsConfig, FieldProps, FormState } from '@tmagic/form';
import { type ColumnConfig, MagicTable } from '@tmagic/table'; import { type ColumnConfig, MagicTable } from '@tmagic/table';
import CodeBlockEditor from '@editor/components/CodeBlockEditor.vue'; import CodeBlockEditor from '@editor/components/CodeBlockEditor.vue';
@ -42,11 +42,39 @@ const props = withDefaults(defineProps<FieldProps<DataSourceMethodsConfig>>(), {
const emit = defineEmits(['change']); const emit = defineEmits(['change']);
const mForm = inject<FormState | undefined>('mForm');
/** 对比模式下隐藏新增/编辑/删除等操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const codeConfig = ref<Omit<CodeBlockContent, 'content'> & { content: string }>(); const codeConfig = ref<Omit<CodeBlockContent, 'content'> & { content: string }>();
const codeBlockEditorRef = useTemplateRef<InstanceType<typeof CodeBlockEditor>>('codeBlockEditor'); const codeBlockEditorRef = useTemplateRef<InstanceType<typeof CodeBlockEditor>>('codeBlockEditor');
let editIndex = -1; let editIndex = -1;
const editMethod = (method: CodeBlockContent, index: number) => {
let codeContent: string = '({ params, dataSource, app }) => {\n // place your code here\n}';
if (method.content) {
if (typeof method.content !== 'string') {
codeContent = method.content.toString();
} else {
codeContent = method.content;
}
}
codeConfig.value = {
...cloneDeep(method),
content: codeContent,
};
editIndex = index;
nextTick(() => {
codeBlockEditorRef.value?.show();
});
};
const methodColumns: ColumnConfig[] = [ const methodColumns: ColumnConfig[] = [
{ {
label: '名称', label: '名称',
@ -72,26 +100,7 @@ const methodColumns: ColumnConfig[] = [
{ {
text: '编辑', text: '编辑',
handler: (method: CodeBlockContent, index: number) => { handler: (method: CodeBlockContent, index: number) => {
let codeContent: string = '({ params, dataSource, app }) => {\n // place your code here\n}'; editMethod(method, index);
if (method.content) {
if (typeof method.content !== 'string') {
codeContent = method.content.toString();
} else {
codeContent = method.content;
}
}
codeConfig.value = {
...cloneDeep(method),
content: codeContent,
};
editIndex = index;
nextTick(() => {
codeBlockEditorRef.value?.show();
});
}, },
}, },
{ {
@ -107,6 +116,11 @@ const methodColumns: ColumnConfig[] = [
}, },
]; ];
/** 对比模式下移除「操作」列(编辑/删除按钮),仅保留只读列。 */
const displayColumns = computed<ColumnConfig[]>(() =>
isCompare.value ? methodColumns.filter((col) => !col.actions) : methodColumns,
);
const createCodeHandler = () => { const createCodeHandler = () => {
codeConfig.value = { codeConfig.value = {
name: '', name: '',
@ -148,4 +162,21 @@ const submitCodeHandler = (value: CodeBlockContent, data: ContainerChangeEventDa
codeBlockEditorRef.value?.hide(); codeBlockEditorRef.value?.hide();
}; };
/** 由 DataSourceConfigPanel 注入:打开数据源详情后需要直接打开的方法名 */
const editingMethodName = inject<ComputedRef<string | undefined>>(
'editingDataSourceMethodName',
computed(() => ''),
);
onMounted(() => {
const methodName = editingMethodName.value;
if (!methodName) return;
const methods: CodeBlockContent[] = props.model[props.name] || [];
const index = methods.findIndex((method) => method.name === methodName);
if (index === -1) return;
editMethod(methods[index], index);
});
</script> </script>

View File

@ -1,16 +1,18 @@
<template> <template>
<div class="m-editor-data-source-fields"> <div class="m-editor-data-source-fields">
<MagicTable :data="model[name]" :columns="columns"></MagicTable> <MagicTable :data="model[name]" :columns="displayColumns"></MagicTable>
<div class="m-editor-data-source-fields-footer"> <div v-if="!isCompare" class="m-editor-data-source-fields-footer">
<TMagicButton size="small" type="primary" :disabled="disabled" plain @click="newHandler()">添加</TMagicButton> <TMagicButton size="small" type="primary" :disabled="disabled" plain @click="newHandler()">添加</TMagicButton>
</div> </div>
<FloatingBox <FloatingBox
:body-style="{ padding: '0 16px' }"
v-model:visible="addDialogVisible" v-model:visible="addDialogVisible"
v-model:width="width" v-model:width="width"
v-model:height="editorHeight" v-model:height="editorHeight"
:title="drawerTitle" :title="drawerTitle"
:framework-width="frameworkWidth"
:position="boxPosition" :position="boxPosition"
> >
<template #body> <template #body>
@ -28,7 +30,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { inject, Ref, ref } from 'vue'; import { computed, inject, Ref, ref } from 'vue';
import type { MockSchema } from '@tmagic/core'; import type { MockSchema } from '@tmagic/core';
import { TMagicButton, tMagicMessageBox, TMagicSwitch } from '@tmagic/design'; import { TMagicButton, tMagicMessageBox, TMagicSwitch } from '@tmagic/design';
@ -54,6 +56,11 @@ const props = withDefaults(defineProps<FieldProps<DataSourceMocksConfig>>(), {
const emit = defineEmits(['change']); const emit = defineEmits(['change']);
const { uiService } = useServices(); const { uiService } = useServices();
const mForm = inject<FormState | undefined>('mForm');
/** 对比模式下隐藏新增/编辑/删除等操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const width = defineModel<number>('width', { default: 670 }); const width = defineModel<number>('width', { default: 670 });
const drawerTitle = ref(''); const drawerTitle = ref('');
@ -202,6 +209,11 @@ const columns: ColumnConfig[] = [
}, },
]; ];
/** 对比模式下移除「操作」列(编辑/删除按钮),仅保留只读列。 */
const displayColumns = computed<ColumnConfig[]>(() =>
isCompare.value ? columns.filter((col) => !col.actions) : columns,
);
const newHandler = () => { const newHandler = () => {
const isFirstRow = props.model[props.name].length === 0; const isFirstRow = props.model[props.name].length === 0;
formValues.value = { formValues.value = {
@ -244,4 +256,5 @@ const addDialogVisible = defineModel<boolean>('visible', { default: false });
const { height: editorHeight } = useEditorContentHeight(); const { height: editorHeight } = useEditorContentHeight();
const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null)); const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null));
const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating); const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating);
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
</script> </script>

View File

@ -11,7 +11,7 @@
@change="changeHandler" @change="changeHandler"
></MSelect> ></MSelect>
<TMagicTooltip v-if="model[name] && hasDataSourceSidePanel" :content="notEditable ? '查看' : '编辑'"> <TMagicTooltip v-if="model[name] && hasDataSourceSidePanel && !isCompare" :content="notEditable ? '查看' : '编辑'">
<TMagicButton class="m-fields-select-action-button" :size="size" @click="editHandler" <TMagicButton class="m-fields-select-action-button" :size="size" @click="editHandler"
><MIcon :icon="!notEditable ? Edit : View"></MIcon ><MIcon :icon="!notEditable ? Edit : View"></MIcon
></TMagicButton> ></TMagicButton>
@ -56,6 +56,9 @@ const dataSources = computed(() => dataSourceService.get('dataSources'));
const notEditable = computed(() => filterFunction(mForm, props.config.notEditable, props)); const notEditable = computed(() => filterFunction(mForm, props.config.notEditable, props));
/** 对比模式下隐藏查看/编辑操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const hasDataSourceSidePanel = computed(() => const hasDataSourceSidePanel = computed(() =>
uiService.get('sideBarItems').find((item) => item.$key === SideItemKey.DATA_SOURCE), uiService.get('sideBarItems').find((item) => item.$key === SideItemKey.DATA_SOURCE),
); );

View File

@ -98,6 +98,11 @@ const config = computed<GroupListConfig>(() => ({
label: '字段', label: '字段',
checkStrictly: false, checkStrictly: false,
onChange: fieldOnChange, onChange: fieldOnChange,
defaultValue: () => [],
rules: [
{ required: true, trigger: 'blur', message: '请选择字段' },
{ typeMatch: true, trigger: 'change' },
],
} }
: { : {
type: 'data-source-field-select', type: 'data-source-field-select',
@ -107,6 +112,11 @@ const config = computed<GroupListConfig>(() => ({
checkStrictly: false, checkStrictly: false,
dataSourceFieldType: ['string', 'number', 'boolean', 'any'], dataSourceFieldType: ['string', 'number', 'boolean', 'any'],
onChange: fieldOnChange, onChange: fieldOnChange,
defaultValue: () => [],
rules: [
{ required: true, trigger: 'blur', message: '请选择字段' },
{ typeMatch: true, trigger: 'change' },
],
}, },
{ {
type: 'cond-op-select', type: 'cond-op-select',
@ -114,6 +124,10 @@ const config = computed<GroupListConfig>(() => ({
label: '条件', label: '条件',
width: 140, width: 140,
name: 'op', name: 'op',
rules: [
{ required: true, trigger: 'blur', message: '请选择条件' },
{ typeMatch: true, trigger: 'change' },
],
}, },
{ {
label: '值', label: '值',

View File

@ -6,22 +6,32 @@
:size="size" :size="size"
:disabled="disabled" :disabled="disabled"
:model="model" :model="model"
:last-values="lastValues"
:is-compare="isCompareMode"
:config="tableConfig" :config="tableConfig"
@change="onChangeHandler" @change="onChangeHandler"
></MTable> ></MTable>
<div v-else class="fullWidth"> <div v-else class="fullWidth">
<TMagicButton class="create-button" type="primary" :size="size" :disabled="disabled" @click="addEvent()" <TMagicButton
v-if="!isCompareMode"
class="create-button"
type="primary"
:size="size"
:disabled="disabled"
@click="addEvent()"
>添加事件</TMagicButton >添加事件</TMagicButton
> >
<MPanel <MPanel
v-for="(cardItem, index) in model[name]" v-for="entry in displayList"
:key="index" :key="entry.index"
:disabled="disabled" :disabled="disabled"
:size="size" :size="size"
:prop="`${prop}.${index}`" :prop="`${prop}.${entry.index}`"
:config="actionsConfig" :config="actionsConfig"
:model="cardItem" :model="entry.cardItem"
:last-values="entry.lastCardItem"
:is-compare="isCompareMode"
:label-width="config.labelWidth || '100px'" :label-width="config.labelWidth || '100px'"
@change="onChangeHandler" @change="onChangeHandler"
> >
@ -29,19 +39,22 @@
<MFormContainer <MFormContainer
class="fullWidth" class="fullWidth"
:config="eventNameConfig" :config="eventNameConfig"
:model="cardItem" :model="entry.cardItem"
:last-values="entry.lastCardItem"
:is-compare="isCompareMode"
:disabled="disabled" :disabled="disabled"
:size="size" :size="size"
:prop="`${prop}.${index}`" :prop="`${prop}.${entry.index}`"
@change="eventNameChangeHandler" @change="eventNameChangeHandler"
></MFormContainer> ></MFormContainer>
<TMagicButton <TMagicButton
v-if="!isCompareMode"
style="color: #f56c6c" style="color: #f56c6c"
link link
:icon="Delete" :icon="Delete"
:disabled="disabled" :disabled="disabled"
:size="size" :size="size"
@click="removeEvent(Number(index))" @click="removeEvent(Number(entry.index))"
></TMagicButton> ></TMagicButton>
</template> </template>
</MPanel> </MPanel>
@ -54,11 +67,9 @@ import { computed } from 'vue';
import { Delete } from '@element-plus/icons-vue'; import { Delete } from '@element-plus/icons-vue';
import { has } from 'lodash-es'; import { has } from 'lodash-es';
import type { EventOption, MComponent, MContainer } from '@tmagic/core';
import { ActionType } from '@tmagic/core'; import { ActionType } from '@tmagic/core';
import { TMagicButton } from '@tmagic/design'; import { TMagicButton } from '@tmagic/design';
import type { import type {
CascaderOption,
CodeSelectColConfig, CodeSelectColConfig,
ContainerChangeEventData, ContainerChangeEventData,
DataSourceMethodSelectConfig, DataSourceMethodSelectConfig,
@ -71,10 +82,15 @@ import type {
UISelectConfig, UISelectConfig,
} from '@tmagic/form'; } from '@tmagic/form';
import { defineFormItem, MContainer as MFormContainer, MPanel, MTable } from '@tmagic/form'; import { defineFormItem, MContainer as MFormContainer, MPanel, MTable } from '@tmagic/form';
import { DATA_SOURCE_FIELDS_CHANGE_EVENT_PREFIX, traverseNode } from '@tmagic/utils';
import { useServices } from '@editor/hooks/use-services'; import { useServices } from '@editor/hooks/use-services';
import { getCascaderOptionsFromFields } from '@editor/utils'; import {
getCompActionAllowedValues,
getCompActionOptions,
getEventNameAllowedValues,
getEventNameOptions,
normalizeCompActionValue,
} from '@editor/utils';
defineOptions({ defineOptions({
name: 'MFieldsEventSelect', name: 'MFieldsEventSelect',
@ -105,76 +121,24 @@ const eventNameConfig = computed(() => {
labelWidth: '40px', labelWidth: '40px',
checkStrictly: () => props.config.src !== 'component', checkStrictly: () => props.config.src !== 'component',
valueSeparator: '.', valueSeparator: '.',
options: (mForm: FormState, { formValue }: any) => { options: (_mForm: FormState, { formValue }: any) => getEventNameOptions(props.config.src, formValue),
let events: EventOption[] | CascaderOption[] = []; rules: [
if (props.config.src === 'component') {
events = eventsService.getEvent(formValue.type);
if (formValue.type === 'page-fragment-container' && formValue.pageFragmentId) {
const pageFragment = editorService.get('root')?.items?.find((page) => page.id === formValue.pageFragmentId);
if (pageFragment) {
events = [
{ {
label: pageFragment.name || '页面片容器', validator: ({ value, callback }: any, { formValue }: any) => {
value: pageFragment.id, const allowedNames = getEventNameAllowedValues(props.config as any, formValue);
children: events, if (allowedNames && allowedNames.size > 0 && value && !allowedNames.has(value)) {
return callback(`事件名(${value})不存在`);
}
callback();
}, },
]; trigger: 'blur',
pageFragment.items.forEach((node) => {
traverseNode<MComponent | MContainer>(node, (node) => {
const nodeEvents = (node.type && eventsService.getEvent(node.type)) || [];
events.push({
label: `${node.name}_${node.id}`,
value: `${node.id}`,
children: nodeEvents,
});
});
});
return events;
}
}
return events.map((option) => ({
text: option.label,
value: option.value,
}));
}
if (props.config.src === 'datasource') {
//
events = dataSourceService.getFormEvent(formValue.type);
//
const dataSource = dataSourceService.getDataSourceById(formValue.id);
const fields = dataSource?.fields || [];
if (fields.length > 0) {
return [
...events,
{
label: '数据变化',
value: DATA_SOURCE_FIELDS_CHANGE_EVENT_PREFIX,
children: getCascaderOptionsFromFields(fields),
},
];
}
return events;
}
}, },
],
}; };
return { ...defaultEventNameConfig, ...props.config.eventNameConfig }; return { ...defaultEventNameConfig, ...props.config.eventNameConfig };
}); });
// const actionTypeOptions = computed(() => {
const actionTypeConfig = computed(() => {
const defaultActionTypeConfig = {
name: 'actionType',
text: '联动类型',
type: 'select',
defaultValue: ActionType.COMP,
options: () => {
const o: { const o: {
text: string; text: string;
label: string; label: string;
@ -206,7 +170,26 @@ const actionTypeConfig = computed(() => {
} }
return o; return o;
});
//
const actionTypeConfig = computed(() => {
const defaultActionTypeConfig = {
name: 'actionType',
text: '联动类型',
type: 'select',
defaultValue: ActionType.COMP,
options: actionTypeOptions.value,
rules: [
{
required: true,
message: '联动类型不能为空',
}, },
{
typeMatch: true,
trigger: 'blur',
},
],
}; };
return { ...defaultActionTypeConfig, ...props.config.actionTypeConfig }; return { ...defaultActionTypeConfig, ...props.config.actionTypeConfig };
}); });
@ -221,6 +204,12 @@ const targetCompConfig = computed(() => {
onChange: (_MForm, _v, { setModel }) => { onChange: (_MForm, _v, { setModel }) => {
setModel('method', ''); setModel('method', '');
}, },
rules: [
{
typeMatch: true,
trigger: 'blur',
},
],
}; };
return { ...defaultTargetCompConfig, ...props.config.targetCompConfig }; return { ...defaultTargetCompConfig, ...props.config.targetCompConfig };
}); });
@ -241,41 +230,20 @@ const compActionConfig = computed(() => {
}, },
checkStrictly: () => props.config.src !== 'component', checkStrictly: () => props.config.src !== 'component',
display: (mForm: FormState | undefined, { model }: any) => model.actionType === ActionType.COMP, display: (mForm: FormState | undefined, { model }: any) => model.actionType === ActionType.COMP,
options: (mForm: FormState, { model }: any) => { options: (_mForm: FormState, { model }: any) => getCompActionOptions(model.to),
const node = editorService.getNodeById(model.to); rules: [
if (!node?.type) return []; {
trigger: 'blur',
let methods: EventOption[] | CascaderOption[] = []; validator: ({ value, callback }: any, { model }: any) => {
const allowedMethods = getCompActionAllowedValues(props.config as any, model);
methods = eventsService.getMethod(node.type, model.to); const normalized = normalizeCompActionValue(value);
if (allowedMethods && allowedMethods.size > 0 && normalized && !allowedMethods.has(normalized)) {
if (node.type === 'page-fragment-container' && node.pageFragmentId) { return callback(`动作名(${normalized})不存在`);
const pageFragment = editorService.get('root')?.items?.find((page) => page.id === node.pageFragmentId);
if (pageFragment) {
methods = [];
pageFragment.items.forEach((node: MComponent | MContainer) => {
traverseNode<MComponent | MContainer>(node, (node) => {
const nodeMethods = (node.type && eventsService.getMethod(node.type, node.id)) || [];
if (nodeMethods.length) {
methods.push({
label: `${node.name}_${node.id}`,
value: `${node.id}`,
children: nodeMethods,
});
} }
}); callback();
});
return methods;
}
}
return methods.map((method) => ({
text: method.label,
value: method.value,
}));
}, },
},
],
}; };
return { ...defaultCompActionConfig, ...props.config.compActionConfig }; return { ...defaultCompActionConfig, ...props.config.compActionConfig };
}); });
@ -374,6 +342,42 @@ const isOldVersion = computed(() => {
return !has(props.model[props.name][0], 'actions'); return !has(props.model[props.name][0], 'actions');
}); });
/**
* 对比模式判定
*
* event-select 内部由事件列表 + 嵌套子表单组成属于复合字段父级 `MFormContainer` 已将其
* 归入自接管对比字段 Container.vue `SELF_DIFF_FIELD_TYPES`即对比时只渲染一次本组件
* 并把当前值 `model` 与历史值 `lastValues` 一并传入由本组件把 `is-compare`/`lastValues` 透传给
* 内部的 MPanel / MFormContainer逐项事件名动作展示前后差异
*
* 仅当存在历史值时才启用对比避免 lastValues 缺失时退化为全部新增的空对比
*/
const isCompareMode = computed(() => Boolean(props.isCompare && props.lastValues));
/**
* 待渲染的事件卡片列表
*
* - 非对比模式直接映射当前事件列表`lastCardItem` 为空
* - 对比模式按索引对齐当前值与历史值取两者长度的最大值使得新增仅当前有
* 删除仅历史有的事件都能被渲染出来缺失的一侧用空对象兜底从而让子级正确高亮差异
*/
const displayList = computed<{ cardItem: any; lastCardItem: any; index: number }[]>(() => {
const current = props.model[props.name] || [];
if (!isCompareMode.value) {
return current.map((cardItem: any, index: number) => ({ cardItem, lastCardItem: undefined, index }));
}
const last = props.lastValues?.[props.name] || [];
const length = Math.max(current.length, last.length);
return Array.from({ length }, (_, index) => ({
cardItem: current[index] ?? {},
lastCardItem: last[index] ?? {},
index,
}));
});
// //
const addEvent = () => { const addEvent = () => {
const defaultEvent = { const defaultEvent = {

View File

@ -19,6 +19,7 @@
></TMagicInput> ></TMagicInput>
<TMagicButton <TMagicButton
v-if="!isCompare"
class="m-fields-key-value-delete" class="m-fields-key-value-delete"
type="danger" type="danger"
:size="size" :size="size"
@ -30,7 +31,14 @@
></TMagicButton> ></TMagicButton>
</div> </div>
<TMagicButton type="primary" :size="size" :disabled="disabled" plain :icon="Plus" @click="addHandler" <TMagicButton
v-if="!isCompare"
type="primary"
:size="size"
:disabled="disabled"
plain
:icon="Plus"
@click="addHandler"
>添加</TMagicButton >添加</TMagicButton
> >
</div> </div>
@ -52,7 +60,7 @@
></MagicCodeEditor> ></MagicCodeEditor>
<TMagicButton <TMagicButton
v-if="config.advanced" v-if="config.advanced && !isCompare"
size="default" size="default"
:disabled="disabled" :disabled="disabled"
link link
@ -63,11 +71,11 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, watchEffect } from 'vue'; import { computed, inject, ref, watchEffect } from 'vue';
import { Delete, Plus } from '@element-plus/icons-vue'; import { Delete, Plus } from '@element-plus/icons-vue';
import { TMagicButton, TMagicInput } from '@tmagic/design'; import { TMagicButton, TMagicInput } from '@tmagic/design';
import type { FieldProps, KeyValueConfig } from '@tmagic/form'; import type { FieldProps, FormState, KeyValueConfig } from '@tmagic/form';
import CodeIcon from '@editor/icons/CodeIcon.vue'; import CodeIcon from '@editor/icons/CodeIcon.vue';
import MagicCodeEditor from '@editor/layouts/CodeEditor.vue'; import MagicCodeEditor from '@editor/layouts/CodeEditor.vue';
@ -84,6 +92,11 @@ const emit = defineEmits<{
change: [value: Record<string, any>]; change: [value: Record<string, any>];
}>(); }>();
const mForm = inject<FormState | undefined>('mForm');
/** 对比模式下隐藏增删/代码切换等操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const records = ref<[string, string][]>([]); const records = ref<[string, string][]>([]);
const showCode = ref(false); const showCode = ref(false);

View File

@ -7,6 +7,7 @@
v-if="item.component" v-if="item.component"
:is="item.component" :is="item.component"
:values="model[name]" :values="model[name]"
:prop="prop || name"
:last-values="lastValues?.[name]" :last-values="lastValues?.[name]"
:is-compare="isCompare" :is-compare="isCompare"
:size="size" :size="size"
@ -35,7 +36,7 @@ defineOptions({
name: 'MFieldsStyleSetter', name: 'MFieldsStyleSetter',
}); });
const props = defineProps<FieldProps<StyleSchema>>(); defineProps<FieldProps<StyleSchema>>();
const emit = defineEmits<{ const emit = defineEmits<{
change: [v: any, eventData: ContainerChangeEventData]; change: [v: any, eventData: ContainerChangeEventData];
@ -77,13 +78,6 @@ const collapseValue = shallowRef(
); );
const change = (v: any, eventData: ContainerChangeEventData) => { const change = (v: any, eventData: ContainerChangeEventData) => {
eventData.changeRecords?.forEach((record) => {
if (props.prop) {
record.propPath = `${props.prop}.${record.propPath}`;
} else if (props.name) {
record.propPath = `${props.name}.${record.propPath}`;
}
});
emit('change', v, eventData); emit('change', v, eventData);
}; };

View File

@ -4,27 +4,31 @@
<div class="border-icon-container-row"> <div class="border-icon-container-row">
<div <div
class="border-icon border-icon-top" class="border-icon border-icon-top"
:class="{ active: direction === 'Top' }" :class="{ active: direction === 'Top', configured: isConfigured('Top') }"
@click="selectDirection('Top')" @click="selectDirection('Top')"
></div> ></div>
</div> </div>
<div class="border-icon-container-row"> <div class="border-icon-container-row">
<div <div
class="border-icon border-icon-left" class="border-icon border-icon-left"
:class="{ active: direction === 'Left' }" :class="{ active: direction === 'Left', configured: isConfigured('Left') }"
@click="selectDirection('Left')" @click="selectDirection('Left')"
></div> ></div>
<div class="border-icon" :class="{ active: direction === '' }" @click="selectDirection()"></div> <div
class="border-icon"
:class="{ active: direction === '', configured: isConfigured('') }"
@click="selectDirection()"
></div>
<div <div
class="border-icon border-icon-right" class="border-icon border-icon-right"
:class="{ active: direction === 'Right' }" :class="{ active: direction === 'Right', configured: isConfigured('Right') }"
@click="selectDirection('Right')" @click="selectDirection('Right')"
></div> ></div>
</div> </div>
<div class="border-icon-container-row"> <div class="border-icon-container-row">
<div <div
class="border-icon border-icon-bottom" class="border-icon border-icon-bottom"
:class="{ active: direction === 'Bottom' }" :class="{ active: direction === 'Bottom', configured: isConfigured('Bottom') }"
@click="selectDirection('Bottom')" @click="selectDirection('Bottom')"
></div> ></div>
</div> </div>
@ -98,7 +102,7 @@ const emit = defineEmits<{
addDiffCount: []; addDiffCount: [];
}>(); }>();
withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
model: FormValue; model: FormValue;
lastValues?: FormValue; lastValues?: FormValue;
@ -109,6 +113,11 @@ withDefaults(
{}, {},
); );
const hasValue = (value: unknown) => value !== undefined && value !== null && value !== '';
const isConfigured = (d: string) =>
['Width', 'Color', 'Style'].some((key) => hasValue(props.model?.[`border${d}${key}`]));
const change = (value: StyleSchema, eventData: ContainerChangeEventData) => { const change = (value: StyleSchema, eventData: ContainerChangeEventData) => {
eventData.changeRecords?.forEach((record) => { eventData.changeRecords?.forEach((record) => {
emit('change', record.value, { emit('change', record.value, {

View File

@ -1,6 +1,9 @@
<template> <template>
<MContainer <MContainer
:config="config" v-for="item in formConfig"
:prop="prop"
:key="item.name"
:config="item"
:model="values" :model="values"
:last-values="lastValues" :last-values="lastValues"
:is-compare="isCompare" :is-compare="isCompare"
@ -14,7 +17,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { markRaw } from 'vue'; import { markRaw } from 'vue';
import { type ContainerChangeEventData, defineFormItem, MContainer } from '@tmagic/form'; import { type ContainerChangeEventData, defineFormConfig, MContainer } from '@tmagic/form';
import type { StyleSchema } from '@tmagic/schema'; import type { StyleSchema } from '@tmagic/schema';
import BackgroundPosition from '../components/BackgroundPosition.vue'; import BackgroundPosition from '../components/BackgroundPosition.vue';
@ -26,6 +29,7 @@ defineProps<{
isCompare?: boolean; isCompare?: boolean;
disabled?: boolean; disabled?: boolean;
size?: 'large' | 'default' | 'small'; size?: 'large' | 'default' | 'small';
prop?: string;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@ -33,8 +37,7 @@ const emit = defineEmits<{
addDiffCount: []; addDiffCount: [];
}>(); }>();
const config = defineFormItem({ const formConfig = defineFormConfig([
items: [
{ {
name: 'backgroundColor', name: 'backgroundColor',
text: '背景色', text: '背景色',
@ -64,6 +67,43 @@ const config = defineFormItem({
{ value: 'contain', text: '等比填充', tooltip: '等比填充 contain' }, { value: 'contain', text: '等比填充', tooltip: '等比填充 contain' },
{ value: 'cover', text: '等比覆盖', tooltip: '等比覆盖 cover' }, { value: 'cover', text: '等比覆盖', tooltip: '等比覆盖 cover' },
], ],
rules: [
{
typeMatch: false,
},
{
validator: ({ value, callback }) => {
if (value === '' || value === null || value === undefined) {
return callback();
}
const keywords = ['auto', 'cover', 'contain', 'inherit', 'initial', 'revert', 'unset'];
// /
const lengthPercent = /^-?\d+(\.\d+)?(px|em|rem|ex|ch|vw|vh|vmin|vmax|cm|mm|in|pt|pc|%)$/;
const singleValue = (v: string) => keywords.includes(v) || lengthPercent.test(v);
const str = String(value).trim();
const parts = str.split(/\s+/);
// cover / contain
if (parts.length > 1 && (parts.includes('cover') || parts.includes('contain'))) {
return callback('cover/contain 不能与其他值组合');
}
//
if (parts.length > 2) {
return callback('backgroundSize 最多支持两个值');
}
// auto /
if (parts.every((part) => singleValue(part))) {
return callback();
}
return callback('backgroundSize 值不合法');
},
},
],
}, },
{ {
name: 'backgroundRepeat', name: 'backgroundRepeat',
@ -85,8 +125,7 @@ const config = defineFormItem({
component: BackgroundPosition, component: BackgroundPosition,
labelWidth: '68px', labelWidth: '68px',
}, },
], ]);
});
const change = (value: StyleSchema, eventData: ContainerChangeEventData) => { const change = (value: StyleSchema, eventData: ContainerChangeEventData) => {
emit('change', value, eventData); emit('change', value, eventData);

View File

@ -1,5 +1,6 @@
<template> <template>
<MContainer <MContainer
:prop="prop"
:config="config" :config="config"
:model="values" :model="values"
:last-values="lastValues" :last-values="lastValues"
@ -32,6 +33,7 @@ defineProps<{
isCompare?: boolean; isCompare?: boolean;
disabled?: boolean; disabled?: boolean;
size?: 'large' | 'default' | 'small'; size?: 'large' | 'default' | 'small';
prop?: string;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@ -40,8 +42,6 @@ const emit = defineEmits<{
}>(); }>();
const config = defineFormItem({ const config = defineFormItem({
items: [
{
labelWidth: '68px', labelWidth: '68px',
name: 'borderRadius', name: 'borderRadius',
text: '圆角', text: '圆角',
@ -49,8 +49,6 @@ const config = defineFormItem({
fieldConfig: { fieldConfig: {
type: 'text', type: 'text',
}, },
},
],
}); });
const change = (value: StyleSchema, eventData: ContainerChangeEventData) => { const change = (value: StyleSchema, eventData: ContainerChangeEventData) => {

View File

@ -1,6 +1,9 @@
<template> <template>
<MContainer <MContainer
:config="config" v-for="(item, index) in formConfig"
:prop="prop"
:key="index"
:config="item"
:model="values" :model="values"
:last-values="lastValues" :last-values="lastValues"
:is-compare="isCompare" :is-compare="isCompare"
@ -14,7 +17,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { markRaw } from 'vue'; import { markRaw } from 'vue';
import { type ContainerChangeEventData, defineFormItem, MContainer } from '@tmagic/form'; import { type ContainerChangeEventData, defineFormConfig, MContainer } from '@tmagic/form';
import type { StyleSchema } from '@tmagic/schema'; import type { StyleSchema } from '@tmagic/schema';
import { AlignCenter, AlignLeft, AlignRight } from '../icons/text-align'; import { AlignCenter, AlignLeft, AlignRight } from '../icons/text-align';
@ -25,6 +28,7 @@ defineProps<{
isCompare?: boolean; isCompare?: boolean;
disabled?: boolean; disabled?: boolean;
size?: 'large' | 'default' | 'small'; size?: 'large' | 'default' | 'small';
prop?: string;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@ -32,8 +36,7 @@ const emit = defineEmits<{
addDiffCount: []; addDiffCount: [];
}>(); }>();
const config = defineFormItem({ const formConfig = defineFormConfig([
items: [
{ {
type: 'row', type: 'row',
items: [ items: [
@ -97,8 +100,7 @@ const config = defineFormItem({
{ value: 'right', icon: markRaw(AlignRight), tooltip: '右对齐 right' }, { value: 'right', icon: markRaw(AlignRight), tooltip: '右对齐 right' },
], ],
}, },
], ]);
});
const change = (value: StyleSchema, eventData: ContainerChangeEventData) => { const change = (value: StyleSchema, eventData: ContainerChangeEventData) => {
emit('change', value, eventData); emit('change', value, eventData);

View File

@ -1,6 +1,9 @@
<template> <template>
<MContainer <MContainer
:config="config" v-for="item in formConfig"
:prop="prop"
:key="item.name"
:config="item"
:model="values" :model="values"
:last-values="lastValues" :last-values="lastValues"
:is-compare="isCompare" :is-compare="isCompare"
@ -23,8 +26,8 @@
<script lang="ts" setup> <script lang="ts" setup>
import { markRaw } from 'vue'; import { markRaw } from 'vue';
import type { ChildConfig, ContainerChangeEventData } from '@tmagic/form'; import type { ContainerChangeEventData } from '@tmagic/form';
import { defineFormItem, MContainer } from '@tmagic/form'; import { defineFormConfig, MContainer } from '@tmagic/form';
import type { StyleSchema } from '@tmagic/schema'; import type { StyleSchema } from '@tmagic/schema';
import Box from '../components/Box.vue'; import Box from '../components/Box.vue';
@ -49,6 +52,7 @@ defineProps<{
isCompare?: boolean; isCompare?: boolean;
disabled?: boolean; disabled?: boolean;
size?: 'large' | 'default' | 'small'; size?: 'large' | 'default' | 'small';
prop?: string;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@ -56,8 +60,7 @@ const emit = defineEmits<{
addDiffCount: []; addDiffCount: [];
}>(); }>();
const config = defineFormItem({ const formConfig = defineFormConfig([
items: [
{ {
name: 'display', name: 'display',
text: '模式', text: '模式',
@ -193,8 +196,7 @@ const config = defineFormItem({
}, },
], ],
}, },
], ]);
}) as ChildConfig;
const change = (value: string | StyleSchema, eventData: ContainerChangeEventData) => { const change = (value: string | StyleSchema, eventData: ContainerChangeEventData) => {
emit('change', value, eventData); emit('change', value, eventData);

View File

@ -1,6 +1,9 @@
<template> <template>
<MContainer <MContainer
:config="config" v-for="(item, index) in formConfig"
:prop="prop"
:key="index"
:config="item"
:model="values" :model="values"
:last-values="lastValues" :last-values="lastValues"
:is-compare="isCompare" :is-compare="isCompare"
@ -12,7 +15,7 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { type ContainerChangeEventData, defineFormItem, MContainer } from '@tmagic/form'; import { type ContainerChangeEventData, defineFormConfig, MContainer } from '@tmagic/form';
import type { StyleSchema } from '@tmagic/schema'; import type { StyleSchema } from '@tmagic/schema';
const props = defineProps<{ const props = defineProps<{
@ -21,6 +24,7 @@ const props = defineProps<{
isCompare?: boolean; isCompare?: boolean;
disabled?: boolean; disabled?: boolean;
size?: 'large' | 'default' | 'small'; size?: 'large' | 'default' | 'small';
prop?: string;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@ -36,8 +40,7 @@ const positionText: Record<string, string> = {
sticky: '粘性定位', sticky: '粘性定位',
}; };
const config = defineFormItem({ const formConfig = defineFormConfig([
items: [
{ {
name: 'position', name: 'position',
text: '定位', text: '定位',
@ -106,8 +109,7 @@ const config = defineFormItem({
type: 'text', type: 'text',
}, },
}, },
], ]);
});
const change = (value: string | StyleSchema, eventData: ContainerChangeEventData) => { const change = (value: string | StyleSchema, eventData: ContainerChangeEventData) => {
emit('change', value, eventData); emit('change', value, eventData);

View File

@ -1,5 +1,6 @@
<template> <template>
<MContainer <MContainer
:prop="prop"
:config="config" :config="config"
:model="values" :model="values"
:last-values="lastValues" :last-values="lastValues"
@ -21,6 +22,7 @@ defineProps<{
isCompare?: boolean; isCompare?: boolean;
disabled?: boolean; disabled?: boolean;
size?: 'large' | 'default' | 'small'; size?: 'large' | 'default' | 'small';
prop?: string;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@ -29,8 +31,6 @@ const emit = defineEmits<{
}>(); }>();
const config = defineFormItem({ const config = defineFormItem({
items: [
{
name: 'transform', name: 'transform',
items: [ items: [
{ {
@ -56,8 +56,6 @@ const config = defineFormItem({
}, },
}, },
], ],
},
],
}); });
const change = (value: StyleSchema, eventData: ContainerChangeEventData) => { const change = (value: StyleSchema, eventData: ContainerChangeEventData) => {

View File

@ -6,7 +6,7 @@
</div> </div>
<div class="m-fields-ui-select" v-else style="display: flex"> <div class="m-fields-ui-select" v-else style="display: flex">
<template v-if="val"> <template v-if="val">
<TMagicTooltip content="清除" placement="top"> <TMagicTooltip v-if="!isCompare" content="清除" placement="top">
<TMagicButton <TMagicButton
style="padding: 0" style="padding: 0"
type="danger" type="danger"
@ -32,7 +32,7 @@
</TMagicTooltip> </TMagicTooltip>
</template> </template>
<TMagicTooltip v-else content="点击此处选择" placement="top"> <TMagicTooltip v-else-if="!isCompare" content="点击此处选择" placement="top">
<TMagicButton link style="padding: 0; margin: 0" :disabled="disabled" :size="size" @click="startSelect" <TMagicButton link style="padding: 0; margin: 0" :disabled="disabled" :size="size" @click="startSelect"
>点击此处选择</TMagicButton >点击此处选择</TMagicButton
> >
@ -67,6 +67,9 @@ const mForm = inject<FormState>('mForm');
const val = computed(() => props.model[props.name]); const val = computed(() => props.model[props.name]);
const uiSelectMode = ref(false); const uiSelectMode = ref(false);
/** 对比模式下隐藏清除/选择等操作按钮,仅保留只读展示。 */
const isCompare = computed(() => Boolean(mForm?.isCompare));
const cancelHandler = () => { const cancelHandler = () => {
uiService.set('uiSelectMode', false); uiService.set('uiSelectMode', false);
uiSelectMode.value = false; uiSelectMode.value = false;
@ -124,15 +127,3 @@ const unhighlight = () => {
stageOverlayService.get('stage')?.clearHighlight(); stageOverlayService.get('stage')?.clearHighlight();
}; };
</script> </script>
<style lang="scss">
.m-fields-ui-select {
cursor: pointer;
i {
margin-right: 3px;
}
span {
color: #2882e0;
}
}
</style>

View File

@ -3,9 +3,10 @@ import { cloneDeep } from 'lodash-es';
import type { CodeBlockContent } from '@tmagic/core'; import type { CodeBlockContent } from '@tmagic/core';
import { tMagicMessage } from '@tmagic/design'; import { tMagicMessage } from '@tmagic/design';
import type { ContainerChangeEventData } from '@tmagic/form';
import CodeBlockEditor from '@editor/components/CodeBlockEditor.vue'; import CodeBlockEditor from '@editor/components/CodeBlockEditor.vue';
import type { Services } from '@editor/type'; import type { HistoryOpSource, Services } from '@editor/type';
export const useCodeBlockEdit = (codeBlockService: Services['codeBlockService']) => { export const useCodeBlockEdit = (codeBlockService: Services['codeBlockService']) => {
const codeConfig = ref<Omit<CodeBlockContent, 'content'> & { content: string }>(); const codeConfig = ref<Omit<CodeBlockContent, 'content'> & { content: string }>();
@ -57,14 +58,17 @@ export const useCodeBlockEdit = (codeBlockService: Services['codeBlockService'])
}; };
// 删除代码块 // 删除代码块
const deleteCode = async (key: string) => { const deleteCode = async (key: string, { historySource }: { historySource?: HistoryOpSource } = {}) => {
codeBlockService.deleteCodeDslByIds([key]); codeBlockService.deleteCodeDslByIds([key], { historySource });
}; };
const submitCodeBlockHandler = async (values: CodeBlockContent) => { const submitCodeBlockHandler = async (values: CodeBlockContent, eventData?: ContainerChangeEventData) => {
if (!codeId.value) return; if (!codeId.value) return;
await codeBlockService.setCodeDslById(codeId.value, values); await codeBlockService.setCodeDslById(codeId.value, values, {
changeRecords: eventData?.changeRecords,
historySource: 'props',
});
codeBlockEditorRef.value?.hide(); codeBlockEditorRef.value?.hide();
}; };

View File

@ -27,9 +27,9 @@ export const useDataSourceEdit = (dataSourceService: Services['dataSourceService
const submitDataSourceHandler = (value: DataSourceSchema, eventData: ContainerChangeEventData) => { const submitDataSourceHandler = (value: DataSourceSchema, eventData: ContainerChangeEventData) => {
if (value.id) { if (value.id) {
dataSourceService.update(value, { changeRecords: eventData.changeRecords }); dataSourceService.update(value, { changeRecords: eventData.changeRecords, historySource: 'props' });
} else { } else {
dataSourceService.add(value); dataSourceService.add(value, { historySource: 'props' });
} }
editDialog.value?.hide(); editDialog.value?.hide();

View File

@ -48,6 +48,7 @@ export const useStage = (stageOptions: StageOptions) => {
disabledMultiSelect: stageOptions.disabledMultiSelect, disabledMultiSelect: stageOptions.disabledMultiSelect,
alwaysMultiSelect: stageOptions.alwaysMultiSelect, alwaysMultiSelect: stageOptions.alwaysMultiSelect,
disabledRule: stageOptions.disabledRule, disabledRule: stageOptions.disabledRule,
disabledFlashTip: stageOptions.disabledFlashTip,
}); });
watch( watch(
@ -97,32 +98,48 @@ export const useStage = (stageOptions: StageOptions) => {
stage.on('update', (ev: UpdateEventData) => { stage.on('update', (ev: UpdateEventData) => {
if (ev.parentEl) { if (ev.parentEl) {
for (const data of ev.data) { // 拖动多选元素到一个新容器:整批合成一次 moveToContainer只产生一条历史记录
const id = getIdFromEl()(data.el);
const pId = getIdFromEl()(ev.parentEl); const pId = getIdFromEl()(ev.parentEl);
id && pId && editorService.moveToContainer({ id, style: data.style }, pId); if (!pId) return;
const configs = ev.data
.map((data) => {
const id = getIdFromEl()(data.el);
if (!id) return null;
const cfg: MNode = { id, style: data.style };
return cfg;
})
.filter((cfg): cfg is MNode => Boolean(cfg));
if (configs.length > 0) {
editorService.moveToContainer(configs, pId);
} }
return; return;
} }
// 为每个元素单独更新,确保 changeRecords 与对应的元素关联 // 多选拖动 / 多选缩放:所有元素整批走一次 update避免历史栈被切成 N 条
// changeRecordList 与 configs 同序,每个节点保留自己的 records
// 不能把多个节点的 records 合并到同一个数组里,否则 doUpdate / nodeUpdateHandler 会把别的节点的 propPath 当成自己的。
const configs: MNode[] = [];
const changeRecordList: ReturnType<typeof buildChangeRecords>[] = [];
ev.data.forEach((data) => { ev.data.forEach((data) => {
const id = getIdFromEl()(data.el); const id = getIdFromEl()(data.el);
if (!id) return; if (!id) return;
const { style = {} } = data; const { style = {} } = data;
configs.push({ id, style });
editorService.update({ id, style }, { changeRecords: buildChangeRecords(style, 'style') }); changeRecordList.push(buildChangeRecords(style, 'style'));
}); });
if (configs.length === 0) return;
editorService.update(configs, { changeRecordList, historySource: 'stage' });
}); });
stage.on('sort', (ev: SortEventData) => { stage.on('sort', (ev: SortEventData) => {
editorService.sort(ev.src, ev.dist); editorService.sort(ev.src, ev.dist, { historySource: 'stage' });
}); });
stage.on('remove', (ev: RemoveEventData) => { stage.on('remove', (ev: RemoveEventData) => {
const nodes = ev.data.map(({ el }) => editorService.getNodeById(getIdFromEl()(el) || '')); const nodes = ev.data.map(({ el }) => editorService.getNodeById(getIdFromEl()(el) || ''));
editorService.remove(nodes.filter((node) => Boolean(node)) as MNode[]); editorService.remove(nodes.filter((node) => Boolean(node)) as MNode[], { historySource: 'stage' });
}); });
stage.on('select-parent', () => { stage.on('select-parent', () => {

View File

@ -44,8 +44,11 @@ export { default as stageOverlayService } from './services/stageOverlay';
export { default as uiService } from './services/ui'; export { default as uiService } from './services/ui';
export { default as codeBlockService } from './services/codeBlock'; export { default as codeBlockService } from './services/codeBlock';
export { default as depService } from './services/dep'; export { default as depService } from './services/dep';
export { default as componentListService } from './services/componentList';
export { default as keybindingService } from './services/keybinding';
export { default as ComponentListPanel } from './layouts/sidebar/ComponentListPanel.vue'; export { default as ComponentListPanel } from './layouts/sidebar/ComponentListPanel.vue';
export { default as LayerPanel } from './layouts/sidebar/layer/LayerPanel.vue'; export { default as LayerPanel } from './layouts/sidebar/layer/LayerPanel.vue';
export { default as LayerNodeContent } from './layouts/sidebar/layer/LayerNodeContent.vue';
export { default as CodeSelect } from './fields/CodeSelect.vue'; export { default as CodeSelect } from './fields/CodeSelect.vue';
export { default as CodeSelectCol } from './fields/CodeSelectCol.vue'; export { default as CodeSelectCol } from './fields/CodeSelectCol.vue';
export { default as DataSourceFields } from './fields/DataSourceFields.vue'; export { default as DataSourceFields } from './fields/DataSourceFields.vue';
@ -70,6 +73,12 @@ export { default as LayoutContainer } from './components/SplitView.vue';
export { default as SplitView } from './components/SplitView.vue'; export { default as SplitView } from './components/SplitView.vue';
export { default as Resizer } from './components/Resizer.vue'; export { default as Resizer } from './components/Resizer.vue';
export { default as CodeBlockEditor } from './components/CodeBlockEditor.vue'; export { default as CodeBlockEditor } from './components/CodeBlockEditor.vue';
export { default as CompareForm } from './components/CompareForm.vue';
export { default as HistoryListBucket } from './layouts/history-list/Bucket.vue';
export { default as HistoryListBucketTab } from './layouts/history-list/BucketTab.vue';
export { default as HistoryDiffDialog } from './layouts/history-list/HistoryDiffDialog.vue';
export { confirmHistoryAction } from './layouts/history-list/composables';
export { useHistoryRevert } from './layouts/history-list/useHistoryRevert';
export { default as FloatingBox } from './components/FloatingBox.vue'; export { default as FloatingBox } from './components/FloatingBox.vue';
export { default as Tree } from './components/Tree.vue'; export { default as Tree } from './components/Tree.vue';
export { default as TreeNode } from './components/TreeNode.vue'; export { default as TreeNode } from './components/TreeNode.vue';

Some files were not shown because too many files have changed in this diff Show More