mirror of
https://github.com/Tencent/tmagic-editor.git
synced 2026-07-11 21:31:26 +08:00
Compare commits
86 Commits
v1.8.0-bet
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42d45bed18 | ||
|
|
de7a4f73ad | ||
|
|
605f07c8fe | ||
|
|
90492ad3ea | ||
|
|
b183e71f64 | ||
|
|
78a1259665 | ||
|
|
4a893d35df | ||
|
|
3c21f45e88 | ||
|
|
aa71fe9ddd | ||
|
|
9e8272b521 | ||
|
|
9aa251ce57 | ||
|
|
3b9fb714e5 | ||
|
|
284be0d276 | ||
|
|
c57ef89715 | ||
|
|
1ef3ea9eb9 | ||
|
|
83f4e52845 | ||
|
|
4330738b9f | ||
|
|
e59c3d2dcd | ||
|
|
55135fc063 | ||
|
|
af197363cf | ||
|
|
7bbb1f24c0 | ||
|
|
f7afed66aa | ||
|
|
fd359e493f | ||
|
|
5e661d0958 | ||
|
|
5ea992f5f7 | ||
|
|
4c81f22485 | ||
|
|
40acb5b34c | ||
|
|
ce65b18dbb | ||
|
|
1c936ff439 | ||
|
|
e32780b0fb | ||
|
|
7e789aa83a | ||
|
|
0f42989ca3 | ||
|
|
bfdaf2b244 | ||
|
|
1ade61d62e | ||
|
|
9f2fa1a9c8 | ||
|
|
38065f013f | ||
|
|
d5c1fab016 | ||
|
|
bbf79fd6df | ||
|
|
24b9b34f65 | ||
|
|
95769d6ae0 | ||
|
|
8933c46b73 | ||
|
|
c811908971 | ||
|
|
0774aa8e59 | ||
|
|
2ff7c479c2 | ||
|
|
4a8289137b | ||
|
|
ffcc734102 | ||
|
|
b35132e93e | ||
|
|
921188d2da | ||
|
|
6960bd50e1 | ||
|
|
27fac02e99 | ||
|
|
1298104732 | ||
|
|
9fe10e274c | ||
|
|
89cef4e9a9 | ||
|
|
273d13dd1f | ||
|
|
771880b994 | ||
|
|
113af7dd51 | ||
|
|
846f05e04d | ||
|
|
fd652b0d13 | ||
|
|
7d45aa5eec | ||
|
|
171d31e207 | ||
|
|
6ba59c0d14 | ||
|
|
4f284e8d9c | ||
|
|
c4ec2c5c72 | ||
|
|
48519b0155 | ||
|
|
a965dfb06e | ||
|
|
614f12adf3 | ||
|
|
bddc6f343c | ||
|
|
be3a900e6a | ||
|
|
bc555ebdc0 | ||
|
|
b7d1cea7c1 | ||
|
|
3bd0eecb42 | ||
|
|
cd19dec790 | ||
|
|
10b70c36bb | ||
|
|
27b2c2c685 | ||
|
|
a8a9cf372d | ||
|
|
6253d7ed23 | ||
|
|
444d4223a9 | ||
|
|
a9e9e65f9c | ||
|
|
42162f2e4a | ||
|
|
7a161cab00 | ||
|
|
1cd69b33fe | ||
|
|
12069e0937 | ||
|
|
1b66ab1b88 | ||
|
|
64d35d5363 | ||
|
|
35fc394199 | ||
|
|
8612311db1 |
144
CHANGELOG.md
144
CHANGELOG.md
@ -1,3 +1,147 @@
|
||||
# [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)
|
||||
|
||||
|
||||
|
||||
@ -201,7 +201,16 @@ export default defineConfig({
|
||||
},
|
||||
{
|
||||
text: 'uiService',
|
||||
link: '/api/editor/uiServiceMethods.md',
|
||||
items: [
|
||||
{
|
||||
text: '方法',
|
||||
link: '/api/editor/uiServiceMethods.md',
|
||||
},
|
||||
{
|
||||
text: '事件',
|
||||
link: '/api/editor/uiServiceEvents.md',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'codeBlockService',
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
# codeBlockService方法
|
||||
|
||||
写入历史栈的方法([setCodeDslById](#setcodedslbyid)、[setCodeDslByIdSync](#setcodedslbyidsync)、[deleteCodeDslByIds](#deletecodedslbyids) 等)的 `options` 支持
|
||||
[historyDescription / historySource](./editorServiceMethods.md#历史记录相关-options),会透传到 `historyService.push('codeBlock', step, id)` 入栈记录的 `historyDescription` / `source` 字段。
|
||||
|
||||
## setCodeDsl
|
||||
|
||||
- **参数:**
|
||||
@ -51,6 +54,8 @@
|
||||
- `{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}
|
||||
@ -72,6 +77,8 @@
|
||||
- `{Object}` options 可选配置
|
||||
- {`ChangeRecord`[]} changeRecords form 端变更记录,用于历史记录的精细化撤销/重做
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- `{void}`
|
||||
@ -81,8 +88,8 @@
|
||||
同步版本的 [setCodeDslById](#setcodedslbyid),并会触发 `addOrUpdate` 事件
|
||||
|
||||
::: tip
|
||||
写入成功时(`force=false` 且同 id 已存在的跳过场景除外)会自动调用 `historyService.pushCodeBlock`
|
||||
把本次变更入历史栈,参见 [historyService.pushCodeBlock](./historyServiceMethods.md#pushcodeblock)。
|
||||
写入成功时(`force=false` 且同 id 已存在的跳过场景除外)会自动调用 `historyService.push('codeBlock', step, id)`
|
||||
把本次变更入历史栈,参见 [historyService.push](./historyServiceMethods.md#push)。
|
||||
传入的 `changeRecords` 会一同写进 step,撤销/重做时调用方可据此按 `propPath` 局部回放。
|
||||
传入 `doNotPushHistory: true` 可跳过写入历史栈,常用于批量导入、外部同步等非用户操作场景。
|
||||
:::
|
||||
@ -213,6 +220,8 @@
|
||||
- `{(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>}`
|
||||
@ -222,10 +231,93 @@
|
||||
在dsl数据源中删除指定id的代码块,每删除一个会触发一次 `remove` 事件
|
||||
|
||||
::: tip
|
||||
对每个实际存在并被删除的代码块,会自动调用 `historyService.pushCodeBlock` 入栈一条
|
||||
`newContent=null` 的删除记录;不存在的 id 不会入历史。传入 `doNotPushHistory: true` 也可显式跳过写入历史栈。
|
||||
对每个实际存在并被删除的代码块,会自动调用 `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
|
||||
|
||||
- **参数:**
|
||||
@ -278,7 +370,7 @@ if (codeBlockService.canUndo("code_1234")) {
|
||||
|
||||
- **详情:**
|
||||
|
||||
当前指定代码块是否可撤销,等价于 `historyService.canUndoCodeBlock(id)`。
|
||||
当前指定代码块是否可撤销,等价于 `historyService.canUndo('codeBlock', id)`。
|
||||
|
||||
## canRedo
|
||||
|
||||
@ -290,7 +382,7 @@ if (codeBlockService.canUndo("code_1234")) {
|
||||
|
||||
- **详情:**
|
||||
|
||||
当前指定代码块是否可重做,等价于 `historyService.canRedoCodeBlock(id)`。
|
||||
当前指定代码块是否可重做,等价于 `historyService.canRedo('codeBlock', id)`。
|
||||
|
||||
## setParamsColConfig
|
||||
|
||||
|
||||
@ -300,6 +300,8 @@ dataSourceService.setFormMethod("http", [
|
||||
- {`DataSourceSchema`} config 数据源配置
|
||||
- `{Object}` options 可选配置
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- {`DataSourceSchema`} 添加后的数据源配置
|
||||
@ -309,8 +311,8 @@ dataSourceService.setFormMethod("http", [
|
||||
添加一个数据源,如果配置中没有id或id已存在,会自动生成新的id
|
||||
|
||||
::: tip
|
||||
添加成功会自动调用 `historyService.pushDataSource` 入栈一条 `oldSchema=null` 的新增记录,
|
||||
参见 [historyService.pushDataSource](./historyServiceMethods.md#pushdatasource)。
|
||||
添加成功会自动调用 `historyService.push('dataSource', step, id)` 入栈一条 `oldSchema=null` 的新增记录,
|
||||
参见 [historyService.push](./historyServiceMethods.md#push)。
|
||||
传入 `doNotPushHistory: true` 可跳过写入历史栈,常用于批量导入、外部同步等非用户操作场景。
|
||||
:::
|
||||
|
||||
@ -338,6 +340,8 @@ console.log(newDs.id); // 自动生成的id
|
||||
- `{Object}` options 可选配置
|
||||
- {`ChangeRecord`[]} changeRecords 变更记录
|
||||
- `{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}
|
||||
@ -351,7 +355,7 @@ console.log(newDs.id); // 自动生成的id
|
||||
更新数据源
|
||||
|
||||
::: tip
|
||||
更新成功会自动调用 `historyService.pushDataSource` 入栈一条 `oldSchema` / `newSchema`
|
||||
更新成功会自动调用 `historyService.push('dataSource', step, id)` 入栈一条 `oldSchema` / `newSchema`
|
||||
均为对应 schema 的更新记录,传入的 `changeRecords` 也会一并写进 step;撤销/重做时调用方可据此按
|
||||
`propPath` 局部回放,缺省才退化为整 schema 替换。传入 `doNotPushHistory: true` 可跳过写入历史栈。
|
||||
:::
|
||||
@ -379,6 +383,8 @@ console.log(updatedDs);
|
||||
- `{string}` id 数据源id
|
||||
- `{Object}` options 可选配置
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见 [editorService 历史记录相关 options](./editorServiceMethods.md#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- `{void}`
|
||||
@ -388,7 +394,7 @@ console.log(updatedDs);
|
||||
删除指定id的数据源
|
||||
|
||||
::: tip
|
||||
对实际存在的数据源会自动调用 `historyService.pushDataSource` 入栈一条 `newSchema=null`
|
||||
对实际存在的数据源会自动调用 `historyService.push('dataSource', step, id)` 入栈一条 `newSchema=null`
|
||||
的删除记录;不存在的 id 不会入历史。传入 `doNotPushHistory: true` 也可显式跳过写入历史栈。
|
||||
:::
|
||||
|
||||
@ -400,6 +406,84 @@ import { dataSourceService } from "@tmagic/editor";
|
||||
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
|
||||
|
||||
- **[扩展支持](../../guide/editor-expand#行为扩展):** 是
|
||||
@ -495,7 +579,7 @@ if (dataSourceService.canUndo("ds_123")) {
|
||||
|
||||
- **详情:**
|
||||
|
||||
当前指定数据源是否可撤销,等价于 `historyService.canUndoDataSource(id)`。
|
||||
当前指定数据源是否可撤销,等价于 `historyService.canUndo('dataSource', id)`。
|
||||
|
||||
## canRedo
|
||||
|
||||
@ -507,7 +591,7 @@ if (dataSourceService.canUndo("ds_123")) {
|
||||
|
||||
- **详情:**
|
||||
|
||||
当前指定数据源是否可重做,等价于 `historyService.canRedoDataSource(id)`。
|
||||
当前指定数据源是否可重做,等价于 `historyService.canRedo('dataSource', id)`。
|
||||
|
||||
## copyWithRelated
|
||||
|
||||
|
||||
@ -87,3 +87,19 @@
|
||||
- **详情:** 历史记录改变,[editorService.redo(),editorService.undo()](./editorServiceMethods.md#undo)后触发
|
||||
|
||||
- **事件回调函数:** `(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}
|
||||
:::
|
||||
|
||||
@ -1,5 +1,50 @@
|
||||
# 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
|
||||
|
||||
- **参数:**
|
||||
@ -359,6 +404,8 @@ editorService.highlight("text_123");
|
||||
- `{boolean}` doNotSelect 添加后是否不更新当前选中节点(默认 false,添加后会选中新增的节点)
|
||||
- `{boolean}` doNotSwitchPage 添加后是否不切换当前页面(默认 false;新增页面 / 跨页新增时为 true 会跳过会引发页面切换的选中操作)
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- {Promise<`MNode` | `MNode`[]>} 新增的组件或组件集合
|
||||
@ -405,6 +452,8 @@ editorService.highlight("text_123");
|
||||
- `{boolean}` doNotSelect 删除后是否不更新当前选中节点(默认 false,删除后会选中父节点或首个页面)
|
||||
- `{boolean}` doNotSwitchPage 删除后是否不切换当前页面(默认 false;删除页面 / 页面片段时为 true 会跳过自动切换到首个剩余页面)
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- `{Promise<void>}`
|
||||
@ -459,6 +508,8 @@ editorService.highlight("text_123");
|
||||
- {`ChangeRecord`[]} changeRecords 单节点 form 端变更记录(多节点场景下被忽略,使用 `changeRecordList`)
|
||||
- {`ChangeRecord`[][]} changeRecordList 多节点 form 端变更记录列表,按 `config` 数组同序对应每个节点;优先级高于 `changeRecords`
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
::: details 查看 ChangeRecord 类型定义
|
||||
<<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts}
|
||||
@ -500,6 +551,7 @@ editorService.highlight("text_123");
|
||||
- `{boolean}` doNotSelect 排序后是否不更新当前选中节点(默认 false)
|
||||
- `{boolean}` doNotSwitchPage 排序后是否不切换当前页面(排序只发生在同一父节点内,方法内为空操作;保留以与其它 DSL 操作 API 一致)
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- `{Promise<void>}`
|
||||
@ -568,6 +620,8 @@ editorService.highlight("text_123");
|
||||
- `{boolean}` doNotSelect 粘贴后是否不更新当前选中节点(默认 false)
|
||||
- `{boolean}` doNotSwitchPage 粘贴后是否不切换当前页面(默认 false;跨页粘贴时为 true 会跳过页面切换)
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- {Promise<`MNode` | `MNode`[]>} 添加后的组件节点配置
|
||||
@ -606,6 +660,8 @@ editorService.highlight("text_123");
|
||||
- `{boolean}` doNotSelect 居中后是否不更新当前选中节点(默认 false)
|
||||
- `{boolean}` doNotSwitchPage 居中后是否不切换当前页面(居中只更新节点 style,方法内为空操作;保留以与其它 DSL 操作 API 一致)
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- {Promise<`MNode` | `MNode`[]>}
|
||||
@ -628,6 +684,8 @@ alignCenter可以支持一次水平居中多个组件,alignCenter是通过调
|
||||
- `{number | 'top' | 'bottom'}` offset
|
||||
- `{Object}` options 可选配置
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- `{Promise<void>}`
|
||||
@ -649,6 +707,8 @@ alignCenter可以支持一次水平居中多个组件,alignCenter是通过调
|
||||
- `{boolean}` doNotSelect 移动后是否不更新当前选中节点(默认 false)
|
||||
- `{boolean}` doNotSwitchPage 移动后是否不切换当前页面(默认 false;目标容器位于其它页面时为 true 会跳过自动选中以避免页面切换)
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- Promise<`MNode` | undefined>
|
||||
@ -665,6 +725,8 @@ alignCenter可以支持一次水平居中多个组件,alignCenter是通过调
|
||||
- `{number}` targetIndex 目标位置索引
|
||||
- `{Object}` options 可选配置
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- `{Promise<void>}`
|
||||
@ -673,6 +735,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
|
||||
|
||||
- **[扩展支持](../../guide/editor-expand#行为扩展):** 是
|
||||
@ -683,8 +862,14 @@ alignCenter可以支持一次水平居中多个组件,alignCenter是通过调
|
||||
::: 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}
|
||||
:::
|
||||
|
||||
@ -699,6 +884,20 @@ alignCenter可以支持一次水平居中多个组件,alignCenter是通过调
|
||||
- **返回:**
|
||||
- {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}
|
||||
:::
|
||||
|
||||
- **详情:**
|
||||
|
||||
恢复到下一步
|
||||
@ -712,6 +911,8 @@ alignCenter可以支持一次水平居中多个组件,alignCenter是通过调
|
||||
- `{number}` top
|
||||
- `{Object}` options 可选配置
|
||||
- `{boolean}` doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
- `{string}` historyDescription 见[历史记录相关 options](#历史记录相关-options)
|
||||
- `{HistoryOpSource}` historySource 见[历史记录相关 options](#历史记录相关-options)
|
||||
|
||||
- **返回:**
|
||||
- `{Promise<void>}`
|
||||
|
||||
@ -1,69 +1,122 @@
|
||||
# historyService事件
|
||||
|
||||
## page-change
|
||||
|
||||
- **详情:** 页面切换
|
||||
|
||||
- **事件回调函数:** `(undoRedo: UndoRedo) => void`
|
||||
|
||||
::: details 查看 UndoRedo 类定义
|
||||
<<< @/../packages/editor/src/utils/undo-redo.ts#UndoRedo{ts}
|
||||
:::
|
||||
|
||||
## change
|
||||
|
||||
- **详情:** 历史记录发生变化
|
||||
- **详情:** 页面历史记录发生变化(`page` 类型 `push` / `undo` / `redo` 成功时触发;与 `code-block-history-change` / `data-source-history-change` 同构)
|
||||
|
||||
- **事件回调函数:** `(state: StepValue | null) => void`
|
||||
- **事件回调函数:** `(pageId: Id, step: StepValue) => void`
|
||||
|
||||
::: 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}
|
||||
|
||||
<<< @/../packages/schema/src/index.ts#MNode{ts}
|
||||
:::
|
||||
|
||||
:::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
|
||||
|
||||
- **详情:** 代码块历史记录发生变化(`pushCodeBlock` / `undoCodeBlock` / `redoCodeBlock` 成功时触发)
|
||||
- **详情:** 代码块历史记录发生变化(`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 中 `oldContent` 为 `null`
|
||||
- 删除触发的 step 中 `newContent` 为 `null`
|
||||
- 新增触发的 step 其 diff 项 `oldSchema` 为 `null`
|
||||
- 删除触发的 step 其 diff 项 `newSchema` 为 `null`
|
||||
- `undo` / `redo` 返回 `null`(边界状态)时不会触发该事件
|
||||
:::
|
||||
|
||||
## data-source-history-change
|
||||
|
||||
- **详情:** 数据源历史记录发生变化(`pushDataSource` / `undoDataSource` / `redoDataSource` 成功时触发)
|
||||
- **详情:** 数据源历史记录发生变化(`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 中 `oldSchema` 为 `null`
|
||||
- 删除触发的 step 中 `newSchema` 为 `null`
|
||||
- 新增触发的 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}
|
||||
:::
|
||||
|
||||
@ -4,45 +4,75 @@
|
||||
|
||||
- **详情:**
|
||||
|
||||
重置全部历史记录(包括页面节点栈、代码块栈、数据源栈),并重置当前页面 id / canRedo / canUndo
|
||||
|
||||
## resetPage
|
||||
|
||||
- **详情:**
|
||||
|
||||
重置当前页面的历史记录状态(清空当前页面id,重置 canRedo/canUndo)
|
||||
重置全部历史记录:清空 `state.steps` 下的页面 / 代码块 / 数据源 / 扩展类型全部栈(保留已注册的扩展类型键)。
|
||||
|
||||
## resetState
|
||||
|
||||
- **详情:**
|
||||
|
||||
重置历史记录全部内部状态(清空 pageId、pageSteps、canRedo、canUndo、codeBlockState、dataSourceState)
|
||||
同 [`reset`](#reset),清空 `state.steps` 下全部栈。
|
||||
|
||||
## changePage
|
||||
::: tip
|
||||
历史服务不再维护「当前活动页」状态(已移除 `state.pageId` / `state.canUndo` / `state.canRedo`)。
|
||||
活动页由 `editorService` 维护,撤销 / 重做 / 读取页面历史时请显式传入 pageId。
|
||||
是否可撤销 / 重做请改用 [`canUndo`](#canundo) / [`canRedo`](#canredo)。
|
||||
:::
|
||||
|
||||
## registerStepType
|
||||
|
||||
- **参数:**
|
||||
- `{MPage | MPageFragment} page`
|
||||
|
||||
::: details 查看 MPage / MPageFragment 类型定义
|
||||
<<< @/../packages/schema/src/index.ts#MPage{ts}
|
||||
|
||||
<<< @/../packages/schema/src/index.ts#MPageFragment{ts}
|
||||
:::
|
||||
- `{string} stepType` 自定义历史类型标识(勿与内置 `page` / `codeBlock` / `dataSource` 重名)
|
||||
- `{Object} options` 可选
|
||||
- `{string} event` push / undo / redo 后派发的事件名;缺省为 `${stepType}-history-change`
|
||||
- `{string} name` 历史面板中的展示名称(tab / 分组标题等);缺省回退到 stepType 本身
|
||||
|
||||
- **详情:**
|
||||
|
||||
按页面切换历史堆栈
|
||||
注册一个扩展历史类型,使其可与内置 `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
|
||||
|
||||
- **参数:**
|
||||
- `{StepValue} state`
|
||||
- `{HistoryStepType} stepType` 历史类型,内置 `'page'` / `'codeBlock'` / `'dataSource'`,并支持通过 [`registerStepType`](#registersteptype) 扩展
|
||||
- `{StepValue | BaseStepValue} step` 已构造好的历史记录(缺省自动补全 `uuid` / `timestamp`)
|
||||
- `{Id} id` 必填;目标栈 id(`page` 为 pageId,其余类型为对应资源 id)
|
||||
|
||||
::: 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}
|
||||
|
||||
<<< @/../packages/schema/src/index.ts#MNode{ts}
|
||||
@ -51,200 +81,209 @@
|
||||
:::
|
||||
|
||||
- **返回:**
|
||||
- `{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'` 的每个 `updatedItems[i]` 上可携带 `changeRecords`,用于撤销 / 重做时仅按
|
||||
`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
|
||||
|
||||
- **参数:**
|
||||
- `{HistoryStepType} stepType` 历史类型
|
||||
- `{Id} id` 必填;目标栈 id(`page` 为 pageId,其余类型为对应资源 id)
|
||||
|
||||
- **返回:**
|
||||
- `{StepValue | null}`
|
||||
- `{StepValue | BaseStepValue | null}`
|
||||
|
||||
- **详情:**
|
||||
|
||||
撤销当前操作。`opType: 'update'` 时,若 `updatedItems[i].changeRecords` 存在,会按
|
||||
`propPath` 从 `oldNode` 取值做局部回滚;否则用 `oldNode` 整节点替换。
|
||||
撤销指定历史栈的最近一次变更。所有类型行为一致:按 `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
|
||||
|
||||
- **参数:**
|
||||
- `{HistoryStepType} stepType` 历史类型
|
||||
- `{Id} id` 必填;目标栈 id(`page` 为 pageId,其余类型为对应资源 id)
|
||||
|
||||
- **返回:**
|
||||
- `{StepValue | null}`
|
||||
- `{StepValue | BaseStepValue | null}`
|
||||
|
||||
- **详情:**
|
||||
|
||||
恢复到下一步。`opType: 'update'` 时,若 `updatedItems[i].changeRecords` 存在,会按
|
||||
`propPath` 从 `newNode` 取值做局部重做;否则用 `newNode` 整节点替换。
|
||||
恢复指定历史栈到下一步,语义与 [`undo`](#undo) 对称。`page` 类型 `opType: 'update'` 时,若 diff 项的 `changeRecords` 存在,会按 `propPath` 从 `newSchema` 取值做局部重做;否则用 `newSchema` 整节点替换。
|
||||
|
||||
## pushCodeBlock
|
||||
## canUndo
|
||||
|
||||
- **参数:**
|
||||
- `{Id} codeBlockId` 代码块 id
|
||||
- `{Object} payload`
|
||||
- `{CodeBlockContent | null} oldContent` 变更前的代码块内容;新增时为 `null`
|
||||
- `{CodeBlockContent | null} newContent` 变更后的代码块内容;删除时为 `null`
|
||||
- `{ChangeRecord[]} changeRecords` 可选;form 端 propPath/value 变更列表,撤销/重做时若有则按 propPath 局部更新;缺省(或空数组)才退化为整内容替换
|
||||
|
||||
::: details 查看 CodeBlockStepValue 及关联类型定义
|
||||
<<< @/../packages/editor/src/type.ts#CodeBlockStepValue{ts}
|
||||
|
||||
<<< @/../packages/schema/src/index.ts#CodeBlockContent{ts}
|
||||
|
||||
<<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts}
|
||||
:::
|
||||
|
||||
- **返回:**
|
||||
- `{CodeBlockStepValue | null}` 入栈失败(未传 id)时返回 `null`
|
||||
|
||||
- **详情:**
|
||||
|
||||
推入一条代码块变更记录。与页面 / 节点完全无关,按 `codeBlockId` 维度独立一份 `UndoRedo` 栈,
|
||||
栈实例存放在 `historyService.state.codeBlockState[codeBlockId]`。
|
||||
|
||||
入栈成功后会触发 `code-block-history-change` 事件。
|
||||
|
||||
::: tip
|
||||
`codeBlockService.setCodeDslByIdSync` 与 `codeBlockService.deleteCodeDslByIds` 内部已经
|
||||
自动调用本方法,业务代码通常无需手动调用。
|
||||
:::
|
||||
|
||||
## undoCodeBlock
|
||||
|
||||
- **参数:**
|
||||
- `{Id} codeBlockId`
|
||||
|
||||
- **返回:**
|
||||
- `{CodeBlockStepValue | null}` 栈不存在或已无可撤销记录时返回 `null`
|
||||
|
||||
- **详情:**
|
||||
|
||||
撤销指定代码块的最近一次变更。成功时会触发 `code-block-history-change` 事件。
|
||||
拿到 step 后由调用方根据 `step.oldContent` 写回 `codeBlockService`(本方法不会自动回放)。
|
||||
|
||||
## redoCodeBlock
|
||||
|
||||
- **参数:**
|
||||
- `{Id} codeBlockId`
|
||||
|
||||
- **返回:**
|
||||
- `{CodeBlockStepValue | null}` 栈不存在或已无可重做记录时返回 `null`
|
||||
|
||||
- **详情:**
|
||||
|
||||
重做指定代码块的下一次变更。成功时会触发 `code-block-history-change` 事件。
|
||||
|
||||
## canUndoCodeBlock
|
||||
|
||||
- **参数:**
|
||||
- `{Id} codeBlockId`
|
||||
- `{HistoryStepType} stepType` 历史类型
|
||||
- `{Id} id` 可选;目标栈 id;缺省 / 无效时返回 `false`
|
||||
|
||||
- **返回:**
|
||||
- `{boolean}`
|
||||
|
||||
- **详情:**
|
||||
|
||||
指定代码块当前是否可撤销。栈不存在时返回 `false`。
|
||||
指定历史栈当前是否可撤销(游标高于 index 0 的 initial 基线底线)。适用于所有类型(`page` / `codeBlock` / `dataSource` / 扩展)。
|
||||
|
||||
## canRedoCodeBlock
|
||||
## canRedo
|
||||
|
||||
- **参数:**
|
||||
- `{Id} codeBlockId`
|
||||
- `{HistoryStepType} stepType` 历史类型
|
||||
- `{Id} id` 可选;目标栈 id;缺省 / 无效时返回 `false`
|
||||
|
||||
- **返回:**
|
||||
- `{boolean}`
|
||||
|
||||
- **详情:**
|
||||
|
||||
指定代码块当前是否可重做。栈不存在时返回 `false`。
|
||||
指定历史栈当前是否可重做。适用于所有类型(`page` / `codeBlock` / `dataSource` / 扩展)。
|
||||
|
||||
## pushDataSource
|
||||
## setMarker
|
||||
|
||||
- **参数:**
|
||||
- `{Id} dataSourceId` 数据源 id
|
||||
- `{Object} payload`
|
||||
- `{DataSourceSchema | null} oldSchema` 变更前的数据源 schema;新增时为 `null`
|
||||
- `{DataSourceSchema | null} newSchema` 变更后的数据源 schema;删除时为 `null`
|
||||
- `{ChangeRecord[]} changeRecords` 可选;form 端 propPath/value 变更列表,撤销/重做时若有则按 propPath 局部更新;缺省(或空数组)才退化为整 schema 替换
|
||||
- `{HistoryStepType} stepType` 历史类型
|
||||
- `{Id} id` 目标栈 id(`page` 为 pageId,其余类型为对应资源 id)
|
||||
- `{Object} options` 可选:`name` / `description` / `source`,用于基线的展示信息
|
||||
|
||||
::: details 查看 DataSourceStepValue 及关联类型定义
|
||||
<<< @/../packages/editor/src/type.ts#DataSourceStepValue{ts}
|
||||
- **返回:**
|
||||
- `{StepValue | null}` 已存在基线时返回原基线;栈非空(无基线)或 id 无效时返回 `null`
|
||||
|
||||
<<< @/../packages/form-schema/src/base.ts#ChangeRecord{ts}
|
||||
- **详情:**
|
||||
|
||||
为指定历史栈种入一条 `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}
|
||||
:::
|
||||
|
||||
- **返回:**
|
||||
- `{DataSourceStepValue | null}` 入栈失败(未传 id)时返回 `null`
|
||||
- `{Promise<PersistedHistoryState>}` 写入成功的快照对象
|
||||
|
||||
- **详情:**
|
||||
|
||||
推入一条数据源变更记录。与页面 / 节点完全无关,按 `dataSourceId` 维度独立一份 `UndoRedo` 栈,
|
||||
栈实例存放在 `historyService.state.dataSourceState[dataSourceId]`。
|
||||
把当前内存中的全部历史栈(页面 / 代码块 / 数据源 / 扩展类型)连同各自游标、容量序列化后写入本地 IndexedDB。
|
||||
|
||||
入栈成功后会触发 `data-source-history-change` 事件。
|
||||
- 最终库名为 `${dbName}-${当前 DSL app id}`,按应用隔离;
|
||||
- `key` 用于在同一 store 下区分不同记录,缺省为 `default`;
|
||||
- 历史记录里可能包含函数(代码块内容 / 节点事件等),内部使用 `serialize-javascript` 序列化为字符串后写入,恢复时再用 `parseDSL` 还原,因此可安全持久化函数 / `Map` 等;
|
||||
- 不支持 IndexedDB 的环境(如 SSR)会 reject。
|
||||
|
||||
::: tip
|
||||
`dataSourceService.add` / `update` / `remove` 内部已经自动调用本方法,业务代码通常无需手动调用。
|
||||
写入成功后触发 `save-to-indexed-db` 事件。
|
||||
|
||||
::: warning
|
||||
`beforeunload` / `pagehide` 阶段浏览器不会等待异步 IndexedDB 事务提交,单纯依赖卸载时写入可能丢失最近一次编辑。建议在历史变更时(防抖)即调用本方法持久化,确保刷新后能完整恢复。
|
||||
:::
|
||||
|
||||
## undoDataSource
|
||||
## restoreFromIndexedDB
|
||||
|
||||
- **参数:**
|
||||
- `{Id} dataSourceId`
|
||||
- `{HistoryPersistOptions} options` 可选
|
||||
|
||||
- **返回:**
|
||||
- `{DataSourceStepValue | null}`
|
||||
- `{Promise<PersistedHistoryState | null>}` 找不到记录时返回 `null`
|
||||
|
||||
- **详情:**
|
||||
|
||||
撤销指定数据源的最近一次变更。成功时会触发 `data-source-history-change` 事件。
|
||||
拿到 step 后由调用方根据 `step.oldSchema` 写回 `dataSourceService`(本方法不会自动回放)。
|
||||
从本地 IndexedDB 读取此前保存的历史快照并重建全部撤销/重做栈。
|
||||
|
||||
## redoDataSource
|
||||
- 每个栈都会按 `listMaxSize` 裁剪并还原游标;
|
||||
- 若某个栈存在已保存记录(见 `markSaved`),其游标会被定位到「最近一条已保存记录」之后,使恢复后的状态与落库的 DSL 对齐;
|
||||
- 会整体覆盖当前内存中的历史状态(活动页由 `editorService` 维护,不在此恢复);
|
||||
- 找不到对应记录时返回 `null` 且不改动当前状态;不支持 IndexedDB 的环境会 reject。
|
||||
|
||||
成功后触发 `restore-from-indexed-db` 事件。
|
||||
|
||||
## findStepLocationByUuid
|
||||
|
||||
- **参数:**
|
||||
- `{Id} dataSourceId`
|
||||
- `{HistoryStepType} stepType` 历史类型
|
||||
- `{string} uuid` 目标历史记录的 uuid
|
||||
- `{Id} id` 可选;目标栈 id
|
||||
|
||||
- **返回:**
|
||||
- `{DataSourceStepValue | null}`
|
||||
- `{ { id: Id; index: number } | null }` 找到时返回所属栈 id 与步骤索引;找不到时返回 `null`
|
||||
|
||||
- **详情:**
|
||||
|
||||
重做指定数据源的下一次变更。成功时会触发 `data-source-history-change` 事件。
|
||||
按历史记录 uuid 在指定历史类型的栈中查找其所属 id 与索引,统一入口。
|
||||
|
||||
## canUndoDataSource
|
||||
- **传入 `id`**:仅在该 id 对应的单个栈中查找(如页面历史按活动页查看,传入 pageId);
|
||||
- **缺省 `id`**:遍历该类型下全部栈查找(代码块 / 数据源等按全部资源分桶的场景)。
|
||||
|
||||
- **参数:**
|
||||
- `{Id} dataSourceId`
|
||||
|
||||
- **返回:**
|
||||
- `{boolean}`
|
||||
|
||||
- **详情:**
|
||||
|
||||
指定数据源当前是否可撤销。栈不存在时返回 `false`。
|
||||
|
||||
## canRedoDataSource
|
||||
|
||||
- **参数:**
|
||||
- `{Id} dataSourceId`
|
||||
|
||||
- **返回:**
|
||||
- `{boolean}`
|
||||
|
||||
- **详情:**
|
||||
|
||||
指定数据源当前是否可重做。栈不存在时返回 `false`。
|
||||
供「按 uuid 回滚」等需要把 uuid 映射回 `(id, index)` 的场景使用,如 [editorService.revertPageStepById](./editorServiceMethods.md#revertpagestepbyid) / [codeBlockService.revertById](./codeBlockServiceMethods.md#revertbyid) / [dataSourceService.revertById](./dataSourceServiceMethods.md#revertbyid) 内部均通过本方法定位步骤。
|
||||
|
||||
## destroy
|
||||
|
||||
- **详情:**
|
||||
|
||||
销毁
|
||||
|
||||
|
||||
@ -1220,6 +1220,28 @@ const guidesOptions = {
|
||||
</template>
|
||||
```
|
||||
|
||||
## disabledFlashTip
|
||||
|
||||
- **详情:**
|
||||
|
||||
禁用「非点击画布选中组件时的高亮闪烁提示」。
|
||||
|
||||
当组件不是通过点击画布选中(如从组件树、面包屑等外部方式选中)时,编辑器会在画布上对选中区域做一次高亮闪烁,帮助用户快速定位组件在画布中的位置。设置为 `true` 可关闭该提示。
|
||||
|
||||
注:选中页面(`magic-ui-page`)时不会触发闪烁。
|
||||
|
||||
- **默认值:** `false`
|
||||
|
||||
- **类型:** `boolean`
|
||||
|
||||
- **示例:**
|
||||
|
||||
```html
|
||||
<template>
|
||||
<m-editor :disabled-flash-tip="true"></m-editor>
|
||||
</template>
|
||||
```
|
||||
|
||||
## disabledStageOverlay
|
||||
|
||||
- **详情:**
|
||||
@ -1508,6 +1530,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
|
||||
|
||||
- **详情:**
|
||||
|
||||
28
docs/api/editor/uiServiceEvents.md
Normal file
28
docs/api/editor/uiServiceEvents.md
Normal 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` 事件
|
||||
:::
|
||||
@ -13,7 +13,7 @@
|
||||
|
||||
- **详情:**
|
||||
|
||||
设置UI服务的状态
|
||||
设置UI服务的状态。新值与旧值不同时会触发 [`state-change`](./uiServiceEvents.md#state-change) 事件
|
||||
|
||||
可用的状态键:
|
||||
- `uiSelectMode`: UI选择模式
|
||||
@ -31,6 +31,7 @@
|
||||
- `showPageListButton`: 是否显示页面列表按钮
|
||||
- `hideSlideBar`: 是否隐藏侧边栏
|
||||
- `sideBarItems`: 侧边栏项目
|
||||
- `sideBarActiveTabName`: 当前激活的侧边栏面板
|
||||
- `navMenuRect`: 导航菜单尺寸
|
||||
- `frameworkRect`: 框架尺寸
|
||||
|
||||
|
||||
@ -150,6 +150,14 @@
|
||||
|
||||
- **类型:** `boolean`
|
||||
|
||||
## useFieldTextInError
|
||||
|
||||
- **详情:** 透传给内部 `Form`,控制表单校验失败时错误提示前缀是否使用字段的 `text` 文案。`false` 时直接使用字段 `name`
|
||||
|
||||
- **默认值:** `true`
|
||||
|
||||
- **类型:** `boolean`
|
||||
|
||||
## closeOnClickModal
|
||||
|
||||
- **详情:** 是否可以通过点击 modal 关闭 Dialog
|
||||
|
||||
@ -40,6 +40,8 @@
|
||||
|
||||
- **详情:** 通过 `name` 从表单 `config` 中查找对应表单项的 `text`
|
||||
|
||||
- **相关:** 表单校验失败时是否使用该方法生成错误提示前缀,由 [`useFieldTextInError`](./form-props.md#usefieldtextinerror) prop 控制(默认 `true`)
|
||||
|
||||
## values
|
||||
|
||||
- **类型:** `Ref<FormValue>`
|
||||
|
||||
@ -206,6 +206,19 @@
|
||||
|
||||
- **类型:** `boolean`
|
||||
|
||||
## useFieldTextInError
|
||||
|
||||
- **详情:**
|
||||
|
||||
表单校验失败时,错误提示前缀是否使用字段的 `text` 文案(通过 `getTextByName` 从 `config` 中查找)。
|
||||
|
||||
- `true`(默认):错误提示形如 `字段文案 -> 错误信息`,找不到 `text` 时回退为字段 `name`;
|
||||
- `false`:跳过查找,直接使用字段 `name` 作为错误提示前缀(形如 `字段name -> 错误信息`)。
|
||||
|
||||
- **默认值:** `true`
|
||||
|
||||
- **类型:** `boolean`
|
||||
|
||||
## extendState
|
||||
|
||||
- **详情:** 扩展 formState 的钩子函数,返回的对象会被合并到 formState 上
|
||||
|
||||
@ -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 |
|
||||
| `popperClass` | `string` | — | 弹层 className |
|
||||
| `preventSubmitDefault` | `boolean` | — | 是否阻止表单原生 submit |
|
||||
| `useFieldTextInError` | `boolean` | `true` | 校验失败时错误提示前缀是否使用字段的 `text` 文案;`false` 时直接使用字段 `name` |
|
||||
| `extendState` | `(state: FormState) => Record<string, any> \| Promise<Record<string, any>>` | — | 扩展 `formState` |
|
||||
| `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` 获取 |
|
||||
| `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('submitForm timeout after ${timeout}ms: form is not initialized.')`
|
||||
|
||||
无论成功或失败,函数都会在最后自动 `unmount` 内部 app 并移除挂载用的 DOM 容器,无需调用方手动清理。
|
||||
|
||||
::: tip 关于 changeRecords
|
||||
`changeRecords` 记录的是表单挂载后发生的字段变更(由各字段的 `change` 事件累积而来)。在 `submitForm` 这种命令式、无用户交互的场景下,通常为空数组;只有在 `extendState` 或字段联动等逻辑中触发了变更时才会有内容。`MForm` 内部的 `submitForm` 在校验通过后会清空变更记录,因此本函数会在调用前先对其做快照再返回。
|
||||
:::
|
||||
|
||||
## 基础用法
|
||||
|
||||
```ts
|
||||
@ -73,6 +79,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` 把父级应用上下文带过去:
|
||||
@ -190,3 +213,7 @@ console.log(values);
|
||||
::: details 查看 `SubmitFormOptions` 类型定义
|
||||
<<< @/../packages/form/src/submitForm.ts#SubmitFormOptions{ts}
|
||||
:::
|
||||
|
||||
::: details 查看 `SubmitFormResult` 类型定义
|
||||
<<< @/../packages/form/src/submitForm.ts#SubmitFormResult{ts}
|
||||
:::
|
||||
|
||||
@ -135,6 +135,18 @@
|
||||
}]
|
||||
}]"></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
|
||||
|
||||
<demo-block type="form" :config="[{
|
||||
|
||||
@ -61,6 +61,51 @@ const menu = ref({
|
||||
- 数据源:`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` 步骤上提供「查看差异」入口,点击后弹出差异对话框。对话框支持两个维度的切换:
|
||||
@ -76,6 +121,47 @@ const menu = ref({
|
||||
表单对比依赖 `@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` 正常工作。
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.8.0-beta.2",
|
||||
"version": "1.8.0-beta.11",
|
||||
"name": "tmagic",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@ -66,8 +66,8 @@
|
||||
"prettier": "^3.8.3",
|
||||
"recast": "^0.23.11",
|
||||
"rimraf": "^3.0.2",
|
||||
"rolldown": "^1.0.1",
|
||||
"rolldown-plugin-dts": "^0.25.1",
|
||||
"rolldown": "^1.1.2",
|
||||
"rolldown-plugin-dts": "^0.26.0",
|
||||
"sass-embedded": "^1.99.0",
|
||||
"semver": "^7.7.3",
|
||||
"serialize-javascript": "^7.0.0",
|
||||
@ -75,7 +75,7 @@
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitepress": "^2.0.0-alpha.17",
|
||||
"vitest": "^4.1.6",
|
||||
"vitest": "^4.1.9",
|
||||
"vue": "catalog:",
|
||||
"vue-tsc": "^3.2.9"
|
||||
},
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.8.0-beta.2",
|
||||
"version": "1.8.0-beta.11",
|
||||
"name": "@tmagic/cli",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.8.0-beta.2",
|
||||
"version": "1.8.0-beta.11",
|
||||
"name": "@tmagic/core",
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
|
||||
@ -76,9 +76,11 @@ class IteratorContainer extends Node {
|
||||
}
|
||||
}
|
||||
|
||||
config.items?.forEach((element: MNode) => {
|
||||
this.initNode(element, node, map);
|
||||
});
|
||||
if (Array.isArray(config.items)) {
|
||||
config.items?.forEach((element: MNode) => {
|
||||
this.initNode(element, node, map);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public setNodes(nodes: MNode[], index: number) {
|
||||
|
||||
@ -79,9 +79,11 @@ class Page extends Node {
|
||||
}
|
||||
}
|
||||
|
||||
config.items?.forEach((element: MComponent | MContainer) => {
|
||||
this.initNode(element, node);
|
||||
});
|
||||
if (Array.isArray(config.items)) {
|
||||
config.items?.forEach((element: MComponent | MContainer) => {
|
||||
this.initNode(element, node);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public getNode<T extends TMagicNode = TMagicNode>(
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.8.0-beta.2",
|
||||
"version": "1.8.0-beta.11",
|
||||
"name": "@tmagic/data-source",
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.8.0-beta.2",
|
||||
"version": "1.8.0-beta.11",
|
||||
"name": "@tmagic/dep",
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.8.0-beta.2",
|
||||
"version": "1.8.0-beta.11",
|
||||
"name": "@tmagic/design",
|
||||
"type": "module",
|
||||
"sideEffects": [
|
||||
|
||||
@ -43,8 +43,16 @@ const props = withDefaults(defineProps<PopoverProps>(), {
|
||||
visible: undefined,
|
||||
tabindex: 0,
|
||||
destroyOnClose: false,
|
||||
closeOnClickOutside: true,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 受控模式(传入了 visible)下点击外部收起时触发,便于配合 v-model:visible。 */
|
||||
'update:visible': [_visible: boolean];
|
||||
/** 点击 popover 及其衍生浮层以外的区域时触发。 */
|
||||
clickoutside: [_event: MouseEvent];
|
||||
}>();
|
||||
|
||||
const popoverVisible = ref(false);
|
||||
|
||||
const visibleWatch = watch(
|
||||
@ -179,6 +187,70 @@ if (props.trigger === 'hover' && typeof props.visible === 'undefined') {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* popover 内部触发、却挂载到 body(在 popper 之外)的浮层:弹窗、二次确认框、tooltip、
|
||||
* 下拉 / 日期选择等。点击它们属于 popover 内部交互,不应顺带把 popover 关闭。
|
||||
*
|
||||
* 由于 @tmagic/design 通过适配器支持 element-plus、tdesign 等多套 UI 库,这里同时列出
|
||||
* 两套库的浮层 class(class 名互不冲突,未命中的选择器无副作用),避免切换适配器后失效。
|
||||
*/
|
||||
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 / MessagePlugin)与各类浮层(tooltip / 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;
|
||||
|
||||
// 点击 reference、popper 自身或衍生浮层时保持打开
|
||||
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 = () => {
|
||||
if (!instanceRef.value) return;
|
||||
|
||||
@ -188,5 +260,6 @@ const destroy = () => {
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
destroy();
|
||||
unbindClickOutside();
|
||||
});
|
||||
</script>
|
||||
|
||||
@ -234,6 +234,9 @@ export interface PaginationProps {
|
||||
|
||||
export interface PopconfirmProps {
|
||||
title?: string;
|
||||
width?: string | number;
|
||||
/** 浮层是否插入到 body,默认 true。设为 false 时浮层内联渲染,便于嵌套在 hover 浮层中避免父级因 mouseleave 收起。 */
|
||||
teleported?: boolean;
|
||||
placement?:
|
||||
| 'top'
|
||||
| 'left'
|
||||
@ -258,6 +261,13 @@ export interface PopoverProps {
|
||||
popperClass?: string;
|
||||
tabindex?: number;
|
||||
destroyOnClose?: boolean;
|
||||
/** 点击 popover 及其衍生浮层以外的区域时收起,默认开启。 */
|
||||
closeOnClickOutside?: boolean;
|
||||
/**
|
||||
* 追加的「点击不关闭」选择器,会与内置的弹窗 / 确认框 / 下拉等浮层选择器合并。
|
||||
* 用于 popover 内部触发、挂载到 body 之外的浮层不应顺带关闭 popover 的场景。
|
||||
*/
|
||||
clickOutsideIgnore?: string;
|
||||
}
|
||||
|
||||
export interface RadioProps {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.8.0-beta.2",
|
||||
"version": "1.8.0-beta.11",
|
||||
"name": "@tmagic/editor",
|
||||
"type": "module",
|
||||
"sideEffects": [
|
||||
|
||||
@ -135,7 +135,7 @@
|
||||
<script lang="ts" setup>
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
import { provide } from 'vue';
|
||||
import { provide, ref } from 'vue';
|
||||
|
||||
import type { MApp } from '@tmagic/core';
|
||||
|
||||
@ -221,11 +221,14 @@ const stageOptions: StageOptions = {
|
||||
guidesOptions: props.guidesOptions,
|
||||
disabledMultiSelect: props.disabledMultiSelect,
|
||||
alwaysMultiSelect: props.alwaysMultiSelect,
|
||||
disabledFlashTip: props.disabledFlashTip,
|
||||
beforeDblclick: props.beforeDblclick,
|
||||
};
|
||||
|
||||
stageOverlayService.set('stageOptions', stageOptions);
|
||||
|
||||
const propsPanelRef = ref<InstanceType<typeof FormPanel> | null>(null);
|
||||
|
||||
provide('services', services);
|
||||
|
||||
provide('codeOptions', props.codeOptions);
|
||||
@ -236,13 +239,27 @@ provide('stageOptions', stageOptions);
|
||||
* 与 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());
|
||||
|
||||
const propsPanelMountedHandler = (e: InstanceType<typeof FormPanel>) => {
|
||||
propsPanelRef.value = e;
|
||||
emit('props-panel-mounted', e);
|
||||
};
|
||||
const propsPanelUnmountedHandler = () => {
|
||||
propsPanelRef.value = null;
|
||||
emit('props-panel-unmounted');
|
||||
};
|
||||
|
||||
|
||||
@ -4,7 +4,9 @@
|
||||
v-model:visible="boxVisible"
|
||||
v-model:width="width"
|
||||
v-model:height="codeBlockEditorHeight"
|
||||
:body-style="{ padding: '0 16px' }"
|
||||
:title="content.name ? `${disabled ? '查看' : '编辑'}${content.name}` : '新增代码'"
|
||||
:framework-width="frameworkWidth"
|
||||
:position="boxPosition"
|
||||
:before-close="beforeClose"
|
||||
>
|
||||
@ -206,6 +208,7 @@ const closedHandler = () => {
|
||||
|
||||
const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null));
|
||||
const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating);
|
||||
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
|
||||
|
||||
watch(boxVisible, (visible) => {
|
||||
nextTick(() => {
|
||||
|
||||
@ -10,34 +10,29 @@
|
||||
:is-compare="true"
|
||||
:disabled="true"
|
||||
:label-width="labelWidth"
|
||||
:extend-state="extendState"
|
||||
:extend-state="mergedExtendState"
|
||||
:show-diff="showDiff"
|
||||
:self-diff-field-types="selfDiffFieldTypes"
|
||||
:size="size"
|
||||
></MForm>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, inject, type Ref, ref, type ShallowRef, useTemplateRef, watch, watchEffect } from 'vue';
|
||||
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 { useServices } from '@editor/hooks/use-services';
|
||||
import type { CompareCategory, CompareFormLoadConfig, Services } from '@editor/type';
|
||||
import { getCodeBlockFormConfig } from '@editor/utils/code-block';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorCompareForm',
|
||||
});
|
||||
|
||||
/**
|
||||
* 对比类型:
|
||||
* - node: 节点组件,按 `type` 从 propsService 获取属性表单配置
|
||||
* - data-source: 数据源,按 `type`(base/http/...) 从 dataSourceService 获取数据源表单配置
|
||||
* - code-block: 数据源代码块,使用内置的代码块表单配置
|
||||
*/
|
||||
export type CompareCategory = 'node' | 'data-source' | 'code-block';
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 当前值(修改后的值) */
|
||||
@ -68,15 +63,35 @@ const props = withDefaults(
|
||||
* 因此在差异对比场景下也需要透传,避免出现 `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,
|
||||
},
|
||||
);
|
||||
|
||||
const { propsService, dataSourceService, codeBlockService, editorService } = useServices();
|
||||
const services = useServices();
|
||||
provide('services', props.services);
|
||||
|
||||
const config = ref<FormConfig>([]);
|
||||
|
||||
@ -153,23 +168,56 @@ const showDiff = ({ curValue, lastValue, config }: { curValue: any; lastValue: a
|
||||
return !isEqual(curValue, lastValue);
|
||||
};
|
||||
|
||||
const loadConfig = async () => {
|
||||
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) {
|
||||
config.value = [];
|
||||
return;
|
||||
return [];
|
||||
}
|
||||
config.value = await propsService.getPropsConfig(props.type);
|
||||
break;
|
||||
return removeStyleDisplayConfig(
|
||||
await props.services.propsService.getPropsConfig(props.type, { node: props.value as unknown as MNode }),
|
||||
);
|
||||
}
|
||||
case 'data-source': {
|
||||
config.value = dataSourceService.getFormConfig(props.type || 'base');
|
||||
break;
|
||||
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': {
|
||||
config.value = getCodeBlockFormConfig({
|
||||
paramColConfig: codeBlockService.getParamsColConfig(),
|
||||
return getCodeBlockFormConfig({
|
||||
paramColConfig: props.services.codeBlockService.getParamsColConfig(),
|
||||
// 通过传入 dataSourceType 间接表达"是数据源代码块"——在对比场景下 props.dataSourceType
|
||||
// 由调用方按 step 上下文显式传入,未传则视为普通代码块,「执行时机」字段隐藏。
|
||||
isDataSource: () => Boolean(props.dataSourceType),
|
||||
@ -178,15 +226,28 @@ const loadConfig = async () => {
|
||||
// 对比模式只读,不需要校验/语法检查
|
||||
editable: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
default:
|
||||
config.value = [];
|
||||
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.category, () => props.type, () => props.dataSourceType, () => props.loadConfig],
|
||||
() => {
|
||||
loadConfig();
|
||||
},
|
||||
@ -204,12 +265,10 @@ const formRef = useTemplateRef<InstanceType<typeof MForm>>('form');
|
||||
* - services:整个 useServices() 返回的服务集合;
|
||||
* - stage:当前 editorService.get('stage') 的最新值。
|
||||
*/
|
||||
const stage = computed(() => editorService.get('stage'));
|
||||
|
||||
watchEffect(() => {
|
||||
if (formRef.value) {
|
||||
formRef.value.formState.stage = stage.value;
|
||||
formRef.value.formState.services = services;
|
||||
if (formRef.value && props.services) {
|
||||
formRef.value.formState.stage = props.services.editorService.get('stage');
|
||||
formRef.value.formState.services = props.services;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@ -1,6 +1,12 @@
|
||||
<template>
|
||||
<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">
|
||||
<slot name="title">
|
||||
<span>{{ title }}</span>
|
||||
@ -9,7 +15,7 @@
|
||||
<TMagicButton link size="small" @click="closeHandler"><MIcon :icon="Close"></MIcon></TMagicButton>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
@ -17,14 +23,13 @@
|
||||
</template>
|
||||
|
||||
<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 VanillaMoveable from 'moveable';
|
||||
|
||||
import { TMagicButton, useZIndex } from '@tmagic/design';
|
||||
|
||||
import MIcon from '@editor/components/Icon.vue';
|
||||
import { useServices } from '@editor/hooks/use-services';
|
||||
|
||||
interface Position {
|
||||
left: number;
|
||||
@ -39,11 +44,18 @@ const props = withDefaults(
|
||||
defineProps<{
|
||||
position?: Position;
|
||||
title?: string;
|
||||
bodyStyle?: CSSProperties;
|
||||
/** 浮窗初始样式,会与内部计算样式合并,外部传入优先 */
|
||||
initialStyle?: CSSProperties;
|
||||
/** 用于约束浮窗 left 的容器宽度,传入时按宽度收敛 left,避免超出右边界;默认取视窗宽度 */
|
||||
frameworkWidth?: number;
|
||||
beforeClose?: (_done: (_cancel?: boolean) => void) => void;
|
||||
}>(),
|
||||
{
|
||||
title: '',
|
||||
position: () => ({ left: 0, top: 0 }),
|
||||
initialStyle: () => ({}),
|
||||
frameworkWidth: 0,
|
||||
},
|
||||
);
|
||||
|
||||
@ -66,12 +78,11 @@ const bodyHeight = computed(() => {
|
||||
return 'auto';
|
||||
});
|
||||
|
||||
const { uiService } = useServices();
|
||||
const frameworkWidth = computed(() => uiService.get('frameworkRect').width || 0);
|
||||
const style = computed(() => {
|
||||
let { left } = props.position;
|
||||
if (width.value) {
|
||||
left = left + width.value > frameworkWidth.value ? frameworkWidth.value - width.value : left;
|
||||
const frameworkWidth = props.frameworkWidth || globalThis.window?.innerWidth || 0;
|
||||
if (width.value && frameworkWidth) {
|
||||
left = left + width.value > frameworkWidth ? frameworkWidth - width.value : left;
|
||||
}
|
||||
|
||||
return {
|
||||
@ -79,11 +90,60 @@ const style = computed(() => {
|
||||
top: `${props.position.top}px`,
|
||||
width: width.value ? `${width.value}px` : 'auto',
|
||||
height: height.value ? `${height.value}px` : 'auto',
|
||||
...props.initialStyle,
|
||||
};
|
||||
});
|
||||
|
||||
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 = () => {
|
||||
moveable = new VanillaMoveable(globalThis.document.body, {
|
||||
className: 'm-editor-floating-box-moveable',
|
||||
@ -101,6 +161,14 @@ const initMoveable = () => {
|
||||
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) => {
|
||||
e.target.style.transform = e.transform;
|
||||
});
|
||||
@ -115,6 +183,7 @@ const initMoveable = () => {
|
||||
};
|
||||
|
||||
const destroyMoveable = () => {
|
||||
hideDragMask();
|
||||
moveable?.destroy();
|
||||
moveable = null;
|
||||
};
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
|
||||
<template v-else-if="data.type === 'button'">
|
||||
<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">
|
||||
<MIcon :icon="data.icon"></MIcon>
|
||||
</template>
|
||||
@ -21,7 +21,7 @@
|
||||
</TMagicButton>
|
||||
</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">
|
||||
<MIcon :icon="data.icon"></MIcon>
|
||||
</template>
|
||||
|
||||
@ -15,6 +15,7 @@ import type {
|
||||
ComponentGroup,
|
||||
CustomContentMenuFunction,
|
||||
DatasourceTypeOption,
|
||||
HistoryListExtraTab,
|
||||
IsExpandableFunction,
|
||||
MenuBarData,
|
||||
MenuButton,
|
||||
@ -86,6 +87,8 @@ export interface EditorProps {
|
||||
alwaysMultiSelect?: boolean;
|
||||
/** 禁用页面片 */
|
||||
disabledPageFragment?: boolean;
|
||||
/** 禁用「非点击画布选中组件时(如从图层树、面包屑等外部选中),对选中区域做高亮闪烁提示」,默认 false(即默认开启闪烁) */
|
||||
disabledFlashTip?: boolean;
|
||||
/** 禁用双击在浮层中单独编辑选中组件 */
|
||||
disabledStageOverlay?: boolean;
|
||||
/** 禁用属性配置面板右下角显示源码的按钮 */
|
||||
@ -125,6 +128,8 @@ export interface EditorProps {
|
||||
/** 组件树节点双击前的钩子函数,返回 false 则阻止默认的双击行为 */
|
||||
beforeLayerNodeDblclick?: (event: MouseEvent, data: TreeNodeData) => Promise<boolean | void> | boolean | void;
|
||||
extendFormState?: (state: FormState) => Record<string, any> | Promise<Record<string, any>>;
|
||||
/** 历史记录面板的自定义扩展 tab,追加在内置的页面/数据源/代码块 tab 之后 */
|
||||
historyListExtraTabs?: HistoryListExtraTab[];
|
||||
/** 页面顺序拖拽配置参数 */
|
||||
pageBarSortOptions?: PageBarSortOptions;
|
||||
/** 页面搜索函数 */
|
||||
@ -136,6 +141,7 @@ export const defaultEditorProps = {
|
||||
disabledMultiSelect: false,
|
||||
alwaysMultiSelect: false,
|
||||
disabledPageFragment: false,
|
||||
disabledFlashTip: false,
|
||||
disabledStageOverlay: false,
|
||||
containerHighlightClassName: CONTAINER_HIGHLIGHT_CLASS_NAME,
|
||||
containerHighlightDuration: 800,
|
||||
@ -145,6 +151,7 @@ export const defaultEditorProps = {
|
||||
disabledCodeBlock: false,
|
||||
componentGroupList: () => [],
|
||||
datasourceList: () => [],
|
||||
historyListExtraTabs: () => [],
|
||||
menu: () => ({ left: [], right: [] }),
|
||||
layerContentMenu: () => [],
|
||||
stageContentMenu: () => [],
|
||||
|
||||
@ -4,11 +4,11 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, reactive, watch } from 'vue';
|
||||
import serialize from 'serialize-javascript';
|
||||
|
||||
import type { CodeLinkConfig, FieldProps, MLink } from '@tmagic/form';
|
||||
|
||||
import { getEditorConfig } from '@editor/utils/config';
|
||||
import { serializeConfig } from '@editor/utils/editor';
|
||||
|
||||
defineOptions({
|
||||
name: 'MFieldsCodeLink',
|
||||
@ -47,10 +47,7 @@ watch(
|
||||
() => props.model[props.name],
|
||||
(value) => {
|
||||
modelValue.form = {
|
||||
[props.name]: serialize(value, {
|
||||
space: 2,
|
||||
unsafe: true,
|
||||
}).replace(/"(\w+)":\s/g, '$1: '),
|
||||
[props.name]: serializeConfig(value),
|
||||
};
|
||||
},
|
||||
{
|
||||
|
||||
@ -107,10 +107,12 @@ const isCompareMode = computed(() => Boolean(props.isCompare && props.lastValues
|
||||
|
||||
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),
|
||||
);
|
||||
|
||||
const hasCodeBlockSidePanel = computed(() => codeBlockSidePanel.value);
|
||||
|
||||
/**
|
||||
* 根据代码块id获取代码块参数配置
|
||||
* @param codeId 代码块ID
|
||||
@ -191,6 +193,10 @@ const onParamsChangeHandler = (value: any, eventData: ContainerChangeEventData)
|
||||
};
|
||||
|
||||
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);
|
||||
};
|
||||
</script>
|
||||
|
||||
@ -211,11 +211,25 @@ const onChangeHandler = (v: string[] = []) => {
|
||||
emit('change', v);
|
||||
};
|
||||
|
||||
const hasDataSourceSidePanel = computed(() =>
|
||||
const dataSourceSidePanel = computed(() =>
|
||||
uiService.get('sideBarItems').find((item) => item.$key === SideItemKey.DATA_SOURCE),
|
||||
);
|
||||
|
||||
const hasDataSourceSidePanel = computed(() => dataSourceSidePanel.value);
|
||||
|
||||
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>
|
||||
|
||||
@ -8,10 +8,12 @@
|
||||
</div>
|
||||
|
||||
<FloatingBox
|
||||
:body-style="{ padding: '0 16px' }"
|
||||
v-model:visible="addDialogVisible"
|
||||
v-model:width="width"
|
||||
v-model:height="editorHeight"
|
||||
:title="fieldTitle"
|
||||
:framework-width="frameworkWidth"
|
||||
:position="boxPosition"
|
||||
>
|
||||
<template #body>
|
||||
@ -28,10 +30,12 @@
|
||||
</FloatingBox>
|
||||
|
||||
<FloatingBox
|
||||
:body-style="{ padding: '0 16px' }"
|
||||
v-model:visible="addFromJsonDialogVisible"
|
||||
v-model:width="width"
|
||||
v-model:height="editorHeight"
|
||||
title="快速添加数据定义"
|
||||
:framework-width="frameworkWidth"
|
||||
:position="boxPosition"
|
||||
>
|
||||
<template #body>
|
||||
@ -47,7 +51,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, Ref, ref } from 'vue';
|
||||
import { computed, type ComputedRef, inject, onMounted, provide, Ref, ref } from 'vue';
|
||||
|
||||
import type { DataSchema } from '@tmagic/core';
|
||||
import { TMagicButton, tMagicMessage, tMagicMessageBox } from '@tmagic/design';
|
||||
@ -101,6 +105,16 @@ const newHandler = () => {
|
||||
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) => {
|
||||
addDialogVisible.value = false;
|
||||
|
||||
@ -158,13 +172,7 @@ const fieldColumns: ColumnConfig[] = [
|
||||
{
|
||||
text: '编辑',
|
||||
handler: (row: Record<string, any>, index: number) => {
|
||||
fieldValues.value = {
|
||||
...row,
|
||||
index,
|
||||
};
|
||||
fieldTitle.value = `编辑${row.title}`;
|
||||
calcBoxPosition();
|
||||
addDialogVisible.value = true;
|
||||
editField(row, index);
|
||||
},
|
||||
},
|
||||
{
|
||||
@ -354,4 +362,30 @@ const { height: editorHeight } = useEditorContentHeight();
|
||||
|
||||
const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null));
|
||||
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>
|
||||
|
||||
@ -30,10 +30,10 @@
|
||||
<template #suffix>
|
||||
<Icon :icon="Coin" />
|
||||
</template>
|
||||
<template #default="{ item }">
|
||||
<template #default="slotProps">
|
||||
<div style="display: flex; flex-direction: column; line-height: 1.2em">
|
||||
<div>{{ item.text }}</div>
|
||||
<span style="font-size: 10px; color: rgba(0, 0, 0, 0.6)">{{ item.value }}</span>
|
||||
<div>{{ slotProps?.item?.text || '' }}</div>
|
||||
<span style="font-size: 10px; color: rgba(0, 0, 0, 0.6)">{{ slotProps?.item?.value || '' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</component>
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
></MCascader>
|
||||
|
||||
<TMagicTooltip
|
||||
v-if="model[name] && isCustomMethod && hasDataSourceSidePanel && !isCompare"
|
||||
v-if="model[name] && isCustomMethod && dataSourceSidePanel && !isCompare"
|
||||
:content="notEditable ? '查看' : '编辑'"
|
||||
>
|
||||
<TMagicButton class="m-fields-select-action-button" :size="size" @click="editCodeHandler">
|
||||
@ -75,7 +75,7 @@ const props = withDefaults(defineProps<FieldProps<DataSourceMethodSelectConfig>>
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
const hasDataSourceSidePanel = computed(() =>
|
||||
const dataSourceSidePanel = computed(() =>
|
||||
(uiService.get('sideBarItems') || []).find((item) => item.$key === SideItemKey.DATA_SOURCE),
|
||||
);
|
||||
|
||||
@ -208,12 +208,17 @@ const onParamsChangeHandler = (value: any, eventData: ContainerChangeEventData)
|
||||
};
|
||||
|
||||
const editCodeHandler = () => {
|
||||
const [id] = props.model[props.name];
|
||||
const [id, methodName] = props.model[props.name];
|
||||
|
||||
const dataSource = dataSourceService.getDataSourceById(id);
|
||||
|
||||
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>
|
||||
|
||||
@ -21,7 +21,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, nextTick, ref, useTemplateRef } from 'vue';
|
||||
import { computed, type ComputedRef, inject, nextTick, onMounted, ref, useTemplateRef } from 'vue';
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
|
||||
import type { CodeBlockContent } from '@tmagic/core';
|
||||
@ -52,6 +52,29 @@ const codeBlockEditorRef = useTemplateRef<InstanceType<typeof CodeBlockEditor>>(
|
||||
|
||||
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[] = [
|
||||
{
|
||||
label: '名称',
|
||||
@ -77,26 +100,7 @@ const methodColumns: ColumnConfig[] = [
|
||||
{
|
||||
text: '编辑',
|
||||
handler: (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();
|
||||
});
|
||||
editMethod(method, index);
|
||||
},
|
||||
},
|
||||
{
|
||||
@ -158,4 +162,21 @@ const submitCodeHandler = (value: CodeBlockContent, data: ContainerChangeEventDa
|
||||
|
||||
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>
|
||||
|
||||
@ -7,10 +7,12 @@
|
||||
</div>
|
||||
|
||||
<FloatingBox
|
||||
:body-style="{ padding: '0 16px' }"
|
||||
v-model:visible="addDialogVisible"
|
||||
v-model:width="width"
|
||||
v-model:height="editorHeight"
|
||||
:title="drawerTitle"
|
||||
:framework-width="frameworkWidth"
|
||||
:position="boxPosition"
|
||||
>
|
||||
<template #body>
|
||||
@ -254,4 +256,5 @@ const addDialogVisible = defineModel<boolean>('visible', { default: false });
|
||||
const { height: editorHeight } = useEditorContentHeight();
|
||||
const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null));
|
||||
const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating);
|
||||
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
|
||||
</script>
|
||||
|
||||
@ -4,27 +4,31 @@
|
||||
<div class="border-icon-container-row">
|
||||
<div
|
||||
class="border-icon border-icon-top"
|
||||
:class="{ active: direction === 'Top' }"
|
||||
:class="{ active: direction === 'Top', configured: isConfigured('Top') }"
|
||||
@click="selectDirection('Top')"
|
||||
></div>
|
||||
</div>
|
||||
<div class="border-icon-container-row">
|
||||
<div
|
||||
class="border-icon border-icon-left"
|
||||
:class="{ active: direction === 'Left' }"
|
||||
:class="{ active: direction === 'Left', configured: isConfigured('Left') }"
|
||||
@click="selectDirection('Left')"
|
||||
></div>
|
||||
<div class="border-icon" :class="{ active: direction === '' }" @click="selectDirection()"></div>
|
||||
<div
|
||||
class="border-icon"
|
||||
:class="{ active: direction === '', configured: isConfigured('') }"
|
||||
@click="selectDirection()"
|
||||
></div>
|
||||
<div
|
||||
class="border-icon border-icon-right"
|
||||
:class="{ active: direction === 'Right' }"
|
||||
:class="{ active: direction === 'Right', configured: isConfigured('Right') }"
|
||||
@click="selectDirection('Right')"
|
||||
></div>
|
||||
</div>
|
||||
<div class="border-icon-container-row">
|
||||
<div
|
||||
class="border-icon border-icon-bottom"
|
||||
:class="{ active: direction === 'Bottom' }"
|
||||
:class="{ active: direction === 'Bottom', configured: isConfigured('Bottom') }"
|
||||
@click="selectDirection('Bottom')"
|
||||
></div>
|
||||
</div>
|
||||
@ -98,7 +102,7 @@ const emit = defineEmits<{
|
||||
addDiffCount: [];
|
||||
}>();
|
||||
|
||||
withDefaults(
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
model: 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) => {
|
||||
eventData.changeRecords?.forEach((record) => {
|
||||
emit('change', record.value, {
|
||||
|
||||
@ -6,7 +6,7 @@ import { tMagicMessage } from '@tmagic/design';
|
||||
import type { ContainerChangeEventData } from '@tmagic/form';
|
||||
|
||||
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']) => {
|
||||
const codeConfig = ref<Omit<CodeBlockContent, 'content'> & { content: string }>();
|
||||
@ -58,8 +58,8 @@ export const useCodeBlockEdit = (codeBlockService: Services['codeBlockService'])
|
||||
};
|
||||
|
||||
// 删除代码块
|
||||
const deleteCode = async (key: string) => {
|
||||
codeBlockService.deleteCodeDslByIds([key]);
|
||||
const deleteCode = async (key: string, { historySource }: { historySource?: HistoryOpSource } = {}) => {
|
||||
codeBlockService.deleteCodeDslByIds([key], { historySource });
|
||||
};
|
||||
|
||||
const submitCodeBlockHandler = async (values: CodeBlockContent, eventData?: ContainerChangeEventData) => {
|
||||
@ -67,6 +67,7 @@ export const useCodeBlockEdit = (codeBlockService: Services['codeBlockService'])
|
||||
|
||||
await codeBlockService.setCodeDslById(codeId.value, values, {
|
||||
changeRecords: eventData?.changeRecords,
|
||||
historySource: 'props',
|
||||
});
|
||||
|
||||
codeBlockEditorRef.value?.hide();
|
||||
|
||||
@ -27,9 +27,9 @@ export const useDataSourceEdit = (dataSourceService: Services['dataSourceService
|
||||
|
||||
const submitDataSourceHandler = (value: DataSourceSchema, eventData: ContainerChangeEventData) => {
|
||||
if (value.id) {
|
||||
dataSourceService.update(value, { changeRecords: eventData.changeRecords });
|
||||
dataSourceService.update(value, { changeRecords: eventData.changeRecords, historySource: 'props' });
|
||||
} else {
|
||||
dataSourceService.add(value);
|
||||
dataSourceService.add(value, { historySource: 'props' });
|
||||
}
|
||||
|
||||
editDialog.value?.hide();
|
||||
|
||||
@ -48,6 +48,7 @@ export const useStage = (stageOptions: StageOptions) => {
|
||||
disabledMultiSelect: stageOptions.disabledMultiSelect,
|
||||
alwaysMultiSelect: stageOptions.alwaysMultiSelect,
|
||||
disabledRule: stageOptions.disabledRule,
|
||||
disabledFlashTip: stageOptions.disabledFlashTip,
|
||||
});
|
||||
|
||||
watch(
|
||||
@ -129,16 +130,16 @@ export const useStage = (stageOptions: StageOptions) => {
|
||||
});
|
||||
if (configs.length === 0) return;
|
||||
|
||||
editorService.update(configs, { changeRecordList });
|
||||
editorService.update(configs, { changeRecordList, historySource: 'stage' });
|
||||
});
|
||||
|
||||
stage.on('sort', (ev: SortEventData) => {
|
||||
editorService.sort(ev.src, ev.dist);
|
||||
editorService.sort(ev.src, ev.dist, { historySource: 'stage' });
|
||||
});
|
||||
|
||||
stage.on('remove', (ev: RemoveEventData) => {
|
||||
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', () => {
|
||||
|
||||
@ -44,6 +44,8 @@ export { default as stageOverlayService } from './services/stageOverlay';
|
||||
export { default as uiService } from './services/ui';
|
||||
export { default as codeBlockService } from './services/codeBlock';
|
||||
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 LayerPanel } from './layouts/sidebar/layer/LayerPanel.vue';
|
||||
export { default as CodeSelect } from './fields/CodeSelect.vue';
|
||||
@ -71,6 +73,11 @@ export { default as SplitView } from './components/SplitView.vue';
|
||||
export { default as Resizer } from './components/Resizer.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 Tree } from './components/Tree.vue';
|
||||
export { default as TreeNode } from './components/TreeNode.vue';
|
||||
|
||||
@ -55,7 +55,7 @@ export const initServiceState = (
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(modelValue) => {
|
||||
editorService.set('root', modelValue || null);
|
||||
editorService.set('root', modelValue || null, { historySource: 'initial' });
|
||||
},
|
||||
{
|
||||
immediate: true,
|
||||
|
||||
@ -21,12 +21,12 @@ import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, ref, useTe
|
||||
import { FullScreen } from '@element-plus/icons-vue';
|
||||
import { throttle } from 'lodash-es';
|
||||
import type * as Monaco from 'monaco-editor';
|
||||
import serialize from 'serialize-javascript';
|
||||
|
||||
import { TMagicButton } from '@tmagic/design';
|
||||
|
||||
import MIcon from '@editor/components/Icon.vue';
|
||||
import { getEditorConfig } from '@editor/utils/config';
|
||||
import { serializeConfig } from '@editor/utils/editor';
|
||||
import loadMonaco from '@editor/utils/monaco-editor';
|
||||
|
||||
defineOptions({
|
||||
@ -163,10 +163,7 @@ const toString = (v: string | any, language: string): string => {
|
||||
if (language === 'json') {
|
||||
value = JSON.stringify(v, null, 2);
|
||||
} else {
|
||||
value = serialize(v, {
|
||||
space: 2,
|
||||
unsafe: true,
|
||||
}).replace(/"(\w+)":\s/g, '$1: ');
|
||||
value = serializeConfig(v);
|
||||
}
|
||||
} else {
|
||||
value = v;
|
||||
|
||||
@ -25,9 +25,9 @@
|
||||
right-class="m-editor-framework-right"
|
||||
:left="hideSidebar ? undefined : columnWidth.left"
|
||||
:right="columnWidth.right"
|
||||
:min-left="hideSidebar ? 0 : MIN_LEFT_COLUMN_WIDTH"
|
||||
:min-right="MIN_RIGHT_COLUMN_WIDTH"
|
||||
:min-center="MIN_CENTER_COLUMN_WIDTH"
|
||||
:min-left="hideSidebar ? 0 : minLeftColumnWidth"
|
||||
:min-right="minRightColumnWidth"
|
||||
:min-center="minCenterColumnWidth"
|
||||
:width="frameworkRect.width"
|
||||
@change="columnWidthChange"
|
||||
>
|
||||
@ -78,9 +78,6 @@ import { getEditorConfig } from '@editor/utils/config';
|
||||
import {
|
||||
DEFAULT_LEFT_COLUMN_WIDTH,
|
||||
LEFT_COLUMN_WIDTH_STORAGE_KEY,
|
||||
MIN_CENTER_COLUMN_WIDTH,
|
||||
MIN_LEFT_COLUMN_WIDTH,
|
||||
MIN_RIGHT_COLUMN_WIDTH,
|
||||
RIGHT_COLUMN_WIDTH_STORAGE_KEY,
|
||||
} from '@editor/utils/const';
|
||||
|
||||
@ -116,6 +113,10 @@ const showSrc = computed(() => uiService.get('showSrc'));
|
||||
|
||||
const columnWidth = computed(() => uiService.get('columnWidth'));
|
||||
|
||||
const minLeftColumnWidth = computed(() => uiService.get('minLeftColumnWidth'));
|
||||
const minCenterColumnWidth = computed(() => uiService.get('minCenterColumnWidth'));
|
||||
const minRightColumnWidth = computed(() => uiService.get('minRightColumnWidth'));
|
||||
|
||||
watch(pageLength, () => {
|
||||
splitViewRef.value?.updateWidth();
|
||||
});
|
||||
@ -168,7 +169,7 @@ onBeforeUnmount(() => {
|
||||
const saveCode = (value: string) => {
|
||||
try {
|
||||
const parseDSL = getEditorConfig('parseDSL');
|
||||
editorService.set('root', parseDSL(value));
|
||||
editorService.set('root', parseDSL(value), { historySource: 'root-code' });
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
@ -80,7 +80,7 @@ const getConfig = (item: MenuItem): (MenuButton | MenuComponent)[] => {
|
||||
disabled: () => editorService.get('node')?.type === NodeType.PAGE,
|
||||
handler: () => {
|
||||
const node = editorService.get('node');
|
||||
node && editorService.remove(node);
|
||||
node && editorService.remove(node, { historySource: 'toolbar' });
|
||||
},
|
||||
});
|
||||
break;
|
||||
@ -90,7 +90,7 @@ const getConfig = (item: MenuItem): (MenuButton | MenuComponent)[] => {
|
||||
className: 'undo',
|
||||
icon: markRaw(Back),
|
||||
tooltip: `后退(${ctrl}+z)`,
|
||||
disabled: () => !historyService.state.canUndo,
|
||||
disabled: () => !historyService.canUndo('page', editorService.get('page')?.id),
|
||||
handler: () => editorService.undo(),
|
||||
});
|
||||
break;
|
||||
@ -100,7 +100,7 @@ const getConfig = (item: MenuItem): (MenuButton | MenuComponent)[] => {
|
||||
className: 'redo',
|
||||
icon: markRaw(Right),
|
||||
tooltip: `前进(${ctrl}+Shift+z)`,
|
||||
disabled: () => !historyService.state.canRedo,
|
||||
disabled: () => !historyService.canRedo('page', editorService.get('page')?.id),
|
||||
handler: () => editorService.redo(),
|
||||
});
|
||||
break;
|
||||
|
||||
@ -1,33 +1,18 @@
|
||||
<template>
|
||||
<div class="m-editor-history-list-bucket">
|
||||
<div class="m-editor-history-list-bucket-title">
|
||||
<span>{{ title }}</span>
|
||||
<span>{{ config.title }}</span>
|
||||
<code>{{ String(bucketId) }}</code>
|
||||
<span class="m-editor-history-list-bucket-count">{{ groups.length }} 组</span>
|
||||
</div>
|
||||
|
||||
<ul class="m-editor-history-list-ul">
|
||||
<GroupRow
|
||||
v-for="(group, gIdx) in groups"
|
||||
:key="`${prefix}-${bucketId}-${gIdx}`"
|
||||
:group-key="`${prefix}-${bucketId}-${gIdx}`"
|
||||
:applied="group.applied"
|
||||
:merged="group.steps.length > 1"
|
||||
:op-type="group.opType"
|
||||
:desc="describeGroup(group)"
|
||||
:step-count="group.steps.length"
|
||||
:sub-steps="
|
||||
group.steps.map((s: any) => ({
|
||||
index: s.index,
|
||||
applied: s.applied,
|
||||
isCurrent: s.isCurrent,
|
||||
desc: describeStep(s.step),
|
||||
diffable: isStepDiffable ? isStepDiffable(s.step) : false,
|
||||
revertable: s.applied,
|
||||
}))
|
||||
"
|
||||
:is-current="group.isCurrent"
|
||||
:expanded="!!expanded[`${prefix}-${bucketId}-${gIdx}`]"
|
||||
v-for="group in groups"
|
||||
:key="rowKey(group)"
|
||||
:group="toRow(group)"
|
||||
:expanded="isHistoryGroupExpanded(expanded, rowKey(group))"
|
||||
:goto-enabled="config.gotoEnabled"
|
||||
@toggle="(key: string) => $emit('toggle', key)"
|
||||
@goto="(index: number) => $emit('goto', bucketId, index)"
|
||||
@diff-step="(index: number) => $emit('diff-step', bucketId, index)"
|
||||
@ -36,17 +21,25 @@
|
||||
<!--
|
||||
初始状态项:永远位于该 bucket 列表底部(同样按倒序展示,最底部 = 最早状态)。
|
||||
当 bucket 内所有 group 都未 applied 时即为当前位置。
|
||||
config.showInitial=false 时不展示(用于没有"撤销到初始状态"语义的自定义历史,如业务模块历史)。
|
||||
-->
|
||||
<InitialRow :is-current="isInitial" @goto-initial="$emit('goto-initial', bucketId)" />
|
||||
<InitialRow
|
||||
v-if="config.showInitial !== false"
|
||||
:is-current="isInitial"
|
||||
:goto-enabled="config.gotoEnabled"
|
||||
@goto-initial="$emit('goto-initial', bucketId)"
|
||||
/>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
<script lang="ts" setup generic="T extends BaseStepValue = BaseStepValue">
|
||||
import { computed } from 'vue';
|
||||
|
||||
import type { HistoryOpType } from '@editor/type';
|
||||
import type { BaseStepValue, HistoryBucketConfig } from '@editor/type';
|
||||
|
||||
import type { HistoryBucketGroup, HistoryRowGroup } from './composables';
|
||||
import { isHistoryGroupExpanded, toRowGroup } from './composables';
|
||||
import GroupRow from './GroupRow.vue';
|
||||
import InitialRow from './InitialRow.vue';
|
||||
|
||||
@ -55,26 +48,16 @@ defineOptions({
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
/** Bucket 标题,例如 "数据源" / "代码块",渲染在 bucket 头部。 */
|
||||
title: string;
|
||||
/**
|
||||
* 该类历史的整体渲染配置(title / prefix / describe* / isStep* / showInitial / gotoEnabled)。
|
||||
* 由父组件按业务类型注入,组件内部按需读取,避免逐项透传多个 props。
|
||||
*/
|
||||
config: HistoryBucketConfig<T>;
|
||||
/** 当前 bucket 对应的目标 id(dataSource.id 或 codeBlock.id),同时用于组装子项的 key。 */
|
||||
bucketId: string | number;
|
||||
/** 子项 key 的命名空间前缀:`ds` 表示数据源,`cb` 表示代码块。与上层折叠状态 key 保持一致。 */
|
||||
prefix: 'ds' | 'cb';
|
||||
/** 当前 bucket 下的所有历史分组,按时间倒序展示(最近的操作在前)。 */
|
||||
groups: {
|
||||
applied: boolean;
|
||||
isCurrent?: boolean;
|
||||
opType: HistoryOpType;
|
||||
steps: { index: number; applied: boolean; isCurrent?: boolean; step: any }[];
|
||||
}[];
|
||||
/** 组级描述文案生成器,接收一个 group,返回展示文本。由父组件按业务类型注入。 */
|
||||
describeGroup: (_group: any) => string;
|
||||
/** 单步描述文案生成器,接收一个 step,返回展示文本。用于合并组展开后的子步列表。 */
|
||||
describeStep: (_step: any) => string;
|
||||
/** 判断某个 step 是否可查看差异(前后值都存在)。由父组件按业务类型注入;不传则一律不展示差异入口。 */
|
||||
isStepDiffable?: (_step: any) => boolean;
|
||||
/** 共享的折叠状态表(key -> 是否展开),由顶层 panel 统一维护以便跨 tab 复用。 */
|
||||
groups: HistoryBucketGroup<T>[];
|
||||
/** 共享的折叠状态表(key -> 是否展开,缺省或 true 为展开、false 为收起),由顶层 panel 统一维护以便跨 tab 复用。 */
|
||||
expanded: Record<string, boolean>;
|
||||
}>();
|
||||
|
||||
@ -94,6 +77,15 @@ defineEmits<{
|
||||
(_e: 'revert-step', _bucketId: string | number, _index: number): void;
|
||||
}>();
|
||||
|
||||
/**
|
||||
* 子项 / 折叠状态 key:`${prefix}-${bucketId}-${组内首步 index}`。
|
||||
* 以稳定的 step 索引(而非展示位置)标识分组,历史数据更新后已展开的分组状态仍能正确保持。
|
||||
*/
|
||||
const rowKey = (group: HistoryBucketGroup<T>) => `${props.config.prefix}-${props.bucketId}-${group.steps[0]?.index}`;
|
||||
|
||||
/** 把原始分组派生为 GroupRow 直接消费的视图模型。 */
|
||||
const toRow = (group: HistoryBucketGroup<T>): HistoryRowGroup => toRowGroup(group, rowKey(group), props.config);
|
||||
|
||||
/** 该 bucket 是否处于初始状态(栈 cursor=0),等价于全部 group 都未 applied。 */
|
||||
const isInitial = computed(() => props.groups.length > 0 && props.groups.every((g) => !g.applied));
|
||||
</script>
|
||||
|
||||
72
packages/editor/src/layouts/history-list/BucketTab.vue
Normal file
72
packages/editor/src/layouts/history-list/BucketTab.vue
Normal file
@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<div v-if="!buckets.length" class="m-editor-history-list-empty">暂无操作记录</div>
|
||||
<template v-else>
|
||||
<div v-if="config.showClear !== false" class="m-editor-history-list-toolbar">
|
||||
<span class="m-editor-history-list-clear" :title="`清空${config.title}的历史记录`" @click="$emit('clear')"
|
||||
>清空</span
|
||||
>
|
||||
</div>
|
||||
<TMagicScrollbar max-height="360px">
|
||||
<Bucket
|
||||
v-for="bucket in buckets"
|
||||
:key="`${config.prefix}-${bucket.id}`"
|
||||
:config="config"
|
||||
:bucket-id="bucket.id"
|
||||
:groups="bucket.groups"
|
||||
:expanded="expanded"
|
||||
@toggle="(key: string) => $emit('toggle', key)"
|
||||
@goto="(id: string | number, index: number) => $emit('goto', id, index)"
|
||||
@goto-initial="(id: string | number) => $emit('goto-initial', id)"
|
||||
@diff-step="(id: string | number, index: number) => $emit('diff-step', id, index)"
|
||||
@revert-step="(id: string | number, index: number) => $emit('revert-step', id, index)"
|
||||
/>
|
||||
</TMagicScrollbar>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup generic="T extends BaseStepValue = BaseStepValue">
|
||||
import { TMagicScrollbar } from '@tmagic/design';
|
||||
|
||||
import type { BaseStepValue, HistoryBucketConfig } from '@editor/type';
|
||||
|
||||
import Bucket from './Bucket.vue';
|
||||
import type { HistoryBucketGroup } from './composables';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorHistoryListBucketTab',
|
||||
});
|
||||
|
||||
defineProps<{
|
||||
/**
|
||||
* 该类历史的整体渲染配置(title / prefix / describe* / isStep* / showInitial / gotoEnabled / showClear),
|
||||
* 由父组件按业务类型注入并整体透传给 Bucket,避免逐项透传多个 props。
|
||||
*/
|
||||
config: HistoryBucketConfig<T>;
|
||||
/**
|
||||
* 已按目标 id 聚拢成的 bucket 列表,每个 bucket 内部的 groups 已按时间倒序排好。
|
||||
* 空数组时显示空态。
|
||||
*/
|
||||
buckets: { id: string | number; groups: HistoryBucketGroup<T>[] }[];
|
||||
/**
|
||||
* 共享的折叠状态表(key -> 是否展开),由顶层 panel 统一维护。
|
||||
* key 形如 `${prefix}-${id}-${组内首步 index}`——以稳定的 step 索引而非展示位置标识分组,
|
||||
* 这样历史数据更新后已展开的分组状态仍能正确保持。
|
||||
*/
|
||||
expanded: Record<string, boolean>;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
/** 透传子组件 Bucket 的 toggle 事件给上层 panel,由其更新 expanded。 */
|
||||
(_e: 'toggle', _key: string): void;
|
||||
/** 透传 Bucket 的 goto 事件,携带目标 id 与目标 step 索引。 */
|
||||
(_e: 'goto', _targetId: string | number, _index: number): void;
|
||||
/** 透传 Bucket 的 goto-initial 事件,携带目标 id(回到该目标未修改时的状态)。 */
|
||||
(_e: 'goto-initial', _targetId: string | number): void;
|
||||
/** 透传 Bucket 的 diff-step 事件,携带目标 id 与 step 索引。 */
|
||||
(_e: 'diff-step', _targetId: string | number, _index: number): void;
|
||||
/** 透传 Bucket 的 revert-step 事件,携带目标 id 与 step 索引(类 git revert)。 */
|
||||
(_e: 'revert-step', _targetId: string | number, _index: number): void;
|
||||
/** 用户点击"清空"按钮,请求清空该类(数据源 / 代码块)的全部历史记录(由上层弹窗二次确认后执行)。 */
|
||||
(_e: 'clear'): void;
|
||||
}>();
|
||||
</script>
|
||||
@ -1,61 +0,0 @@
|
||||
<template>
|
||||
<div v-if="!buckets.length" class="m-editor-history-list-empty">暂无操作记录</div>
|
||||
<TMagicScrollbar v-else max-height="360px">
|
||||
<Bucket
|
||||
v-for="bucket in buckets"
|
||||
:key="`cb-${bucket.id}`"
|
||||
title="代码块"
|
||||
:bucket-id="bucket.id"
|
||||
prefix="cb"
|
||||
:groups="bucket.groups"
|
||||
:describe-group="describeCodeBlockGroup"
|
||||
:describe-step="describeCodeBlockStep"
|
||||
:is-step-diffable="isCodeBlockStepDiffable"
|
||||
:expanded="expanded"
|
||||
@toggle="(key: string) => $emit('toggle', key)"
|
||||
@goto="(id: string | number, index: number) => $emit('goto', id, index)"
|
||||
@goto-initial="(id: string | number) => $emit('goto-initial', id)"
|
||||
@diff-step="(id: string | number, index: number) => $emit('diff-step', id, index)"
|
||||
@revert-step="(id: string | number, index: number) => $emit('revert-step', id, index)"
|
||||
/>
|
||||
</TMagicScrollbar>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { TMagicScrollbar } from '@tmagic/design';
|
||||
|
||||
import type { CodeBlockHistoryGroup, CodeBlockStepValue } from '@editor/type';
|
||||
|
||||
import Bucket from './Bucket.vue';
|
||||
import { describeCodeBlockGroup, describeCodeBlockStep } from './composables';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorHistoryListCodeBlockTab',
|
||||
});
|
||||
|
||||
defineProps<{
|
||||
/**
|
||||
* 已按 codeBlock.id 聚拢成的 bucket 列表,每个 bucket 内部的 groups 已按时间倒序排好。
|
||||
* 空数组时显示空态。
|
||||
*/
|
||||
buckets: { id: string | number; groups: CodeBlockHistoryGroup[] }[];
|
||||
/** 共享的折叠状态表(key -> 是否展开),由顶层 panel 统一维护。本 tab 使用 `cb-${id}-${idx}` 作为 key。 */
|
||||
expanded: Record<string, boolean>;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
/** 透传子组件 Bucket 的 toggle 事件给上层 panel,由其更新 expanded。 */
|
||||
(_e: 'toggle', _key: string): void;
|
||||
/** 透传 Bucket 的 goto 事件,携带 codeBlock id 与目标 step 索引。 */
|
||||
(_e: 'goto', _codeBlockId: string | number, _index: number): void;
|
||||
/** 透传 Bucket 的 goto-initial 事件,携带 codeBlock id(回到该代码块未修改时的状态)。 */
|
||||
(_e: 'goto-initial', _codeBlockId: string | number): void;
|
||||
/** 透传 Bucket 的 diff-step 事件,携带 codeBlock id 与 step 索引。 */
|
||||
(_e: 'diff-step', _codeBlockId: string | number, _index: number): void;
|
||||
/** 透传 Bucket 的 revert-step 事件,携带 codeBlock id 与 step 索引(类 git revert)。 */
|
||||
(_e: 'revert-step', _codeBlockId: string | number, _index: number): void;
|
||||
}>();
|
||||
|
||||
/** 仅 update(前后 content 都存在)时可查看差异。 */
|
||||
const isCodeBlockStepDiffable = (step: CodeBlockStepValue) => Boolean(step.oldContent && step.newContent);
|
||||
</script>
|
||||
@ -1,61 +0,0 @@
|
||||
<template>
|
||||
<div v-if="!buckets.length" class="m-editor-history-list-empty">暂无操作记录</div>
|
||||
<TMagicScrollbar v-else max-height="360px">
|
||||
<Bucket
|
||||
v-for="bucket in buckets"
|
||||
:key="`ds-${bucket.id}`"
|
||||
title="数据源"
|
||||
:bucket-id="bucket.id"
|
||||
prefix="ds"
|
||||
:groups="bucket.groups"
|
||||
:describe-group="describeDataSourceGroup"
|
||||
:describe-step="describeDataSourceStep"
|
||||
:is-step-diffable="isDataSourceStepDiffable"
|
||||
:expanded="expanded"
|
||||
@toggle="(key: string) => $emit('toggle', key)"
|
||||
@goto="(id: string | number, index: number) => $emit('goto', id, index)"
|
||||
@goto-initial="(id: string | number) => $emit('goto-initial', id)"
|
||||
@diff-step="(id: string | number, index: number) => $emit('diff-step', id, index)"
|
||||
@revert-step="(id: string | number, index: number) => $emit('revert-step', id, index)"
|
||||
/>
|
||||
</TMagicScrollbar>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { TMagicScrollbar } from '@tmagic/design';
|
||||
|
||||
import type { DataSourceHistoryGroup, DataSourceStepValue } from '@editor/type';
|
||||
|
||||
import Bucket from './Bucket.vue';
|
||||
import { describeDataSourceGroup, describeDataSourceStep } from './composables';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorHistoryListDataSourceTab',
|
||||
});
|
||||
|
||||
defineProps<{
|
||||
/**
|
||||
* 已按 dataSource.id 聚拢成的 bucket 列表,每个 bucket 内部的 groups 已按时间倒序排好。
|
||||
* 空数组时显示空态。
|
||||
*/
|
||||
buckets: { id: string | number; groups: DataSourceHistoryGroup[] }[];
|
||||
/** 共享的折叠状态表(key -> 是否展开),由顶层 panel 统一维护。本 tab 使用 `ds-${id}-${idx}` 作为 key。 */
|
||||
expanded: Record<string, boolean>;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
/** 透传子组件 Bucket 的 toggle 事件给上层 panel,由其更新 expanded。 */
|
||||
(_e: 'toggle', _key: string): void;
|
||||
/** 透传 Bucket 的 goto 事件,携带 dataSource id 与目标 step 索引。 */
|
||||
(_e: 'goto', _dataSourceId: string | number, _index: number): void;
|
||||
/** 透传 Bucket 的 goto-initial 事件,携带 dataSource id(回到该数据源未修改时的状态)。 */
|
||||
(_e: 'goto-initial', _dataSourceId: string | number): void;
|
||||
/** 透传 Bucket 的 diff-step 事件,携带 dataSource id 与 step 索引。 */
|
||||
(_e: 'diff-step', _dataSourceId: string | number, _index: number): void;
|
||||
/** 透传 Bucket 的 revert-step 事件,携带 dataSource id 与 step 索引(类 git revert)。 */
|
||||
(_e: 'revert-step', _dataSourceId: string | number, _index: number): void;
|
||||
}>();
|
||||
|
||||
/** 仅 update(前后 schema 都存在)时可查看差异。 */
|
||||
const isDataSourceStepDiffable = (step: DataSourceStepValue) => Boolean(step.oldSchema && step.newSchema);
|
||||
</script>
|
||||
@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<li
|
||||
class="m-editor-history-list-item m-editor-history-list-group"
|
||||
:class="{ 'is-undone': !applied, 'is-merged': merged, 'is-current': isCurrent }"
|
||||
:class="{ 'is-undone': !group.applied, 'is-merged': merged, 'is-current': group.isCurrent }"
|
||||
>
|
||||
<div
|
||||
class="m-editor-history-list-group-head"
|
||||
@ -10,24 +10,60 @@
|
||||
@click="onHeadClick"
|
||||
>
|
||||
<span class="m-editor-history-list-item-index" :title="headIndexTitle">{{ headIndexLabel }}</span>
|
||||
<span class="m-editor-history-list-item-op" :class="`op-${opType}`">{{ opLabel(opType) }}</span>
|
||||
<span class="m-editor-history-list-item-desc">{{ desc }}</span>
|
||||
<span v-if="isCurrent" class="m-editor-history-list-item-current">当前</span>
|
||||
<span class="m-editor-history-list-item-op" :class="`op-${group.opType}`">{{ opLabel(group.opType) }}</span>
|
||||
<span class="m-editor-history-list-item-desc">{{ group.desc }}</span>
|
||||
|
||||
<span v-if="headSaved" class="m-editor-history-list-item-saved" title="该记录为最近一次保存的状态">已保存</span>
|
||||
|
||||
<span
|
||||
v-if="!merged && headDiffable"
|
||||
class="m-editor-history-list-item-diff"
|
||||
title="查看修改差异"
|
||||
@click.stop="onDiffClick(subSteps[0].index)"
|
||||
>查看差异</span
|
||||
v-if="!merged && (headRevertable || headDiffable || canHeadGoto)"
|
||||
class="m-editor-history-list-item-actions"
|
||||
>
|
||||
<span
|
||||
v-if="headRevertable"
|
||||
class="m-editor-history-list-item-revert"
|
||||
title="将该步骤的修改作为一次新操作反向应用(不影响后续历史)"
|
||||
@click.stop="onRevertClick(group.subSteps[0].index)"
|
||||
>回滚</span
|
||||
>
|
||||
<span
|
||||
v-if="canHeadGoto"
|
||||
class="m-editor-history-list-item-goto"
|
||||
title="回到该记录"
|
||||
@click.stop="onGotoClick(group.subSteps[0].index)"
|
||||
>回到</span
|
||||
>
|
||||
<span
|
||||
v-if="headDiffable"
|
||||
class="m-editor-history-list-item-diff"
|
||||
title="查看修改差异"
|
||||
@click.stop="onDiffClick(group.subSteps[0].index)"
|
||||
>查看差异</span
|
||||
>
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-if="!merged && sourceLabel(group.source)"
|
||||
class="m-editor-history-list-item-source"
|
||||
:title="`操作途径:${sourceLabel(group.source)}`"
|
||||
>{{ sourceLabel(group.source) }}</span
|
||||
>
|
||||
|
||||
<span
|
||||
v-if="!merged && group.operator"
|
||||
class="m-editor-history-list-item-operator"
|
||||
:title="`操作人:${group.operator}`"
|
||||
>{{ group.operator }}</span
|
||||
>
|
||||
|
||||
<span
|
||||
v-if="!merged && group.time"
|
||||
class="m-editor-history-list-item-time"
|
||||
:title="group.timeTitle || group.time"
|
||||
>{{ group.time }}</span
|
||||
>
|
||||
|
||||
<span v-if="merged" class="m-editor-history-list-item-merge">合并 {{ stepCount }} 步</span>
|
||||
<span
|
||||
v-if="!merged && headRevertable"
|
||||
class="m-editor-history-list-item-revert"
|
||||
title="将该步骤的修改作为一次新操作反向应用(不影响后续历史)"
|
||||
@click.stop="onRevertClick(subSteps[0].index)"
|
||||
>回滚</span
|
||||
>
|
||||
<span v-if="merged" class="m-editor-history-list-group-toggle" :class="{ 'is-expanded': expanded }">▾</span>
|
||||
</div>
|
||||
|
||||
@ -35,27 +71,49 @@
|
||||
<li
|
||||
v-for="s in subStepsDisplay"
|
||||
:key="s.index"
|
||||
:class="{ 'is-undone': !s.applied, 'is-current': s.isCurrent, 'is-clickable': !s.isCurrent }"
|
||||
:title="s.isCurrent ? '当前所在记录' : '点击跳转到该记录'"
|
||||
@click="onSubStepClick(s)"
|
||||
:class="{ 'is-undone': !s.applied, 'is-current': s.isCurrent, 'is-clickable': selectEnabled }"
|
||||
:title="subStepTitle(s)"
|
||||
@click="onSubStepClick(s.index)"
|
||||
>
|
||||
<span class="m-editor-history-list-item-index">#{{ s.index + 1 }}</span>
|
||||
<span class="m-editor-history-list-substep-desc">{{ s.desc }}</span>
|
||||
<span v-if="s.isCurrent" class="m-editor-history-list-item-current">当前</span>
|
||||
<span v-if="s.saved" class="m-editor-history-list-item-saved" title="该记录为最近一次保存的状态">已保存</span>
|
||||
<span
|
||||
v-if="s.diffable"
|
||||
class="m-editor-history-list-item-diff"
|
||||
title="查看修改差异"
|
||||
@click.stop="onDiffClick(s.index)"
|
||||
>查看差异</span
|
||||
v-if="s.revertable || s.diffable || (gotoEnabled && !s.isCurrent)"
|
||||
class="m-editor-history-list-item-actions"
|
||||
>
|
||||
<span
|
||||
v-if="s.revertable"
|
||||
class="m-editor-history-list-item-revert"
|
||||
title="将该步骤的修改作为一次新操作反向应用(不影响后续历史)"
|
||||
@click.stop="onRevertClick(s.index)"
|
||||
>回滚</span
|
||||
>
|
||||
<span
|
||||
v-if="gotoEnabled && !s.isCurrent"
|
||||
class="m-editor-history-list-item-goto"
|
||||
title="回到该记录"
|
||||
@click.stop="onGotoClick(s.index)"
|
||||
>回到</span
|
||||
>
|
||||
<span
|
||||
v-if="s.diffable"
|
||||
class="m-editor-history-list-item-diff"
|
||||
title="查看修改差异"
|
||||
@click.stop="onDiffClick(s.index)"
|
||||
>查看差异</span
|
||||
>
|
||||
</span>
|
||||
<span
|
||||
v-if="s.revertable"
|
||||
class="m-editor-history-list-item-revert"
|
||||
title="将该步骤的修改作为一次新操作反向应用(不影响后续历史)"
|
||||
@click.stop="onRevertClick(s.index)"
|
||||
>回滚</span
|
||||
v-if="sourceLabel(s.source)"
|
||||
class="m-editor-history-list-item-source"
|
||||
:title="`操作途径:${sourceLabel(s.source)}`"
|
||||
>{{ sourceLabel(s.source) }}</span
|
||||
>
|
||||
<span v-if="s.operator" class="m-editor-history-list-item-operator" :title="`操作人:${s.operator}`">{{
|
||||
s.operator
|
||||
}}</span>
|
||||
<span v-if="s.time" class="m-editor-history-list-item-time" :title="s.timeTitle || s.time">{{ s.time }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
@ -64,53 +122,51 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue';
|
||||
|
||||
import type { HistoryOpType } from '@editor/type';
|
||||
|
||||
import { opLabel } from './composables';
|
||||
import type { HistoryRowGroup, HistoryRowStep } from './composables';
|
||||
import { opLabel, sourceLabel } from './composables';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorHistoryListGroupRow',
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
/** 唯一标识当前组的 key,作为 toggle 事件的 payload 回传给上层。形如 `pg-${idx}` / `ds-${id}-${idx}` / `cb-${id}-${idx}`。 */
|
||||
groupKey: string;
|
||||
/** 该组当前是否处于已应用状态(false 表示已被 undo 撤销,UI 会显示为灰态)。 */
|
||||
applied: boolean;
|
||||
/** 是否为合并组(即组内 step 数大于 1,由多次连续操作合并而来)。决定是否展示合并标记与可展开的子步列表。 */
|
||||
merged: boolean;
|
||||
/** 操作类型:`add` / `remove` / `update`,用于决定操作徽标的颜色和文案。 */
|
||||
opType: HistoryOpType;
|
||||
/** 组的整体描述文案,由上层根据 step / group 计算后传入,例如 "修改 button · style.color"。 */
|
||||
desc: string;
|
||||
/** 组内的 step 总数,仅在 merged 为 true 时显示为 "合并 N 步"。 */
|
||||
stepCount: number;
|
||||
/** 子步列表,用于在展开状态下逐条展示每个 step 的索引、应用状态与描述文案。 */
|
||||
subSteps: {
|
||||
index: number;
|
||||
applied: boolean;
|
||||
desc: string;
|
||||
isCurrent?: boolean;
|
||||
diffable?: boolean;
|
||||
/** 是否可对该子步执行「回滚」(已应用 + 业务侧确认支持反向)。父级根据 step 与 applied 决定。 */
|
||||
revertable?: boolean;
|
||||
}[];
|
||||
/** 当前组是否处于展开状态。仅在 merged 为 true 时生效,控制子步列表是否渲染。 */
|
||||
expanded: boolean;
|
||||
/** 是否为当前所在的分组(包含栈中最近一次已应用步骤的那一组),UI 高亮展示。 */
|
||||
isCurrent?: boolean;
|
||||
}>();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/**
|
||||
* 该组的视图模型(由 `toRowGroup` 统一派生):包含 key、应用状态、操作类型、描述、
|
||||
* 来源 / 时间等头部信息以及子步列表。原先散落的十余个扁平 props 收敛于此单一对象。
|
||||
*/
|
||||
group: HistoryRowGroup;
|
||||
/** 当前组是否处于展开状态(合并组默认展开)。仅在合并组(子步数 > 1)时生效,控制子步列表是否渲染。 */
|
||||
expanded: boolean;
|
||||
/**
|
||||
* 是否支持「跳转到该记录」(goto)。默认 true。
|
||||
* 为 false 时:单步组头部与子步条目都不再可点击跳转、也不会触发 goto 事件,
|
||||
* 仅保留合并组头部的展开 / 收起能力,以及查看差异、回滚等其它入口。
|
||||
*/
|
||||
gotoEnabled?: boolean;
|
||||
/**
|
||||
* 是否支持「点击记录选中对应节点」。默认 false(仅页面 tab 启用,数据源 / 代码块无节点概念)。
|
||||
* 为 true 时:点击单步组头部、子步条目或合并组头部都会发出 `select` 事件(携带对应 step 索引),
|
||||
* 由上层解析出节点 id 并在画布选中;合并组头部同时保留展开 / 收起能力。
|
||||
*/
|
||||
selectEnabled?: boolean;
|
||||
}>(),
|
||||
{
|
||||
gotoEnabled: true,
|
||||
selectEnabled: false,
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
/**
|
||||
* 用户点击合并组头部时触发,携带 groupKey;上层用其切换 expanded 状态。
|
||||
* 用户点击合并组头部时触发,携带 group.key;上层用其切换 expanded 状态。
|
||||
* 对单步组(非合并)头部点击不会发该事件——因为单步组没有"展开"的概念。
|
||||
*/
|
||||
(_e: 'toggle', _key: string): void;
|
||||
/**
|
||||
* 用户希望跳转到该记录时触发,携带"目标 step 在所属栈中的索引"——上层据此计算目标 cursor (= index + 1)。
|
||||
* 触发场景:
|
||||
* - 单步组(merged=false)头部:取该唯一 step 的 index;
|
||||
* - 单步组(非合并)头部:取该唯一 step 的 index;
|
||||
* - 子步条目:取该子步的 index。
|
||||
* 合并组头部不再触发 goto,避免与展开/收起冲突;用户应展开后点具体子步精准跳转。
|
||||
* 当前所在的步骤(isCurrent)始终不会触发 goto。
|
||||
@ -118,7 +174,7 @@ const emit = defineEmits<{
|
||||
(_e: 'goto', _index: number): void;
|
||||
/**
|
||||
* 用户希望查看该 step 的修改差异(旧值 vs 新值)。
|
||||
* 只在 step 满足"前后值都存在"(如 update / 数据源、代码块的 update)时由父级标记 `diffable=true`。
|
||||
* 只在 step 满足"前后值都存在"(如 update / 数据源、代码块的 update)时由 `toRowGroup` 标记 `diffable=true`。
|
||||
* payload 为该 step 在所属栈中的索引,由上层根据 index 取 step 内容并展示对比。
|
||||
*/
|
||||
(_e: 'diff-step', _index: number): void;
|
||||
@ -127,74 +183,115 @@ const emit = defineEmits<{
|
||||
* payload 为该 step 在所属栈中的索引。仅在单步组头部(headRevertable)或合并组的可回滚子步上触发。
|
||||
*/
|
||||
(_e: 'revert-step', _index: number): void;
|
||||
/**
|
||||
* 用户希望「选中该记录对应的节点」。payload 为该 step 在所属栈中的索引,
|
||||
* 由上层据 index 取出 step、解析出节点 id 并在画布选中。仅在 `selectEnabled` 为 true 时触发。
|
||||
*/
|
||||
(_e: 'select', _index: number): void;
|
||||
}>();
|
||||
|
||||
/** 单步组:头部可点击 goto;合并组:头部可点击切换展开。当前组(isCurrent)的单步组头部不可点击。 */
|
||||
const isHeadClickable = computed(() => {
|
||||
if (props.merged) return true;
|
||||
return !props.isCurrent;
|
||||
});
|
||||
/** 子步数大于 1 即为合并组:决定是否展示合并标记与可展开的子步列表。 */
|
||||
const merged = computed(() => props.group.subSteps.length > 1);
|
||||
|
||||
/** 组内 step 总数,仅在合并组时显示为 "合并 N 步"。 */
|
||||
const stepCount = computed(() => props.group.subSteps.length);
|
||||
|
||||
/**
|
||||
* 头部可点击的场景:
|
||||
* - 合并组:点击切换展开 / 收起;
|
||||
* - 开启 `selectEnabled`(页面 tab):点击选中对应节点。
|
||||
* 单步组的跳转仍由头部的「回到」按钮触发。
|
||||
*/
|
||||
const isHeadClickable = computed(() => merged.value || props.selectEnabled);
|
||||
|
||||
const headTitle = computed(() => {
|
||||
if (props.merged) return props.expanded ? '点击收起子步' : '点击展开子步';
|
||||
if (props.isCurrent) return '当前所在记录';
|
||||
return '点击跳转到该记录';
|
||||
if (merged.value) {
|
||||
const expandHint = props.expanded ? '点击收起子步' : '点击展开子步';
|
||||
return props.selectEnabled ? `${expandHint}(并选中该节点)` : expandHint;
|
||||
}
|
||||
if (props.selectEnabled) return '点击选中该节点';
|
||||
if (props.group.isCurrent) return '当前所在记录';
|
||||
return '';
|
||||
});
|
||||
|
||||
/**
|
||||
* 头部点击行为分流:
|
||||
* - 合并组:仅切换展开 / 收起,不触发 goto;
|
||||
* - 单步组:跳转到该唯一步骤;当前组忽略点击。
|
||||
* 头部点击行为:
|
||||
* - 开启 selectEnabled 时,发出 select(携带组内首步 index,上层据此选中节点);
|
||||
* - 合并组同时切换展开 / 收起。
|
||||
*/
|
||||
const onHeadClick = () => {
|
||||
if (props.merged) {
|
||||
emit('toggle', props.groupKey);
|
||||
return;
|
||||
if (props.selectEnabled && props.group.subSteps.length) {
|
||||
emit('select', props.group.subSteps[0].index);
|
||||
}
|
||||
if (merged.value) {
|
||||
emit('toggle', props.group.key);
|
||||
}
|
||||
if (props.isCurrent) return;
|
||||
if (!props.subSteps.length) return;
|
||||
emit('goto', props.subSteps[0].index);
|
||||
};
|
||||
|
||||
const onSubStepClick = (s: { index: number; isCurrent?: boolean }) => {
|
||||
if (s.isCurrent) return;
|
||||
emit('goto', s.index);
|
||||
const onGotoClick = (index: number) => {
|
||||
if (!props.gotoEnabled) return;
|
||||
emit('goto', index);
|
||||
};
|
||||
|
||||
/** 点击子步行:开启 selectEnabled 时选中该子步对应的节点。 */
|
||||
const onSubStepClick = (index: number) => {
|
||||
if (!props.selectEnabled) return;
|
||||
emit('select', index);
|
||||
};
|
||||
|
||||
const subStepTitle = (s: { isCurrent?: boolean }) => {
|
||||
if (props.selectEnabled) return '点击选中该节点';
|
||||
if (s.isCurrent) return '当前所在记录';
|
||||
return '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 头部是否展示「已保存」标记:
|
||||
* - 单步组:取该唯一子步的 saved;
|
||||
* - 合并组:组内任一子步为已保存即在头部提示(具体落在哪一步可展开查看)。
|
||||
*/
|
||||
const headSaved = computed(() =>
|
||||
merged.value ? props.group.subSteps.some((s) => s.saved) : Boolean(props.group.subSteps[0]?.saved),
|
||||
);
|
||||
|
||||
/** 单步组头部是否展示"查看差异"入口:要求该唯一子步本身可对比。 */
|
||||
const headDiffable = computed(() => !props.merged && Boolean(props.subSteps[0]?.diffable));
|
||||
const headDiffable = computed(() => !merged.value && Boolean(props.group.subSteps[0]?.diffable));
|
||||
|
||||
/** 单步组头部是否展示"回滚"入口:要求该唯一子步本身可回滚(已应用)。 */
|
||||
const headRevertable = computed(() => !props.merged && Boolean(props.subSteps[0]?.revertable));
|
||||
const headRevertable = computed(() => !merged.value && Boolean(props.group.subSteps[0]?.revertable));
|
||||
|
||||
/** 单步组头部是否展示"回到"入口:可跳转、非当前、且存在唯一子步。 */
|
||||
const canHeadGoto = computed(
|
||||
() => !merged.value && props.gotoEnabled && !props.group.isCurrent && props.group.subSteps.length > 0,
|
||||
);
|
||||
|
||||
/**
|
||||
* 合并组展开后的子步渲染顺序:与外层分组列表保持一致——倒序展示(最新的子步在最上方)。
|
||||
* 外层 page tab / bucket 都已对 groups 做了 reverse,子步沿用同样的视觉规则更直观。
|
||||
* 注意:仅用于渲染,原 `subSteps` 保持时间正序,`headIndexLabel` 等基于首尾索引的展示语义不变。
|
||||
*/
|
||||
const subStepsDisplay = computed(() => props.subSteps.slice().reverse());
|
||||
const subStepsDisplay = computed<HistoryRowStep[]>(() => props.group.subSteps.slice().reverse());
|
||||
|
||||
/**
|
||||
* 头部索引展示:
|
||||
* - 单步组(merged=false):显示该唯一 step 的编号,如 `#5`;
|
||||
* - 单步组(非合并):显示该唯一 step 的编号,如 `#5`;
|
||||
* - 合并组:显示组内 step 的编号范围,如 `#3-#7`(首尾相同则退化为 `#5`)。
|
||||
*
|
||||
* 这里展示的是 step.index + 1(与子步列表 `#{{ s.index + 1 }}` 保持一致),从 1 起编号更符合直觉。
|
||||
*/
|
||||
const headIndexLabel = computed(() => {
|
||||
const list = props.subSteps;
|
||||
const list = props.group.subSteps;
|
||||
if (!list.length) return '';
|
||||
const first = list[0].index + 1;
|
||||
const last = list[list.length - 1].index + 1;
|
||||
if (!props.merged || first === last) return `#${first}`;
|
||||
if (!merged.value || first === last) return `#${first}`;
|
||||
return `#${first}-#${last}`;
|
||||
});
|
||||
|
||||
const headIndexTitle = computed(() => {
|
||||
if (!props.merged) return `历史步骤编号 #${props.subSteps[0]?.index + 1}`;
|
||||
return `合并了第 ${props.subSteps[0]?.index + 1} 至第 ${
|
||||
props.subSteps[props.subSteps.length - 1]?.index + 1
|
||||
} 共 ${props.subSteps.length} 条历史步骤`;
|
||||
const list = props.group.subSteps;
|
||||
if (!merged.value) return `历史步骤编号 #${list[0]?.index + 1}`;
|
||||
return `合并了第 ${list[0]?.index + 1} 至第 ${list[list.length - 1]?.index + 1} 共 ${list.length} 条历史步骤`;
|
||||
});
|
||||
|
||||
const onDiffClick = (index: number) => {
|
||||
|
||||
@ -1,111 +1,130 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<TMagicDialog
|
||||
v-model="visible"
|
||||
class="m-editor-history-diff-dialog"
|
||||
title="查看修改差异"
|
||||
width="900px"
|
||||
top="5vh"
|
||||
destroy-on-close
|
||||
append-to-body
|
||||
>
|
||||
<div v-if="payload" class="m-editor-history-diff-dialog-body">
|
||||
<div class="m-editor-history-diff-dialog-header">
|
||||
<span class="m-editor-history-diff-dialog-target">{{ targetText }}</span>
|
||||
<div class="m-editor-history-diff-dialog-controls">
|
||||
<TMagicRadioGroup v-model="viewMode" size="small" class="m-editor-history-diff-dialog-view">
|
||||
<TMagicRadioButton value="form">表单对比</TMagicRadioButton>
|
||||
<TMagicRadioButton value="code">源码对比</TMagicRadioButton>
|
||||
</TMagicRadioGroup>
|
||||
<TMagicDialog
|
||||
v-model="visible"
|
||||
class="m-editor-history-diff-dialog"
|
||||
:title="dialogTitle"
|
||||
top="5vh"
|
||||
destroy-on-close
|
||||
append-to-body
|
||||
:width="width"
|
||||
@close="onClose"
|
||||
>
|
||||
<div v-if="payload && visible" class="m-editor-history-diff-dialog-body">
|
||||
<div v-if="onConfirm" class="m-editor-history-diff-dialog-notice">仅回滚有差异的字段</div>
|
||||
|
||||
<TMagicRadioGroup v-model="mode" size="small" class="m-editor-history-diff-dialog-mode">
|
||||
<TMagicRadioButton value="before">与修改前对比</TMagicRadioButton>
|
||||
<TMagicRadioButton value="current" :disabled="!hasCurrent">与当前对比</TMagicRadioButton>
|
||||
</TMagicRadioGroup>
|
||||
</div>
|
||||
<div class="m-editor-history-diff-dialog-header">
|
||||
<span class="m-editor-history-diff-dialog-target">{{ targetText }}</span>
|
||||
<div class="m-editor-history-diff-dialog-controls">
|
||||
<TMagicRadioGroup v-model="viewMode" size="small" class="m-editor-history-diff-dialog-view">
|
||||
<TMagicRadioButton value="form">表单对比</TMagicRadioButton>
|
||||
<TMagicRadioButton value="code">源码对比</TMagicRadioButton>
|
||||
</TMagicRadioGroup>
|
||||
|
||||
<TMagicRadioGroup v-model="mode" size="small" class="m-editor-history-diff-dialog-mode">
|
||||
<TMagicRadioButton value="before" :disabled="!hasValue">与修改前对比</TMagicRadioButton>
|
||||
<TMagicRadioButton value="current" :disabled="!hasCurrent">与当前对比</TMagicRadioButton>
|
||||
</TMagicRadioGroup>
|
||||
</div>
|
||||
|
||||
<div class="m-editor-history-diff-dialog-legend">
|
||||
<TMagicTag size="small" type="danger">{{ leftLabel }}</TMagicTag>
|
||||
<span class="m-editor-history-diff-dialog-arrow">→</span>
|
||||
<TMagicTag size="small" type="success">{{ rightLabel }}</TMagicTag>
|
||||
<span v-if="mode === 'current' && isSameAsCurrent" class="m-editor-history-diff-dialog-tip">
|
||||
当前值与该步修改后一致,无差异
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<CompareForm
|
||||
v-if="viewMode === 'form'"
|
||||
:category="payload.category"
|
||||
:type="payload.type"
|
||||
:data-source-type="payload.dataSourceType"
|
||||
:value="rightValue"
|
||||
:last-value="leftValue"
|
||||
:extend-state="extendState"
|
||||
height="70vh"
|
||||
/>
|
||||
|
||||
<CodeEditor
|
||||
v-else
|
||||
type="diff"
|
||||
language="json"
|
||||
:init-values="leftValue"
|
||||
:modified-values="rightValue"
|
||||
:options="codeDiffOptions"
|
||||
disabled-full-screen
|
||||
height="70vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<TMagicButton size="small" @click="visible = false">关闭</TMagicButton>
|
||||
<div class="m-editor-history-diff-dialog-legend">
|
||||
<TMagicTag size="small" type="danger">{{ leftLabel }}</TMagicTag>
|
||||
<span class="m-editor-history-diff-dialog-arrow">→</span>
|
||||
<TMagicTag size="small" type="success">{{ rightLabel }}</TMagicTag>
|
||||
<span v-if="mode === 'current' && isSameAsCurrent" class="m-editor-history-diff-dialog-tip">
|
||||
当前值与该步修改后一致,无差异
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<CompareForm
|
||||
v-if="viewMode === 'form'"
|
||||
:category="payload.category"
|
||||
:type="payload.type"
|
||||
:data-source-type="payload.dataSourceType"
|
||||
:value="rightValue"
|
||||
:last-value="leftValue"
|
||||
:base-form-state="compareFormState"
|
||||
:extend-state="extendState"
|
||||
:load-config="loadConfig"
|
||||
:self-diff-field-types="selfDiffFieldTypes"
|
||||
:services="props.services"
|
||||
:size="props.size"
|
||||
height="70vh"
|
||||
/>
|
||||
|
||||
<CodeEditor
|
||||
v-else
|
||||
type="diff"
|
||||
language="json"
|
||||
:init-values="leftValue"
|
||||
:modified-values="rightValue"
|
||||
:options="codeDiffOptions"
|
||||
disabled-full-screen
|
||||
height="70vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<template v-if="isConfirm">
|
||||
<TMagicButton size="small" @click="visible = false">取消</TMagicButton>
|
||||
<TMagicButton size="small" type="primary" @click="onConfirmClick">确定回滚</TMagicButton>
|
||||
</template>
|
||||
</TMagicDialog>
|
||||
</Teleport>
|
||||
<TMagicButton v-else size="small" @click="visible = false">关闭</TMagicButton>
|
||||
</template>
|
||||
</TMagicDialog>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { isEqual } from 'lodash-es';
|
||||
|
||||
import { TMagicButton, TMagicDialog, TMagicRadioButton, TMagicRadioGroup, TMagicTag } from '@tmagic/design';
|
||||
import {
|
||||
type FieldSize,
|
||||
TMagicButton,
|
||||
TMagicDialog,
|
||||
TMagicRadioButton,
|
||||
TMagicRadioGroup,
|
||||
TMagicTag,
|
||||
} from '@tmagic/design';
|
||||
import type { FormState } from '@tmagic/form';
|
||||
|
||||
import CompareForm, { type CompareCategory } from '@editor/components/CompareForm.vue';
|
||||
import CompareForm from '@editor/components/CompareForm.vue';
|
||||
import CodeEditor from '@editor/layouts/CodeEditor.vue';
|
||||
import type { CompareCategory, CompareFormLoadConfig, DiffDialogPayload, Services } from '@editor/type';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorHistoryDiffDialog',
|
||||
});
|
||||
|
||||
defineProps<{
|
||||
/**
|
||||
* 来自 Editor 顶层的 `extendFormState`,用于扩展 MForm.formState。
|
||||
* 透传给 CompareForm,从而让差异对比时表单 item 中依赖业务上下文的
|
||||
* `display` / `disabled` 等 filterFunction 正常工作。
|
||||
*/
|
||||
extendState?: (_state: FormState) => Record<string, any> | Promise<Record<string, any>>;
|
||||
}>();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 编辑器服务集合,由调用方传入(不再通过 inject('services') 获取)。 */
|
||||
services?: Services;
|
||||
/**
|
||||
* 来自 Editor 顶层的 `extendFormState`,用于扩展 MForm.formState。
|
||||
* 透传给 CompareForm,从而让差异对比时表单 item 中依赖业务上下文的
|
||||
* `display` / `disabled` 等 filterFunction 正常工作。
|
||||
*/
|
||||
extendState?: (_state: FormState) => Record<string, any> | Promise<Record<string, any>>;
|
||||
/**
|
||||
* 自定义 FormConfig 加载逻辑,透传给 CompareForm。传入后将接管内置的按 `category`
|
||||
* 取配置逻辑,可通过 `ctx.defaultLoadConfig()` 复用默认结果再做二次加工。
|
||||
*/
|
||||
loadConfig?: CompareFormLoadConfig;
|
||||
width?: string;
|
||||
/** 差异对比表单内组件的尺寸(透传给 CompareForm 的 `size`),可选 'large' | 'default' | 'small'。 */
|
||||
size?: FieldSize;
|
||||
isConfirm?: boolean;
|
||||
onConfirm?: () => void;
|
||||
selfDiffFieldTypes?: string[];
|
||||
compareFormState?: FormState;
|
||||
}>(),
|
||||
{
|
||||
width: '900px',
|
||||
},
|
||||
);
|
||||
|
||||
/** 差异对话框的入参 */
|
||||
export interface DiffDialogPayload {
|
||||
/** 表单类别 */
|
||||
category: CompareCategory;
|
||||
/** 节点类型 / 数据源类型 */
|
||||
type?: string;
|
||||
/** 代码块场景下的数据源类型 */
|
||||
dataSourceType?: string;
|
||||
/** 该 step 修改前的值(oldNode / oldSchema / oldContent) */
|
||||
lastValue: Record<string, any>;
|
||||
/** 该 step 修改后的值(newNode / newSchema / newContent) */
|
||||
value: Record<string, any>;
|
||||
/** 当前编辑器中实际的最新值;不传或为 null 时禁用「与当前对比」 */
|
||||
currentValue?: Record<string, any> | null;
|
||||
/** 用于标题展示的目标名称 */
|
||||
targetLabel?: string;
|
||||
/** 用于标题展示的目标 id */
|
||||
id?: string | number;
|
||||
}
|
||||
const emit = defineEmits(['close']);
|
||||
|
||||
/**
|
||||
* 差异对比模式:
|
||||
@ -146,8 +165,27 @@ const codeDiffOptions = {
|
||||
},
|
||||
};
|
||||
|
||||
const dialogTitle = computed(() => (props.onConfirm ? '确认回滚' : '查看修改差异'));
|
||||
|
||||
const hasCurrent = computed(() => payload.value?.currentValue !== undefined && payload.value?.currentValue !== null);
|
||||
|
||||
/** 是否存在该步「修改后的值」:不存在(如仅删除)时「与修改前对比」无意义,置灰禁用。 */
|
||||
const hasValue = computed(() => payload.value?.value !== undefined && payload.value?.value !== null);
|
||||
|
||||
/** 指定模式当前是否可用:before 依赖「修改后的值」,current 依赖「当前值」。 */
|
||||
const isModeAvailable = (m: DiffMode): boolean => (m === 'current' ? hasCurrent.value : hasValue.value);
|
||||
|
||||
/**
|
||||
* 计算 open 时的初始对比模式:
|
||||
* - 调用方通过 payload.mode 指定且该模式可用时,优先使用指定模式;
|
||||
* - 否则没有「修改后的值」但有当前值时(「与修改前对比」不可用),默认进入「与当前对比」;
|
||||
* - 其余情况默认「与修改前对比」。
|
||||
*/
|
||||
const resolveInitialMode = (specified?: DiffMode): DiffMode => {
|
||||
if (specified && isModeAvailable(specified)) return specified;
|
||||
return !hasValue.value && hasCurrent.value ? 'current' : 'before';
|
||||
};
|
||||
|
||||
/** 左侧(旧/参照)值 */
|
||||
const leftValue = computed<Record<string, any>>(() => {
|
||||
if (!payload.value) return {};
|
||||
@ -171,6 +209,19 @@ const isSameAsCurrent = computed(() => {
|
||||
return isEqual(payload.value.value, payload.value.currentValue);
|
||||
});
|
||||
|
||||
/** confirm() 的 resolve,仅在「等待用户确认回滚」期间存在 */
|
||||
let confirmResolve: ((_value: boolean) => void) | null = null;
|
||||
|
||||
const onConfirmClick = () => {
|
||||
props.onConfirm?.();
|
||||
|
||||
// 用户确认回滚:resolve(true),并清空以避免随后 visible=false 再 resolve(false)
|
||||
confirmResolve?.(true);
|
||||
confirmResolve = null;
|
||||
|
||||
visible.value = false;
|
||||
};
|
||||
|
||||
const targetText = computed(() => {
|
||||
if (!payload.value) return '';
|
||||
const categoryText: Record<CompareCategory, string> = {
|
||||
@ -178,7 +229,8 @@ const targetText = computed(() => {
|
||||
'data-source': '数据源',
|
||||
'code-block': '代码块',
|
||||
};
|
||||
const prefix = categoryText[payload.value.category] || '';
|
||||
const { category } = payload.value;
|
||||
const prefix = category ? categoryText[category] : '';
|
||||
const label = payload.value.targetLabel || payload.value.type || '';
|
||||
const { id } = payload.value;
|
||||
const labelWithId = id !== undefined && id !== '' ? `${label}(${id})` : label;
|
||||
@ -187,13 +239,32 @@ const targetText = computed(() => {
|
||||
|
||||
const open = (p: DiffDialogPayload) => {
|
||||
payload.value = p;
|
||||
// 每次打开按需重置默认模式:有当前值时优先「与当前对比」更贴近"看现在差什么",否则回退到默认
|
||||
mode.value = 'before';
|
||||
// 每次打开按 payload 重置对比模式(hasValue / hasCurrent 依赖 payload,需先赋值):
|
||||
// 优先使用 payload.mode 指定的模式;不可用或未指定时按数据自动推断。
|
||||
mode.value = resolveInitialMode(p.mode);
|
||||
// 默认回到表单对比形态,避免残留上一次选择的源码模式
|
||||
viewMode.value = 'form';
|
||||
visible.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 以 Promise 形式打开确认回滚弹窗:
|
||||
* - 用户点击「确定回滚」时 resolve(true);
|
||||
* - 取消 / 关闭 / 按 Esc 等其他方式关闭弹窗时 resolve(false)。
|
||||
*
|
||||
* 同一时刻只允许一个待确认流程,重复调用会先 resolve(false) 掉上一个。
|
||||
*/
|
||||
const confirm = (p: DiffDialogPayload): Promise<boolean> => {
|
||||
// 终止上一个未完成的确认流程,避免悬挂的 Promise
|
||||
confirmResolve?.(false);
|
||||
confirmResolve = null;
|
||||
|
||||
return new Promise<boolean>((resolve) => {
|
||||
confirmResolve = resolve;
|
||||
open(p);
|
||||
});
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
visible.value = false;
|
||||
};
|
||||
@ -202,11 +273,19 @@ const close = () => {
|
||||
watch(visible, (v) => {
|
||||
if (!v) {
|
||||
payload.value = null;
|
||||
// 非「确定回滚」方式关闭(取消 / Esc / 点遮罩等)时,resolve(false)
|
||||
confirmResolve?.(false);
|
||||
confirmResolve = null;
|
||||
}
|
||||
});
|
||||
|
||||
const onClose = () => {
|
||||
emit('close');
|
||||
};
|
||||
|
||||
defineExpose({
|
||||
open,
|
||||
confirm,
|
||||
close,
|
||||
});
|
||||
</script>
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
popper-class="m-editor-history-list-popover"
|
||||
placement="bottom"
|
||||
trigger="click"
|
||||
:visible="visible"
|
||||
v-model:visible="visible"
|
||||
:width="660"
|
||||
>
|
||||
<div class="m-editor-history-list">
|
||||
@ -18,24 +18,37 @@
|
||||
<TMagicTabs v-model="activeTab" class="m-editor-history-list-tabs">
|
||||
<component
|
||||
:is="tabPaneComponent?.component || 'el-tab-pane'"
|
||||
v-bind="tabPaneComponent?.props({ name: 'page', label: `页面 (${pageGroups.length})` }) || {}"
|
||||
v-bind="
|
||||
tabPaneComponent?.props({ name: 'page', label: `${pageName} (${pageGroups.length})`, lazy: true }) || {}
|
||||
"
|
||||
>
|
||||
<PageTab
|
||||
:list="pageGroupsDisplay"
|
||||
:expanded="expanded"
|
||||
:marker="pageMarker"
|
||||
@toggle="toggleGroup"
|
||||
@goto="onPageGoto"
|
||||
@goto-initial="onPageGotoInitial"
|
||||
@diff-step="onPageDiff"
|
||||
@revert-step="onPageRevert"
|
||||
@select="onPageSelect"
|
||||
@clear="onPageClear"
|
||||
/>
|
||||
</component>
|
||||
|
||||
<component
|
||||
v-if="!disabledDataSource"
|
||||
:is="tabPaneComponent?.component || 'el-tab-pane'"
|
||||
v-bind="tabPaneComponent?.props({ name: 'data-source', label: `数据源 (${dataSourceGroups.length})` }) || {}"
|
||||
v-bind="
|
||||
tabPaneComponent?.props({
|
||||
name: 'data-source',
|
||||
label: `${dataSourceName} (${dataSourceGroups.length})`,
|
||||
lazy: true,
|
||||
}) || {}
|
||||
"
|
||||
>
|
||||
<DataSourceTab
|
||||
<BucketTab
|
||||
:config="dataSourceConfig"
|
||||
:buckets="dataSourceGroupsByTarget"
|
||||
:expanded="expanded"
|
||||
@toggle="toggleGroup"
|
||||
@ -43,14 +56,23 @@
|
||||
@goto-initial="onDataSourceGotoInitial"
|
||||
@diff-step="onDataSourceDiff"
|
||||
@revert-step="onDataSourceRevert"
|
||||
@clear="onDataSourceClear"
|
||||
/>
|
||||
</component>
|
||||
|
||||
<component
|
||||
v-if="!disabledCodeBlock"
|
||||
:is="tabPaneComponent?.component || 'el-tab-pane'"
|
||||
v-bind="tabPaneComponent?.props({ name: 'code-block', label: `代码块 (${codeBlockGroups.length})` }) || {}"
|
||||
v-bind="
|
||||
tabPaneComponent?.props({
|
||||
name: 'code-block',
|
||||
label: `${codeBlockName} (${codeBlockGroups.length})`,
|
||||
lazy: true,
|
||||
}) || {}
|
||||
"
|
||||
>
|
||||
<CodeBlockTab
|
||||
<BucketTab
|
||||
:config="codeBlockConfig"
|
||||
:buckets="codeBlockGroupsByTarget"
|
||||
:expanded="expanded"
|
||||
@toggle="toggleGroup"
|
||||
@ -58,8 +80,18 @@
|
||||
@goto-initial="onCodeBlockGotoInitial"
|
||||
@diff-step="onCodeBlockDiff"
|
||||
@revert-step="onCodeBlockRevert"
|
||||
@clear="onCodeBlockClear"
|
||||
/>
|
||||
</component>
|
||||
|
||||
<component
|
||||
v-for="tab in extraTabs"
|
||||
:key="tab.name"
|
||||
:is="tabPaneComponent?.component || 'el-tab-pane'"
|
||||
v-bind="tabPaneComponent?.props({ name: tab.name, label: resolveTabLabel(tab), lazy: true }) || {}"
|
||||
>
|
||||
<component :is="tab.component" v-bind="tab.props || {}" v-on="tab.listeners || {}" />
|
||||
</component>
|
||||
</TMagicTabs>
|
||||
</div>
|
||||
|
||||
@ -73,16 +105,14 @@
|
||||
</TMagicTooltip>
|
||||
</template>
|
||||
</TMagicPopover>
|
||||
|
||||
<HistoryDiffDialog ref="diffDialog" :extend-state="extendFormState" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 历史记录面板:在顶部 NavMenu 上点击图标打开 popover,分三个 tab:
|
||||
* - 页面:当前活动页面的历史栈,连续修改同一节点的多步会被合并成一组
|
||||
* - 数据源:以 dataSource.id 分组,每组内部相邻的连续 update 自动合并
|
||||
* - 代码块:同上,按 codeBlock.id 分组并合并相邻 update
|
||||
* - 数据源:以 dataSource.id 分桶,每条操作记录独立展示
|
||||
* - 代码块:同上,按 codeBlock.id 分桶,每条操作记录独立展示
|
||||
*
|
||||
* 数据通过 historyService 暴露的聚合 API 读取,UI 仅用于只读展示,
|
||||
* 同时支持点击任意一条记录跳转至该状态:
|
||||
@ -95,23 +125,31 @@
|
||||
* 此外每条 step 上提供"查看差异"入口(仅在前后值都存在的 update 步骤显示),
|
||||
* 点击后弹出 HistoryDiffDialog,使用 CompareForm 组件以表单形式展示新旧值差异。
|
||||
*
|
||||
* 各 tab 的内容拆分为独立的 SFC(PageTab / DataSourceTab / CodeBlockTab),
|
||||
* 各 tab 的内容拆分为独立的 SFC:页面用 PageTab,数据源 / 代码块复用通用的 BucketTab
|
||||
* (通过 title / prefix / describe* / isStepDiffable 注入差异)。
|
||||
* 共享的描述生成与折叠状态在 composables.ts 中维护。
|
||||
*/
|
||||
import { inject, markRaw, ref, useTemplateRef } from 'vue';
|
||||
import { computed, inject, markRaw, ref, watch } from 'vue';
|
||||
import { Clock, Close } from '@element-plus/icons-vue';
|
||||
|
||||
import { getDesignConfig, TMagicButton, TMagicPopover, TMagicTabs, TMagicTooltip } from '@tmagic/design';
|
||||
import { getDesignConfig, TMagicButton, tMagicMessage, TMagicPopover, TMagicTabs, TMagicTooltip } from '@tmagic/design';
|
||||
import type { FormState } from '@tmagic/form';
|
||||
|
||||
import MIcon from '@editor/components/Icon.vue';
|
||||
import { useServices } from '@editor/hooks/use-services';
|
||||
import type {
|
||||
BaseStepValue,
|
||||
CodeBlockStepValue,
|
||||
DataSourceStepValue,
|
||||
HistoryBucketConfig,
|
||||
HistoryListExtraTab,
|
||||
} from '@editor/type';
|
||||
|
||||
import CodeBlockTab from './CodeBlockTab.vue';
|
||||
import { useHistoryList } from './composables';
|
||||
import DataSourceTab from './DataSourceTab.vue';
|
||||
import HistoryDiffDialog from './HistoryDiffDialog.vue';
|
||||
import BucketTab from './BucketTab.vue';
|
||||
import { confirmHistoryAction, describeStep, isSingleDiffStepRevertable } from './composables';
|
||||
import PageTab from './PageTab.vue';
|
||||
import { useHistoryList } from './useHistoryList';
|
||||
import { useHistoryRevert } from './useHistoryRevert';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorHistoryListPanel',
|
||||
@ -119,14 +157,41 @@ defineOptions({
|
||||
|
||||
const ClockIcon = markRaw(Clock);
|
||||
const CloseIcon = markRaw(Close);
|
||||
const activeTab = ref<'page' | 'data-source' | 'code-block'>('page');
|
||||
const activeTab = ref<string>('page');
|
||||
|
||||
/** 面板显隐受控:reference 图标点击切换,右上角关闭按钮置为 false。 */
|
||||
/**
|
||||
* 面板显隐受控:reference 图标点击切换,右上角关闭按钮置为 false。
|
||||
* 点击面板以外区域的自动收起由 TMagicPopover 通过 v-model:visible 回写完成。
|
||||
*/
|
||||
const visible = ref(false);
|
||||
|
||||
const tabPaneComponent = getDesignConfig('components')?.tabPane;
|
||||
|
||||
const { editorService, dataSourceService, codeBlockService, historyService } = useServices();
|
||||
/**
|
||||
* 业务方自定义的扩展 tab,由 Editor 顶层通过 `historyListExtraTabs` 注入。
|
||||
* 追加在内置「页面 / 数据源 / 代码块」三个 tab 之后,未提供时为空数组。
|
||||
*/
|
||||
const extraTabs = inject<HistoryListExtraTab[]>('historyListExtraTabs', []);
|
||||
|
||||
/** label 支持字符串或函数,函数形式便于展示动态数量等内容。 */
|
||||
const resolveTabLabel = (tab: HistoryListExtraTab) => (typeof tab.label === 'function' ? tab.label() : tab.label);
|
||||
|
||||
const services = useServices();
|
||||
const { editorService, dataSourceService, codeBlockService, historyService, propsService, stageOverlayService } =
|
||||
services;
|
||||
|
||||
/**
|
||||
* 数据源 / 代码块功能可被业务方通过 `disabledDataSource` / `disabledCodeBlock` 禁用,
|
||||
* 禁用后对应的历史记录 tab 不再展示。若当前激活的 tab 恰好被禁用,则回退到「页面」tab。
|
||||
*/
|
||||
const disabledDataSource = computed(() => propsService.getDisabledDataSource());
|
||||
const disabledCodeBlock = computed(() => propsService.getDisabledCodeBlock());
|
||||
|
||||
watch([disabledDataSource, disabledCodeBlock], ([dsDisabled, cbDisabled]) => {
|
||||
if ((activeTab.value === 'data-source' && dsDisabled) || (activeTab.value === 'code-block' && cbDisabled)) {
|
||||
activeTab.value = 'page';
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 通过 inject 拿到 Editor 顶层注入的 `extendFormState`,转交给 HistoryDiffDialog
|
||||
@ -137,6 +202,7 @@ const extendFormState = inject<((_state: FormState) => Record<string, any> | Pro
|
||||
'extendFormState',
|
||||
undefined,
|
||||
);
|
||||
const getPropsPanelFormState = inject<(() => FormState | undefined) | undefined>('getPropsPanelFormState', undefined);
|
||||
|
||||
const {
|
||||
expanded,
|
||||
@ -149,6 +215,47 @@ const {
|
||||
codeBlockGroupsByTarget,
|
||||
} = useHistoryList();
|
||||
|
||||
/**
|
||||
* 当前活动页的「加载/初始」标记记录(设置 root 时生成),透传给 PageTab 的底部初始行展示。
|
||||
* 基于 historyService 的 reactive state 派生,活动页切换或标记写入后自动刷新。
|
||||
*/
|
||||
const pageMarker = computed(() => historyService.getMarker('page', editorService.get('page')?.id));
|
||||
|
||||
/**
|
||||
* 各历史类型的展示名称(页面 / 数据源 / 代码块),由 historyService.state.stepNames 配置,
|
||||
* 业务方可通过 historyService.setStepName / registerStepType 覆盖。基于 reactive state 派生,配置变更后自动刷新。
|
||||
*/
|
||||
const pageName = computed(() => historyService.getStepName('page'));
|
||||
const dataSourceName = computed(() => historyService.getStepName('dataSource'));
|
||||
const codeBlockName = computed(() => historyService.getStepName('codeBlock'));
|
||||
|
||||
/** 代码块 step 仅 update(前后 content 都存在)时可查看差异。 */
|
||||
const isStepDiffable = (step: BaseStepValue) => Boolean(step.diff?.[0]?.oldSchema && step.diff?.[0]?.newSchema);
|
||||
|
||||
/**
|
||||
* 数据源 / 代码块两类 bucket 历史的整体渲染配置:把 title / prefix 与各自的描述、
|
||||
* 可差异、可回滚判定收敛为单一对象整体注入 BucketTab,组件内部按需读取。
|
||||
* title / 描述回退名取自可配置的展示名称,故用 computed 使其随 stepNames 变更刷新。
|
||||
*/
|
||||
// 数据源/代码块不做相邻合并,每组恒为单步,省略 describeGroup,由 toRowGroup 回退到 describeStep。
|
||||
const dataSourceConfig = computed<HistoryBucketConfig<DataSourceStepValue>>(() => ({
|
||||
title: dataSourceName.value,
|
||||
prefix: 'ds',
|
||||
describeStep: (step: DataSourceStepValue): string =>
|
||||
describeStep(step, (schema) => schema?.title, dataSourceName.value),
|
||||
isStepDiffable,
|
||||
isStepRevertable: isSingleDiffStepRevertable,
|
||||
}));
|
||||
|
||||
const codeBlockConfig = computed<HistoryBucketConfig<CodeBlockStepValue>>(() => ({
|
||||
title: codeBlockName.value,
|
||||
prefix: 'cb',
|
||||
describeStep: (step: CodeBlockStepValue): string =>
|
||||
describeStep(step, (content) => content?.name, codeBlockName.value),
|
||||
isStepDiffable,
|
||||
isStepRevertable: isSingleDiffStepRevertable,
|
||||
}));
|
||||
|
||||
/** 把"目标 step 索引"翻译成"目标 cursor"(已应用步骤数量)。 */
|
||||
const indexToCursor = (index: number) => index + 1;
|
||||
|
||||
@ -156,6 +263,29 @@ const onPageGoto = (index: number) => {
|
||||
editorService.gotoPageStep(indexToCursor(index));
|
||||
};
|
||||
|
||||
/**
|
||||
* 点击页面历史记录行:选中该记录对应的画布节点。
|
||||
* - 从目标 step 的 diff 中取节点 id(优先 newSchema,回退 oldSchema),按出现顺序找到第一个当前仍存在的节点;
|
||||
* - 与图层树点击选中一致:editorService.select + 画布 / overlay 画布 select 三者联动;
|
||||
* - 该 step 涉及的节点都已不存在(如删除记录、被撤销的新增)时给出提示,不做选中。
|
||||
*/
|
||||
const onPageSelect = async (index: number) => {
|
||||
const step = historyService.getStepList('page', editorService.get('page')?.id)[index]?.step;
|
||||
if (!step) return;
|
||||
const targetId = (step.diff ?? [])
|
||||
.map((item) => item.newSchema?.id ?? item.oldSchema?.id)
|
||||
.find((id) => id !== undefined && id !== null && editorService.getNodeById(id, false));
|
||||
if (targetId === undefined || targetId === null) {
|
||||
tMagicMessage.warning('该记录对应的节点已不存在,无法选中');
|
||||
return;
|
||||
}
|
||||
const node = editorService.getNodeById(targetId, false);
|
||||
if (!node) return;
|
||||
await editorService.select(node);
|
||||
editorService.get('stage')?.select(targetId);
|
||||
stageOverlayService.get('stage')?.select(targetId);
|
||||
};
|
||||
|
||||
const onDataSourceGoto = (id: string | number, index: number) => {
|
||||
dataSourceService.goto(id, indexToCursor(index));
|
||||
};
|
||||
@ -181,91 +311,57 @@ const onCodeBlockGotoInitial = (id: string | number) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* 「回滚」入口:把目标历史步骤的修改作为一次新操作反向应用(类 git revert),
|
||||
* 不破坏原有栈结构。各 service 内部完成反向 + 入栈,并自带描述用于面板展示。
|
||||
* 「单步回滚」与「查看差异」的完整逻辑收敛到 useHistoryRevert,面板与业务方共用:
|
||||
* 二者均由 useHistoryRevert 内部按需动态挂载 HistoryDiffDialog,
|
||||
* 业务方亦可直接 import useHistoryRevert(options, services) 调用,无需自行挂载任何弹窗。
|
||||
*/
|
||||
const onPageRevert = (index: number) => {
|
||||
editorService.revertPageStep(index);
|
||||
};
|
||||
|
||||
const onDataSourceRevert = (id: string | number, index: number) => {
|
||||
dataSourceService.revert(id, index);
|
||||
};
|
||||
|
||||
const onCodeBlockRevert = (id: string | number, index: number) => {
|
||||
codeBlockService.revert(id, index);
|
||||
};
|
||||
|
||||
const diffDialogRef = useTemplateRef<InstanceType<typeof HistoryDiffDialog>>('diffDialog');
|
||||
const { onPageRevert, onDataSourceRevert, onCodeBlockRevert, onPageDiff, onDataSourceDiff, onCodeBlockDiff } =
|
||||
useHistoryRevert({ extendState: extendFormState, getPropsPanelFormState }, services);
|
||||
|
||||
/**
|
||||
* 页面 step 差异:仅 update 单节点修改可对比,传入旧/新节点。
|
||||
* 节点类型 `type` 优先取 newNode.type,再回退 oldNode.type。
|
||||
* `currentValue` 取自 editorService 中该节点当前实际值,用于支持「与当前对比」。
|
||||
* 把内存中(已清空对应类别后的)历史状态重新写回 IndexedDB,
|
||||
* 使本地持久化的那份与内存保持一致——即「连同本地保存的一并删除」。
|
||||
* 不支持 IndexedDB 或写入失败时静默忽略(内存清空已生效)。
|
||||
*/
|
||||
const onPageDiff = (index: number) => {
|
||||
const groups = historyService.getPageHistoryGroups();
|
||||
for (const group of groups) {
|
||||
const entry = group.steps.find((s) => s.index === index);
|
||||
if (!entry) continue;
|
||||
const item = entry.step.updatedItems?.[0];
|
||||
if (!item?.oldNode || !item?.newNode) return;
|
||||
const type = (item.newNode.type as string) || (item.oldNode.type as string) || '';
|
||||
const nodeId = item.newNode.id ?? item.oldNode.id;
|
||||
const currentNode = nodeId !== undefined ? editorService.getNodeById(nodeId) : null;
|
||||
diffDialogRef.value?.open({
|
||||
category: 'node',
|
||||
type,
|
||||
lastValue: item.oldNode as Record<string, any>,
|
||||
value: item.newNode as Record<string, any>,
|
||||
currentValue: (currentNode as Record<string, any>) || null,
|
||||
targetLabel: (item.newNode.name as string) || (item.oldNode.name as string) || type,
|
||||
id: nodeId,
|
||||
});
|
||||
return;
|
||||
const syncIndexedDB = async () => {
|
||||
try {
|
||||
await historyService.saveToIndexedDB();
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
} catch (e) {
|
||||
// ignore: 内存清空已生效,本地同步失败不阻塞交互
|
||||
}
|
||||
};
|
||||
|
||||
const onDataSourceDiff = (id: string | number, index: number) => {
|
||||
const groups = historyService.getDataSourceHistoryGroups();
|
||||
for (const group of groups) {
|
||||
if (group.id !== id) continue;
|
||||
const entry = group.steps.find((s) => s.index === index);
|
||||
if (!entry) continue;
|
||||
const { oldSchema, newSchema } = entry.step;
|
||||
if (!oldSchema || !newSchema) return;
|
||||
const currentSchema = dataSourceService.getDataSourceById(`${id}`);
|
||||
diffDialogRef.value?.open({
|
||||
category: 'data-source',
|
||||
type: newSchema.type || oldSchema.type || 'base',
|
||||
lastValue: oldSchema as Record<string, any>,
|
||||
value: newSchema as Record<string, any>,
|
||||
currentValue: (currentSchema as Record<string, any>) || null,
|
||||
targetLabel: newSchema.title || oldSchema.title || `${id}`,
|
||||
id,
|
||||
});
|
||||
return;
|
||||
const onPageClear = async () => {
|
||||
if (
|
||||
await confirmHistoryAction(
|
||||
'确定清空当前页面的历史记录吗?清空后将无法撤销/重做之前的操作,本地保存的记录也会一并删除。',
|
||||
)
|
||||
) {
|
||||
historyService.clear('page', editorService.get('page')?.id);
|
||||
await syncIndexedDB();
|
||||
}
|
||||
};
|
||||
|
||||
const onCodeBlockDiff = (id: string | number, index: number) => {
|
||||
const groups = historyService.getCodeBlockHistoryGroups();
|
||||
for (const group of groups) {
|
||||
if (group.id !== id) continue;
|
||||
const entry = group.steps.find((s) => s.index === index);
|
||||
if (!entry) continue;
|
||||
const { oldContent, newContent } = entry.step;
|
||||
if (!oldContent || !newContent) return;
|
||||
const currentContent = codeBlockService.getCodeContentById(id);
|
||||
diffDialogRef.value?.open({
|
||||
category: 'code-block',
|
||||
lastValue: oldContent as Record<string, any>,
|
||||
value: newContent as Record<string, any>,
|
||||
currentValue: (currentContent as Record<string, any>) || null,
|
||||
targetLabel: newContent.name || oldContent.name || `${id}`,
|
||||
id,
|
||||
});
|
||||
return;
|
||||
const onDataSourceClear = async () => {
|
||||
if (
|
||||
await confirmHistoryAction(
|
||||
'确定清空数据源的历史记录吗?清空后将无法撤销/重做之前的操作,本地保存的记录也会一并删除。',
|
||||
)
|
||||
) {
|
||||
historyService.clear('dataSource');
|
||||
await syncIndexedDB();
|
||||
}
|
||||
};
|
||||
|
||||
const onCodeBlockClear = async () => {
|
||||
if (
|
||||
await confirmHistoryAction(
|
||||
'确定清空代码块的历史记录吗?清空后将无法撤销/重做之前的操作,本地保存的记录也会一并删除。',
|
||||
)
|
||||
) {
|
||||
historyService.clear('codeBlock');
|
||||
await syncIndexedDB();
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
@ -2,13 +2,16 @@
|
||||
<li
|
||||
class="m-editor-history-list-item m-editor-history-list-initial"
|
||||
:class="{ 'is-current': isCurrent, 'is-clickable': !isCurrent }"
|
||||
:title="isCurrent ? '当前已回到未修改的初始状态' : '点击回到未修改的初始状态'"
|
||||
@click="onClick"
|
||||
:title="rowTitle"
|
||||
>
|
||||
<span class="m-editor-history-list-item-index" title="历史步骤编号 #0(未修改的初始状态)">#0</span>
|
||||
<span class="m-editor-history-list-item-op op-initial">初始</span>
|
||||
<span class="m-editor-history-list-item-desc">未修改的初始状态</span>
|
||||
<span v-if="isCurrent" class="m-editor-history-list-item-current">当前</span>
|
||||
<span class="m-editor-history-list-item-desc">{{ desc }}</span>
|
||||
<span v-if="saved" class="m-editor-history-list-item-saved" title="该记录为最近一次保存的状态">已保存</span>
|
||||
<span v-if="gotoEnabled && !isCurrent" class="m-editor-history-list-item-actions">
|
||||
<span class="m-editor-history-list-item-goto" title="回到该记录" @click.stop="onClick">回到</span>
|
||||
</span>
|
||||
<span v-if="time" class="m-editor-history-list-item-time" :title="timeTitle">{{ time }}</span>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
@ -17,17 +20,44 @@
|
||||
* 「初始状态」记录行:渲染于历史列表底部,作为整个栈的"零点"。
|
||||
* - 点击该行会把对应栈撤销到 cursor === 0(即没有任何已应用步骤),等同于回到所有修改之前。
|
||||
* - 当对应栈本身已处于 cursor === 0 时(isCurrent=true),用户已在初始状态,点击不再触发动作。
|
||||
* - 当上层传入 `marker`(设置 root 时为该页生成的「未修改的初始状态」标记)时,
|
||||
* 用标记的文案与时间渲染本行;标记不进入撤销/重做栈,仅作为该页基线展示。
|
||||
*
|
||||
* 该行不是真实 step,仅作为 UI 入口;上层负责把"点击"翻译为 `service.goto*(0)`。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
|
||||
import type { StepValue } from '@editor/type';
|
||||
|
||||
import { formatHistoryFullTime, formatHistoryTime } from './composables';
|
||||
|
||||
defineOptions({
|
||||
name: 'MEditorHistoryListInitialRow',
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
/** 当前对应栈是否已经处于初始状态 (cursor === 0)。true 时用蓝条高亮并禁用点击。 */
|
||||
isCurrent: boolean;
|
||||
}>();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 当前对应栈是否已经处于初始状态 (cursor === 0)。true 时用蓝条高亮并禁用点击。 */
|
||||
isCurrent: boolean;
|
||||
gotoEnabled?: boolean;
|
||||
/** 该页面的「加载/初始」基线记录(设置 root 时生成的 `opType: 'initial'` StepValue);提供时用其文案与时间展示。 */
|
||||
marker?: StepValue;
|
||||
}>(),
|
||||
{
|
||||
gotoEnabled: true,
|
||||
marker: undefined,
|
||||
},
|
||||
);
|
||||
|
||||
const desc = computed(() => props.marker?.historyDescription || '未修改的初始状态');
|
||||
/** 基线(初始状态)是否为最近一次保存点:仅页面栈的 `initial` 基线 step 会被 markSaved 标记。 */
|
||||
const saved = computed(() => Boolean(props.marker?.saved));
|
||||
const time = computed(() => formatHistoryTime(props.marker?.timestamp));
|
||||
const timeTitle = computed(() => formatHistoryFullTime(props.marker?.timestamp));
|
||||
const rowTitle = computed(() => {
|
||||
const base = props.marker?.historyDescription || '未修改的初始状态';
|
||||
return props.isCurrent ? `当前已回到${base}` : `点击回到${base}`;
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 点击非当前的初始项时触发,由上层调用对应 service 的 goto 把 cursor 移到 0。 */
|
||||
|
||||
@ -1,40 +1,32 @@
|
||||
<template>
|
||||
<div v-if="!list.length" class="m-editor-history-list-empty">暂无操作记录</div>
|
||||
<TMagicScrollbar v-else max-height="360px">
|
||||
<ul class="m-editor-history-list-ul">
|
||||
<GroupRow
|
||||
v-for="(group, gIdx) in list"
|
||||
:key="`pg-${gIdx}`"
|
||||
:group-key="`pg-${gIdx}`"
|
||||
:applied="group.applied"
|
||||
:merged="group.steps.length > 1"
|
||||
:op-type="group.opType"
|
||||
:desc="describePageGroup(group)"
|
||||
:step-count="group.steps.length"
|
||||
:sub-steps="
|
||||
group.steps.map((s) => ({
|
||||
index: s.index,
|
||||
applied: s.applied,
|
||||
isCurrent: s.isCurrent,
|
||||
desc: describePageStep(s.step),
|
||||
diffable: isPageStepDiffable(s.step),
|
||||
revertable: s.applied,
|
||||
}))
|
||||
"
|
||||
:is-current="group.isCurrent"
|
||||
:expanded="!!expanded[`pg-${gIdx}`]"
|
||||
@toggle="(key: string) => $emit('toggle', key)"
|
||||
@goto="(index: number) => $emit('goto', index)"
|
||||
@diff-step="(index: number) => $emit('diff-step', index)"
|
||||
@revert-step="(index: number) => $emit('revert-step', index)"
|
||||
/>
|
||||
<!--
|
||||
<div v-if="!list.length && !marker" class="m-editor-history-list-empty">暂无操作记录</div>
|
||||
<template v-else>
|
||||
<div v-if="list.length" class="m-editor-history-list-toolbar">
|
||||
<span class="m-editor-history-list-clear" title="清空当前页面的历史记录" @click="$emit('clear')">清空</span>
|
||||
</div>
|
||||
<TMagicScrollbar max-height="360px">
|
||||
<ul class="m-editor-history-list-ul">
|
||||
<GroupRow
|
||||
v-for="group in list"
|
||||
:key="rowKey(group)"
|
||||
:group="toRow(group)"
|
||||
:expanded="isHistoryGroupExpanded(expanded, rowKey(group))"
|
||||
:select-enabled="true"
|
||||
@toggle="(key: string) => $emit('toggle', key)"
|
||||
@goto="(index: number) => $emit('goto', index)"
|
||||
@diff-step="(index: number) => $emit('diff-step', index)"
|
||||
@revert-step="(index: number) => $emit('revert-step', index)"
|
||||
@select="(index: number) => $emit('select', index)"
|
||||
/>
|
||||
<!--
|
||||
初始状态项:永远位于列表底部(页面 tab 倒序展示,最底部=最早),
|
||||
作为"未修改"零点。当所有 group 都未 applied 时它即为当前位置。
|
||||
设置 root 时生成的「未修改的初始状态」标记(marker)会作为该行的文案与时间来源。
|
||||
-->
|
||||
<InitialRow :is-current="isInitial" @goto-initial="$emit('goto-initial')" />
|
||||
</ul>
|
||||
</TMagicScrollbar>
|
||||
<InitialRow :is-current="isInitial" :marker="marker" @goto-initial="$emit('goto-initial')" />
|
||||
</ul>
|
||||
</TMagicScrollbar>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
@ -42,9 +34,16 @@ import { computed } from 'vue';
|
||||
|
||||
import { TMagicScrollbar } from '@tmagic/design';
|
||||
|
||||
import type { PageHistoryGroup, StepValue } from '@editor/type';
|
||||
import type { HistoryGroup, HistoryRowDescriptor, StepValue } from '@editor/type';
|
||||
|
||||
import { describePageGroup, describePageStep } from './composables';
|
||||
import type { HistoryRowGroup } from './composables';
|
||||
import {
|
||||
describePageGroup,
|
||||
describePageStep,
|
||||
isHistoryGroupExpanded,
|
||||
isPageStepRevertable,
|
||||
toRowGroup,
|
||||
} from './composables';
|
||||
import GroupRow from './GroupRow.vue';
|
||||
import InitialRow from './InitialRow.vue';
|
||||
|
||||
@ -54,9 +53,18 @@ defineOptions({
|
||||
|
||||
const props = defineProps<{
|
||||
/** 当前活动页面的历史分组列表,已按时间倒序排好(最新一组在最前)。空数组时显示空态。 */
|
||||
list: PageHistoryGroup[];
|
||||
/** 共享的折叠状态表(key -> 是否展开),由顶层 panel 统一维护。本 tab 使用 `pg-${idx}` 作为 key。 */
|
||||
list: HistoryGroup<StepValue>[];
|
||||
/**
|
||||
* 共享的折叠状态表(key -> 是否展开,缺省或 true 为展开、false 为收起),由顶层 panel 统一维护。
|
||||
* 本 tab 使用 `pg-${组内首步 index}` 作为 key——以稳定的 step 索引而非展示位置标识分组,
|
||||
* 这样历史数据更新(新增 / 撤销重做导致列表顺序变化)后,已展开的分组状态仍能正确保持。
|
||||
*/
|
||||
expanded: Record<string, boolean>;
|
||||
/**
|
||||
* 当前活动页的「加载/初始」基线记录(设置 root 时生成的 `opType: 'initial'` StepValue)。
|
||||
* 提供时即使没有任何操作记录也会展示底部初始行,并用其文案 / 时间渲染。
|
||||
*/
|
||||
marker?: StepValue;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
@ -70,25 +78,41 @@ defineEmits<{
|
||||
(_e: 'diff-step', _index: number): void;
|
||||
/** 用户点击"回滚"按钮,携带目标 step 在栈中的索引,类 git revert。 */
|
||||
(_e: 'revert-step', _index: number): void;
|
||||
/** 用户点击记录行希望选中对应节点,携带目标 step 在栈中的索引。 */
|
||||
(_e: 'select', _index: number): void;
|
||||
/** 用户点击"清空"按钮,请求清空当前页面的历史记录(由上层弹窗二次确认后执行)。 */
|
||||
(_e: 'clear'): void;
|
||||
}>();
|
||||
|
||||
/**
|
||||
* 当前 step 是否可查看差异:
|
||||
* - 仅 update 操作;
|
||||
* - 单节点更新(updatedItems.length === 1),且 oldNode / newNode 都存在。
|
||||
* - 单节点更新(diff.length === 1),且 oldSchema / newSchema 都存在。
|
||||
* 多节点更新难以选定单一对比目标,统一不展示差异入口。
|
||||
*/
|
||||
const isPageStepDiffable = (step: StepValue): boolean => {
|
||||
if (step.opType !== 'update') return false;
|
||||
const items = step.updatedItems ?? [];
|
||||
const items = step.diff ?? [];
|
||||
if (items.length !== 1) return false;
|
||||
return Boolean(items[0]?.oldNode && items[0]?.newNode);
|
||||
return Boolean(items[0]?.oldSchema && items[0]?.newSchema);
|
||||
};
|
||||
|
||||
/** 页面历史的描述 / 可操作性判定集合,注入给统一的 `toRowGroup`。 */
|
||||
const descriptor: HistoryRowDescriptor<StepValue> = {
|
||||
describeGroup: describePageGroup,
|
||||
describeStep: describePageStep,
|
||||
isStepDiffable: isPageStepDiffable,
|
||||
isStepRevertable: isPageStepRevertable,
|
||||
};
|
||||
|
||||
const rowKey = (group: HistoryGroup<StepValue>) => `pg-${group.steps[0]?.index}`;
|
||||
|
||||
const toRow = (group: HistoryGroup<StepValue>): HistoryRowGroup => toRowGroup(group, rowKey(group), descriptor);
|
||||
|
||||
/**
|
||||
* 是否处于"初始状态"——即对应页面历史栈 cursor===0:
|
||||
* 当 list 中所有 group 的 applied 都为 false 时即为该状态。
|
||||
* 没有任何 group 的情况由外层"暂无操作记录"分支兜底,本计算可以不考虑。
|
||||
* 当 list 中所有 group 的 applied 都为 false 时即为该状态(空列表 `every` 返回 true,
|
||||
* 即仅有 marker、无任何操作记录时也视为处于初始状态)。
|
||||
*/
|
||||
const isInitial = computed(() => props.list.length > 0 && props.list.every((g) => !g.applied));
|
||||
const isInitial = computed(() => props.list.every((g) => !g.applied));
|
||||
</script>
|
||||
|
||||
@ -1,69 +1,106 @@
|
||||
import { computed, reactive } from 'vue';
|
||||
import { tMagicMessageBox } from '@tmagic/design';
|
||||
import { datetimeFormatter } from '@tmagic/form';
|
||||
|
||||
import { useServices } from '@editor/hooks/use-services';
|
||||
import type {
|
||||
CodeBlockHistoryGroup,
|
||||
CodeBlockStepValue,
|
||||
DataSourceHistoryGroup,
|
||||
DataSourceStepValue,
|
||||
BaseStepValue,
|
||||
HistoryGroup,
|
||||
HistoryOpSource,
|
||||
HistoryOpType,
|
||||
PageHistoryGroup,
|
||||
HistoryRowDescriptor,
|
||||
StepValue,
|
||||
} from '@editor/type';
|
||||
|
||||
/**
|
||||
* 历史记录面板共享逻辑:
|
||||
* - 暴露三类历史的聚合数据(页面 / 数据源 / 代码块);
|
||||
* - 提供折叠状态管理;
|
||||
* - 提供操作描述文案生成器。
|
||||
*
|
||||
* 所有数据基于 historyService 的 reactive state 派生,自动跟随历史变化刷新。
|
||||
* 通用 bucket 分组(数据源 / 代码块及业务自定义历史)在面板中的展示结构。
|
||||
* 由 Bucket / BucketTab 复用,step 类型通过泛型 T 收窄(约束为 {@link BaseStepValue})。
|
||||
*/
|
||||
export const useHistoryList = () => {
|
||||
const { historyService } = useServices();
|
||||
export interface HistoryBucketGroup<T extends BaseStepValue = BaseStepValue> {
|
||||
/** 组内最后一步是否已应用 */
|
||||
applied: boolean;
|
||||
/** 是否为当前所在的分组 */
|
||||
isCurrent?: boolean;
|
||||
/** 该分组的操作类型 */
|
||||
opType: HistoryOpType;
|
||||
/** 组内所有步骤 */
|
||||
steps: { index: number; applied: boolean; isCurrent?: boolean; step: T }[];
|
||||
}
|
||||
|
||||
/** 折叠状态:key 形如 `pg-${groupIdx}` / `ds-${id}-${groupIdx}` / `cb-${id}-${groupIdx}`。 */
|
||||
const expanded = reactive<Record<string, boolean>>({});
|
||||
const toggleGroup = (key: string) => {
|
||||
expanded[key] = !expanded[key];
|
||||
};
|
||||
/**
|
||||
* GroupRow 的组头部与子步共用的展示字段(均由 {@link toRowGroup} 预先派生)。
|
||||
* 抽出公共部分避免 {@link HistoryRowStep} / {@link HistoryRowGroup} 重复声明,
|
||||
* 也便于消费方用本类型收窄「组头 / 子步」通用渲染逻辑的入参。
|
||||
*/
|
||||
export interface HistoryRowDisplay {
|
||||
/** 是否已应用(false 表示已被 undo,UI 灰态)。 */
|
||||
applied: boolean;
|
||||
/** 是否为当前所在步骤 / 分组。 */
|
||||
isCurrent: boolean;
|
||||
/** 描述文案。 */
|
||||
desc: string;
|
||||
/** 操作途径。 */
|
||||
source?: HistoryOpSource;
|
||||
/** 操作人。 */
|
||||
operator?: string;
|
||||
/** 时间文案。 */
|
||||
time?: string;
|
||||
/** 时间的完整 title 提示。 */
|
||||
timeTitle?: string;
|
||||
}
|
||||
|
||||
const pageGroups = computed(() => historyService.getPageHistoryGroups());
|
||||
const dataSourceGroups = computed(() => historyService.getDataSourceHistoryGroups());
|
||||
const codeBlockGroups = computed(() => historyService.getCodeBlockHistoryGroups());
|
||||
/** GroupRow 渲染所需的单个子步视图模型(已由 {@link toRowGroup} 预先派生,组件内部不再触碰原始 step)。 */
|
||||
export interface HistoryRowStep extends HistoryRowDisplay {
|
||||
/** 该子步在所属栈中的稳定索引。 */
|
||||
index: number;
|
||||
/** 是否为最近一次保存的记录。 */
|
||||
saved?: boolean;
|
||||
/** 是否可查看差异。 */
|
||||
diffable?: boolean;
|
||||
/** 是否可回滚。 */
|
||||
revertable?: boolean;
|
||||
}
|
||||
|
||||
/** 页面 tab 倒序展示(最新一组在最上面)。 */
|
||||
const pageGroupsDisplay = computed(() => pageGroups.value.slice().reverse());
|
||||
/**
|
||||
* GroupRow 渲染所需的整组视图模型(由 {@link toRowGroup} 统一派生)。
|
||||
* 把原先 GroupRow 上十多个扁平 props 收敛为单一对象,header 信息与子步列表一并携带。
|
||||
*/
|
||||
export interface HistoryRowGroup extends HistoryRowDisplay {
|
||||
/** 分组的稳定 key,作为 toggle 事件 payload 与折叠状态的索引。 */
|
||||
key: string;
|
||||
/** 操作类型,用于徽标颜色与文案。 */
|
||||
opType: HistoryOpType;
|
||||
/** 子步列表(时间正序);其长度即合并步数,length > 1 即为合并组。 */
|
||||
subSteps: HistoryRowStep[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 把按时间正序的 group 列表,再按 id 聚拢成 bucket(同 id 的所有分组放一起)。
|
||||
* 每个 bucket 内部仍然按时间倒序展示(最近的操作最先看到)。
|
||||
*/
|
||||
const groupByTarget = <G extends { id: string | number }>(groups: G[]) => {
|
||||
const map = new Map<string | number, G[]>();
|
||||
groups.forEach((g) => {
|
||||
const list = map.get(g.id) ?? [];
|
||||
list.push(g);
|
||||
map.set(g.id, list);
|
||||
});
|
||||
return Array.from(map.entries()).map(([id, gs]) => ({ id, groups: gs.slice().reverse() }));
|
||||
};
|
||||
/** 合并组默认展开;仅当 expanded[key] === false 时为收起。 */
|
||||
export const isHistoryGroupExpanded = (expanded: Record<string, boolean>, key: string) => expanded[key] !== false;
|
||||
|
||||
const dataSourceGroupsByTarget = computed(() => groupByTarget(dataSourceGroups.value));
|
||||
const codeBlockGroupsByTarget = computed(() => groupByTarget(codeBlockGroups.value));
|
||||
|
||||
return {
|
||||
expanded,
|
||||
toggleGroup,
|
||||
pageGroups,
|
||||
dataSourceGroups,
|
||||
codeBlockGroups,
|
||||
pageGroupsDisplay,
|
||||
dataSourceGroupsByTarget,
|
||||
codeBlockGroupsByTarget,
|
||||
};
|
||||
/**
|
||||
* 历史面板的时间展示:
|
||||
* - 当天的记录只显示 `HH:mm:ss`;
|
||||
* - 跨天的记录显示 `MM-DD HH:mm:ss`。
|
||||
* 无时间戳(旧数据 / 未写入)时返回空串,UI 据此不渲染时间。
|
||||
*/
|
||||
export const formatHistoryTime = (timestamp?: number): string => {
|
||||
if (!timestamp) return '';
|
||||
const isToday =
|
||||
datetimeFormatter(new Date(timestamp), '', 'YYYY-MM-DD') ===
|
||||
(datetimeFormatter(new Date(), '', 'YYYY-MM-DD') as string);
|
||||
return `${
|
||||
isToday
|
||||
? datetimeFormatter(new Date(timestamp), '', 'HH:mm:ss')
|
||||
: datetimeFormatter(new Date(timestamp), '', 'MM-DD HH:mm:ss')
|
||||
}`;
|
||||
};
|
||||
|
||||
/** 完整时间(含年份与秒),用于 title 悬浮提示。无时间戳时返回空串。 */
|
||||
export const formatHistoryFullTime = (timestamp?: number): string =>
|
||||
timestamp ? `${datetimeFormatter(new Date(timestamp), '', 'YYYY-MM-DD HH:mm:ss')}` : '';
|
||||
|
||||
/** 取一组历史步骤里最后一步(最近一次)的时间戳,用于组头部展示。 */
|
||||
export const groupTimestamp = (group: { steps: { step: { timestamp?: number } }[] }): number | undefined =>
|
||||
group.steps[group.steps.length - 1]?.step.timestamp;
|
||||
|
||||
export const opLabel = (op: HistoryOpType) => {
|
||||
switch (op) {
|
||||
case 'add':
|
||||
@ -76,7 +113,88 @@ export const opLabel = (op: HistoryOpType) => {
|
||||
}
|
||||
};
|
||||
|
||||
const nameOf = (node: { name?: string; id?: string | number; type?: string }) =>
|
||||
/** 内置操作途径的中文文案;自定义来源直接回显原值,未知 / 缺省返回空串(UI 据此不渲染)。 */
|
||||
const HISTORY_SOURCE_LABELS: Record<string, string> = {
|
||||
stage: '画布',
|
||||
tree: '树面板',
|
||||
'component-panel': '组件面板',
|
||||
props: '配置面板',
|
||||
code: '源码',
|
||||
'root-code': 'DSL源码',
|
||||
'stage-contextmenu': '画布菜单',
|
||||
'tree-contextmenu': '树菜单',
|
||||
toolbar: '工具栏',
|
||||
shortcut: '快捷键',
|
||||
rollback: '回滚',
|
||||
api: '接口',
|
||||
ai: 'AI',
|
||||
initial: '初始值',
|
||||
sync: '同步',
|
||||
unknown: '未知',
|
||||
};
|
||||
|
||||
/** 操作途径文案:用于历史面板展示「画布 / 树面板 / 配置面板…」标签。 */
|
||||
export const sourceLabel = (source: HistoryOpSource = 'unknown'): string => {
|
||||
return HISTORY_SOURCE_LABELS[source] ?? `${source}`;
|
||||
};
|
||||
|
||||
/** 取一组历史步骤里最后一步(最近一次)的操作途径,用于组头部展示。 */
|
||||
export const groupSource = (group: { steps: { step: { source?: HistoryOpSource } }[] }): HistoryOpSource | undefined =>
|
||||
group.steps[group.steps.length - 1]?.step.source;
|
||||
|
||||
/** 取一组历史步骤里最后一步(最近一次)的操作人,用于组头部展示。 */
|
||||
export const groupOperator = (group: { steps: { step: { operator?: string } }[] }): string | undefined =>
|
||||
group.steps[group.steps.length - 1]?.step.operator;
|
||||
|
||||
/** {@link toRowGroup} 接受的最小分组结构 */
|
||||
interface RowGroupInput<T extends BaseStepValue = BaseStepValue> {
|
||||
applied: boolean;
|
||||
isCurrent?: boolean;
|
||||
opType: HistoryOpType;
|
||||
steps: { index: number; applied: boolean; isCurrent?: boolean; step: T }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一个历史分组(页面 / bucket)派生为 GroupRow 直接消费的视图模型 {@link HistoryRowGroup}。
|
||||
* 统一了原先 PageTab / Bucket 各自内联的 sub-steps 映射逻辑:描述、可差异、可回滚、时间、途径
|
||||
* 全部在此一次性算好,组件层只负责渲染。
|
||||
*/
|
||||
export const toRowGroup = <T extends BaseStepValue = BaseStepValue>(
|
||||
group: RowGroupInput<T>,
|
||||
key: string,
|
||||
descriptor: HistoryRowDescriptor<T>,
|
||||
): HistoryRowGroup => {
|
||||
const { describeGroup, describeStep, isStepDiffable, isStepRevertable } = descriptor;
|
||||
const timestamp = groupTimestamp(group);
|
||||
// 无 describeGroup 时回退到组内最后一步的 describeStep:数据源/代码块不做相邻合并,每组恒为单步,二者等价。
|
||||
const lastStep = group.steps[group.steps.length - 1]?.step;
|
||||
return {
|
||||
key,
|
||||
applied: group.applied,
|
||||
isCurrent: Boolean(group.isCurrent),
|
||||
opType: group.opType,
|
||||
desc: describeGroup ? describeGroup(group) : describeStep(lastStep),
|
||||
source: groupSource(group),
|
||||
operator: groupOperator(group),
|
||||
time: formatHistoryTime(timestamp),
|
||||
timeTitle: formatHistoryFullTime(timestamp),
|
||||
subSteps: group.steps.map((s) => ({
|
||||
index: s.index,
|
||||
applied: s.applied,
|
||||
isCurrent: Boolean(s.isCurrent),
|
||||
saved: s.step.saved,
|
||||
desc: describeStep(s.step),
|
||||
diffable: isStepDiffable ? isStepDiffable(s.step) : false,
|
||||
revertable: s.applied && (isStepRevertable ? isStepRevertable(s.step) : true),
|
||||
source: s.step.source,
|
||||
operator: s.step.operator,
|
||||
time: formatHistoryTime(s.step.timestamp),
|
||||
timeTitle: formatHistoryFullTime(s.step.timestamp),
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const nameOf = (node?: { name?: string; id?: string | number; type?: string }) =>
|
||||
node?.name || node?.type || `${node?.id ?? ''}`;
|
||||
|
||||
/**
|
||||
@ -98,98 +216,94 @@ const pickLastDescription = (descs: (string | undefined)[]): string | undefined
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const describePageStep = (step: StepValue) => {
|
||||
/**
|
||||
* 页面 / 数据源 / 代码块三类历史共用的单步描述核心。
|
||||
* 各类型只在「取展示名」与「实体单位名」上有差异,通过参数注入,文案模板完全一致:
|
||||
* - 新增 / 删除:单实体展示「label」,多实体(仅页面可能出现)退化为「N 个X」;
|
||||
* - 修改:展示「label · propPath」,无 diff 时兜底「X」,多实体退化为「N 个X」。
|
||||
* 操作类型(新增 / 删除 / 修改)已由列表行的 op 徽标单独展示,故描述文案不再重复动词。
|
||||
* 展示 id 统一取 schema.id;调用方显式传入的 historyDescription 永远优先。
|
||||
*/
|
||||
export const describeStep = <T>(
|
||||
step: BaseStepValue<T>,
|
||||
getLabel: (_schema?: T) => string | number | undefined,
|
||||
unit: string,
|
||||
): string => {
|
||||
if (step.historyDescription) return step.historyDescription;
|
||||
const { opType } = step;
|
||||
if (opType === 'add') {
|
||||
const count = step.nodes?.length ?? 0;
|
||||
const node = step.nodes?.[0];
|
||||
return `新增 ${count} 个节点${count === 1 && node ? `(${labelWithId(nameOf(node), node.id)})` : ''}`;
|
||||
const items = step.diff ?? [];
|
||||
const label = (schema?: T) => labelWithId(getLabel(schema), (schema as { id?: string | number } | undefined)?.id);
|
||||
|
||||
if (step.opType === 'add') {
|
||||
const node = items[0]?.newSchema;
|
||||
return items.length === 1 && node ? label(node) : `${items.length} 个${unit}`;
|
||||
}
|
||||
if (opType === 'remove') {
|
||||
const count = step.removedItems?.length ?? 0;
|
||||
const node = step.removedItems?.[0]?.node;
|
||||
return `删除 ${count} 个节点${count === 1 && node ? `(${labelWithId(nameOf(node), node.id)})` : ''}`;
|
||||
if (step.opType === 'remove') {
|
||||
const node = items[0]?.oldSchema;
|
||||
return items.length === 1 && node ? label(node) : `${items.length} 个${unit}`;
|
||||
}
|
||||
const updated = step.updatedItems ?? [];
|
||||
if (!updated.length) return '修改节点';
|
||||
if (updated.length === 1) {
|
||||
const { newNode, changeRecords } = updated[0];
|
||||
const propPath = changeRecords?.[0]?.propPath;
|
||||
const target = labelWithId(nameOf(newNode), newNode?.id);
|
||||
return `修改 ${target}${propPath ? ` · ${propPath}` : ''}`;
|
||||
if (!items.length) return unit;
|
||||
if (items.length === 1) {
|
||||
const { newSchema, oldSchema, changeRecords } = items[0];
|
||||
const propPath = changeRecords?.map((changeRecord) => changeRecord.propPath).join(',');
|
||||
const target = label(newSchema ?? oldSchema);
|
||||
return propPath ? `${target} · ${propPath}` : target;
|
||||
}
|
||||
return `修改 ${updated.length} 个节点`;
|
||||
return `${items.length} 个${unit}`;
|
||||
};
|
||||
|
||||
export const describePageStep = (step: StepValue): string => describeStep(step, (node) => nameOf(node), '节点');
|
||||
|
||||
/**
|
||||
* 合并组的展示文案:
|
||||
* - 若组内任一步显式提供了 historyDescription:取最后一条非空 historyDescription(最近一次的描述更准确);
|
||||
* - 单步组:复用 describePageStep;
|
||||
* - 多步组(连续修改同一节点):展示节点名 + 涉及的前几个 propPath。
|
||||
*/
|
||||
export const describePageGroup = (group: PageHistoryGroup) => {
|
||||
export const describePageGroup = (group: HistoryGroup<StepValue>) => {
|
||||
const lastDesc = pickLastDescription(group.steps.map((s) => s.step.historyDescription));
|
||||
if (lastDesc) return lastDesc;
|
||||
if (group.steps.length === 1) return describePageStep(group.steps[0].step);
|
||||
const paths = new Set<string>();
|
||||
group.steps.forEach((s) => {
|
||||
s.step.updatedItems?.[0]?.changeRecords?.forEach((r) => r.propPath && paths.add(r.propPath));
|
||||
});
|
||||
const pathList = Array.from(paths).slice(0, 3).join(', ');
|
||||
const target = labelWithId(
|
||||
group.targetName ?? (group.targetId !== undefined ? `${group.targetId}` : '节点'),
|
||||
group.targetId,
|
||||
);
|
||||
return pathList ? `修改 ${target} · ${pathList}${paths.size > 3 ? '…' : ''}` : `修改 ${target}`;
|
||||
|
||||
return labelWithId(group.targetName ?? (group.targetId !== undefined ? `${group.targetId}` : '节点'), group.targetId);
|
||||
};
|
||||
|
||||
export const describeDataSourceStep = (step: DataSourceStepValue) => {
|
||||
if (step.historyDescription) return step.historyDescription;
|
||||
if (step.oldSchema === null && step.newSchema)
|
||||
return `创建 ${labelWithId(step.newSchema.title, step.newSchema.id ?? step.id)}`;
|
||||
if (step.newSchema === null && step.oldSchema)
|
||||
return `删除 ${labelWithId(step.oldSchema.title, step.oldSchema.id ?? step.id)}`;
|
||||
const propPath = step.changeRecords?.[0]?.propPath;
|
||||
const title = labelWithId(step.newSchema?.title || step.oldSchema?.title, step.id);
|
||||
return propPath ? `修改 ${title} · ${propPath}` : `修改 ${title}`;
|
||||
/**
|
||||
* 页面 step 是否支持「回滚」(类 git revert):
|
||||
* - 新增 / 删除:不依赖 changeRecords,反向应用即删除 / 加回,始终可回滚;
|
||||
* - 更新:必须每个被更新节点都带有 changeRecords,才支持按 propPath 局部反向 patch。
|
||||
* 缺失 changeRecords 的更新只能整节点替换,会冲掉该节点后续的无关变更,因此不支持回滚。
|
||||
*/
|
||||
export const isPageStepRevertable = (step: StepValue): boolean => {
|
||||
if (step.opType !== 'update') return true;
|
||||
const items = step.diff ?? [];
|
||||
if (!items.length) return false;
|
||||
return items.every((item) => Boolean(item.changeRecords?.length));
|
||||
};
|
||||
|
||||
export const describeDataSourceGroup = (group: DataSourceHistoryGroup) => {
|
||||
const lastDesc = pickLastDescription(group.steps.map((s) => s.step.historyDescription));
|
||||
if (lastDesc) return lastDesc;
|
||||
if (group.steps.length === 1) return describeDataSourceStep(group.steps[0].step);
|
||||
const paths = new Set<string>();
|
||||
group.steps.forEach((s) => {
|
||||
s.step.changeRecords?.forEach((r) => r.propPath && paths.add(r.propPath));
|
||||
});
|
||||
const pathList = Array.from(paths).slice(0, 3).join(', ');
|
||||
const rawTitle = group.steps[group.steps.length - 1].step.newSchema?.title || group.steps[0].step.oldSchema?.title;
|
||||
const target = labelWithId(rawTitle, group.id);
|
||||
return pathList ? `修改 ${target} · ${pathList}${paths.size > 3 ? '…' : ''}` : `修改 ${target}`;
|
||||
/**
|
||||
* 单 diff 项历史(数据源 / 代码块)是否支持「回滚」:
|
||||
* - 新增(无 oldSchema)/ 删除(无 newSchema):不依赖 changeRecords,始终可回滚;
|
||||
* - 更新(前后内容都存在):必须有 changeRecords 才支持局部反向 patch,否则不支持回滚。
|
||||
*/
|
||||
export const isSingleDiffStepRevertable = (step: BaseStepValue): boolean => {
|
||||
const item = step.diff?.[0];
|
||||
if (!item?.oldSchema || !item?.newSchema) return true;
|
||||
return Boolean(item.changeRecords?.length);
|
||||
};
|
||||
|
||||
export const describeCodeBlockStep = (step: CodeBlockStepValue) => {
|
||||
if (step.historyDescription) return step.historyDescription;
|
||||
if (step.oldContent === null && step.newContent)
|
||||
return `创建 ${labelWithId(step.newContent.name, step.newContent.id ?? step.id)}`;
|
||||
if (step.newContent === null && step.oldContent)
|
||||
return `删除 ${labelWithId(step.oldContent.name, step.oldContent.id ?? step.id)}`;
|
||||
const propPath = step.changeRecords?.[0]?.propPath;
|
||||
const title = labelWithId(step.newContent?.name || step.oldContent?.name, step.id);
|
||||
return propPath ? `修改 ${title} · ${propPath}` : `修改 ${title}`;
|
||||
};
|
||||
|
||||
export const describeCodeBlockGroup = (group: CodeBlockHistoryGroup) => {
|
||||
const lastDesc = pickLastDescription(group.steps.map((s) => s.step.historyDescription));
|
||||
if (lastDesc) return lastDesc;
|
||||
if (group.steps.length === 1) return describeCodeBlockStep(group.steps[0].step);
|
||||
const paths = new Set<string>();
|
||||
group.steps.forEach((s) => {
|
||||
s.step.changeRecords?.forEach((r) => r.propPath && paths.add(r.propPath));
|
||||
});
|
||||
const pathList = Array.from(paths).slice(0, 3).join(', ');
|
||||
const rawName = group.steps[group.steps.length - 1].step.newContent?.name || group.steps[0].step.oldContent?.name;
|
||||
const target = labelWithId(rawName, group.id);
|
||||
return pathList ? `修改 ${target} · ${pathList}${paths.size > 3 ? '…' : ''}` : `修改 ${target}`;
|
||||
/**
|
||||
* 通用二次确认弹窗:清空历史 / 无法差异对比的回滚等会改变状态的操作,先弹出确认框,
|
||||
* 用户点击「确定」返回 true,取消(confirm reject)时返回 false 并静默忽略。
|
||||
*/
|
||||
export const confirmHistoryAction = async (message: string): Promise<boolean> => {
|
||||
try {
|
||||
await tMagicMessageBox.confirm(message, '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
60
packages/editor/src/layouts/history-list/useHistoryList.ts
Normal file
60
packages/editor/src/layouts/history-list/useHistoryList.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import { computed, reactive } from 'vue';
|
||||
|
||||
import { useServices } from '@editor/hooks/use-services';
|
||||
|
||||
/**
|
||||
* 历史记录面板共享逻辑:
|
||||
* - 暴露三类历史的聚合数据(页面 / 数据源 / 代码块);
|
||||
* - 提供折叠状态管理;
|
||||
* - 提供操作描述文案生成器。
|
||||
*
|
||||
* 所有数据基于 historyService 的 reactive state 派生,自动跟随历史变化刷新。
|
||||
*/
|
||||
export const useHistoryList = () => {
|
||||
const { editorService, historyService } = useServices();
|
||||
|
||||
/**
|
||||
* 折叠状态:key 形如 `pg-${组内首步 index}` / `ds-${id}-${组内首步 index}` / `cb-${id}-${组内首步 index}`。
|
||||
* 用组内首步的稳定 index(而非展示位置)作为 key,确保历史数据更新后已展开的分组状态保持不变。
|
||||
* 合并组默认展开;仅当值为 `false` 时表示收起。
|
||||
*/
|
||||
const expanded = reactive<Record<string, boolean>>({});
|
||||
const toggleGroup = (key: string) => {
|
||||
expanded[key] = expanded[key] === false;
|
||||
};
|
||||
|
||||
const pageGroups = computed(() => historyService.getHistoryGroups('page', editorService.get('page')?.id));
|
||||
const dataSourceGroups = computed(() => historyService.getHistoryGroups('dataSource'));
|
||||
const codeBlockGroups = computed(() => historyService.getHistoryGroups('codeBlock'));
|
||||
|
||||
/** 页面 tab 倒序展示(最新一组在最上面)。 */
|
||||
const pageGroupsDisplay = computed(() => pageGroups.value.slice().reverse());
|
||||
|
||||
/**
|
||||
* 把按时间正序的 group 列表,再按 id 聚拢成 bucket(同 id 的所有分组放一起)。
|
||||
* 每个 bucket 内部仍然按时间倒序展示(最近的操作最先看到)。
|
||||
*/
|
||||
const groupByTarget = <G extends { id: string | number }>(groups: G[]) => {
|
||||
const map = new Map<string | number, G[]>();
|
||||
groups.forEach((g) => {
|
||||
const list = map.get(g.id) ?? [];
|
||||
list.push(g);
|
||||
map.set(g.id, list);
|
||||
});
|
||||
return Array.from(map.entries()).map(([id, gs]) => ({ id, groups: gs.slice().reverse() }));
|
||||
};
|
||||
|
||||
const dataSourceGroupsByTarget = computed(() => groupByTarget(dataSourceGroups.value));
|
||||
const codeBlockGroupsByTarget = computed(() => groupByTarget(codeBlockGroups.value));
|
||||
|
||||
return {
|
||||
expanded,
|
||||
toggleGroup,
|
||||
pageGroups,
|
||||
dataSourceGroups,
|
||||
codeBlockGroups,
|
||||
pageGroupsDisplay,
|
||||
dataSourceGroupsByTarget,
|
||||
codeBlockGroupsByTarget,
|
||||
};
|
||||
};
|
||||
425
packages/editor/src/layouts/history-list/useHistoryRevert.ts
Normal file
425
packages/editor/src/layouts/history-list/useHistoryRevert.ts
Normal file
@ -0,0 +1,425 @@
|
||||
import { createApp, getCurrentInstance } from 'vue';
|
||||
|
||||
import { tMagicMessage } from '@tmagic/design';
|
||||
|
||||
import type {
|
||||
ConfirmAndRevertOptions,
|
||||
CustomDiffFormOptions,
|
||||
DiffDialogPayload,
|
||||
Services,
|
||||
UseHistoryRevertOptions,
|
||||
} from '@editor/type';
|
||||
|
||||
import { confirmHistoryAction } from './composables';
|
||||
|
||||
/**
|
||||
* 三类历史(页面 / 数据源 / 代码块)差异弹窗入参的构造差异,收敛为一份配置:
|
||||
* 仅「分组来源、当前值读取、类型 / 展示名提取」不同,定位 step、校验前后值、组装 payload 的流程共用。
|
||||
*/
|
||||
interface DiffPayloadSource {
|
||||
/** 表单类别:节点 / 数据源 / 代码块。 */
|
||||
category: DiffDialogPayload['category'];
|
||||
/** 该类别按时间正序的历史分组列表(含已撤销)。 */
|
||||
groups: () => { id?: string | number; steps: { index: number; step: { diff?: any[] } }[] }[];
|
||||
/** 读取目标当前实际值,用于「与当前对比」;不存在时返回空即禁用对比。 */
|
||||
getCurrent: (_id: string | number) => Record<string, any> | null | undefined;
|
||||
/** 由新/旧快照提取展示名(含各自的兜底,如节点回退 type、数据源 / 代码块回退 id)。 */
|
||||
resolveLabel: (_newSchema: Record<string, any>, _oldSchema: Record<string, any>, _id: string | number) => string;
|
||||
/** 由新/旧快照提取类型;代码块无 type 字段则不传。 */
|
||||
resolveType?: (_newSchema: Record<string, any>, _oldSchema: Record<string, any>) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造差异弹窗入参:仅 update(前后值都存在)可对比。
|
||||
* - 页面(无 id):在全部分组中按 index 定位 step,目标 id 取自快照;
|
||||
* - 数据源 / 代码块(带 id):先匹配分组 id 再按 index 定位。
|
||||
* 无可对比内容(多节点 / add / remove)或定位不到时返回 null。
|
||||
*/
|
||||
const buildDiffPayload = (source: DiffPayloadSource, index: number, id?: string | number): DiffDialogPayload | null => {
|
||||
for (const group of source.groups()) {
|
||||
if (id !== undefined && group.id !== id) continue;
|
||||
const step = group.steps.find((s) => s.index === index)?.step;
|
||||
if (!step) continue;
|
||||
const oldSchema = step.diff?.[0]?.oldSchema as Record<string, any> | undefined;
|
||||
const newSchema = step.diff?.[0]?.newSchema as Record<string, any> | undefined;
|
||||
if (!oldSchema || !newSchema) return null;
|
||||
const targetId = id ?? newSchema.id ?? oldSchema.id;
|
||||
const type = source.resolveType?.(newSchema, oldSchema);
|
||||
return {
|
||||
category: source.category,
|
||||
...(type !== undefined ? { type } : {}),
|
||||
lastValue: oldSchema,
|
||||
value: newSchema,
|
||||
currentValue: (targetId !== undefined ? source.getCurrent(targetId) : null) || null,
|
||||
targetLabel: source.resolveLabel(newSchema, oldSchema, targetId),
|
||||
id: targetId,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
interface MountedDiffDialog {
|
||||
app: ReturnType<typeof createApp>;
|
||||
instance: {
|
||||
open: (_payload: DiffDialogPayload) => void;
|
||||
confirm: (_payload: DiffDialogPayload) => Promise<boolean>;
|
||||
};
|
||||
/** 卸载弹窗并清理容器(延迟以等待关闭过渡播放完成,避免动画被强行打断)。 */
|
||||
destroy: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按需动态 import 并挂载一个游离的 HistoryDiffDialog,返回其实例与清理函数。
|
||||
* 通过继承 appContext 复用全局组件 / 指令 / provide / 插件(Element Plus、@tmagic/form 字段组件等),
|
||||
* 弹窗组件动态 import,避免拖累其它消费者。供「确认回滚」与「查看差异」两种交互共用。
|
||||
*/
|
||||
const mountHistoryDiffDialog = async (
|
||||
options: Pick<UseHistoryRevertOptions, 'appContext' | 'extendState'> &
|
||||
CustomDiffFormOptions & {
|
||||
services?: Services;
|
||||
isConfirm?: boolean;
|
||||
onClose?: () => void;
|
||||
},
|
||||
): Promise<MountedDiffDialog> => {
|
||||
const { default: historyDiffDialog } = await import('./HistoryDiffDialog.vue');
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.style.display = 'none';
|
||||
document.body.appendChild(container);
|
||||
|
||||
const app = createApp(historyDiffDialog, {
|
||||
services: options.services,
|
||||
isConfirm: options.isConfirm,
|
||||
extendState: options.extendState,
|
||||
loadConfig: options.loadConfig,
|
||||
selfDiffFieldTypes: options.selfDiffFieldTypes,
|
||||
compareFormState: options.compareFormState,
|
||||
width: options.width,
|
||||
size: options.size ?? options.services?.uiService?.get('propsPanelSize'),
|
||||
onClose: options.onClose,
|
||||
});
|
||||
if (options.appContext) {
|
||||
Object.assign(app._context, options.appContext);
|
||||
}
|
||||
|
||||
const instance = app.mount(container) as unknown as MountedDiffDialog['instance'];
|
||||
|
||||
const destroy = () => {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
app.unmount();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
container.parentNode?.removeChild(container);
|
||||
}, 300);
|
||||
};
|
||||
|
||||
return { app, instance, destroy };
|
||||
};
|
||||
|
||||
/**
|
||||
* 动态挂载一个「确认回滚」模式的 HistoryDiffDialog,等待用户确认:
|
||||
* - 用户点「确定回滚」resolve(true),取消 / 关闭 resolve(false);
|
||||
* - 确认流程结束后自动卸载。
|
||||
*/
|
||||
const confirmRevertWithDiffDialog = async (
|
||||
payload: DiffDialogPayload,
|
||||
options: Pick<UseHistoryRevertOptions, 'appContext' | 'extendState'> &
|
||||
CustomDiffFormOptions & {
|
||||
services?: Services;
|
||||
},
|
||||
): Promise<boolean> => {
|
||||
const { instance, destroy } = await mountHistoryDiffDialog({
|
||||
...options,
|
||||
isConfirm: true,
|
||||
});
|
||||
try {
|
||||
return await instance.confirm(payload);
|
||||
} finally {
|
||||
destroy();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 动态挂载一个「查看差异」模式(只读)的 HistoryDiffDialog 并打开:
|
||||
* 弹窗保持打开直到用户关闭,关闭(close 事件)后自动卸载并清理容器。
|
||||
*/
|
||||
const viewHistoryDiffDialog = async (
|
||||
payload: DiffDialogPayload,
|
||||
options: Pick<UseHistoryRevertOptions, 'appContext' | 'extendState'> &
|
||||
CustomDiffFormOptions & {
|
||||
services?: Services;
|
||||
},
|
||||
): Promise<void> => {
|
||||
// onClose 在用户关闭弹窗时才触发,此时 handle.destroy 早已赋值。
|
||||
const handle: { destroy?: () => void } = {};
|
||||
const { instance, destroy } = await mountHistoryDiffDialog({
|
||||
...options,
|
||||
isConfirm: false,
|
||||
onClose: () => handle.destroy?.(),
|
||||
});
|
||||
handle.destroy = destroy;
|
||||
instance.open(payload);
|
||||
};
|
||||
|
||||
/**
|
||||
* 历史记录「单步回滚」与「查看差异」的完整交互流程,供历史面板与业务方共用。
|
||||
*
|
||||
* 单步回滚(类 git revert):
|
||||
* 1. 前置校验:目标数据已被删除(update 写回目标 / 页面 remove 的原父容器缺失)时给出「回滚失败」提示并中止;
|
||||
* 2. 二次确认:可差异对比的步骤(单实体 update)弹出差异确认弹窗,其余步骤弹普通二次确认框;
|
||||
* 3. 用户确认后执行对应 service 的 revert(页面 / 数据源 / 代码块)。
|
||||
*
|
||||
* 查看差异:可差异对比的步骤动态挂载只读 HistoryDiffDialog 展示前后值差异。
|
||||
*
|
||||
* 上述弹窗均按需动态挂载 HistoryDiffDialog 实现,业务方无需自行挂载任何弹窗。
|
||||
*
|
||||
* 返回的能力分三组:
|
||||
* - 内置三类(页面 / 数据源 / 代码块):`onPageRevert` / `onDataSourceRevert` / `onCodeBlockRevert` 单步回滚,
|
||||
* `onPageDiff` / `onDataSourceDiff` / `onCodeBlockDiff` 查看差异,及配套的 `buildXxxDiffPayload` / `isXxxRevertTargetMissing`;
|
||||
* - 业务自有历史(如管理台「模块」):`confirmAndRevert` / `viewDiff` 复用同一套交互流程,由业务方自行构造差异入参;
|
||||
* 即上述内置三类本质上是它们各自预置好 payload 构造与 service.revert 的特例。
|
||||
*
|
||||
* 业务方可在拿到 Editor 实例暴露的 `services` 后直接 import 调用:
|
||||
*
|
||||
* ```ts
|
||||
* import { useHistoryRevert } from '@tmagic/editor';
|
||||
*
|
||||
* const { onPageRevert, onPageDiff } = useHistoryRevert({}, editorRef.value); // editorRef.value 即 Editor 暴露的 services
|
||||
* await onPageRevert(index); // 弹出差异 / 二次确认弹窗后回滚
|
||||
* onPageDiff(index); // 弹出只读差异弹窗查看前后值差异
|
||||
* ```
|
||||
*/
|
||||
export const useHistoryRevert = (options: UseHistoryRevertOptions = {}, services?: Services) => {
|
||||
// 自动捕获调用方所在组件的 appContext(在 setup 中调用时),业务方亦可显式覆盖。
|
||||
const appContext = options.appContext ?? getCurrentInstance()?.appContext ?? null;
|
||||
const { extendState, getPropsPanelFormState, dialogWidth } = options;
|
||||
|
||||
/** 目标数据已被删除、无法回滚时的统一提示。 */
|
||||
const showRevertTargetMissing = () => {
|
||||
tMagicMessage.error('回滚失败:该记录对应的数据已被删除');
|
||||
};
|
||||
|
||||
/**
|
||||
* 「回滚」二次确认:新增 / 删除 / 多节点更新等无法做差异对比的步骤,
|
||||
* 不弹差异弹窗,改用一个普通确认框替代「确定回滚」按钮,避免点击后无任何提示直接执行。
|
||||
* 用户取消时返回 false,调用方据此中止回滚。
|
||||
*/
|
||||
const confirmRevert = (): Promise<boolean> =>
|
||||
confirmHistoryAction(
|
||||
'确定回滚该步骤吗?回滚会将该操作作为一条新记录反向应用(新增将被删除、删除将被还原),不影响后续历史记录。',
|
||||
);
|
||||
|
||||
/**
|
||||
* 「回滚」统一确认入口:可差异对比的步骤动态挂载 HistoryDiffDialog 走差异确认弹窗,
|
||||
* 无法对比的步骤(add / remove / 多节点更新)回退到普通二次确认框。
|
||||
* `extra` 供业务自有历史(如模块)透传自定义表单配置加载等渲染入参。
|
||||
*/
|
||||
const runRevert = (payload: DiffDialogPayload | null, extra?: CustomDiffFormOptions): Promise<boolean> => {
|
||||
if (payload) {
|
||||
return confirmRevertWithDiffDialog(payload, {
|
||||
appContext,
|
||||
extendState,
|
||||
services,
|
||||
...extra,
|
||||
width: extra?.width ?? dialogWidth,
|
||||
size: extra?.size,
|
||||
});
|
||||
}
|
||||
return confirmRevert();
|
||||
};
|
||||
|
||||
const buildPageDiffPayload = (index: number): DiffDialogPayload | null =>
|
||||
buildDiffPayload(
|
||||
{
|
||||
category: 'node',
|
||||
groups: () => services?.historyService.getHistoryGroups('page', services?.editorService.get('page')?.id) ?? [],
|
||||
getCurrent: (id) => services?.editorService.getNodeById(id) as Record<string, any> | null,
|
||||
resolveType: (n, o) => n.type || o.type || '',
|
||||
resolveLabel: (n, o) => n.name || o.name || n.type || o.type || '',
|
||||
},
|
||||
index,
|
||||
);
|
||||
|
||||
const buildDataSourceDiffPayload = (id: string | number, index: number): DiffDialogPayload | null =>
|
||||
buildDiffPayload(
|
||||
{
|
||||
category: 'data-source',
|
||||
groups: () => services?.historyService.getHistoryGroups('dataSource') ?? [],
|
||||
getCurrent: (id) => services?.dataSourceService.getDataSourceById(`${id}`) as Record<string, any> | null,
|
||||
resolveType: (n, o) => n.type || o.type || 'base',
|
||||
resolveLabel: (n, o, id) => n.title || o.title || `${id}`,
|
||||
},
|
||||
index,
|
||||
id,
|
||||
);
|
||||
|
||||
const buildCodeBlockDiffPayload = (id: string | number, index: number): DiffDialogPayload | null =>
|
||||
buildDiffPayload(
|
||||
{
|
||||
category: 'code-block',
|
||||
groups: () => services?.historyService.getHistoryGroups('codeBlock') ?? [],
|
||||
getCurrent: (id) => services?.codeBlockService.getCodeContentById(id) as Record<string, any> | null,
|
||||
resolveLabel: (n, o, id) => n.name || o.name || `${id}`,
|
||||
},
|
||||
index,
|
||||
id,
|
||||
);
|
||||
|
||||
/**
|
||||
* 回滚前置校验:若该历史步骤回滚所依赖的目标数据已被删除,则无法回滚。
|
||||
* - update(把旧值写回):被修改的目标必须仍存在;
|
||||
* - 页面 remove(还原被删节点):被删节点的原父容器必须仍存在,否则无处插回;
|
||||
* add(回滚即删除)即使目标已不在,也已达成「删除」目的,不视为失败。
|
||||
*/
|
||||
const isPageRevertTargetMissing = (index: number): boolean => {
|
||||
const step = services?.historyService.getStepList('page', services?.editorService.get('page')?.id)[index]?.step;
|
||||
if (!step) return false;
|
||||
if (step.opType === 'update') {
|
||||
return (step.diff ?? []).some((item) => {
|
||||
const id = item.newSchema?.id ?? item.oldSchema?.id;
|
||||
return id !== undefined && !services?.editorService.getNodeById(id, false);
|
||||
});
|
||||
}
|
||||
if (step.opType === 'remove') {
|
||||
return (step.diff ?? []).some(
|
||||
(item) => item.parentId !== undefined && !services?.editorService.getNodeById(item.parentId, false),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/** 数据源 update 步骤回滚时,对应数据源必须仍存在(已删除则无处写回旧值)。 */
|
||||
const isDataSourceRevertTargetMissing = (id: string | number, index: number): boolean => {
|
||||
const step = services?.historyService.getStepList('dataSource', id)[index]?.step;
|
||||
return Boolean(step?.opType === 'update' && !services?.dataSourceService.getDataSourceById(`${id}`));
|
||||
};
|
||||
|
||||
/** 代码块 update 步骤回滚时,对应代码块必须仍存在(已删除则无处写回旧值)。 */
|
||||
const isCodeBlockRevertTargetMissing = (id: string | number, index: number): boolean => {
|
||||
const step = services?.historyService.getStepList('codeBlock', id)[index]?.step;
|
||||
return Boolean(step?.opType === 'update' && !services?.codeBlockService.getCodeContentById(id));
|
||||
};
|
||||
|
||||
const onPageRevert = (index: number) => {
|
||||
if (isPageRevertTargetMissing(index)) {
|
||||
showRevertTargetMissing();
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
return runRevert(buildPageDiffPayload(index), { compareFormState: getPropsPanelFormState?.() }).then((result) =>
|
||||
result ? services?.editorService.revertPageStep(index) : null,
|
||||
);
|
||||
};
|
||||
|
||||
const onDataSourceRevert = (id: string | number, index: number) => {
|
||||
if (isDataSourceRevertTargetMissing(id, index)) {
|
||||
showRevertTargetMissing();
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
return runRevert(buildDataSourceDiffPayload(id, index)).then((result) =>
|
||||
result ? services?.dataSourceService.revert(id, index) : null,
|
||||
);
|
||||
};
|
||||
|
||||
const onCodeBlockRevert = (id: string | number, index: number) => {
|
||||
if (isCodeBlockRevertTargetMissing(id, index)) {
|
||||
showRevertTargetMissing();
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
return runRevert(buildCodeBlockDiffPayload(id, index)).then((result) =>
|
||||
result ? services?.codeBlockService.revert(id, index) : null,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 「查看差异」:可差异对比的步骤(单实体 update)动态挂载只读 HistoryDiffDialog 展示前后值差异,
|
||||
* 无可对比内容(add / remove / 多节点更新)时不弹窗、静默返回。
|
||||
*/
|
||||
const onPageDiff = (index: number): Promise<void> | void => {
|
||||
const payload = buildPageDiffPayload(index);
|
||||
if (payload) {
|
||||
return viewHistoryDiffDialog(payload, {
|
||||
appContext,
|
||||
extendState,
|
||||
services,
|
||||
width: dialogWidth,
|
||||
compareFormState: getPropsPanelFormState?.(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onDataSourceDiff = (id: string | number, index: number): Promise<void> | void => {
|
||||
const payload = buildDataSourceDiffPayload(id, index);
|
||||
if (payload) return viewHistoryDiffDialog(payload, { appContext, extendState, services, width: dialogWidth });
|
||||
};
|
||||
|
||||
const onCodeBlockDiff = (id: string | number, index: number): Promise<void> | void => {
|
||||
const payload = buildCodeBlockDiffPayload(id, index);
|
||||
if (payload) return viewHistoryDiffDialog(payload, { appContext, extendState, services, width: dialogWidth });
|
||||
};
|
||||
|
||||
/**
|
||||
* 业务自有历史(如管理台「模块」)的「单步回滚」统一入口:
|
||||
* 复用与页面/数据源/代码块一致的「目标校验 → 差异/二次确认弹窗 → 反向回滚」流程,
|
||||
* 内置三类只是它的特例(各自预置了 buildXxxDiffPayload + service.revert)。
|
||||
*
|
||||
* 用户取消或前置校验未过时返回 null,确认并执行回滚后返回 `revert()` 的结果。
|
||||
*
|
||||
* ```ts
|
||||
* await confirmAndRevert({
|
||||
* diffPayload: oldSchema && newSchema ? { category: 'module', lastValue: oldSchema, value: newSchema, ... } : null,
|
||||
* loadConfig: (ctx) => loadModFormConfig(modTypeId, values),
|
||||
* selfDiffFieldTypes: ['mod-cond'],
|
||||
* revert: () => moduleHistoryStore.revert(id, index),
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
const confirmAndRevert = async <T = unknown>(revertOptions: ConfirmAndRevertOptions<T>): Promise<T | null> => {
|
||||
if (revertOptions.isTargetMissing?.()) {
|
||||
showRevertTargetMissing();
|
||||
return null;
|
||||
}
|
||||
const confirmed = await runRevert(revertOptions.diffPayload ?? null, {
|
||||
loadConfig: revertOptions.loadConfig,
|
||||
selfDiffFieldTypes: revertOptions.selfDiffFieldTypes,
|
||||
width: revertOptions.width,
|
||||
size: revertOptions.size,
|
||||
});
|
||||
if (!confirmed) return null;
|
||||
return await revertOptions.revert();
|
||||
};
|
||||
|
||||
/**
|
||||
* 业务自有历史的「查看差异」统一入口:传入自行构造的差异入参即弹出只读差异弹窗,
|
||||
* 可透传 `loadConfig` / `selfDiffFieldTypes`。payload 为 null(不可对比)时静默返回。
|
||||
*/
|
||||
const viewDiff = (payload: DiffDialogPayload | null, extra?: CustomDiffFormOptions): Promise<void> | void => {
|
||||
if (payload)
|
||||
return viewHistoryDiffDialog(payload, {
|
||||
appContext,
|
||||
extendState,
|
||||
services,
|
||||
...extra,
|
||||
width: extra?.width ?? dialogWidth,
|
||||
size: extra?.size,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
onPageRevert,
|
||||
onDataSourceRevert,
|
||||
onCodeBlockRevert,
|
||||
onPageDiff,
|
||||
onDataSourceDiff,
|
||||
onCodeBlockDiff,
|
||||
buildPageDiffPayload,
|
||||
buildDataSourceDiffPayload,
|
||||
buildCodeBlockDiffPayload,
|
||||
isPageRevertTargetMissing,
|
||||
isDataSourceRevertTargetMissing,
|
||||
isCodeBlockRevertTargetMissing,
|
||||
confirmAndRevert,
|
||||
viewDiff,
|
||||
};
|
||||
};
|
||||
@ -51,6 +51,7 @@
|
||||
type: 'button',
|
||||
text: '删除',
|
||||
icon: Delete,
|
||||
buttonProps: { type: 'danger' },
|
||||
handler: () => remove(item),
|
||||
}"
|
||||
></ToolButton>
|
||||
@ -72,7 +73,7 @@ import { computed, ref, useTemplateRef, watch } from 'vue';
|
||||
import { CaretBottom, Delete, DocumentCopy } from '@element-plus/icons-vue';
|
||||
|
||||
import { type Id, type MPage, type MPageFragment, NodeType } from '@tmagic/core';
|
||||
import { TMagicIcon, TMagicPopover } from '@tmagic/design';
|
||||
import { TMagicIcon, tMagicMessageBox, TMagicPopover } from '@tmagic/design';
|
||||
|
||||
import ToolButton from '@editor/components/ToolButton.vue';
|
||||
import { useServices } from '@editor/hooks/use-services';
|
||||
@ -140,7 +141,8 @@ const copy = (node: MPage | MPageFragment) => {
|
||||
});
|
||||
};
|
||||
|
||||
const remove = (node: MPage | MPageFragment) => {
|
||||
const remove = async (node: MPage | MPageFragment) => {
|
||||
await tMagicMessageBox.confirm('确定删除该页面吗?');
|
||||
editorService.remove(node);
|
||||
};
|
||||
|
||||
|
||||
@ -151,7 +151,11 @@ const submit = async (v: MNode, eventData?: ContainerChangeEventData) => {
|
||||
});
|
||||
}
|
||||
|
||||
editorService.update(newValue, { changeRecords: eventData?.changeRecords });
|
||||
// 区分操作途径:表单字段编辑(MForm @change)会带上 eventData(含 changeRecords);
|
||||
// 源码编辑器(CodeEditor @save → saveCode)保存时不带 eventData,据此标记为「源码编辑器」。
|
||||
const historySource = eventData ? 'props' : 'code';
|
||||
|
||||
editorService.update(newValue, { changeRecords: eventData?.changeRecords, historySource });
|
||||
} catch (e: any) {
|
||||
emit('submit-error', e);
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@ import { computed, type Ref, watch } from 'vue';
|
||||
|
||||
import { Protocol } from '@editor/services/storage';
|
||||
import { Services } from '@editor/type';
|
||||
import { MIN_CENTER_COLUMN_WIDTH, RIGHT_COLUMN_WIDTH_STORAGE_KEY } from '@editor/utils/const';
|
||||
import { RIGHT_COLUMN_WIDTH_STORAGE_KEY } from '@editor/utils/const';
|
||||
|
||||
export const useStylePanel = (
|
||||
{ uiService, storageService }: Pick<Services, 'uiService' | 'storageService'>,
|
||||
@ -47,8 +47,9 @@ export const useStylePanel = (
|
||||
}
|
||||
|
||||
if (columnWidth.center < 0) {
|
||||
columnWidth.right = columnWidth.right + columnWidth.center - MIN_CENTER_COLUMN_WIDTH;
|
||||
columnWidth.center = MIN_CENTER_COLUMN_WIDTH;
|
||||
const minCenterColumnWidth = uiService.get('minCenterColumnWidth');
|
||||
columnWidth.right = columnWidth.right + columnWidth.center - minCenterColumnWidth;
|
||||
columnWidth.center = minCenterColumnWidth;
|
||||
|
||||
propsPanelWidth.value = columnWidth.right / 2;
|
||||
}
|
||||
|
||||
@ -94,11 +94,15 @@ let clientX: number;
|
||||
let clientY: number;
|
||||
|
||||
const appendComponent = ({ text, type, data = {} }: ComponentItem): void => {
|
||||
editorService.add({
|
||||
name: text,
|
||||
type,
|
||||
...data,
|
||||
});
|
||||
editorService.add(
|
||||
{
|
||||
name: text,
|
||||
type,
|
||||
...data,
|
||||
},
|
||||
undefined,
|
||||
{ historySource: 'component-panel' },
|
||||
);
|
||||
};
|
||||
|
||||
const dragstartHandler = ({ text, type, data = {} }: ComponentItem, e: DragEvent) => {
|
||||
|
||||
@ -132,6 +132,7 @@
|
||||
v-model:height="columnLeftHeight"
|
||||
:width="columnLeftWidth"
|
||||
:title="config.text"
|
||||
:framework-width="frameworkWidth"
|
||||
:position="{
|
||||
left: floatBoxStates[config.$key].left,
|
||||
top: floatBoxStates[config.$key].top,
|
||||
@ -221,6 +222,7 @@ const taskLength = computed(() => depService.get('taskLength'));
|
||||
const tipsBarVisible = ref(true);
|
||||
|
||||
const columnLeftWidth = computed(() => uiService.get('columnWidth')[ColumnLayout.LEFT]);
|
||||
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
|
||||
const { height: editorContentHeight } = useEditorContentHeight();
|
||||
const columnLeftHeight = ref(0);
|
||||
|
||||
@ -239,7 +241,12 @@ const unWatchEditorContentHeight = watch(
|
||||
},
|
||||
);
|
||||
|
||||
const activeTabName = ref(props.data?.status);
|
||||
const activeTabName = computed<string>({
|
||||
get: () => uiService.get('sideBarActiveTabName'),
|
||||
set: (value) => uiService.set('sideBarActiveTabName', value),
|
||||
});
|
||||
|
||||
uiService.set('sideBarActiveTabName', props.data?.status || '');
|
||||
|
||||
const getItemConfig = (data: SideItem): SideComponent => {
|
||||
const map: Record<string, SideComponent> = {
|
||||
@ -252,7 +259,7 @@ const getItemConfig = (data: SideItem): SideComponent => {
|
||||
slots: {},
|
||||
},
|
||||
layer: {
|
||||
$key: 'layer',
|
||||
$key: SideItemKey.LAYER,
|
||||
type: 'component',
|
||||
icon: List,
|
||||
text: '已选组件',
|
||||
@ -272,7 +279,7 @@ const getItemConfig = (data: SideItem): SideComponent => {
|
||||
slots: {},
|
||||
},
|
||||
[SideItemKey.CODE_BLOCK]: {
|
||||
$key: 'code-block',
|
||||
$key: SideItemKey.CODE_BLOCK,
|
||||
type: 'component',
|
||||
icon: EditPen,
|
||||
text: '代码编辑',
|
||||
|
||||
@ -24,7 +24,7 @@
|
||||
<Icon :icon="editable ? Edit : View" class="edit-icon" @click.stop="editCode(`${data.key}`)"></Icon>
|
||||
</TMagicTooltip>
|
||||
<TMagicTooltip v-if="data.type === 'code' && editable" effect="dark" content="删除" placement="bottom">
|
||||
<Icon :icon="Close" class="edit-icon" @click.stop="deleteCode(`${data.key}`)"></Icon>
|
||||
<Icon :icon="Close" class="edit-icon" @click.stop="deleteCode(`${data.key}`, { historySource: 'tree' })"></Icon>
|
||||
</TMagicTooltip>
|
||||
<slot name="code-block-panel-tool" :id="data.key" :data="data"></slot>
|
||||
</template>
|
||||
@ -44,7 +44,7 @@ import Tree from '@editor/components/Tree.vue';
|
||||
import { useFilter } from '@editor/hooks/use-filter';
|
||||
import { useNodeStatus } from '@editor/hooks/use-node-status';
|
||||
import { useServices } from '@editor/hooks/use-services';
|
||||
import { type CodeBlockListSlots, CodeDeleteErrorType, type TreeNodeData } from '@editor/type';
|
||||
import { type CodeBlockListSlots, CodeDeleteErrorType, HistoryOpSource, type TreeNodeData } from '@editor/type';
|
||||
|
||||
defineSlots<CodeBlockListSlots>();
|
||||
|
||||
@ -60,7 +60,7 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
edit: [id: string];
|
||||
remove: [id: string];
|
||||
remove: [id: string, { historySource?: HistoryOpSource }];
|
||||
'node-contextmenu': [event: MouseEvent, data: TreeNodeData];
|
||||
}>();
|
||||
|
||||
@ -142,7 +142,7 @@ const editCode = (id: string) => {
|
||||
emit('edit', id);
|
||||
};
|
||||
|
||||
const deleteCode = async (id: string) => {
|
||||
const deleteCode = async (id: string, { historySource }: { historySource?: HistoryOpSource } = {}) => {
|
||||
const currentCode = codeList.value.find((codeItem) => codeItem.id === id);
|
||||
const existBinds = Boolean(currentCode?.items?.length);
|
||||
const undeleteableList = codeBlockService.getUndeletableList() || [];
|
||||
@ -154,7 +154,7 @@ const deleteCode = async (id: string) => {
|
||||
});
|
||||
|
||||
// 无绑定关系,且不在不可删除列表中
|
||||
emit('remove', id);
|
||||
emit('remove', id, { historySource });
|
||||
} else {
|
||||
if (typeof props.customError === 'function') {
|
||||
props.customError(id, existBinds ? CodeDeleteErrorType.BIND : CodeDeleteErrorType.UNDELETEABLE);
|
||||
|
||||
@ -122,7 +122,7 @@ const {
|
||||
menuData: contentMenuData,
|
||||
contentMenuHideHandler,
|
||||
} = useContentMenu((id: string) => {
|
||||
codeBlockListRef.value?.deleteCode(id);
|
||||
codeBlockListRef.value?.deleteCode(id, { historySource: 'tree-contextmenu' });
|
||||
});
|
||||
const menuData = computed<(MenuButton | MenuComponent)[]>(() => props.customContentMenu(contentMenuData, 'code-block'));
|
||||
</script>
|
||||
|
||||
@ -41,7 +41,7 @@ export const useContentMenu = (deleteCode: (id: string) => void) => {
|
||||
|
||||
const newCodeId = await codeBlockService.getUniqueId();
|
||||
|
||||
codeBlockService.setCodeDslById(newCodeId, cloneDeep(codeBlock));
|
||||
codeBlockService.setCodeDslById(newCodeId, cloneDeep(codeBlock), { historySource: 'tree-contextmenu' });
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
<template>
|
||||
<FloatingBox
|
||||
:body-style="{ padding: '0 16px' }"
|
||||
v-model:visible="boxVisible"
|
||||
v-model:width="width"
|
||||
v-model:height="editorHeight"
|
||||
:title="title"
|
||||
:framework-width="frameworkWidth"
|
||||
:position="boxPosition"
|
||||
>
|
||||
<template #body>
|
||||
@ -22,7 +24,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject, nextTick, Ref, ref, watch, watchEffect } from 'vue';
|
||||
import { computed, inject, nextTick, provide, Ref, ref, watch, watchEffect } from 'vue';
|
||||
|
||||
import type { DataSourceSchema } from '@tmagic/core';
|
||||
import { tMagicMessage } from '@tmagic/design';
|
||||
@ -41,6 +43,10 @@ const props = defineProps<{
|
||||
title?: string;
|
||||
values: any;
|
||||
disabled: boolean;
|
||||
/** 打开后需要直接定位并打开的方法名,传入时默认激活「方法定义」tab */
|
||||
editMethodName?: string;
|
||||
/** 打开后需要直接定位并打开的字段路径,传入时默认激活「数据定义」tab */
|
||||
editFieldPath?: string[];
|
||||
}>();
|
||||
|
||||
const boxVisible = defineModel<boolean>('visible', { default: false });
|
||||
@ -61,10 +67,36 @@ const { height: editorHeight } = useEditorContentHeight();
|
||||
|
||||
const parentFloating = inject<Ref<HTMLDivElement | null>>('parentFloating', ref(null));
|
||||
const { boxPosition, calcBoxPosition } = useNextFloatBoxPosition(uiService, parentFloating);
|
||||
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
|
||||
|
||||
/** 供「方法定义」tab 内的字段消费,用于打开数据源详情后自动打开指定方法 */
|
||||
provide(
|
||||
'editingDataSourceMethodName',
|
||||
computed(() => props.editMethodName),
|
||||
);
|
||||
|
||||
/** 供「数据定义」tab 内的字段消费,用于打开数据源详情后自动打开指定字段 */
|
||||
provide(
|
||||
'editingDataSourceFieldPath',
|
||||
computed(() => props.editFieldPath || []),
|
||||
);
|
||||
|
||||
watchEffect(() => {
|
||||
initValues.value = props.values;
|
||||
dataSourceConfig.value = dataSourceService.getFormConfig(initValues.value.type);
|
||||
const config = dataSourceService.getFormConfig(initValues.value.type);
|
||||
|
||||
// 传入方法名/字段路径时,将外层 tab 容器默认激活到对应 tab(status: methods / fields)
|
||||
// 未传入时默认激活「数据定义」tab(fields)
|
||||
let activeTab = 'fields';
|
||||
if (props.editMethodName) {
|
||||
activeTab = 'methods';
|
||||
} else if (props.editFieldPath?.length) {
|
||||
activeTab = 'fields';
|
||||
}
|
||||
|
||||
dataSourceConfig.value = config.map((item) =>
|
||||
(item as { type?: string }).type === 'tab' ? { ...item, active: activeTab } : item,
|
||||
);
|
||||
});
|
||||
|
||||
const submitHandler = (values: any, data: ContainerChangeEventData) => {
|
||||
|
||||
@ -29,6 +29,8 @@
|
||||
:disabled="!editable"
|
||||
:values="dataSourceValues"
|
||||
:title="dialogTitle"
|
||||
:edit-method-name="editMethodName"
|
||||
:edit-field-path="editFieldPath"
|
||||
@submit="submitDataSourceHandler"
|
||||
@close="editDialogCloseHandler"
|
||||
></DataSourceConfigPanel>
|
||||
@ -45,7 +47,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, useTemplateRef, watch } from 'vue';
|
||||
import { computed, inject, ref, useTemplateRef, watch } from 'vue';
|
||||
import { mergeWith } from 'lodash-es';
|
||||
|
||||
import { tMagicMessageBox, TMagicScrollbar } from '@tmagic/design';
|
||||
@ -79,7 +81,16 @@ const { dataSourceService } = useServices();
|
||||
const { editDialog, dataSourceValues, dialogTitle, editable, editHandler, submitDataSourceHandler } =
|
||||
useDataSourceEdit(dataSourceService);
|
||||
|
||||
/** 打开数据源详情时需要直接定位并打开的方法名,为空则正常展示「数据定义」tab */
|
||||
const editMethodName = ref('');
|
||||
|
||||
/** 打开数据源详情时需要直接定位并打开的字段路径,为空则不自动打开字段配置 */
|
||||
const editFieldPath = ref<string[]>([]);
|
||||
|
||||
const editDialogCloseHandler = () => {
|
||||
editMethodName.value = '';
|
||||
editFieldPath.value = [];
|
||||
|
||||
if (dataSourceListRef.value) {
|
||||
for (const [, status] of dataSourceListRef.value.nodeStatusMap.entries()) {
|
||||
status.selected = false;
|
||||
@ -129,7 +140,7 @@ const removeHandler = async (id: string) => {
|
||||
type: 'warning',
|
||||
});
|
||||
|
||||
dataSourceService.remove(id);
|
||||
dataSourceService.remove(id, { historySource: 'tree-contextmenu' });
|
||||
};
|
||||
|
||||
const dataSourceListRef = useTemplateRef<InstanceType<typeof DataSourceList>>('dataSourceList');
|
||||
@ -139,6 +150,20 @@ const filterTextChangeHandler = (val: string) => {
|
||||
};
|
||||
|
||||
eventBus?.on('edit-data-source', (id: string) => {
|
||||
editMethodName.value = '';
|
||||
editFieldPath.value = [];
|
||||
editHandler(id);
|
||||
});
|
||||
|
||||
eventBus?.on('edit-data-source-method', (id: string, methodName: string) => {
|
||||
editMethodName.value = methodName;
|
||||
editFieldPath.value = [];
|
||||
editHandler(id);
|
||||
});
|
||||
|
||||
eventBus?.on('edit-data-source-field', (id: string, fieldPath: string[]) => {
|
||||
editMethodName.value = '';
|
||||
editFieldPath.value = fieldPath;
|
||||
editHandler(id);
|
||||
});
|
||||
|
||||
|
||||
@ -39,7 +39,7 @@ export const useContentMenu = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
dataSourceService.add(cloneDeep(ds));
|
||||
dataSourceService.add(cloneDeep(ds), { historySource: 'tree-contextmenu' });
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@ -41,11 +41,15 @@ const createMenuItems = (group: ComponentGroup): MenuButton[] =>
|
||||
type: 'button',
|
||||
icon: component.icon,
|
||||
handler: () => {
|
||||
editorService.add({
|
||||
name: component.text,
|
||||
type: component.type,
|
||||
...(component.data || {}),
|
||||
});
|
||||
editorService.add(
|
||||
{
|
||||
name: component.text,
|
||||
type: component.type,
|
||||
...(component.data || {}),
|
||||
},
|
||||
undefined,
|
||||
{ historySource: 'tree-contextmenu' },
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
@ -57,9 +61,13 @@ const getSubMenuData = computed<MenuButton[]>(() => {
|
||||
type: 'button',
|
||||
icon: Files,
|
||||
handler: () => {
|
||||
editorService.add({
|
||||
type: 'tab-pane',
|
||||
});
|
||||
editorService.add(
|
||||
{
|
||||
type: 'tab-pane',
|
||||
},
|
||||
undefined,
|
||||
{ historySource: 'tree-contextmenu' },
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
@ -106,9 +114,9 @@ const menuData = computed<(MenuButton | MenuComponent)[]>(() =>
|
||||
items: getSubMenuData.value,
|
||||
},
|
||||
useCopyMenu(),
|
||||
usePasteMenu(),
|
||||
useDeleteMenu(),
|
||||
useMoveToMenu(services),
|
||||
usePasteMenu('tree-contextmenu'),
|
||||
useDeleteMenu('tree-contextmenu'),
|
||||
useMoveToMenu(services, 'tree-contextmenu'),
|
||||
...props.layerContentMenu,
|
||||
],
|
||||
'layer',
|
||||
|
||||
@ -25,9 +25,12 @@ const props = defineProps<{
|
||||
const { editorService } = useServices();
|
||||
|
||||
const setNodeVisible = (visible: boolean) => {
|
||||
editorService.update({
|
||||
id: props.data.id,
|
||||
visible,
|
||||
});
|
||||
editorService.update(
|
||||
{
|
||||
id: props.data.id,
|
||||
visible,
|
||||
},
|
||||
{ historySource: 'tree' },
|
||||
);
|
||||
};
|
||||
</script>
|
||||
|
||||
@ -8,6 +8,7 @@
|
||||
ref="box"
|
||||
v-model:visible="visible"
|
||||
title="当前位置下的组件"
|
||||
:framework-width="frameworkWidth"
|
||||
:position="menuPosition"
|
||||
>
|
||||
<template #body>
|
||||
@ -36,7 +37,9 @@ import { useNodeStatus } from '@editor/layouts/sidebar/layer/use-node-status';
|
||||
import type { TreeNodeData } from '@editor/type';
|
||||
|
||||
const services = useServices();
|
||||
const { editorService } = services;
|
||||
const { editorService, uiService } = services;
|
||||
|
||||
const frameworkWidth = computed(() => uiService.get('frameworkRect')?.width || 0);
|
||||
|
||||
const visible = ref(false);
|
||||
const buttonVisible = ref(false);
|
||||
|
||||
@ -380,7 +380,7 @@ const dropHandler = async (e: DragEvent) => {
|
||||
|
||||
config.data.inputEvent = e;
|
||||
|
||||
editorService.add(config.data, parent);
|
||||
editorService.add(config.data, parent, { historySource: 'component-panel' });
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
@ -49,11 +49,11 @@ const menuData = computed<(MenuButton | MenuComponent)[]>(() =>
|
||||
display: () => canCenter.value,
|
||||
handler: () => {
|
||||
if (!nodes.value) return;
|
||||
editorService.alignCenter(nodes.value);
|
||||
editorService.alignCenter(nodes.value, { historySource: 'stage-contextmenu' });
|
||||
},
|
||||
},
|
||||
useCopyMenu(),
|
||||
usePasteMenu(menuRef),
|
||||
usePasteMenu('stage-contextmenu', menuRef),
|
||||
{
|
||||
type: 'divider',
|
||||
direction: 'horizontal',
|
||||
@ -68,7 +68,7 @@ const menuData = computed<(MenuButton | MenuComponent)[]>(() =>
|
||||
icon: markRaw(Top),
|
||||
display: () => !isPage(node.value) && !isPageFragment(node.value) && !props.isMultiSelect,
|
||||
handler: () => {
|
||||
editorService.moveLayer(1);
|
||||
editorService.moveLayer(1, { historySource: 'stage-contextmenu' });
|
||||
},
|
||||
},
|
||||
{
|
||||
@ -77,7 +77,7 @@ const menuData = computed<(MenuButton | MenuComponent)[]>(() =>
|
||||
icon: markRaw(Bottom),
|
||||
display: () => !isPage(node.value) && !isPageFragment(node.value) && !props.isMultiSelect,
|
||||
handler: () => {
|
||||
editorService.moveLayer(-1);
|
||||
editorService.moveLayer(-1, { historySource: 'stage-contextmenu' });
|
||||
},
|
||||
},
|
||||
{
|
||||
@ -86,7 +86,7 @@ const menuData = computed<(MenuButton | MenuComponent)[]>(() =>
|
||||
icon: markRaw(Top),
|
||||
display: () => !isPage(node.value) && !isPageFragment(node.value) && !props.isMultiSelect,
|
||||
handler: () => {
|
||||
editorService.moveLayer(LayerOffset.TOP);
|
||||
editorService.moveLayer(LayerOffset.TOP, { historySource: 'stage-contextmenu' });
|
||||
},
|
||||
},
|
||||
{
|
||||
@ -95,16 +95,16 @@ const menuData = computed<(MenuButton | MenuComponent)[]>(() =>
|
||||
icon: markRaw(Bottom),
|
||||
display: () => !isPage(node.value) && !isPageFragment(node.value) && !props.isMultiSelect,
|
||||
handler: () => {
|
||||
editorService.moveLayer(LayerOffset.BOTTOM);
|
||||
editorService.moveLayer(LayerOffset.BOTTOM, { historySource: 'stage-contextmenu' });
|
||||
},
|
||||
},
|
||||
useMoveToMenu(services),
|
||||
useMoveToMenu(services, 'stage-contextmenu'),
|
||||
{
|
||||
type: 'divider',
|
||||
direction: 'horizontal',
|
||||
display: () => !isPage(node.value) && !isPageFragment(node.value) && !props.isMultiSelect,
|
||||
},
|
||||
useDeleteMenu(),
|
||||
useDeleteMenu('stage-contextmenu'),
|
||||
{
|
||||
type: 'divider',
|
||||
direction: 'horizontal',
|
||||
|
||||
@ -32,12 +32,14 @@ import type {
|
||||
AsyncHookPlugin,
|
||||
CodeBlockStepValue,
|
||||
CodeState,
|
||||
DslOpWithHistoryIdsResult,
|
||||
HistoryOpOptions,
|
||||
HistoryOpOptionsWithChangeRecords,
|
||||
} from '@editor/type';
|
||||
import { CODE_DRAFT_STORAGE_KEY } from '@editor/type';
|
||||
import { getEditorConfig } from '@editor/utils/config';
|
||||
import { COPY_CODE_STORAGE_KEY } from '@editor/utils/editor';
|
||||
import { createStackStep, describeRevertStep, getLastPushedHistoryIds } from '@editor/utils/history';
|
||||
|
||||
import BaseService from './BaseService';
|
||||
|
||||
@ -48,18 +50,6 @@ const canUsePluginMethods = {
|
||||
|
||||
type AsyncMethodName = Writable<(typeof canUsePluginMethods)['async']>;
|
||||
|
||||
/**
|
||||
* 「回滚」生成的新 step 简短描述。仅 service 层使用。
|
||||
*/
|
||||
const describeRevertCodeBlockStep = (step: CodeBlockStepValue): string => {
|
||||
const { oldContent, newContent, changeRecords, id } = step;
|
||||
if (oldContent === null && newContent) return `撤回新增 ${newContent.name || newContent.id || id}`;
|
||||
if (oldContent && newContent === null) return `还原已删除的 ${oldContent.name || oldContent.id || id}`;
|
||||
const name = newContent?.name || oldContent?.name || `${id}`;
|
||||
const propPath = changeRecords?.[0]?.propPath;
|
||||
return propPath ? `还原 ${name} · ${propPath}` : `还原 ${name}`;
|
||||
};
|
||||
|
||||
class CodeBlock extends BaseService {
|
||||
private state = reactive<CodeState>({
|
||||
codeDsl: null,
|
||||
@ -69,6 +59,17 @@ class CodeBlock extends BaseService {
|
||||
paramsColConfig: undefined,
|
||||
});
|
||||
|
||||
/**
|
||||
* 最近一次写入历史栈的代码块历史记录 uuid(单条写入场景:新增 / 更新)。
|
||||
* 供 setCodeDslById(Sync)AndGetHistoryId 取回,普通方法不读取它。
|
||||
*/
|
||||
private lastPushedHistoryId: string | null = null;
|
||||
/**
|
||||
* deleteCodeDslByIds 一次删除多个代码块时,按写入顺序收集的历史记录 uuid 列表。
|
||||
* 在 deleteCodeDslByIds 入口处重置,供 deleteCodeDslByIdsAndGetHistoryId 取回。
|
||||
*/
|
||||
private lastDeletedHistoryIds: string[] = [];
|
||||
|
||||
constructor() {
|
||||
super([
|
||||
...canUsePluginMethods.async.map((methodName) => ({ name: methodName, isAsync: true })),
|
||||
@ -84,6 +85,7 @@ class CodeBlock extends BaseService {
|
||||
public async setCodeDsl(codeDsl: CodeBlockDSL): Promise<void> {
|
||||
this.state.codeDsl = codeDsl;
|
||||
this.emit('code-dsl-change', this.state.codeDsl);
|
||||
this.emit('change', this.state.codeDsl);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -120,9 +122,19 @@ class CodeBlock extends BaseService {
|
||||
public async setCodeDslById(
|
||||
id: Id,
|
||||
codeConfig: Partial<CodeBlockContent>,
|
||||
{ changeRecords, doNotPushHistory = false }: HistoryOpOptionsWithChangeRecords = {},
|
||||
{
|
||||
changeRecords,
|
||||
doNotPushHistory = false,
|
||||
historyDescription,
|
||||
historySource,
|
||||
}: HistoryOpOptionsWithChangeRecords = {},
|
||||
): Promise<void> {
|
||||
this.setCodeDslByIdSync(id, codeConfig, true, { changeRecords, doNotPushHistory });
|
||||
this.setCodeDslByIdSync(id, codeConfig, true, {
|
||||
changeRecords,
|
||||
doNotPushHistory,
|
||||
historyDescription,
|
||||
historySource,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -141,7 +153,12 @@ class CodeBlock extends BaseService {
|
||||
id: Id,
|
||||
codeConfig: Partial<CodeBlockContent>,
|
||||
force = true,
|
||||
{ changeRecords, doNotPushHistory = false, historyDescription }: HistoryOpOptionsWithChangeRecords = {},
|
||||
{
|
||||
changeRecords,
|
||||
doNotPushHistory = false,
|
||||
historyDescription,
|
||||
historySource,
|
||||
}: HistoryOpOptionsWithChangeRecords = {},
|
||||
): void {
|
||||
const codeDsl = this.getCodeDsl();
|
||||
|
||||
@ -172,10 +189,18 @@ class CodeBlock extends BaseService {
|
||||
const newContent = cloneDeep(codeDsl[id]);
|
||||
|
||||
if (!doNotPushHistory) {
|
||||
historyService.pushCodeBlock(id, { oldContent, newContent, changeRecords, historyDescription });
|
||||
const step = createStackStep<CodeBlockContent, CodeBlockStepValue>(id, {
|
||||
oldValue: oldContent,
|
||||
newValue: newContent,
|
||||
changeRecords,
|
||||
historyDescription,
|
||||
source: historySource,
|
||||
});
|
||||
this.lastPushedHistoryId = (step ? historyService.push('codeBlock', step, id) : null)?.uuid ?? null;
|
||||
}
|
||||
|
||||
this.emit('addOrUpdate', id, codeDsl[id]);
|
||||
this.emit('change', this.getCodeDsl());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -268,26 +293,83 @@ class CodeBlock extends BaseService {
|
||||
*/
|
||||
public async deleteCodeDslByIds(
|
||||
codeIds: Id[],
|
||||
{ doNotPushHistory = false, historyDescription }: HistoryOpOptions = {},
|
||||
{ doNotPushHistory = false, historyDescription, historySource }: HistoryOpOptions = {},
|
||||
): Promise<void> {
|
||||
const currentDsl = await this.getCodeDsl();
|
||||
|
||||
if (!currentDsl) return;
|
||||
|
||||
this.lastDeletedHistoryIds = [];
|
||||
|
||||
codeIds.forEach((id) => {
|
||||
// 历史记录:删除前快照内容;不存在的 id 直接跳过历史推入
|
||||
const oldContent: CodeBlockContent | null = currentDsl[id] ? cloneDeep(currentDsl[id]) : null;
|
||||
const oldValue: CodeBlockContent | null = currentDsl[id] ? cloneDeep(currentDsl[id]) : null;
|
||||
|
||||
delete currentDsl[id];
|
||||
|
||||
if (oldContent && !doNotPushHistory) {
|
||||
historyService.pushCodeBlock(id, { oldContent, newContent: null, historyDescription });
|
||||
if (oldValue && !doNotPushHistory) {
|
||||
const step = createStackStep<CodeBlockContent, CodeBlockStepValue>(id, {
|
||||
oldValue,
|
||||
newValue: null,
|
||||
historyDescription,
|
||||
source: historySource,
|
||||
});
|
||||
const uuid = step ? historyService.push('codeBlock', step, id)?.uuid : undefined;
|
||||
if (uuid) this.lastDeletedHistoryIds.push(uuid);
|
||||
}
|
||||
|
||||
this.emit('remove', id);
|
||||
});
|
||||
|
||||
this.emit('change', this.getCodeDsl());
|
||||
}
|
||||
|
||||
// #region AndGetHistoryId
|
||||
/**
|
||||
* 下列 *AndGetHistoryId 方法与对应的写入方法行为完全一致,
|
||||
* 返回值在 {@link DslOpWithHistoryIdsResult} 中同时包含原操作结果与本次写入的历史 uuid 列表,
|
||||
* 可用于精确引用 / 定位该条历史记录(埋点、revert、跨端同步等)。
|
||||
*
|
||||
* 当本次操作未写入历史(doNotPushHistory 为 true、或无对应记录)时 historyIds 为 `[]`。
|
||||
*/
|
||||
|
||||
/** 等价于 {@link setCodeDslById},并额外返回本次写入历史记录的 uuid 列表(未入栈时 historyIds 为 `[]`)。 */
|
||||
public async setCodeDslByIdAndGetHistoryId(
|
||||
id: Id,
|
||||
codeConfig: Partial<CodeBlockContent>,
|
||||
options: HistoryOpOptionsWithChangeRecords = {},
|
||||
): Promise<DslOpWithHistoryIdsResult<void>> {
|
||||
this.lastPushedHistoryId = null;
|
||||
await this.setCodeDslById(id, codeConfig, options);
|
||||
return { result: undefined, historyIds: getLastPushedHistoryIds(this.lastPushedHistoryId) };
|
||||
}
|
||||
|
||||
/** 等价于 {@link setCodeDslByIdSync},并额外返回本次写入历史记录的 uuid 列表(未入栈时 historyIds 为 `[]`)。 */
|
||||
public setCodeDslByIdSyncAndGetHistoryId(
|
||||
id: Id,
|
||||
codeConfig: Partial<CodeBlockContent>,
|
||||
force = true,
|
||||
options: HistoryOpOptionsWithChangeRecords = {},
|
||||
): DslOpWithHistoryIdsResult<void> {
|
||||
this.lastPushedHistoryId = null;
|
||||
this.setCodeDslByIdSync(id, codeConfig, force, options);
|
||||
return { result: undefined, historyIds: getLastPushedHistoryIds(this.lastPushedHistoryId) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 等价于 {@link deleteCodeDslByIds},并额外返回本次写入的全部历史记录 uuid(按删除顺序)。
|
||||
* 一次删除多个代码块会产生多条历史记录;未写入任何历史时 historyIds 为 `[]`。
|
||||
*/
|
||||
public async deleteCodeDslByIdsAndGetHistoryId(
|
||||
codeIds: Id[],
|
||||
options: HistoryOpOptions = {},
|
||||
): Promise<DslOpWithHistoryIdsResult<void>> {
|
||||
this.lastDeletedHistoryIds = [];
|
||||
await this.deleteCodeDslByIds(codeIds, options);
|
||||
return { result: undefined, historyIds: [...this.lastDeletedHistoryIds] };
|
||||
}
|
||||
// #endregion AndGetHistoryId
|
||||
|
||||
public setParamsColConfig(config: TableColumnConfig): void {
|
||||
this.state.paramsColConfig = config;
|
||||
}
|
||||
@ -308,7 +390,7 @@ class CodeBlock extends BaseService {
|
||||
* @returns 撤销的 step;栈不存在或已无可撤销时返回 null
|
||||
*/
|
||||
public async undo(id: Id): Promise<CodeBlockStepValue | null> {
|
||||
const step = historyService.undoCodeBlock(id);
|
||||
const step = historyService.undo('codeBlock', id);
|
||||
if (!step) return null;
|
||||
await this.applyHistoryStep(step, true);
|
||||
return step;
|
||||
@ -320,7 +402,7 @@ class CodeBlock extends BaseService {
|
||||
* @returns 重做的 step;栈不存在或已无可重做时返回 null
|
||||
*/
|
||||
public async redo(id: Id): Promise<CodeBlockStepValue | null> {
|
||||
const step = historyService.redoCodeBlock(id);
|
||||
const step = historyService.redo('codeBlock', id);
|
||||
if (!step) return null;
|
||||
await this.applyHistoryStep(step, false);
|
||||
return step;
|
||||
@ -328,12 +410,12 @@ class CodeBlock extends BaseService {
|
||||
|
||||
/** 是否可对指定代码块撤销。 */
|
||||
public canUndo(id: Id): boolean {
|
||||
return historyService.canUndoCodeBlock(id);
|
||||
return historyService.canUndo('codeBlock', id);
|
||||
}
|
||||
|
||||
/** 是否可对指定代码块重做。 */
|
||||
public canRedo(id: Id): boolean {
|
||||
return historyService.canRedoCodeBlock(id);
|
||||
return historyService.canRedo('codeBlock', id);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -344,7 +426,7 @@ class CodeBlock extends BaseService {
|
||||
* @returns 实际移动到的最终游标位置
|
||||
*/
|
||||
public async goto(id: Id, targetCursor: number): Promise<number> {
|
||||
let cursor = historyService.getCodeBlockCursor(id);
|
||||
let cursor = historyService.getCursor('codeBlock', id);
|
||||
const target = Math.max(0, targetCursor);
|
||||
while (cursor > target) {
|
||||
const step = await this.undo(id);
|
||||
@ -370,13 +452,33 @@ class CodeBlock extends BaseService {
|
||||
* @returns 反向后产生的新 step;目标不存在 / 未应用时返回 null
|
||||
*/
|
||||
public async revert(id: Id, index: number): Promise<CodeBlockStepValue | null> {
|
||||
const list = historyService.getCodeBlockStepList(id);
|
||||
const list = historyService.getStepList('codeBlock', id);
|
||||
const entry = list[index];
|
||||
if (!entry?.applied) return null;
|
||||
const description = `回滚 #${index + 1}: ${describeRevertCodeBlockStep(entry.step)}`;
|
||||
// 更新类步骤(前后 content 都存在)必须带 changeRecords 才支持回滚,否则只能整内容替换,会冲掉后续无关变更。
|
||||
const { oldSchema, newSchema, changeRecords } = entry.step.diff?.[0] ?? {};
|
||||
|
||||
if (oldSchema && newSchema && !changeRecords?.length) return null;
|
||||
const description = `回滚 #${index + 1}: ${describeRevertStep<CodeBlockContent>(entry.step.data.id, entry.step.diff?.[0], (s) => s.name)}`;
|
||||
return await this.applyRevertStep(entry.step, description);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过历史记录 uuid 回滚代码块历史步骤,语义同 {@link revert},
|
||||
* 仅无需调用方再传 codeBlockId 与 index:内部会按 uuid 在全部代码块栈中定位对应步骤后再回滚。
|
||||
* 按数组顺序依次回滚,返回与入参同序的结果列表(某项失败时为 `null`)。
|
||||
*
|
||||
* @param uuids 目标历史记录的 uuid 列表,通常由 {@link setCodeDslByIdAndGetHistoryId} 等方法返回的 `historyIds`
|
||||
*/
|
||||
public async revertById(uuids: string[]): Promise<(CodeBlockStepValue | null)[]> {
|
||||
const results: (CodeBlockStepValue | null)[] = [];
|
||||
for (const uuid of uuids) {
|
||||
const location = historyService.findStepLocationByUuid('codeBlock', uuid);
|
||||
results.push(location ? await this.revert(location.id, location.index) : null);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成代码块唯一id
|
||||
* @returns {Id} 代码块唯一id
|
||||
@ -467,21 +569,22 @@ class CodeBlock extends BaseService {
|
||||
step: CodeBlockStepValue,
|
||||
historyDescription: string,
|
||||
): Promise<CodeBlockStepValue | null> {
|
||||
const { id, oldContent, newContent, changeRecords } = step;
|
||||
const { id } = step.data;
|
||||
const { oldSchema, newSchema, changeRecords } = step.diff?.[0] ?? {};
|
||||
|
||||
// 原本是新增 → revert 即删除
|
||||
if (oldContent === null && newContent) {
|
||||
await this.deleteCodeDslByIds([id], { historyDescription });
|
||||
return historyService.getCodeBlockStepList(id).slice(-1)[0]?.step ?? null;
|
||||
if (!oldSchema && newSchema) {
|
||||
await this.deleteCodeDslByIds([id], { historyDescription, historySource: 'rollback' });
|
||||
return historyService.getStepList('codeBlock', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
// 原本是删除 → revert 即写回
|
||||
if (oldContent && newContent === null) {
|
||||
this.setCodeDslByIdSync(id, cloneDeep(oldContent), true, { historyDescription });
|
||||
return historyService.getCodeBlockStepList(id).slice(-1)[0]?.step ?? null;
|
||||
if (oldSchema && !newSchema) {
|
||||
this.setCodeDslByIdSync(id, cloneDeep(oldSchema), true, { historyDescription, historySource: 'rollback' });
|
||||
return historyService.getStepList('codeBlock', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
if (!oldContent || !newContent) return null;
|
||||
if (!oldSchema || !newSchema) return null;
|
||||
|
||||
// 原本是更新 → 把 oldContent 写回;优先按 changeRecords 局部 patch
|
||||
if (changeRecords?.length) {
|
||||
@ -494,18 +597,19 @@ class CodeBlock extends BaseService {
|
||||
fallbackToFullReplace = true;
|
||||
break;
|
||||
}
|
||||
const value = cloneDeep(getValueByKeyPath(record.propPath, oldContent));
|
||||
const value = cloneDeep(getValueByKeyPath(record.propPath, oldSchema));
|
||||
setValueByKeyPath(record.propPath, value, patched);
|
||||
}
|
||||
this.setCodeDslByIdSync(id, fallbackToFullReplace ? cloneDeep(oldContent) : patched, true, {
|
||||
this.setCodeDslByIdSync(id, fallbackToFullReplace ? cloneDeep(oldSchema) : patched, true, {
|
||||
changeRecords,
|
||||
historyDescription,
|
||||
historySource: 'rollback',
|
||||
});
|
||||
return historyService.getCodeBlockStepList(id).slice(-1)[0]?.step ?? null;
|
||||
return historyService.getStepList('codeBlock', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
this.setCodeDslByIdSync(id, cloneDeep(oldContent), true, { historyDescription });
|
||||
return historyService.getCodeBlockStepList(id).slice(-1)[0]?.step ?? null;
|
||||
this.setCodeDslByIdSync(id, cloneDeep(oldSchema), true, { historyDescription, historySource: 'rollback' });
|
||||
return historyService.getStepList('codeBlock', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -523,31 +627,32 @@ class CodeBlock extends BaseService {
|
||||
* @param reverse true=撤销,false=重做
|
||||
*/
|
||||
private async applyHistoryStep(step: CodeBlockStepValue, reverse: boolean): Promise<void> {
|
||||
const { id, oldContent, newContent, changeRecords } = step;
|
||||
const { id } = step.data;
|
||||
const { oldSchema, newSchema, changeRecords } = step.diff?.[0] ?? {};
|
||||
|
||||
// 新增 / 删除:直接 set 或 delete,不走 patch 逻辑
|
||||
if (oldContent === null && newContent) {
|
||||
if (!oldSchema && newSchema) {
|
||||
if (reverse) {
|
||||
await this.deleteCodeDslByIds([id], { doNotPushHistory: true });
|
||||
} else {
|
||||
this.setCodeDslByIdSync(id, cloneDeep(newContent), true, { doNotPushHistory: true });
|
||||
this.setCodeDslByIdSync(id, cloneDeep(newSchema), true, { doNotPushHistory: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (oldContent && newContent === null) {
|
||||
if (oldSchema && !newSchema) {
|
||||
if (reverse) {
|
||||
this.setCodeDslByIdSync(id, cloneDeep(oldContent), true, { doNotPushHistory: true });
|
||||
this.setCodeDslByIdSync(id, cloneDeep(oldSchema), true, { doNotPushHistory: true });
|
||||
} else {
|
||||
await this.deleteCodeDslByIds([id], { doNotPushHistory: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!oldContent || !newContent) return;
|
||||
if (!oldSchema || !newSchema) return;
|
||||
|
||||
// 更新场景:优先按 changeRecords 局部 patch;缺省退化为整内容替换
|
||||
const sourceForValues = reverse ? oldContent : newContent;
|
||||
const sourceForValues = reverse ? oldSchema : newSchema;
|
||||
|
||||
if (changeRecords?.length) {
|
||||
const current = this.getCodeContentById(id);
|
||||
|
||||
@ -13,12 +13,14 @@ import storageService, { Protocol } from '@editor/services/storage';
|
||||
import type {
|
||||
DataSourceStepValue,
|
||||
DatasourceTypeOption,
|
||||
DslOpWithHistoryIdsResult,
|
||||
HistoryOpOptions,
|
||||
HistoryOpOptionsWithChangeRecords,
|
||||
SyncHookPlugin,
|
||||
} from '@editor/type';
|
||||
import { getFormConfig, getFormValue } from '@editor/utils/data-source';
|
||||
import { COPY_DS_STORAGE_KEY } from '@editor/utils/editor';
|
||||
import { createStackStep, describeRevertStep, getLastPushedHistoryIds } from '@editor/utils/history';
|
||||
|
||||
import BaseService from './BaseService';
|
||||
|
||||
@ -54,19 +56,6 @@ const canUsePluginMethods = {
|
||||
|
||||
type SyncMethodName = Writable<(typeof canUsePluginMethods)['sync']>;
|
||||
|
||||
/**
|
||||
* 「回滚」生成的新 step 简短描述。
|
||||
* 仅在 service 层使用,避免依赖 UI 层 composables。
|
||||
*/
|
||||
const describeRevertDataSourceStep = (step: DataSourceStepValue): string => {
|
||||
const { oldSchema, newSchema, changeRecords, id } = step;
|
||||
if (oldSchema === null && newSchema) return `撤回新增 ${newSchema.title || newSchema.id || id}`;
|
||||
if (oldSchema && newSchema === null) return `还原已删除的 ${oldSchema.title || oldSchema.id || id}`;
|
||||
const title = newSchema?.title || oldSchema?.title || `${id}`;
|
||||
const propPath = changeRecords?.[0]?.propPath;
|
||||
return propPath ? `还原 ${title} · ${propPath}` : `还原 ${title}`;
|
||||
};
|
||||
|
||||
class DataSource extends BaseService {
|
||||
private state = reactive<State>({
|
||||
datasourceTypeList: [],
|
||||
@ -78,6 +67,13 @@ class DataSource extends BaseService {
|
||||
methods: {},
|
||||
});
|
||||
|
||||
/**
|
||||
* 最近一次写入历史栈的数据源历史记录 uuid。
|
||||
* 供 *AndGetHistoryId 系列方法在调用 add / update / remove 后取回本次产生的历史记录 id;
|
||||
* 普通方法不读取它,调用前由 *AndGetHistoryId 重置为 null。
|
||||
*/
|
||||
private lastPushedHistoryId: string | null = null;
|
||||
|
||||
constructor() {
|
||||
super(canUsePluginMethods.sync.map((methodName) => ({ name: methodName, isAsync: false })));
|
||||
}
|
||||
@ -129,7 +125,10 @@ class DataSource extends BaseService {
|
||||
* @param options.doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
* @param options.historyDescription 入栈时附带的人类可读描述,用于历史面板展示
|
||||
*/
|
||||
public add(config: DataSourceSchema, { doNotPushHistory = false, historyDescription }: HistoryOpOptions = {}) {
|
||||
public add(
|
||||
config: DataSourceSchema,
|
||||
{ doNotPushHistory = false, historyDescription, historySource }: HistoryOpOptions = {},
|
||||
) {
|
||||
const newConfig = {
|
||||
...config,
|
||||
id: config.id && !this.getDataSourceById(config.id) ? config.id : this.createId(),
|
||||
@ -138,10 +137,17 @@ class DataSource extends BaseService {
|
||||
this.get('dataSources').push(newConfig);
|
||||
|
||||
if (!doNotPushHistory) {
|
||||
historyService.pushDataSource(newConfig.id, { oldSchema: null, newSchema: newConfig, historyDescription });
|
||||
const step = createStackStep<DataSourceSchema, DataSourceStepValue>(newConfig.id, {
|
||||
oldValue: null,
|
||||
newValue: newConfig,
|
||||
historyDescription,
|
||||
source: historySource,
|
||||
});
|
||||
this.lastPushedHistoryId = (step ? historyService.push('dataSource', step, newConfig.id) : null)?.uuid ?? null;
|
||||
}
|
||||
|
||||
this.emit('add', newConfig);
|
||||
this.emit('change', this.get('dataSources'));
|
||||
|
||||
return newConfig;
|
||||
}
|
||||
@ -156,7 +162,12 @@ class DataSource extends BaseService {
|
||||
*/
|
||||
public update(
|
||||
config: DataSourceSchema,
|
||||
{ changeRecords = [], doNotPushHistory = false, historyDescription }: HistoryOpOptionsWithChangeRecords = {},
|
||||
{
|
||||
changeRecords = [],
|
||||
doNotPushHistory = false,
|
||||
historyDescription,
|
||||
historySource,
|
||||
}: HistoryOpOptionsWithChangeRecords = {},
|
||||
) {
|
||||
const dataSources = this.get('dataSources');
|
||||
|
||||
@ -168,18 +179,21 @@ class DataSource extends BaseService {
|
||||
dataSources[index] = newConfig;
|
||||
|
||||
if (!doNotPushHistory) {
|
||||
historyService.pushDataSource(newConfig.id, {
|
||||
oldSchema: oldConfig ? cloneDeep(oldConfig) : null,
|
||||
newSchema: newConfig,
|
||||
const step = createStackStep<DataSourceSchema, DataSourceStepValue>(newConfig.id, {
|
||||
oldValue: oldConfig ? cloneDeep(oldConfig) : null,
|
||||
newValue: newConfig,
|
||||
changeRecords,
|
||||
historyDescription,
|
||||
source: historySource,
|
||||
});
|
||||
this.lastPushedHistoryId = (step ? historyService.push('dataSource', step, newConfig.id) : null)?.uuid ?? null;
|
||||
}
|
||||
|
||||
this.emit('update', newConfig, {
|
||||
oldConfig,
|
||||
changeRecords,
|
||||
});
|
||||
this.emit('change', this.get('dataSources'));
|
||||
|
||||
return newConfig;
|
||||
}
|
||||
@ -191,19 +205,63 @@ class DataSource extends BaseService {
|
||||
* @param options.doNotPushHistory 是否不写入历史记录(默认 false)
|
||||
* @param options.historyDescription 入栈时附带的人类可读描述,用于历史面板展示
|
||||
*/
|
||||
public remove(id: string, { doNotPushHistory = false, historyDescription }: HistoryOpOptions = {}) {
|
||||
public remove(id: string, { doNotPushHistory = false, historyDescription, historySource }: HistoryOpOptions = {}) {
|
||||
const dataSources = this.get('dataSources');
|
||||
const index = dataSources.findIndex((ds) => ds.id === id);
|
||||
const oldConfig = index !== -1 ? dataSources[index] : null;
|
||||
dataSources.splice(index, 1);
|
||||
|
||||
if (oldConfig && !doNotPushHistory) {
|
||||
historyService.pushDataSource(id, { oldSchema: cloneDeep(oldConfig), newSchema: null, historyDescription });
|
||||
const step = createStackStep<DataSourceSchema, DataSourceStepValue>(id, {
|
||||
oldValue: cloneDeep(oldConfig),
|
||||
newValue: null,
|
||||
historyDescription,
|
||||
source: historySource,
|
||||
});
|
||||
this.lastPushedHistoryId = (step ? historyService.push('dataSource', step, id) : null)?.uuid ?? null;
|
||||
}
|
||||
|
||||
this.emit('remove', id);
|
||||
this.emit('change', this.get('dataSources'));
|
||||
}
|
||||
|
||||
// #region AndGetHistoryId
|
||||
/**
|
||||
* 下列 *AndGetHistoryId 方法与对应的 add / update / remove 行为完全一致,
|
||||
* 返回值在 {@link DslOpWithHistoryIdsResult} 中同时包含原操作结果与本次写入历史栈的 uuid 列表({@link DataSourceStepValue.uuid}),
|
||||
* 可用于精确引用 / 定位该条历史记录(埋点、revert、跨端同步等)。
|
||||
*
|
||||
* 当本次操作未写入历史(doNotPushHistory 为 true、或无对应记录)时 historyIds 为 `[]`。
|
||||
*/
|
||||
|
||||
/** 等价于 {@link add},并额外返回本次写入历史记录的 uuid 列表(未入栈时 historyIds 为 `[]`)。 */
|
||||
public addAndGetHistoryId(
|
||||
config: DataSourceSchema,
|
||||
options: HistoryOpOptions = {},
|
||||
): DslOpWithHistoryIdsResult<DataSourceSchema> {
|
||||
this.lastPushedHistoryId = null;
|
||||
const result = this.add(config, options);
|
||||
return { result, historyIds: getLastPushedHistoryIds(this.lastPushedHistoryId) };
|
||||
}
|
||||
|
||||
/** 等价于 {@link update},并额外返回本次写入历史记录的 uuid 列表(未入栈时 historyIds 为 `[]`)。 */
|
||||
public updateAndGetHistoryId(
|
||||
config: DataSourceSchema,
|
||||
options: HistoryOpOptionsWithChangeRecords = {},
|
||||
): DslOpWithHistoryIdsResult<DataSourceSchema> {
|
||||
this.lastPushedHistoryId = null;
|
||||
const result = this.update(config, options);
|
||||
return { result, historyIds: getLastPushedHistoryIds(this.lastPushedHistoryId) };
|
||||
}
|
||||
|
||||
/** 等价于 {@link remove},并额外返回本次写入历史记录的 uuid 列表(未入栈时 historyIds 为 `[]`)。 */
|
||||
public removeAndGetHistoryId(id: string, options: HistoryOpOptions = {}): DslOpWithHistoryIdsResult<void> {
|
||||
this.lastPushedHistoryId = null;
|
||||
this.remove(id, options);
|
||||
return { result: undefined, historyIds: getLastPushedHistoryIds(this.lastPushedHistoryId) };
|
||||
}
|
||||
// #endregion AndGetHistoryId
|
||||
|
||||
/**
|
||||
* 撤销指定数据源的最近一次变更。
|
||||
*
|
||||
@ -215,7 +273,7 @@ class DataSource extends BaseService {
|
||||
* @returns 撤销的 step;栈不存在或已无可撤销时返回 null
|
||||
*/
|
||||
public undo(id: Id) {
|
||||
const step = historyService.undoDataSource(id);
|
||||
const step = historyService.undo('dataSource', id);
|
||||
if (!step) return null;
|
||||
this.applyHistoryStep(step, true);
|
||||
return step;
|
||||
@ -227,7 +285,7 @@ class DataSource extends BaseService {
|
||||
* @returns 重做的 step;栈不存在或已无可重做时返回 null
|
||||
*/
|
||||
public redo(id: Id) {
|
||||
const step = historyService.redoDataSource(id);
|
||||
const step = historyService.redo('dataSource', id);
|
||||
if (!step) return null;
|
||||
this.applyHistoryStep(step, false);
|
||||
return step;
|
||||
@ -235,12 +293,12 @@ class DataSource extends BaseService {
|
||||
|
||||
/** 是否可对指定数据源撤销。 */
|
||||
public canUndo(id: Id): boolean {
|
||||
return historyService.canUndoDataSource(id);
|
||||
return historyService.canUndo('dataSource', id);
|
||||
}
|
||||
|
||||
/** 是否可对指定数据源重做。 */
|
||||
public canRedo(id: Id): boolean {
|
||||
return historyService.canRedoDataSource(id);
|
||||
return historyService.canRedo('dataSource', id);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -251,7 +309,7 @@ class DataSource extends BaseService {
|
||||
* @returns 实际移动到的最终游标位置
|
||||
*/
|
||||
public goto(id: Id, targetCursor: number): number {
|
||||
let cursor = historyService.getDataSourceCursor(id);
|
||||
let cursor = historyService.getCursor('dataSource', id);
|
||||
const target = Math.max(0, targetCursor);
|
||||
while (cursor > target) {
|
||||
if (!this.undo(id)) break;
|
||||
@ -275,13 +333,31 @@ class DataSource extends BaseService {
|
||||
* @returns 反向后产生的新 step;目标不存在 / 未应用时返回 null
|
||||
*/
|
||||
public revert(id: Id, index: number): DataSourceStepValue | null {
|
||||
const list = historyService.getDataSourceStepList(id);
|
||||
const list = historyService.getStepList('dataSource', id);
|
||||
const entry = list[index];
|
||||
if (!entry?.applied) return null;
|
||||
const description = `回滚 #${index + 1}: ${describeRevertDataSourceStep(entry.step)}`;
|
||||
// 更新类步骤(前后 schema 都存在)必须带 changeRecords 才支持回滚,否则只能整 schema 替换,会冲掉后续无关变更。
|
||||
const { oldSchema, newSchema, changeRecords } = entry.step.diff?.[0] ?? {};
|
||||
if (oldSchema && newSchema && !changeRecords?.length) return null;
|
||||
const description = `回滚 #${index + 1}: ${describeRevertStep<DataSourceSchema>(entry.step.data.id, entry.step.diff?.[0], (s) => s.title)}`;
|
||||
return this.applyRevertStep(entry.step, description);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过历史记录 uuid 回滚数据源历史步骤,语义同 {@link revert},
|
||||
* 仅无需调用方再传 dataSourceId 与 index:内部会按 uuid 在全部数据源栈中定位对应步骤后再回滚。
|
||||
* 按数组顺序依次回滚,返回与入参同序的结果列表(某项失败时为 `null`)。
|
||||
*
|
||||
* @param uuids 目标历史记录的 uuid 列表,通常由 {@link addAndGetHistoryId} 等方法返回的 `historyIds`
|
||||
*/
|
||||
public revertById(uuids: string[]): (DataSourceStepValue | null)[] {
|
||||
return uuids.map((uuid) => {
|
||||
const location = historyService.findStepLocationByUuid('dataSource', uuid);
|
||||
if (!location) return null;
|
||||
return this.revert(location.id, location.index);
|
||||
});
|
||||
}
|
||||
|
||||
public createId(): string {
|
||||
return `ds_${guid()}`;
|
||||
}
|
||||
@ -362,18 +438,19 @@ class DataSource extends BaseService {
|
||||
* 同构,差异仅在于走对应的公共 add / update / remove 而不是带 doNotPushHistory 的版本。
|
||||
*/
|
||||
private applyRevertStep(step: DataSourceStepValue, historyDescription: string): DataSourceStepValue | null {
|
||||
const { id, oldSchema, newSchema, changeRecords } = step;
|
||||
const { id } = step.data;
|
||||
const { oldSchema, newSchema, changeRecords } = step.diff?.[0] ?? {};
|
||||
|
||||
// 原本是新增 → revert 即删除
|
||||
if (oldSchema === null && newSchema) {
|
||||
this.remove(`${id}`, { historyDescription });
|
||||
return historyService.getDataSourceStepList(id).slice(-1)[0]?.step ?? null;
|
||||
if (!oldSchema && newSchema) {
|
||||
this.remove(`${id}`, { historyDescription, historySource: 'rollback' });
|
||||
return historyService.getStepList('dataSource', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
// 原本是删除 → revert 即重新加回
|
||||
if (oldSchema && newSchema === null) {
|
||||
this.add(cloneDeep(oldSchema), { historyDescription });
|
||||
return historyService.getDataSourceStepList(id).slice(-1)[0]?.step ?? null;
|
||||
if (oldSchema && !newSchema) {
|
||||
this.add(cloneDeep(oldSchema), { historyDescription, historySource: 'rollback' });
|
||||
return historyService.getStepList('dataSource', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
if (!oldSchema || !newSchema) return null;
|
||||
@ -395,12 +472,13 @@ class DataSource extends BaseService {
|
||||
this.update(fallbackToFullReplace ? cloneDeep(oldSchema) : patched, {
|
||||
changeRecords,
|
||||
historyDescription,
|
||||
historySource: 'rollback',
|
||||
});
|
||||
return historyService.getDataSourceStepList(id).slice(-1)[0]?.step ?? null;
|
||||
return historyService.getStepList('dataSource', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
this.update(cloneDeep(oldSchema), { historyDescription });
|
||||
return historyService.getDataSourceStepList(id).slice(-1)[0]?.step ?? null;
|
||||
this.update(cloneDeep(oldSchema), { historyDescription, historySource: 'rollback' });
|
||||
return historyService.getStepList('dataSource', id).slice(-1)[0]?.step ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -418,10 +496,11 @@ class DataSource extends BaseService {
|
||||
* @param reverse true=撤销,false=重做
|
||||
*/
|
||||
private applyHistoryStep(step: DataSourceStepValue, reverse: boolean): void {
|
||||
const { id, oldSchema, newSchema, changeRecords } = step;
|
||||
const { id } = step.data;
|
||||
const { oldSchema, newSchema, changeRecords } = step.diff?.[0] ?? {};
|
||||
|
||||
// 新增 / 删除:直接 add 或 remove,不走 patch 逻辑
|
||||
if (oldSchema === null && newSchema) {
|
||||
if (!oldSchema && newSchema) {
|
||||
if (reverse) {
|
||||
this.remove(`${id}`, { doNotPushHistory: true });
|
||||
} else {
|
||||
@ -430,7 +509,7 @@ class DataSource extends BaseService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (oldSchema && newSchema === null) {
|
||||
if (oldSchema && !newSchema) {
|
||||
if (reverse) {
|
||||
this.add(cloneDeep(oldSchema), { doNotPushHistory: true });
|
||||
} else {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -20,7 +20,7 @@ class Keybinding extends BaseService {
|
||||
const nodes = editorService.get('nodes');
|
||||
|
||||
if (!nodes || isPage(nodes[0]) || isPageFragment(nodes[0])) return;
|
||||
editorService.remove(nodes);
|
||||
editorService.remove(nodes, { historySource: 'shortcut' });
|
||||
},
|
||||
[KeyBindingCommand.COPY_NODE]: () => {
|
||||
const nodes = editorService.get('nodes');
|
||||
@ -31,11 +31,11 @@ class Keybinding extends BaseService {
|
||||
|
||||
if (!nodes || isPage(nodes[0]) || isPageFragment(nodes[0])) return;
|
||||
editorService.copy(nodes);
|
||||
editorService.remove(nodes);
|
||||
editorService.remove(nodes, { historySource: 'shortcut' });
|
||||
},
|
||||
[KeyBindingCommand.PASTE_NODE]: () => {
|
||||
const nodes = editorService.get('nodes');
|
||||
nodes && editorService.paste({ offsetX: 10, offsetY: 10 });
|
||||
nodes && editorService.paste({ offsetX: 10, offsetY: 10 }, undefined, { historySource: 'shortcut' });
|
||||
},
|
||||
[KeyBindingCommand.UNDO]: () => {
|
||||
editorService.undo();
|
||||
|
||||
@ -27,6 +27,9 @@ import {
|
||||
DEFAULT_LEFT_COLUMN_WIDTH,
|
||||
DEFAULT_RIGHT_COLUMN_WIDTH,
|
||||
LEFT_COLUMN_WIDTH_STORAGE_KEY,
|
||||
MIN_CENTER_COLUMN_WIDTH,
|
||||
MIN_LEFT_COLUMN_WIDTH,
|
||||
MIN_RIGHT_COLUMN_WIDTH,
|
||||
RIGHT_COLUMN_WIDTH_STORAGE_KEY,
|
||||
} from '@editor/utils/const';
|
||||
|
||||
@ -54,6 +57,9 @@ const state = shallowReactive<UiState>({
|
||||
storageService.getItem(RIGHT_COLUMN_WIDTH_STORAGE_KEY, { protocol: Protocol.NUMBER }) ||
|
||||
DEFAULT_RIGHT_COLUMN_WIDTH,
|
||||
},
|
||||
minLeftColumnWidth: MIN_LEFT_COLUMN_WIDTH,
|
||||
minCenterColumnWidth: MIN_CENTER_COLUMN_WIDTH,
|
||||
minRightColumnWidth: MIN_RIGHT_COLUMN_WIDTH,
|
||||
showGuides: true,
|
||||
hasGuides: false,
|
||||
showRule: true,
|
||||
@ -62,6 +68,7 @@ const state = shallowReactive<UiState>({
|
||||
showPageListButton: true,
|
||||
hideSlideBar: false,
|
||||
sideBarItems: [],
|
||||
sideBarActiveTabName: '',
|
||||
navMenuRect: {
|
||||
left: 0,
|
||||
top: 0,
|
||||
@ -104,7 +111,13 @@ class Ui extends BaseService {
|
||||
mask?.showRule(value as unknown as boolean);
|
||||
}
|
||||
|
||||
const preValue = state[name];
|
||||
|
||||
state[name] = value;
|
||||
|
||||
if (preValue !== value) {
|
||||
this.emit('state-change', name, value, preValue);
|
||||
}
|
||||
}
|
||||
|
||||
public get<K extends keyof UiState>(name: K) {
|
||||
|
||||
@ -25,10 +25,18 @@
|
||||
.m-editor-float-box-body {
|
||||
overflow: auto;
|
||||
flex: 1;
|
||||
padding: 0 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.m-editor-floating-box-moveable {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.m-editor-float-box-drag-mask {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
z-index: 1;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 40px;
|
||||
@ -45,6 +45,28 @@
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
// 历史列表工具条:放置「清空」等列表级操作,右对齐。
|
||||
.m-editor-history-list-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding: 0 4px 4px;
|
||||
}
|
||||
|
||||
// 「清空」按钮:红色文字按钮,强调破坏性操作(点击后会二次确认)。
|
||||
.m-editor-history-list-clear {
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
color: #f56c6c;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(245, 108, 108, 0.12);
|
||||
}
|
||||
}
|
||||
|
||||
.m-editor-history-list-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@ -125,19 +147,19 @@
|
||||
&.is-merged {
|
||||
margin: 4px 0;
|
||||
padding: 4px 8px 6px;
|
||||
background-color: rgba(144, 105, 219, 0.06);
|
||||
border: 1px solid rgba(144, 105, 219, 0.18);
|
||||
border-left: 3px solid #9069db;
|
||||
background-color: rgba(47, 84, 235, 0.06);
|
||||
border: 1px solid rgba(47, 84, 235, 0.18);
|
||||
border-left: 3px solid #2f54eb;
|
||||
border-radius: 4px;
|
||||
|
||||
// 卡片本体已经有背景色,hover 状态以更深的同色提示交互
|
||||
&:hover {
|
||||
background-color: rgba(144, 105, 219, 0.1);
|
||||
background-color: rgba(47, 84, 235, 0.1);
|
||||
}
|
||||
|
||||
.m-editor-history-list-group-head {
|
||||
font-weight: 600;
|
||||
color: #5b3fa5;
|
||||
color: #1d39c4;
|
||||
}
|
||||
|
||||
// 已撤销态:整张卡片去色
|
||||
@ -169,7 +191,7 @@
|
||||
margin: 6px 0 0 6px;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
border-left: 1px dashed rgba(144, 105, 219, 0.45);
|
||||
border-left: 1px dashed rgba(47, 84, 235, 0.45);
|
||||
|
||||
li {
|
||||
display: flex;
|
||||
@ -185,7 +207,7 @@
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(144, 105, 219, 0.1);
|
||||
background-color: rgba(47, 84, 235, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
@ -215,6 +237,10 @@
|
||||
|
||||
.m-editor-history-list-item-index {
|
||||
flex: 0 0 auto;
|
||||
// 固定最小宽度并右对齐:序号位数不一(#6 / #16)时右边界仍统一,
|
||||
// 使紧随其后的「类型」徽标在各行间对齐成整齐的一列。
|
||||
min-width: 30px;
|
||||
text-align: right;
|
||||
color: #909399;
|
||||
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
|
||||
font-size: 11px;
|
||||
@ -222,6 +248,25 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
// 合并组头部展示的是步骤区间(如 #10-#20),宽度本就不定、也无需与单步行对齐,
|
||||
// 恢复自然宽度与左对齐,避免被强制成固定列后显得突兀。
|
||||
.m-editor-history-list-group.is-merged
|
||||
> .m-editor-history-list-group-head
|
||||
> .m-editor-history-list-item-index {
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
// 操作时间:弱化展示,紧贴在描述之后、各操作按钮之前。
|
||||
.m-editor-history-list-item-time {
|
||||
flex: 0 0 auto;
|
||||
color: #a8abb2;
|
||||
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
|
||||
font-size: 11px;
|
||||
font-weight: 400; // 防止被合并组头部的粗体继承
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.m-editor-history-list-item-op {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 6px;
|
||||
@ -240,7 +285,7 @@
|
||||
}
|
||||
|
||||
&.op-update {
|
||||
background-color: #409eff;
|
||||
background-color: #e6a23c;
|
||||
}
|
||||
|
||||
&.op-initial {
|
||||
@ -271,6 +316,48 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
// 「操作途径」徽标:浅灰描边胶囊,弱化展示来源(画布 / 图层 / 配置面板…),不抢占描述焦点。
|
||||
.m-editor-history-list-item-source {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 6px;
|
||||
border: 1px solid #dcdfe6;
|
||||
border-radius: 8px;
|
||||
font-size: 10px;
|
||||
line-height: 14px;
|
||||
color: #909399;
|
||||
background-color: #f4f4f5;
|
||||
white-space: nowrap;
|
||||
font-weight: 400; // 防止被合并组头部的粗体继承
|
||||
}
|
||||
|
||||
// 「操作人」徽标:浅蓝描边胶囊,弱化展示操作人,仅在 step.operator 有值时渲染。
|
||||
.m-editor-history-list-item-operator {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 6px;
|
||||
border: 1px solid #c6e2ff;
|
||||
border-radius: 8px;
|
||||
font-size: 10px;
|
||||
line-height: 14px;
|
||||
color: #409eff;
|
||||
background-color: #ecf5ff;
|
||||
white-space: nowrap;
|
||||
font-weight: 400; // 防止被合并组头部的粗体继承
|
||||
}
|
||||
|
||||
// 「已保存」徽标:绿色实心胶囊,标记最近一次保存对应的历史记录(与 historyService.markSaved 对应)。
|
||||
.m-editor-history-list-item-saved {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 6px;
|
||||
border-radius: 8px;
|
||||
font-size: 10px;
|
||||
line-height: 16px;
|
||||
color: #fff;
|
||||
background-color: #67c23a;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
// 「合并 N 步」徽标:紫色实心胶囊,与合并组卡片色系一致,醒目区分单步条目。
|
||||
.m-editor-history-list-item-merge {
|
||||
flex: 0 0 auto;
|
||||
@ -279,11 +366,29 @@
|
||||
font-size: 10px;
|
||||
line-height: 16px;
|
||||
color: #fff;
|
||||
background-color: #9069db;
|
||||
background-color: #2f54eb;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
// 操作区:把「回滚 / 回到 / 查看差异」收敛为一个统一容器,默认隐藏,
|
||||
// 仅在指针悬停于所在行时显示。静止状态下每行最右侧固定为「时间」,
|
||||
// 各行因此能对齐成整齐的右侧列,避免按钮数量不一导致的参差错乱。
|
||||
.m-editor-history-list-item-actions {
|
||||
display: none;
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.m-editor-history-list-group-head:hover > .m-editor-history-list-item-actions,
|
||||
.m-editor-history-list-substeps
|
||||
> li:hover
|
||||
> .m-editor-history-list-item-actions,
|
||||
.m-editor-history-list-initial:hover > .m-editor-history-list-item-actions {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.m-editor-history-list-item-diff {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 6px;
|
||||
@ -300,21 +405,39 @@
|
||||
}
|
||||
}
|
||||
|
||||
// 「回到」按钮:将历史游标移动到该 step。使用绿色色系,
|
||||
// 与红色「回滚」、蓝色「查看差异」区分,也避免与紧邻的灰色「来源」徽标混淆。
|
||||
.m-editor-history-list-item-goto {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 6px;
|
||||
border-radius: 2px;
|
||||
font-size: 10px;
|
||||
line-height: 16px;
|
||||
color: #529b2e;
|
||||
background-color: rgba(103, 194, 58, 0.12);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(103, 194, 58, 0.24);
|
||||
}
|
||||
}
|
||||
|
||||
// 「回滚」按钮:类 git revert,把目标 step 反向应用一次作为新提交。
|
||||
// 使用与「查看差异」不同的色调(橙黄),用来区分"可逆操作"与"只读对比"。
|
||||
// 使用红色色调,强调其为"破坏性/可逆操作",与「查看差异」「跳转」区分开。
|
||||
.m-editor-history-list-item-revert {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 6px;
|
||||
border-radius: 2px;
|
||||
font-size: 10px;
|
||||
line-height: 16px;
|
||||
color: #e6a23c;
|
||||
background-color: rgba(230, 162, 60, 0.12);
|
||||
color: #f56c6c;
|
||||
background-color: rgba(245, 108, 108, 0.12);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(230, 162, 60, 0.25);
|
||||
background-color: rgba(245, 108, 108, 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
@ -369,6 +492,17 @@
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.m-editor-history-diff-dialog-notice {
|
||||
margin-bottom: 8px;
|
||||
padding: 8px 12px;
|
||||
background-color: #fdf6ec;
|
||||
border: 1px solid #faecd8;
|
||||
border-radius: 4px;
|
||||
color: #e6a23c;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.m-editor-history-diff-dialog-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@ -102,10 +102,6 @@
|
||||
transition: all 0.2s ease 0s;
|
||||
padding: 5px 14px;
|
||||
|
||||
.tmagic-design-button {
|
||||
color: $font-color;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: $hover-color;
|
||||
}
|
||||
|
||||
@ -58,7 +58,7 @@
|
||||
position: absolute;
|
||||
right: 15px;
|
||||
bottom: 15px;
|
||||
z-index: 30;
|
||||
z-index: 32;
|
||||
opacity: 0.5;
|
||||
|
||||
&:hover {
|
||||
@ -70,7 +70,7 @@
|
||||
position: absolute;
|
||||
right: 15px;
|
||||
bottom: 60px;
|
||||
z-index: 30;
|
||||
z-index: 31;
|
||||
opacity: 0.5;
|
||||
|
||||
&:hover {
|
||||
@ -82,7 +82,7 @@
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
z-index: 31;
|
||||
}
|
||||
|
||||
.m-editor-resizer {
|
||||
|
||||
@ -24,9 +24,12 @@
|
||||
& + .border-icon {
|
||||
margin-left: 8px;
|
||||
}
|
||||
&.configured {
|
||||
border-color: var(--el-color-success, var(--td-success-color, #2ba471));
|
||||
}
|
||||
&.active {
|
||||
border-width: 1px;
|
||||
border-color: var(--el-color-primary);
|
||||
border-color: var(--el-color-primary, var(--td-brand-color, #0052d9));
|
||||
}
|
||||
&.border-icon-top {
|
||||
border-top-width: 2px;
|
||||
|
||||
@ -16,7 +16,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type { Component } from 'vue';
|
||||
import type { AppContext, Component } from 'vue';
|
||||
import type EventEmitter from 'events';
|
||||
import type * as Monaco from 'monaco-editor';
|
||||
import type { default as Sortable, Options, SortableEvent } from 'sortablejs';
|
||||
@ -33,7 +33,8 @@ import type {
|
||||
MPage,
|
||||
MPageFragment,
|
||||
} from '@tmagic/core';
|
||||
import type { ChangeRecord, FormConfig, TableColumnConfig, TypeFunction } from '@tmagic/form';
|
||||
import type { FieldSize } from '@tmagic/design';
|
||||
import type { ChangeRecord, FormConfig, FormState, TableColumnConfig, TypeFunction } from '@tmagic/form';
|
||||
import type StageCore from '@tmagic/stage';
|
||||
import type {
|
||||
CanDropIn,
|
||||
@ -56,7 +57,7 @@ import type { PropsService } from './services/props';
|
||||
import type { StageOverlayService } from './services/stageOverlay';
|
||||
import type { StorageService } from './services/storage';
|
||||
import type { UiService } from './services/ui';
|
||||
import type { UndoRedo } from './utils/undo-redo';
|
||||
import type { SerializedUndoRedo, UndoRedo } from './utils/undo-redo';
|
||||
|
||||
export type EditorSlots = FrameworkSlots &
|
||||
WorkspaceSlots &
|
||||
@ -199,6 +200,11 @@ export interface StageOptions {
|
||||
*/
|
||||
alwaysMultiSelect?: boolean;
|
||||
disabledRule?: boolean;
|
||||
/**
|
||||
* 禁用「非点击画布选中组件时(如从图层树、面包屑等外部选中),对选中区域做高亮闪烁提示」,
|
||||
* 默认 false(即默认开启闪烁)
|
||||
*/
|
||||
disabledFlashTip?: boolean;
|
||||
zoom?: number;
|
||||
/** 画布双击前的钩子函数,返回 false 则阻止默认的双击行为 */
|
||||
beforeDblclick?: (event: MouseEvent) => Promise<boolean | void> | boolean | void;
|
||||
@ -291,6 +297,12 @@ export interface UiState {
|
||||
stageRect: StageRect;
|
||||
/** 编辑器列布局每一列的宽度,分为左中右三列 */
|
||||
columnWidth: GetColumnWidth;
|
||||
/** 编辑器列布局左侧列最小宽度 */
|
||||
minLeftColumnWidth: number;
|
||||
/** 编辑器列布局中间列最小宽度 */
|
||||
minCenterColumnWidth: number;
|
||||
/** 编辑器列布局右侧列最小宽度 */
|
||||
minRightColumnWidth: number;
|
||||
/** 是否显示画布参考线,true: 显示,false: 不显示,默认为true */
|
||||
showGuides: boolean;
|
||||
/** 画布上是否存在参考线 */
|
||||
@ -307,6 +319,8 @@ export interface UiState {
|
||||
hideSlideBar: boolean;
|
||||
/** 侧边栏面板配置 */
|
||||
sideBarItems: SideComponent[];
|
||||
/** 当前激活的侧边栏面板 */
|
||||
sideBarActiveTabName: string;
|
||||
|
||||
// navMenu 的宽高
|
||||
navMenuRect: {
|
||||
@ -328,6 +342,7 @@ export interface EditorNodeInfo {
|
||||
node: MNode | null;
|
||||
parent: MContainer | null;
|
||||
page: MPage | MPageFragment | null;
|
||||
path: MNode[];
|
||||
}
|
||||
// #endregion EditorNodeInfo
|
||||
|
||||
@ -385,6 +400,9 @@ export interface MenuButton {
|
||||
items?: MenuButton[];
|
||||
/** 唯一标识,用于高亮 */
|
||||
id?: string | number;
|
||||
buttonProps?: {
|
||||
type?: string;
|
||||
};
|
||||
}
|
||||
// #endregion MenuButton
|
||||
|
||||
@ -475,6 +493,63 @@ export interface SideComponent extends MenuComponent {
|
||||
}
|
||||
// #endregion SideComponent
|
||||
|
||||
// #region HistoryListExtraTab
|
||||
/**
|
||||
* 历史记录面板(HistoryListPanel)的自定义扩展 tab。
|
||||
*
|
||||
* 业务方可通过 Editor 的 `historyListExtraTabs` 注入额外的历史记录 tab,
|
||||
* 例如某个自定义模块维护自己的操作历史时,可以在历史记录面板中增加一个
|
||||
* 独立的 tab 来展示与回滚。内置的「页面 / 数据源 / 代码块」三个 tab 之后
|
||||
* 会依次追加这些扩展 tab。
|
||||
*/
|
||||
export interface HistoryListExtraTab {
|
||||
/** tab 唯一标识,作为 TMagicTabs 的 name */
|
||||
name: string;
|
||||
/** tab 显示文案,支持传入函数以展示动态内容(如记录数量) */
|
||||
label: string | (() => string);
|
||||
/** tab 内容区渲染的组件(Vue 组件或字符串标签) */
|
||||
component: any;
|
||||
/** 传入内容组件的 props */
|
||||
props?: Record<string, any>;
|
||||
/** 内容组件的事件监听 */
|
||||
listeners?: Record<string, (..._args: any[]) => any>;
|
||||
}
|
||||
// #endregion HistoryListExtraTab
|
||||
|
||||
// #region CompareForm
|
||||
/**
|
||||
* 对比表单(CompareForm)的对比类型:
|
||||
* - node: 节点组件,按 `type` 从 propsService 获取属性表单配置
|
||||
* - data-source: 数据源,按 `type`(base/http/...) 从 dataSourceService 获取数据源表单配置
|
||||
* - code-block: 数据源代码块,使用内置的代码块表单配置
|
||||
*/
|
||||
export type CompareCategory = 'node' | 'data-source' | 'code-block' | string;
|
||||
|
||||
/**
|
||||
* 自定义 `loadConfig` 时回传的上下文,聚合了组件当前的对比入参,
|
||||
* 方便调用方在外部按需拼装 FormConfig。
|
||||
*/
|
||||
export interface CompareFormLoadConfigContext {
|
||||
/** 对比类型,见 CompareCategory */
|
||||
category: string;
|
||||
/** 节点 / 数据源类型 */
|
||||
type?: string;
|
||||
/** 数据源代码块场景下的数据源类型 */
|
||||
dataSourceType?: string;
|
||||
/**
|
||||
* 内置的默认 FormConfig 加载逻辑(按 `category` 从 propsService / dataSourceService /
|
||||
* 代码块工具取配置)。自定义 `loadConfig` 可调用它复用默认结果,再做二次加工。
|
||||
*/
|
||||
defaultLoadConfig: () => Promise<FormConfig>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义 FormConfig 加载逻辑。传入后将接管内置的按 `category` 取配置逻辑,
|
||||
* 可通过 `ctx.defaultLoadConfig()` 复用默认结果再做二次加工。
|
||||
*/
|
||||
export type CompareFormLoadConfig = (ctx: CompareFormLoadConfigContext) => FormConfig | Promise<FormConfig>;
|
||||
// #endregion CompareForm
|
||||
|
||||
// #region SideItemKey
|
||||
export enum SideItemKey {
|
||||
COMPONENT_LIST = 'component-list',
|
||||
@ -618,114 +693,285 @@ export interface CodeParamStatement {
|
||||
}
|
||||
|
||||
// #region HistoryOpType
|
||||
export type HistoryOpType = 'add' | 'remove' | 'update';
|
||||
/**
|
||||
* 历史记录操作类型:
|
||||
* - `add` / `remove` / `update`:普通可撤销/重做的节点变更;
|
||||
* - `initial`:页面「未修改的初始状态」基线(设置 root 时生成),作为页面栈 index 0 的固定底线 step。
|
||||
* 该 step 不可被撤销/回滚(cursor 不会低于它),仅用于历史面板底部的初始行展示。
|
||||
*/
|
||||
export type HistoryOpType = 'add' | 'remove' | 'update' | 'initial';
|
||||
// #endregion HistoryOpType
|
||||
|
||||
// #region StepValue
|
||||
export interface StepValue {
|
||||
/** 页面信息 */
|
||||
data: { name: string; id: Id };
|
||||
opType: HistoryOpType;
|
||||
/** 操作前选中的节点 ID,用于撤销后恢复选择状态 */
|
||||
selectedBefore: Id[];
|
||||
/** 操作后选中的节点 ID,用于重做后恢复选择状态 */
|
||||
selectedAfter: Id[];
|
||||
modifiedNodeIds: Map<Id, Id>;
|
||||
/** opType 'add': 新增的节点 */
|
||||
nodes?: MNode[];
|
||||
/** opType 'add': 父节点 ID */
|
||||
// #region HistoryOpSource
|
||||
/**
|
||||
* 历史记录的「操作途径」——标记本次变更由哪条交互入口触发,仅用于历史面板展示 / 业务埋点,
|
||||
* 不影响 undo/redo 行为。缺省(未传)时 UI 视为「未知」。
|
||||
*
|
||||
* - `stage`:画布(拖拽 / 缩放 / 排序等舞台直接操作)
|
||||
* - `tree`:树形面板(图层 / 数据源 / 代码块等树形结构里的拖拽 / 菜单操作)
|
||||
* - `component-panel`:组件面板(左侧组件列表点击 / 拖拽新增组件)
|
||||
* - `props`:配置面板表单(属性表单字段编辑)
|
||||
* - `code`:源码编辑器(配置面板「源码」面板里直接编辑 JSON/代码后保存)
|
||||
* - `stage-contextmenu`:画布右键菜单(舞台上节点的右键上下文菜单)
|
||||
* - `tree-contextmenu`:树面板右键菜单(图层 / 数据源 / 代码块等树形列表上的右键上下文菜单)
|
||||
* - `toolbar`:工具栏菜单(顶部导航工具栏按钮)
|
||||
* - `shortcut`:键盘快捷键
|
||||
* - `rollback`:历史回滚(历史面板里对某条历史「回滚」,反向应用为一条新记录,类 git revert)
|
||||
* - `api`:代码 / 接口调用(程序化触发)
|
||||
* - `ai`:AI 生成 / 智能助手触发的变更
|
||||
* - `unknown`:未知来源
|
||||
*
|
||||
* 通过 `(string & {})` 允许业务侧扩展自定义途径字符串,同时保留内置值的自动补全。
|
||||
*/
|
||||
export type HistoryOpSource =
|
||||
| 'initial'
|
||||
| 'stage'
|
||||
| 'tree'
|
||||
| 'component-panel'
|
||||
| 'props'
|
||||
| 'code'
|
||||
| 'root-code'
|
||||
| 'stage-contextmenu'
|
||||
| 'tree-contextmenu'
|
||||
| 'toolbar'
|
||||
| 'shortcut'
|
||||
| 'rollback'
|
||||
| 'api'
|
||||
| 'ai'
|
||||
// 同步
|
||||
| 'sync'
|
||||
| 'unknown'
|
||||
| (string & {});
|
||||
// #endregion HistoryOpSource
|
||||
|
||||
// #region DslOpWithHistoryIdsResult
|
||||
/** *AndGetHistoryId 系列方法返回值:原操作结果 + 本次写入历史记录的 uuid 列表(未入栈时为 `[]`)。 */
|
||||
export type DslOpWithHistoryIdsResult<T> = {
|
||||
result: T;
|
||||
historyIds: string[];
|
||||
};
|
||||
// #endregion DslOpWithHistoryIdsResult
|
||||
|
||||
// #region StepDiffItem
|
||||
/**
|
||||
* 单条变更的 diff 描述,统一表达「页面节点 / 代码块 / 数据源」的变化内容,
|
||||
* 被 {@link StepValue} / {@link CodeBlockStepValue} / {@link DataSourceStepValue} 的 `diff` 复用。
|
||||
*
|
||||
* 按 `opType` 区分携带的字段:
|
||||
* - `add`:仅 `newSchema`(页面节点还带 `parentId` / `index`);
|
||||
* - `remove`:仅 `oldSchema`(页面节点还带 `parentId` / `index`);
|
||||
* - `update`:`oldSchema` + `newSchema`,并可带 `changeRecords` 做局部更新。
|
||||
*
|
||||
* 泛型 `T` 为变化内容的快照类型:页面节点为 `MNode`,代码块为 `CodeBlockContent`,数据源为 `DataSourceSchema`。
|
||||
*/
|
||||
export interface StepDiffItem<T = unknown> {
|
||||
/** 变更后的内容快照。`opType` 为 `add` / `update` 时有,`remove` 时无。 */
|
||||
newSchema?: T;
|
||||
/** 变更前的内容快照。`opType` 为 `remove` / `update` 时有,`add` 时无。 */
|
||||
oldSchema?: T;
|
||||
/** 父节点 id。仅页面节点有(数据源 / 代码块没有父节点)。 */
|
||||
parentId?: Id;
|
||||
/** opType 'add': 每个新增节点在父节点 items 中的索引 */
|
||||
indexMap?: Record<string, number>;
|
||||
/** opType 'remove': 被删除的节点及其位置信息 */
|
||||
removedItems?: { node: MNode; parentId: Id; index: number }[];
|
||||
/** 在父节点 items 数组中的索引。仅页面节点有(数据源 / 代码块无需排序)。 */
|
||||
index?: number;
|
||||
/**
|
||||
* opType 'update': 变更前后的节点快照
|
||||
*
|
||||
* `changeRecords` 来自 form 端的 propPath/value 列表,撤销/重做时只对这些 propPath 做局部更新;
|
||||
* 缺省(未传 / 空数组)才退化为整节点替换。
|
||||
* form 端 propPath/value 变更列表,仅 `opType` 为 `update` 时有;
|
||||
* 撤销/重做时若有则按 propPath 局部更新,缺省才退化为整内容替换。
|
||||
*/
|
||||
updatedItems?: { oldNode: MNode; newNode: MNode; changeRecords?: ChangeRecord[] }[];
|
||||
changeRecords?: ChangeRecord[];
|
||||
}
|
||||
// #endregion StepDiffItem
|
||||
|
||||
// #region BaseStepValue
|
||||
/**
|
||||
* 历史记录条目公共字段,被 {@link StepValue} / {@link CodeBlockStepValue} / {@link DataSourceStepValue} 复用。
|
||||
*
|
||||
* 泛型 `T` 为 `diff` 中变化内容的快照类型(页面节点 `MNode` / 代码块 `CodeBlockContent` / 数据源 `DataSourceSchema`)。
|
||||
*/
|
||||
export interface BaseStepValue<T = unknown, U extends Record<string, any> = {}> {
|
||||
/**
|
||||
* 历史记录唯一标识(uuid)。入栈时自动写入(若调用方未指定),
|
||||
* 用于精确定位 / 引用某一条历史记录(如 revert、埋点、跨端同步等)。
|
||||
* 注意与 `data.id`(关联的页面 / 代码块 / 数据源 id)区分。
|
||||
*/
|
||||
uuid: string;
|
||||
/**
|
||||
* 关联目标信息:`id` 为关联的页面 / 代码块 / 数据源等资源 id(也是历史栈的分组 key),
|
||||
* `name` 为展示名。所有历史类型统一携带。
|
||||
*/
|
||||
data: { name: string; id: Id };
|
||||
/** 操作类型:新增 / 删除 / 更新(三类历史记录统一携带)。 */
|
||||
opType: HistoryOpType;
|
||||
/**
|
||||
* 本次变更的内容(统一 diff 表达),每项见 {@link StepDiffItem}。
|
||||
* 页面节点(add/remove 多节点、update 多节点)会有多项,代码块 / 数据源通常只有一项。
|
||||
*/
|
||||
diff: StepDiffItem<T>[];
|
||||
/**
|
||||
* 调用方可选传入的人类可读描述(如「调整按钮颜色」),用于历史面板展示。
|
||||
* 不影响 undo/redo 行为;缺省时面板会根据节点 / propPath 自动生成描述。
|
||||
*/
|
||||
historyDescription?: string;
|
||||
/**
|
||||
* 操作途径:标记本次变更由哪条交互入口触发,取值见 {@link HistoryOpSource}
|
||||
* (画布 / 树面板 / 组件面板 / 配置面板 / 源码编辑器 / 右键菜单 / 工具栏 / 快捷键 / 回滚 / 接口 等)。
|
||||
* 仅用于历史面板展示与业务埋点,不影响 undo/redo 行为;缺省时面板视为「未知」。
|
||||
*/
|
||||
source?: HistoryOpSource;
|
||||
/**
|
||||
* 入栈时间戳(毫秒)。入栈时自动写入(若调用方未指定),仅用于历史面板展示。
|
||||
*/
|
||||
timestamp?: number;
|
||||
/**
|
||||
* 是否为「已保存」记录:DSL 落库(如保存到后端 / 本地)时由 historyService.markSaved 标记。
|
||||
* 同一栈内任意时刻最多只有一条记录为 true;从 IndexedDB 恢复时游标会被定位到最近一条已保存记录之后。
|
||||
*/
|
||||
saved?: boolean;
|
||||
/**
|
||||
* 是否为「整体设置 root」(set root)产生的记录(由 {@link Editor.pushRootDiffHistory} 写入)。
|
||||
* 用于「连续 set root 合并」:当某页栈最新一条已是 root 记录时,下一条 set root 会替换它而非新增,
|
||||
* 避免源码反复保存 / 外部重设 DSL 时堆积多条 root 记录。
|
||||
*/
|
||||
rootStep?: boolean;
|
||||
/** 操作人 */
|
||||
operator?: string;
|
||||
/** 扩展信息 */
|
||||
extra?: U;
|
||||
}
|
||||
// #endregion BaseStepValue
|
||||
|
||||
// #region StepExtra
|
||||
/**
|
||||
* 历史记录的扩展上下文({@link BaseStepValue.extra})。
|
||||
* 内置字段供 `page` 类型在撤销 / 重做时恢复选区与受影响节点;扩展类型可自由附加其它键。
|
||||
*/
|
||||
export interface StepExtra {
|
||||
/** 操作前选中的节点 ID,用于撤销后恢复选择状态(page 类型) */
|
||||
selectedBefore?: Id[];
|
||||
/** 操作后选中的节点 ID,用于重做后恢复选择状态(page 类型) */
|
||||
selectedAfter?: Id[];
|
||||
/** 本次操作涉及的节点 id 集合(page 类型) */
|
||||
modifiedNodeIds?: Map<Id, Id>;
|
||||
[key: string]: any;
|
||||
}
|
||||
// #endregion StepExtra
|
||||
|
||||
// #region StepValue
|
||||
/**
|
||||
* 页面节点历史记录条目(`diff` 内容为 {@link MNode})。结构已与代码块 / 数据源统一收敛到
|
||||
* {@link BaseStepValue}:关联 id 见 `data.id`,选区等上下文见 `extra`。
|
||||
*/
|
||||
export type StepValue = BaseStepValue<MNode, StepExtra>;
|
||||
// #endregion StepValue
|
||||
|
||||
// #region CodeBlockStepValue
|
||||
/**
|
||||
* 代码块历史记录条目。按 codeBlock.id 分组保存到 historyState.codeBlockState。
|
||||
* - 新增:oldContent = null,newContent = 新内容
|
||||
* - 更新:oldContent / newContent 都为对应内容
|
||||
* - 删除:newContent = null,oldContent = 删除前内容
|
||||
* 代码块历史记录条目(`diff` 内容为 {@link CodeBlockContent}),按 `data.id`(codeBlock.id)
|
||||
* 分组保存到 historyState.steps.codeBlock。结构与 {@link StepValue} / {@link DataSourceStepValue}
|
||||
* 一致,仅 `diff` 快照类型不同。
|
||||
*/
|
||||
export interface CodeBlockStepValue {
|
||||
/** 关联的代码块 id */
|
||||
id: Id;
|
||||
/** 变更前的代码块内容,新增时为 null */
|
||||
oldContent: CodeBlockContent | null;
|
||||
/** 变更后的代码块内容,删除时为 null */
|
||||
newContent: CodeBlockContent | null;
|
||||
/**
|
||||
* form 端 propPath/value 列表。撤销/重做时若有则按 propPath 局部更新;
|
||||
* 缺省才退化为整内容替换。新增/删除场景通常无 changeRecords。
|
||||
*/
|
||||
changeRecords?: ChangeRecord[];
|
||||
/** 调用方可选传入的人类可读描述,用于历史面板展示;不影响 undo/redo 行为。 */
|
||||
historyDescription?: string;
|
||||
}
|
||||
export type CodeBlockStepValue = BaseStepValue<CodeBlockContent>;
|
||||
// #endregion CodeBlockStepValue
|
||||
|
||||
// #region DataSourceStepValue
|
||||
/**
|
||||
* 数据源历史记录条目。按 dataSource.id 分组保存到 historyState.dataSourceState。
|
||||
* - 新增:oldSchema = null,newSchema = 新 schema
|
||||
* - 更新:oldSchema / newSchema 都为对应 schema
|
||||
* - 删除:newSchema = null,oldSchema = 删除前 schema
|
||||
* 数据源历史记录条目(`diff` 内容为 {@link DataSourceSchema}),按 `data.id`(dataSource.id)
|
||||
* 分组保存到 historyState.steps.dataSource。结构与 {@link StepValue} / {@link CodeBlockStepValue}
|
||||
* 一致,仅 `diff` 快照类型不同。
|
||||
*/
|
||||
export interface DataSourceStepValue {
|
||||
/** 关联的数据源 id */
|
||||
id: Id;
|
||||
/** 变更前的数据源 schema,新增时为 null */
|
||||
oldSchema: DataSourceSchema | null;
|
||||
/** 变更后的数据源 schema,删除时为 null */
|
||||
newSchema: DataSourceSchema | null;
|
||||
/**
|
||||
* form 端 propPath/value 列表。撤销/重做时若有则按 propPath 局部更新;
|
||||
* 缺省才退化为整 schema 替换。新增/删除场景通常无 changeRecords。
|
||||
*/
|
||||
changeRecords?: ChangeRecord[];
|
||||
/** 调用方可选传入的人类可读描述,用于历史面板展示;不影响 undo/redo 行为。 */
|
||||
historyDescription?: string;
|
||||
}
|
||||
export type DataSourceStepValue = BaseStepValue<DataSourceSchema>;
|
||||
// #endregion DataSourceStepValue
|
||||
|
||||
export interface HistoryState {
|
||||
pageId?: Id;
|
||||
pageSteps: Record<Id, UndoRedo<StepValue>>;
|
||||
canRedo: boolean;
|
||||
canUndo: boolean;
|
||||
/**
|
||||
* 代码块历史栈,按 codeBlock.id 分组(每个代码块独立一份 UndoRedo)。
|
||||
* 与页面/节点无关,支持独立 undo/redo。
|
||||
*/
|
||||
codeBlockState: Record<Id, UndoRedo<CodeBlockStepValue>>;
|
||||
/**
|
||||
* 数据源历史栈,按 dataSource.id 分组(每个数据源独立一份 UndoRedo)。
|
||||
* 与页面/节点无关,支持独立 undo/redo。
|
||||
*/
|
||||
dataSourceState: Record<Id, UndoRedo<DataSourceStepValue>>;
|
||||
// #region HistorySteps
|
||||
/**
|
||||
* 历史记录类型标识:内置 `page` / `codeBlock` / `dataSource`,并允许业务扩展自定义类型。
|
||||
* `(string & {})` 保留对内置字面量的智能提示,同时不限制扩展取值。
|
||||
*/
|
||||
export type HistoryStepType = 'page' | 'codeBlock' | 'dataSource' | (string & {});
|
||||
|
||||
/**
|
||||
* 全部历史栈的统一容器,按「类型 -> id -> UndoRedo 栈」两级分组。
|
||||
*
|
||||
* - `page`:页面历史栈,按 page.id 分组(每页一份 UndoRedo);
|
||||
* - `codeBlock`:代码块历史栈,按 codeBlock.id 分组;
|
||||
* - `dataSource`:数据源历史栈,按 dataSource.id 分组;
|
||||
* - 其余键:业务通过 {@link HistoryService.registerStepType} 注册的自定义历史类型。
|
||||
*
|
||||
* 所有类型(含扩展类型)一视同仁:均按 id 独立分栈、独立 undo/redo,且都可通过
|
||||
* {@link HistoryService.setMarker} 在 index 0 种入 `initial` 基线(撤销 / 回滚不会越过该基线)。
|
||||
*/
|
||||
export interface HistorySteps {
|
||||
page: Record<Id, UndoRedo<StepValue>>;
|
||||
codeBlock: Record<Id, UndoRedo<CodeBlockStepValue>>;
|
||||
dataSource: Record<Id, UndoRedo<DataSourceStepValue>>;
|
||||
/** 扩展历史类型:按 id 分组的 UndoRedo 栈。 */
|
||||
[stepType: string]: Record<Id, UndoRedo<any>>;
|
||||
}
|
||||
// #endregion HistorySteps
|
||||
|
||||
export interface HistoryState {
|
||||
/**
|
||||
* 全部历史栈的统一容器(页面 / 代码块 / 数据源 / 扩展类型),见 {@link HistorySteps}。
|
||||
* 各类型互不影响,支持按 id 独立 undo/redo;是否可撤销 / 重做改用 {@link HistoryService.canUndo} /
|
||||
* {@link HistoryService.canRedo}(按 stepType + id 查询)替代旧的全局 canUndo / canRedo 字段。
|
||||
*/
|
||||
steps: HistorySteps;
|
||||
/**
|
||||
* 各历史类型的展示名称,用于历史面板({@link HistorySteps} 的 tab / 分组标题等)。
|
||||
* 内置 `page` / `codeBlock` / `dataSource` 有默认中文名(页面 / 代码块 / 数据源),
|
||||
* 扩展类型可通过 {@link HistoryService.registerStepType} 的 `name` 选项或
|
||||
* {@link HistoryService.setStepName} 登记;读取请用 {@link HistoryService.getStepName}。
|
||||
*/
|
||||
stepNames: Record<string, string>;
|
||||
}
|
||||
|
||||
// #region PersistedHistoryState
|
||||
/**
|
||||
* 历史记录的可持久化快照。由 historyService.saveToIndexedDB 写入 IndexedDB,
|
||||
* 再由 historyService.restoreFromIndexedDB 读出并重建各 UndoRedo 栈。
|
||||
*/
|
||||
export interface PersistedHistoryState {
|
||||
/** 快照结构版本号,便于后续兼容升级。 */
|
||||
version: number;
|
||||
/**
|
||||
* 全部历史栈的序列化快照,按「类型 -> id」两级分组,与 {@link HistorySteps} 对应。
|
||||
* 内置 `page` / `codeBlock` / `dataSource`,并包含业务注册的扩展类型。
|
||||
*/
|
||||
steps: {
|
||||
page: Record<Id, SerializedUndoRedo<StepValue>>;
|
||||
codeBlock: Record<Id, SerializedUndoRedo<CodeBlockStepValue>>;
|
||||
dataSource: Record<Id, SerializedUndoRedo<DataSourceStepValue>>;
|
||||
[stepType: string]: Record<Id, SerializedUndoRedo<any>>;
|
||||
};
|
||||
/** 保存时间戳(毫秒)。 */
|
||||
savedAt: number;
|
||||
}
|
||||
// #endregion PersistedHistoryState
|
||||
|
||||
// #region HistoryPersistOptions
|
||||
/** historyService 持久化相关 API 的可选配置。 */
|
||||
export interface HistoryPersistOptions {
|
||||
/** IndexedDB 数据库名,默认 `tmagic-editor`(最终库名会拼上当前 DSL app id)。 */
|
||||
dbName?: string;
|
||||
/** objectStore 名,默认 `history`。 */
|
||||
storeName?: string;
|
||||
/** 记录 key,用于区分不同活动页 / 项目,默认 `default`。 */
|
||||
key?: IDBValidKey;
|
||||
/**
|
||||
* 显式指定用于库名隔离的 DSL app id。
|
||||
* 缺省时回退到当前 editorService 的 `root.id`;在「先恢复历史再 set root」场景下 root 尚未设置,
|
||||
* 需由调用方(如从待加载 DSL 取 id)显式传入,否则会读 / 写到未按 app 隔离的默认库。
|
||||
*/
|
||||
appId?: Id;
|
||||
}
|
||||
// #endregion HistoryPersistOptions
|
||||
|
||||
// #region HistoryListEntry
|
||||
/**
|
||||
* 历史面板用:当前页面的一条历史步骤(包含位置和是否已应用)。
|
||||
*/
|
||||
export interface PageHistoryStepEntry {
|
||||
export interface HistoryStepEntry<T> {
|
||||
/** 步骤内容 */
|
||||
step: StepValue;
|
||||
step: T;
|
||||
/** 在所属栈中的索引(0 为最早) */
|
||||
index: number;
|
||||
/** 是否处于"已应用"段(即位于栈游标之前)。撤销后变为 false。 */
|
||||
@ -735,63 +981,39 @@ export interface PageHistoryStepEntry {
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面历史面板分组。
|
||||
* - 连续修改同一目标节点(updatedItems[0].oldNode.id 一致)的 'update' 步骤合并成一组;
|
||||
* - 多节点更新 / add / remove 始终独立成组(无法明确归属单一目标)。
|
||||
* - targetId 为 undefined 表示"无明确目标"(如 add/remove/多节点 update),不参与合并。
|
||||
* 历史面板分组(页面 / 数据源 / 代码块 / 扩展类型统一结构)。
|
||||
*
|
||||
* 把指定历史栈的步骤列表按"目标"做相邻合并:
|
||||
* - 连续修改同一目标(单实体 update,targetId 一致)的多步合并成一组,组内可展开查看每步;
|
||||
* - add / remove / 多实体 update 始终独立成组(无法明确归属单一目标);
|
||||
* - targetId 为 undefined 表示"无明确目标",不参与合并。
|
||||
*
|
||||
* 各类型仅 `kind` 与 step 快照类型不同,统一由泛型描述:
|
||||
* - 页面:`HistoryGroup<StepValue>`,`kind: 'page'`,`id` 为 pageId,`targetId` 为被改节点 id;
|
||||
* - 数据源:`HistoryGroup<DataSourceStepValue>`,`kind: 'data-source'`,`id` 为 dataSource.id;
|
||||
* - 代码块:`HistoryGroup<CodeBlockStepValue>`,`kind: 'code-block'`,`id` 为 codeBlock.id。
|
||||
*/
|
||||
export interface PageHistoryGroup {
|
||||
kind: 'page';
|
||||
/** 所属页面 id */
|
||||
pageId: Id;
|
||||
/** 该分组的操作类型 */
|
||||
export interface HistoryGroup<T extends BaseStepValue = BaseStepValue> {
|
||||
/** 历史类型标识:page / code-block / data-source(扩展类型同理)。 */
|
||||
kind: string;
|
||||
/** 所属栈 id(page 为 pageId,代码块 / 数据源为对应资源 id)。 */
|
||||
id: Id;
|
||||
/** 该分组的操作类型。 */
|
||||
opType: HistoryOpType;
|
||||
/**
|
||||
* 合并的目标节点 id;只有"单节点 update"才有值,并按此 id 与相邻同 id 的 update 合并。
|
||||
* undefined 表示该分组不可被合并(add / remove / 多节点 update)。
|
||||
* 合并的目标 id:仅"单实体 update"有值,并按此与相邻同 id 的 update 合并。
|
||||
* undefined 表示该分组不可被合并(add / remove / 多实体 update)。
|
||||
*/
|
||||
targetId?: Id;
|
||||
/** 目标节点的可读名(取最后一步的 newNode.name/type/id) */
|
||||
/** 目标可读名(取最后一步快照的 name/type/id)。 */
|
||||
targetName?: string;
|
||||
/** 组内所有步骤,按时间正序 */
|
||||
steps: PageHistoryStepEntry[];
|
||||
/** 组内最后一步是否已应用 */
|
||||
/** 组内所有步骤,按时间正序。 */
|
||||
steps: { step: T; index: number; applied: boolean; isCurrent?: boolean }[];
|
||||
/** 组内最后一步是否已应用。 */
|
||||
applied: boolean;
|
||||
/** 是否为当前所在的分组(包含栈中最近一次已应用步骤的那一组)。 */
|
||||
isCurrent?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 代码块历史面板分组。
|
||||
* - 同一 codeBlockId 的栈内,相邻的 'update' 操作会合并成一个 group;
|
||||
* - 'add' / 'remove' 始终独立成组(语义上是一次性事件)。
|
||||
*/
|
||||
export interface CodeBlockHistoryGroup {
|
||||
kind: 'code-block';
|
||||
/** 关联的 codeBlock id */
|
||||
id: Id;
|
||||
/** 该分组的操作类型 */
|
||||
opType: HistoryOpType;
|
||||
/** 组内所有步骤,按时间正序 */
|
||||
steps: { step: CodeBlockStepValue; index: number; applied: boolean; isCurrent?: boolean }[];
|
||||
/** 组内最后一步是否已应用,用于整组的状态展示 */
|
||||
applied: boolean;
|
||||
/** 是否为当前所在的分组(包含该栈最近一次已应用步骤的那一组)。 */
|
||||
isCurrent?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据源历史面板分组,结构同 CodeBlockHistoryGroup。
|
||||
*/
|
||||
export interface DataSourceHistoryGroup {
|
||||
kind: 'data-source';
|
||||
id: Id;
|
||||
opType: HistoryOpType;
|
||||
steps: { step: DataSourceStepValue; index: number; applied: boolean; isCurrent?: boolean }[];
|
||||
applied: boolean;
|
||||
/** 是否为当前所在的分组(包含该栈最近一次已应用步骤的那一组)。 */
|
||||
isCurrent?: boolean;
|
||||
}
|
||||
// #endregion HistoryListEntry
|
||||
|
||||
export enum KeyBindingCommand {
|
||||
@ -956,6 +1178,8 @@ export type SyncHookPlugin<
|
||||
|
||||
export interface EventBusEvent {
|
||||
'edit-data-source': [id: string];
|
||||
'edit-data-source-method': [id: string, methodName: string];
|
||||
'edit-data-source-field': [id: string, fieldPath: string[]];
|
||||
'remove-data-source': [id: string];
|
||||
'edit-code': [id: string];
|
||||
}
|
||||
@ -989,7 +1213,11 @@ export type CustomContentMenuFunction = (
|
||||
) => (MenuButton | MenuComponent)[];
|
||||
|
||||
export interface EditorEvents {
|
||||
'root-change': [value: StoreState['root'], preValue?: StoreState['root']];
|
||||
'root-change': [
|
||||
value: StoreState['root'],
|
||||
preValue?: StoreState['root'],
|
||||
options?: { historySource?: HistoryOpSource },
|
||||
];
|
||||
select: [node: MNode | null];
|
||||
add: [nodes: MNode[]];
|
||||
remove: [nodes: MNode[]];
|
||||
@ -997,6 +1225,54 @@ export interface EditorEvents {
|
||||
'move-layer': [offset: number | LayerOffset];
|
||||
'drag-to': [data: { targetIndex: number; configs: MNode | MNode[]; targetParent: MContainer }];
|
||||
'history-change': [data: MPage | MPageFragment];
|
||||
/**
|
||||
* DSL 发生变更后统一触发,免去分别监听 add / remove / update / move-layer / drag-to。
|
||||
* 回调参数为 {@link EditorChangeEvent},按 `type` 区分操作类型并携带各自的操作内容(payload)
|
||||
* 以及变更所在的当前 page(可能为 null)。撤销 / 重做内部同样会经由
|
||||
* add / remove / update 触发本事件;如需区分「用户操作」与「撤销重做」请配合 `history-change`。
|
||||
*/
|
||||
change: [event: EditorChangeEvent];
|
||||
}
|
||||
|
||||
// #region EditorChangeEvent
|
||||
/** `change` 事件中单个变更项:变更的 node 及其所属的 page(可能为 null)。 */
|
||||
export interface EditorChangeItem {
|
||||
node: MNode;
|
||||
page: StoreState['page'];
|
||||
}
|
||||
|
||||
/** `update` 类型变更项:node 为前后快照及 form 端变更记录,page 为其所属页面。 */
|
||||
export interface EditorUpdateChangeItem {
|
||||
node: { newNode: MNode; oldNode: MNode; changeRecords?: ChangeRecord[] };
|
||||
page: StoreState['page'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link EditorEvents.change} 的回调参数:以 `type` 区分操作类型,并携带对应的操作内容。
|
||||
* `data` 为本次变更的节点列表,每项包含 node 及其所属的 page(可能为 null);
|
||||
* `move-layer` 额外带层级偏移 `offset`,`drag-to` 额外带目标位置 `targetIndex` / `targetParent`。
|
||||
*/
|
||||
export type EditorChangeEvent =
|
||||
| { type: 'add'; data: EditorChangeItem[] }
|
||||
| { type: 'remove'; data: EditorChangeItem[] }
|
||||
| { type: 'update'; data: EditorUpdateChangeItem[] }
|
||||
| { type: 'move-layer'; data: EditorChangeItem[]; offset: number | LayerOffset }
|
||||
| { type: 'drag-to'; data: EditorChangeItem[]; targetIndex: number; targetParent: MContainer };
|
||||
// #endregion EditorChangeEvent
|
||||
|
||||
export interface HistoryEvents {
|
||||
change: [
|
||||
state: BaseStepValue | StepValue | CodeBlockStepValue | DataSourceStepValue,
|
||||
stepType: HistoryStepType,
|
||||
id: Id,
|
||||
];
|
||||
'code-block-history-change': [id: Id, state: CodeBlockStepValue];
|
||||
'data-source-history-change': [id: Id, state: DataSourceStepValue];
|
||||
'restore-from-indexed-db': [snapshot: PersistedHistoryState | null];
|
||||
'save-to-indexed-db': [snapshot: PersistedHistoryState];
|
||||
'mark-saved': [{ kind: HistoryStepType; id?: Id }];
|
||||
clear: [{ id: Id; stepType: HistoryStepType }];
|
||||
'marker-change': [{ id: Id; marker: StepValue; stepType: HistoryStepType }];
|
||||
}
|
||||
|
||||
export const canUsePluginMethods = {
|
||||
@ -1029,16 +1305,21 @@ export const canUsePluginMethods = {
|
||||
|
||||
export type AsyncMethodName = Writable<(typeof canUsePluginMethods)['async']>;
|
||||
|
||||
// #region HistoryOpOptions
|
||||
/**
|
||||
* 历史记录写入相关的通用配置(codeBlock / dataSource / editor 共用)
|
||||
* - doNotPushHistory: 操作完成后是否不要将本次操作压入历史栈(撤销/重做记录),默认 false
|
||||
* - historyDescription: 入栈时附带的人类可读描述,用于历史面板展示;不影响 undo/redo 行为,缺省时面板会自动生成描述
|
||||
* - historySource: 操作途径,取值见 {@link HistoryOpSource}(画布 / 树面板 / 组件面板 / 配置面板 / 源码编辑器 / 右键菜单 / 工具栏 / 快捷键 / 回滚 / 接口 等),用于历史面板展示与埋点;不影响 undo/redo 行为
|
||||
*/
|
||||
export interface HistoryOpOptions {
|
||||
doNotPushHistory?: boolean;
|
||||
historyDescription?: string;
|
||||
historySource?: HistoryOpSource;
|
||||
}
|
||||
// #endregion HistoryOpOptions
|
||||
|
||||
// #region HistoryOpOptionsWithChangeRecords
|
||||
/**
|
||||
* 在 HistoryOpOptions 基础上携带 form 端 propPath/value 变更记录,
|
||||
* 用于历史记录的精细化撤销/重做(按 propPath 局部 patch)。
|
||||
@ -1046,7 +1327,9 @@ export interface HistoryOpOptions {
|
||||
export interface HistoryOpOptionsWithChangeRecords extends HistoryOpOptions {
|
||||
changeRecords?: ChangeRecord[];
|
||||
}
|
||||
// #endregion HistoryOpOptionsWithChangeRecords
|
||||
|
||||
// #region DslOpOptions
|
||||
/**
|
||||
* DSL 修改类操作的通用配置
|
||||
* - doNotSelect: 操作后是否不要自动触发选中(不调用 this.select / this.multiSelect / stage.select / stage.multiSelect)
|
||||
@ -1056,3 +1339,141 @@ export interface DslOpOptions extends HistoryOpOptions {
|
||||
doNotSelect?: boolean;
|
||||
doNotSwitchPage?: boolean;
|
||||
}
|
||||
// #endregion DslOpOptions
|
||||
|
||||
/** 差异对话框的入参 */
|
||||
export interface DiffDialogPayload {
|
||||
/** 表单类别 */
|
||||
category?: CompareCategory;
|
||||
/** 节点类型 / 数据源类型 */
|
||||
type?: string;
|
||||
/** 代码块场景下的数据源类型 */
|
||||
dataSourceType?: string;
|
||||
/** 该 step 修改前的值(oldNode / oldSchema / oldContent) */
|
||||
lastValue: Record<string, any>;
|
||||
/** 该 step 修改后的值(newNode / newSchema / newContent) */
|
||||
value: Record<string, any>;
|
||||
/** 当前编辑器中实际的最新值;不传或为 null 时禁用「与当前对比」 */
|
||||
currentValue?: Record<string, any> | null;
|
||||
/** 用于标题展示的目标名称 */
|
||||
targetLabel?: string;
|
||||
/** 用于标题展示的目标 id */
|
||||
id?: string | number;
|
||||
/**
|
||||
* 指定打开时的初始对比模式:
|
||||
* - before:该步骤修改前 vs 修改后
|
||||
* - current:该步骤修改后 vs 当前最新值
|
||||
* 不传时按是否存在「修改后的值」/「当前值」自动推断。
|
||||
* 若指定的模式当前不可用(对应数据缺失),将回退到自动推断结果。
|
||||
*/
|
||||
mode?: 'before' | 'current';
|
||||
}
|
||||
|
||||
/**
|
||||
* 一组「描述 + 可操作性」的判定函数集合。页面 / 数据源 / 代码块及业务自定义历史
|
||||
* 各自实现一份,作为整体注入,避免把 describe* / isStep* 拆成多个独立 props 反复透传。
|
||||
*/
|
||||
export interface HistoryRowDescriptor<T extends BaseStepValue = BaseStepValue> {
|
||||
/**
|
||||
* 组级描述文案生成器,接收一个 group,返回展示文本。
|
||||
* 不传时回退到对组内最后一步调用 {@link describeStep}(适用于不做相邻合并、每组恒为单步的历史,如数据源/代码块)。
|
||||
*/
|
||||
describeGroup?: (_group: any) => string;
|
||||
/** 单步描述文案生成器,接收一个 step,返回展示文本(合并组展开后的子步列表用)。 */
|
||||
describeStep: (_step: T) => string;
|
||||
/** 判断某个 step 是否可查看差异(前后值都存在)。不传则一律不展示差异入口。 */
|
||||
isStepDiffable?: (_step: T) => boolean;
|
||||
/** 判断某个 step 是否支持回滚(如更新需带 changeRecords)。不传则已应用即可回滚。 */
|
||||
isStepRevertable?: (_step: T) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用 bucket(数据源 / 代码块 / 业务自定义历史)的整体渲染配置。
|
||||
* 把原先散落在 Bucket / BucketTab 上的 title / prefix / describe* / isStep* / showInitial / gotoEnabled
|
||||
* 收敛成一个对象作为单一 prop 传递,调用方一次配齐、组件内部按需读取。
|
||||
*/
|
||||
export interface HistoryBucketConfig<T extends BaseStepValue = BaseStepValue> extends HistoryRowDescriptor<T> {
|
||||
/** bucket 头部标题,例如 "数据源" / "代码块"。 */
|
||||
title: string;
|
||||
/** 子项 key 的命名空间前缀(`ds` 数据源 / `cb` 代码块 / 业务自定义如 `mod`)。 */
|
||||
prefix: string;
|
||||
/** 是否展示底部「回到初始状态」入口,默认 true。无 undo cursor 语义的自定义历史可传 false。 */
|
||||
showInitial?: boolean;
|
||||
/** 是否支持「跳转到该记录」(goto),默认 true。 */
|
||||
gotoEnabled?: boolean;
|
||||
/** 是否展示顶部「清空」按钮,默认 true。无需提供清空能力的自定义历史可传 false。 */
|
||||
showClear?: boolean;
|
||||
}
|
||||
|
||||
export interface UseHistoryRevertOptions {
|
||||
/**
|
||||
* 父级应用上下文,用于让动态挂载的「差异确认弹窗」继承全局组件 / 指令 / provide / 插件
|
||||
* (Element Plus、@tmagic/form 字段组件等)。未显式传入时,会自动取调用方所在组件的 appContext
|
||||
* (`getCurrentInstance()?.appContext`)。业务方若在组件 setup 之外调用,需手动传入(如 `editorApp._context`)。
|
||||
*/
|
||||
appContext?: AppContext | null;
|
||||
/**
|
||||
* 透传给差异确认弹窗的 `extendState`(即 Editor 的 `extendFormState`),
|
||||
* 使对比表单中依赖业务上下文的 `display` / `disabled` 等 filterFunction 正常工作。
|
||||
*/
|
||||
extendState?: (_state: FormState) => Record<string, any> | Promise<Record<string, any>>;
|
||||
/**
|
||||
* 返回 PropsPanel 主属性表单(FormPanel -> MForm)的 formState。
|
||||
* 仅页面历史「查看差异 / 回滚确认」场景会使用该 formState 覆盖 CompareForm 中同名扩展字段,
|
||||
* 以保证两处 filterFunction 读取到一致的运行态上下文。
|
||||
*/
|
||||
getPropsPanelFormState?: () => FormState | undefined;
|
||||
/**
|
||||
* 内置页面 / 数据源 / 代码块的差异 / 回滚确认弹窗默认宽度(透传给 TMagicDialog 的 `width`),
|
||||
* 如 `'1200px'` / `'80%'`。缺省时使用弹窗内置默认宽度(900px)。
|
||||
* 业务自有历史(`viewDiff` / `confirmAndRevert`)可在调用时通过各自入参的 `width` 单独覆盖。
|
||||
*/
|
||||
dialogWidth?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务自有历史(如管理台「模块」)做差异对比时所需的额外渲染入参。
|
||||
* 内置的页面 / 数据源 / 代码块按 `category` 自动取表单配置,无需传这些;
|
||||
* 业务自有类别可通过 `loadConfig` 注入自定义表单配置加载逻辑。
|
||||
*/
|
||||
export interface CustomDiffFormOptions {
|
||||
/**
|
||||
* 自定义差异表单配置加载逻辑(如「模块」按 c_type 重建表单配置),
|
||||
* 透传给弹窗内部的 CompareForm;缺省时按 `category` 走内置加载。
|
||||
*/
|
||||
loadConfig?: CompareFormLoadConfig;
|
||||
/** 需要走 self diff 的字段类型(如模块的 mod-cond)。 */
|
||||
selfDiffFieldTypes?: string[];
|
||||
/**
|
||||
* 可选:外部提供的 formState(通常来自 PropsPanel 主表单),
|
||||
* 对比弹窗会用它覆盖 CompareForm 中同名扩展字段,避免上下文不一致。
|
||||
*/
|
||||
compareFormState?: FormState;
|
||||
/**
|
||||
* 差异 / 确认回滚弹窗宽度(透传给 HistoryDiffDialog 的 TMagicDialog `width`),
|
||||
* 如 `'1200px'` / `'80%'`。缺省时使用弹窗内置默认宽度(900px)。
|
||||
*/
|
||||
width?: string;
|
||||
/**
|
||||
* 差异 / 确认回滚弹窗内 form 表单的尺寸(透传给 CompareForm 的 `size`),
|
||||
* 可选 `'large' | 'default' | 'small'`,缺省时使用表单内置默认尺寸。
|
||||
*/
|
||||
size?: FieldSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务自有历史复用「单步回滚」交互({@link useHistoryRevert} 的 `confirmAndRevert`)的入参。
|
||||
* 与内置页面 / 数据源 / 代码块回滚共用「目标校验 → 差异/二次确认弹窗 → 反向回滚」流程,
|
||||
* 业务方只需提供:差异弹窗入参(可选)、表单配置加载(可选)、实际回滚执行函数。
|
||||
*/
|
||||
export interface ConfirmAndRevertOptions<T = unknown> extends CustomDiffFormOptions {
|
||||
/**
|
||||
* 差异确认弹窗入参;可对比的步骤(单实体 update)传入后弹差异确认弹窗,
|
||||
* 传 null / 省略则退化为普通二次确认框(add / remove / 不可对比)。
|
||||
*/
|
||||
diffPayload?: DiffDialogPayload | null;
|
||||
/** 回滚前置校验:返回 true 表示目标数据已删除等不可回滚,给出统一提示并中止。 */
|
||||
isTargetMissing?: () => boolean;
|
||||
/** 用户确认后执行的实际回滚逻辑。 */
|
||||
revert: () => T | Promise<T>;
|
||||
}
|
||||
|
||||
@ -5,11 +5,16 @@ import { cloneDeep, Id, MContainer, NodeType } from '@tmagic/core';
|
||||
import { calcValueByFontsize, isPage, isPageFragment } from '@tmagic/utils';
|
||||
|
||||
import ContentMenu from '@editor/components/ContentMenu.vue';
|
||||
import type { MenuButton, Services } from '@editor/type';
|
||||
import type { HistoryOpSource, MenuButton, Services } from '@editor/type';
|
||||
|
||||
import { COPY_STORAGE_KEY } from './editor';
|
||||
|
||||
export const useDeleteMenu = (): MenuButton => ({
|
||||
/**
|
||||
* 共享的右键菜单项构造器(画布 ViewerMenu 与图层树 LayerMenu 共用)。
|
||||
* `historySource` 用于标记本次操作的途径,调用方按所在面板传入:
|
||||
* 画布传 `'stage-contextmenu'`,树形面板传 `'tree-contextmenu'`。
|
||||
*/
|
||||
export const useDeleteMenu = (historySource?: HistoryOpSource): MenuButton => ({
|
||||
type: 'button',
|
||||
text: '删除',
|
||||
icon: Delete,
|
||||
@ -19,7 +24,7 @@ export const useDeleteMenu = (): MenuButton => ({
|
||||
},
|
||||
handler: ({ editorService }) => {
|
||||
const nodes = editorService.get('nodes');
|
||||
nodes && editorService.remove(nodes);
|
||||
nodes && editorService.remove(nodes, { historySource });
|
||||
},
|
||||
});
|
||||
|
||||
@ -33,7 +38,10 @@ export const useCopyMenu = (): MenuButton => ({
|
||||
},
|
||||
});
|
||||
|
||||
export const usePasteMenu = (menu?: ShallowRef<InstanceType<typeof ContentMenu> | null>): MenuButton => ({
|
||||
export const usePasteMenu = (
|
||||
historySource?: HistoryOpSource,
|
||||
menu?: ShallowRef<InstanceType<typeof ContentMenu> | null>,
|
||||
): MenuButton => ({
|
||||
type: 'button',
|
||||
text: '粘贴',
|
||||
icon: markRaw(DocumentCopy),
|
||||
@ -52,14 +60,14 @@ export const usePasteMenu = (menu?: ShallowRef<InstanceType<typeof ContentMenu>
|
||||
const initialTop =
|
||||
calcValueByFontsize(stage?.renderer?.getDocument(), (rect.top || 0) - (parentRect?.top || 0)) /
|
||||
uiService.get('zoom');
|
||||
editorService.paste({ left: initialLeft, top: initialTop });
|
||||
editorService.paste({ left: initialLeft, top: initialTop }, undefined, { historySource });
|
||||
} else {
|
||||
editorService.paste();
|
||||
editorService.paste(undefined, undefined, { historySource });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const moveTo = async (id: Id, { editorService }: Services) => {
|
||||
const moveTo = async (id: Id, { editorService }: Services, historySource?: HistoryOpSource) => {
|
||||
const nodes = editorService.get('nodes') || [];
|
||||
const parent = editorService.getNodeById(id) as MContainer;
|
||||
|
||||
@ -69,10 +77,11 @@ const moveTo = async (id: Id, { editorService }: Services) => {
|
||||
// 不要再走 remove + add 两步,否则会被切成两条历史(且语义也不正确)。
|
||||
await editorService.moveToContainer(cloneDeep(nodes), parent.id, {
|
||||
doNotSwitchPage: true,
|
||||
historySource,
|
||||
});
|
||||
};
|
||||
|
||||
export const useMoveToMenu = ({ editorService }: Services): MenuButton => {
|
||||
export const useMoveToMenu = ({ editorService }: Services, historySource?: HistoryOpSource): MenuButton => {
|
||||
const root = computed(() => editorService.get('root'));
|
||||
|
||||
return {
|
||||
@ -89,7 +98,7 @@ export const useMoveToMenu = ({ editorService }: Services): MenuButton => {
|
||||
text: `${page.name}(${page.id})`,
|
||||
type: 'button',
|
||||
handler: (services: Services) => {
|
||||
moveTo(page.id, services);
|
||||
moveTo(page.id, services, historySource);
|
||||
},
|
||||
})),
|
||||
};
|
||||
|
||||
@ -10,6 +10,7 @@ const dataSourceFormConfig: TabConfig = {
|
||||
items: [
|
||||
{
|
||||
title: '数据定义',
|
||||
status: 'fields',
|
||||
items: [
|
||||
{
|
||||
name: 'fields',
|
||||
@ -20,6 +21,7 @@ const dataSourceFormConfig: TabConfig = {
|
||||
},
|
||||
{
|
||||
title: '方法定义',
|
||||
status: 'methods',
|
||||
items: [
|
||||
{
|
||||
name: 'methods',
|
||||
|
||||
@ -35,7 +35,7 @@ import {
|
||||
isValueIncludeDataSource,
|
||||
} from '@tmagic/utils';
|
||||
|
||||
import type { EditorNodeInfo } from '@editor/type';
|
||||
import type { EditorNodeInfo, StepValue } from '@editor/type';
|
||||
import { LayerOffset, Layout } from '@editor/type';
|
||||
|
||||
export const COPY_STORAGE_KEY = '$MagicEditorCopyData';
|
||||
@ -132,6 +132,34 @@ const getMiddleTop = (node: MNode, parentNode: MNode, stage: StageCore | null) =
|
||||
return (Math.min(parentHeight, wrapperHeightDeal) - height) / 2;
|
||||
};
|
||||
|
||||
// 同时存在一对相反的定位属性(如 left/right)时只保留一个,避免元素被拉伸
|
||||
const removeConflictPosition = (style: Record<string, any>, primary: string, secondary: string) => {
|
||||
// '' / 0 / undefined / null 视为无效值
|
||||
const isInvalid = (value: any) => value === '' || value === 0 || value === undefined || value === null;
|
||||
|
||||
if (!(primary in style) || !(secondary in style)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const primaryValue = style[primary];
|
||||
const secondaryValue = style[secondary];
|
||||
const primaryInvalid = isInvalid(primaryValue);
|
||||
const secondaryInvalid = isInvalid(secondaryValue);
|
||||
|
||||
if (primaryInvalid && !secondaryInvalid) {
|
||||
delete style[primary];
|
||||
} else if (secondaryInvalid && !primaryInvalid) {
|
||||
delete style[secondary];
|
||||
} else if (primaryInvalid && secondaryInvalid) {
|
||||
// 都是无效值时优先保留 0,否则保留 primary(left/top)
|
||||
if (secondaryValue === 0 && primaryValue !== 0) {
|
||||
delete style[primary];
|
||||
} else {
|
||||
delete style[secondary];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const getInitPositionStyle = (style: Record<string, any> = {}, layout: Layout) => {
|
||||
if (layout === Layout.ABSOLUTE) {
|
||||
const newStyle: Record<string, any> = {
|
||||
@ -139,6 +167,9 @@ export const getInitPositionStyle = (style: Record<string, any> = {}, layout: La
|
||||
position: 'absolute',
|
||||
};
|
||||
|
||||
removeConflictPosition(newStyle, 'left', 'right');
|
||||
removeConflictPosition(newStyle, 'top', 'bottom');
|
||||
|
||||
if (typeof newStyle.left === 'undefined' && typeof newStyle.right === 'undefined') {
|
||||
newStyle.left = 0;
|
||||
}
|
||||
@ -178,43 +209,68 @@ export const setLayout = (node: MNode, layout: Layout) => {
|
||||
return node;
|
||||
};
|
||||
|
||||
export const change2Fixed = (node: MNode, root: MApp) => {
|
||||
type PositionKey = 'left' | 'top' | 'right' | 'bottom';
|
||||
|
||||
// 判断 style 是否显式设置了某个定位属性,使用 typeof 判断以避免将 0(如 right: 0)误判为未设置
|
||||
const hasPositionValue = (style: Record<string, any> | undefined, key: PositionKey): boolean =>
|
||||
typeof style?.[key] !== 'undefined' && style?.[key] !== '';
|
||||
|
||||
/**
|
||||
* 沿节点路径累加(或抵消)某一方向上的定位偏移量
|
||||
* 当路径上的祖先使用了反方向定位(例如计算 left 时祖先用了 right)或非数值定位时,
|
||||
* 无法简单地通过求和换算坐标,此时返回 0 表示放弃补偿、保持原值
|
||||
* @param path 从根到目标节点的路径(含节点自身)
|
||||
* @param dir 需要累加的定位方向
|
||||
* @param opposite 反方向定位属性
|
||||
* @param sign change2Fixed 取 1(累加祖先偏移),Fixed2Other 取 -1(抵消祖先偏移)
|
||||
* @param init 偏移量初始值
|
||||
*/
|
||||
const accumulatePositionOffset = (
|
||||
path: MNode[],
|
||||
dir: PositionKey,
|
||||
opposite: PositionKey,
|
||||
sign: 1 | -1,
|
||||
init = 0,
|
||||
): number => {
|
||||
let offset = init;
|
||||
for (const value of path) {
|
||||
if (hasPositionValue(value.style, opposite) || !isNumber(value.style?.[dir] || 0)) {
|
||||
return 0;
|
||||
}
|
||||
offset = offset + sign * Number(value.style?.[dir] || 0);
|
||||
}
|
||||
return offset;
|
||||
};
|
||||
|
||||
export const change2Fixed = (node: MNode, path: MNode[]) => {
|
||||
const style = {
|
||||
...(node.style || {}),
|
||||
};
|
||||
|
||||
const path = getNodePath(node.id, root.items);
|
||||
const offset = {
|
||||
left: 0,
|
||||
top: 0,
|
||||
};
|
||||
|
||||
if (!node.style?.right && isNumber(node.style?.left || 0)) {
|
||||
for (const value of path) {
|
||||
if (value.style?.right || !isNumber(value.style?.left || 0)) {
|
||||
offset.left = 0;
|
||||
break;
|
||||
}
|
||||
offset.left = offset.left + Number(value.style?.left || 0);
|
||||
// 水平方向:以 left 锚定则累加祖先 left,以 right 锚定则累加祖先 right
|
||||
if (!hasPositionValue(node.style, 'right') && isNumber(node.style?.left || 0)) {
|
||||
const left = accumulatePositionOffset(path, 'left', 'right', 1);
|
||||
if (left) {
|
||||
style.left = left;
|
||||
}
|
||||
} else if (hasPositionValue(node.style, 'right') && isNumber(node.style?.right || 0)) {
|
||||
const right = accumulatePositionOffset(path, 'right', 'left', 1);
|
||||
if (right) {
|
||||
style.right = right;
|
||||
}
|
||||
}
|
||||
|
||||
if (!node.style?.bottom && isNumber(node.style?.top || 0)) {
|
||||
for (const value of path) {
|
||||
if (value.style?.bottom || !isNumber(value.style?.top || 0)) {
|
||||
offset.top = 0;
|
||||
break;
|
||||
}
|
||||
offset.top = offset.top + Number(value.style?.top || 0);
|
||||
// 垂直方向:以 top 锚定则累加祖先 top,以 bottom 锚定则累加祖先 bottom
|
||||
if (!hasPositionValue(node.style, 'bottom') && isNumber(node.style?.top || 0)) {
|
||||
const top = accumulatePositionOffset(path, 'top', 'bottom', 1);
|
||||
if (top) {
|
||||
style.top = top;
|
||||
}
|
||||
} else if (hasPositionValue(node.style, 'bottom') && isNumber(node.style?.bottom || 0)) {
|
||||
const bottom = accumulatePositionOffset(path, 'bottom', 'top', 1);
|
||||
if (bottom) {
|
||||
style.bottom = bottom;
|
||||
}
|
||||
}
|
||||
|
||||
if (offset.left) {
|
||||
style.left = offset.left;
|
||||
}
|
||||
|
||||
if (offset.top) {
|
||||
style.top = offset.top;
|
||||
}
|
||||
|
||||
return style;
|
||||
@ -222,34 +278,29 @@ export const change2Fixed = (node: MNode, root: MApp) => {
|
||||
|
||||
export const Fixed2Other = async (
|
||||
node: MNode,
|
||||
root: MApp,
|
||||
path: MNode[],
|
||||
getLayout: (parent: MNode, node?: MNode) => Promise<Layout>,
|
||||
) => {
|
||||
const path = getNodePath(node.id, root.items);
|
||||
const cur = path.pop();
|
||||
const offset = {
|
||||
left: cur?.style?.left || 0,
|
||||
top: cur?.style?.top || 0,
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
};
|
||||
|
||||
if (!node.style?.right && isNumber(node.style?.left || 0)) {
|
||||
for (const value of path) {
|
||||
if (value.style?.right || !isNumber(value.style?.left || 0)) {
|
||||
offset.left = 0;
|
||||
break;
|
||||
}
|
||||
offset.left = offset.left - Number(value.style?.left || 0);
|
||||
}
|
||||
// 水平方向:抵消祖先在对应锚定方向上的偏移量,初始值为节点自身的偏移
|
||||
if (!hasPositionValue(node.style, 'right') && isNumber(node.style?.left || 0)) {
|
||||
offset.left = accumulatePositionOffset(path, 'left', 'right', -1, Number(cur?.style?.left || 0));
|
||||
} else if (hasPositionValue(node.style, 'right') && isNumber(node.style?.right || 0)) {
|
||||
offset.right = accumulatePositionOffset(path, 'right', 'left', -1, Number(cur?.style?.right || 0));
|
||||
}
|
||||
|
||||
if (!node.style?.bottom && isNumber(node.style?.top || 0)) {
|
||||
for (const value of path) {
|
||||
if (value.style?.bottom || !isNumber(value.style?.top || 0)) {
|
||||
offset.top = 0;
|
||||
break;
|
||||
}
|
||||
offset.top = offset.top - Number(value.style?.top || 0);
|
||||
}
|
||||
// 垂直方向:同上
|
||||
if (!hasPositionValue(node.style, 'bottom') && isNumber(node.style?.top || 0)) {
|
||||
offset.top = accumulatePositionOffset(path, 'top', 'bottom', -1, Number(cur?.style?.top || 0));
|
||||
} else if (hasPositionValue(node.style, 'bottom') && isNumber(node.style?.bottom || 0)) {
|
||||
offset.bottom = accumulatePositionOffset(path, 'bottom', 'top', -1, Number(cur?.style?.bottom || 0));
|
||||
}
|
||||
|
||||
const style = node.style || {};
|
||||
@ -269,6 +320,14 @@ export const Fixed2Other = async (
|
||||
style.top = offset.top;
|
||||
}
|
||||
|
||||
if (offset.right) {
|
||||
style.right = offset.right;
|
||||
}
|
||||
|
||||
if (offset.bottom) {
|
||||
style.bottom = offset.bottom;
|
||||
}
|
||||
|
||||
return {
|
||||
...style,
|
||||
position: 'absolute',
|
||||
@ -316,11 +375,18 @@ export const fixNodePosition = (config: MNode, parent: MContainer, stage: StageC
|
||||
return config.style;
|
||||
}
|
||||
|
||||
return {
|
||||
...(config.style || {}),
|
||||
top: getMiddleTop(config, parent, stage),
|
||||
left: fixNodeLeft(config, parent, stage?.renderer?.contentWindow?.document),
|
||||
};
|
||||
const style = { ...(config.style || {}) };
|
||||
const baseStyle = config.style || {};
|
||||
|
||||
if (!('right' in baseStyle)) {
|
||||
style.left = fixNodeLeft(config, parent, stage?.renderer?.contentWindow?.document);
|
||||
}
|
||||
|
||||
if (!('top' in baseStyle) && !('bottom' in baseStyle)) {
|
||||
style.top = getMiddleTop(config, parent, stage);
|
||||
}
|
||||
|
||||
return style;
|
||||
};
|
||||
|
||||
// 序列化配置
|
||||
@ -460,11 +526,11 @@ export const resolveSelectedNode = (
|
||||
throw new Error('没有ID,无法选中');
|
||||
}
|
||||
|
||||
const { node, parent, page } = getNodeInfoFn(id);
|
||||
const { node, parent, page, path } = getNodeInfoFn(id);
|
||||
if (!node) throw new Error('获取不到组件信息');
|
||||
if (node.id === rootId) throw new Error('不能选根节点');
|
||||
|
||||
return { node, parent, page };
|
||||
return { node, parent, page, path };
|
||||
};
|
||||
|
||||
/**
|
||||
@ -479,16 +545,16 @@ export const resolveSelectedNode = (
|
||||
export const toggleFixedPosition = async (
|
||||
dist: MNode,
|
||||
src: MNode,
|
||||
root: MApp,
|
||||
path: MNode[],
|
||||
getLayoutFn: (parent: MNode, node?: MNode | null) => Promise<Layout>,
|
||||
): Promise<MNode> => {
|
||||
const newConfig = cloneDeep(dist);
|
||||
|
||||
if (!isPop(src) && newConfig.style?.position) {
|
||||
if (isFixed(newConfig.style) && !isFixed(src.style || {})) {
|
||||
newConfig.style = change2Fixed(newConfig, root);
|
||||
newConfig.style = change2Fixed(newConfig, path);
|
||||
} else if (!isFixed(newConfig.style) && isFixed(src.style || {})) {
|
||||
newConfig.style = await Fixed2Other(newConfig, root, getLayoutFn);
|
||||
newConfig.style = await Fixed2Other(newConfig, path, getLayoutFn);
|
||||
}
|
||||
}
|
||||
|
||||
@ -684,3 +750,43 @@ export const classifyDragSources = (
|
||||
|
||||
return { sameParentIndices, crossParentConfigs, aborted: false };
|
||||
};
|
||||
|
||||
/**
|
||||
* 给「回滚」生成的新 step 用的简短描述生成器。
|
||||
* 与 UI 层 `describePageStep` 同义,但避免 service 反向依赖 layouts/,故放在此工具函数中。
|
||||
*/
|
||||
export const describeStepForRevert = (step: StepValue): string => {
|
||||
const items = step.diff ?? [];
|
||||
// 在可读名后拼接组件 id,便于在历史面板中精确定位被回滚的组件;id 缺失时退化为仅展示名称。
|
||||
const withId = (node: MNode | undefined, label: string): string => {
|
||||
const id = node?.id;
|
||||
if (id === undefined || id === null || `${id}` === '') return label;
|
||||
return label ? `${label}(id: ${id})` : `id: ${id}`;
|
||||
};
|
||||
switch (step.opType) {
|
||||
case 'add': {
|
||||
const count = items.length;
|
||||
const node = items[0]?.newSchema;
|
||||
const label = node?.name || node?.type || '';
|
||||
return `撤回新增 ${count} 个节点${count === 1 ? `(${withId(node, label)})` : ''}`;
|
||||
}
|
||||
case 'remove': {
|
||||
const count = items.length;
|
||||
const node = items[0]?.oldSchema;
|
||||
const label = node?.name || node?.type || '';
|
||||
return `还原已删除的 ${count} 个节点${count === 1 ? `(${withId(node, label)})` : ''}`;
|
||||
}
|
||||
case 'update':
|
||||
default: {
|
||||
if (items.length === 1) {
|
||||
const { newSchema, oldSchema, changeRecords } = items[0];
|
||||
const node = newSchema || oldSchema;
|
||||
const label = newSchema?.name || newSchema?.type || oldSchema?.name || oldSchema?.type || '';
|
||||
const target = withId(node, label);
|
||||
const propPath = changeRecords?.[0]?.propPath;
|
||||
return propPath ? `还原 ${target} · ${propPath}` : `还原 ${target}`;
|
||||
}
|
||||
return `还原 ${items.length} 个节点的修改`;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
286
packages/editor/src/utils/history.ts
Normal file
286
packages/editor/src/utils/history.ts
Normal file
@ -0,0 +1,286 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
import serialize from 'serialize-javascript';
|
||||
|
||||
import type { Id } from '@tmagic/core';
|
||||
import type { ChangeRecord } from '@tmagic/form';
|
||||
import { guid } from '@tmagic/utils';
|
||||
|
||||
import type { BaseStepValue, HistoryGroup, StepDiffItem } from '@editor/type';
|
||||
|
||||
import { UndoRedo } from './undo-redo';
|
||||
|
||||
/**
|
||||
* 「回滚」生成的新 step 简短描述。代码块 / 数据源共用。
|
||||
* 二者逻辑一致,仅展示名取值字段不同(代码块取 `name`,数据源取 `title`),
|
||||
* 因此通过 `getLabel` 注入取值方式。
|
||||
*
|
||||
* @param id 关联的代码块 / 数据源 id
|
||||
* @param diff 单条变更 diff(缺省视为空)
|
||||
* @param getLabel 从快照取展示名
|
||||
*/
|
||||
export const describeRevertStep = <T extends object>(
|
||||
id: Id,
|
||||
{ oldSchema, newSchema, changeRecords }: StepDiffItem<T> = {},
|
||||
getLabel: (schema: T) => string | undefined,
|
||||
): string => {
|
||||
const labelOf = (schema: T) => getLabel(schema) || (schema as { id?: Id }).id;
|
||||
if (!oldSchema && newSchema) return `撤回新增 ${labelOf(newSchema) || id}`;
|
||||
if (oldSchema && !newSchema) return `还原已删除的 ${labelOf(oldSchema) || id}`;
|
||||
const label = (newSchema && getLabel(newSchema)) || (oldSchema && getLabel(oldSchema)) || `${id}`;
|
||||
const propPath = changeRecords?.[0]?.propPath;
|
||||
return propPath ? `还原 ${label} · ${propPath}` : `还原 ${label}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据 old/new 是否为 null 推断 opType(与 push 时的约定一致)。
|
||||
*/
|
||||
export const detectStackOpType = (oldVal: unknown, newVal: unknown): 'add' | 'remove' | 'update' => {
|
||||
if (oldVal === null && newVal !== null) return 'add';
|
||||
if (oldVal !== null && newVal === null) return 'remove';
|
||||
return 'update';
|
||||
};
|
||||
|
||||
/**
|
||||
* 构造一条代码块 / 数据源「按 id 分栈」的历史记录:两者除 payload 字段命名外完全一致。
|
||||
*
|
||||
* - `add`:oldValue = null;`remove`:newValue = null;`update`:两者都有,可带 changeRecords 做局部更新。
|
||||
* - 内容会做 cloneDeep 防止后续被外部引用篡改;opType 依据 old/new 是否为 null 推断。
|
||||
* - 仅负责构造 step 并返回,入栈与事件 emit 由统一的 history.push(stepType, step, id) 处理。
|
||||
* - 不直接驱动业务 service,调用方负责实际写回。
|
||||
*/
|
||||
export const createStackStep = <T, S extends BaseStepValue<T>>(
|
||||
id: Id,
|
||||
// payload 以 {@link BaseStepValue} 为基础:透传字段(historyDescription / source / operator / rootStep / extra)
|
||||
// 随 BaseStepValue 演进自动同步,原样写入 step;自动生成字段(uuid / data / opType / diff / timestamp / saved)
|
||||
// 从 payload 中排除,由本方法内部构造。oldValue / newValue / changeRecords / name 为构造 diff 与 data 用的输入。
|
||||
payload: Omit<BaseStepValue<T>, 'uuid' | 'data' | 'opType' | 'diff' | 'timestamp' | 'saved'> & {
|
||||
oldValue: T | null;
|
||||
newValue: T | null;
|
||||
changeRecords?: ChangeRecord[];
|
||||
/** 展示名(缺省时从快照 name / title 推断)。 */
|
||||
name?: string;
|
||||
},
|
||||
): S | null => {
|
||||
if (!id) return null;
|
||||
|
||||
const oldSchema = payload.oldValue ? cloneDeep(payload.oldValue) : null;
|
||||
const newSchema = payload.newValue ? cloneDeep(payload.newValue) : null;
|
||||
const changeRecords = payload.changeRecords?.length ? cloneDeep(payload.changeRecords) : undefined;
|
||||
const opType = detectStackOpType(payload.oldValue, payload.newValue);
|
||||
// 展示名:代码块取 name,数据源取 title,取不到则留空(不影响 undo/redo,仅用于展示)。
|
||||
const schema = (payload.newValue ?? payload.oldValue) as { name?: string; title?: string } | null;
|
||||
const name = payload.name ?? schema?.name ?? schema?.title ?? '';
|
||||
|
||||
const step: BaseStepValue<T> = {
|
||||
uuid: guid(),
|
||||
data: { name, id },
|
||||
opType,
|
||||
diff: [
|
||||
{
|
||||
...(newSchema !== null ? { newSchema } : {}),
|
||||
...(oldSchema !== null ? { oldSchema } : {}),
|
||||
...(opType === 'update' && changeRecords ? { changeRecords } : {}),
|
||||
},
|
||||
],
|
||||
historyDescription: payload.historyDescription,
|
||||
source: payload.source,
|
||||
operator: payload.operator,
|
||||
rootStep: payload.rootStep,
|
||||
timestamp: Date.now(),
|
||||
extra: payload.extra,
|
||||
};
|
||||
|
||||
return step as S;
|
||||
};
|
||||
|
||||
export const markStackSaved = <S extends { saved?: boolean }>(undoRedo?: UndoRedo<S>): void => {
|
||||
if (!undoRedo) return;
|
||||
undoRedo.updateElements((element) => {
|
||||
element.saved = false;
|
||||
});
|
||||
undoRedo.updateCurrentElement((element) => {
|
||||
element.saved = true;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 把单个历史栈(页面 / 代码块 / 数据源 / 扩展类型)的步骤列表按"目标"做相邻合并:
|
||||
* - 单实体的 'update' 按 targetId 与相邻同 targetId 的 update 合并到一个 group,组内可展开查看每步;
|
||||
* - 'add' / 'remove' 始终独立成组(语义上是结构变更,不应被收纳进单实体修改组);
|
||||
* - 多实体 'update'(如页面批量改属性)也独立成组(无明确单一目标,避免误合并)。
|
||||
*
|
||||
* 各类型行为完全一致,仅 `kind` 与 step 快照类型不同,统一由本方法处理。
|
||||
*/
|
||||
export const mergeSteps = <T extends BaseStepValue>(
|
||||
kind: string,
|
||||
id: Id,
|
||||
list: T[],
|
||||
cursor: number,
|
||||
): HistoryGroup<T>[] => {
|
||||
const groups: HistoryGroup<T>[] = [];
|
||||
let current: HistoryGroup<T> | null = null;
|
||||
const currentIndex = cursor - 1;
|
||||
list.forEach((step, index) => {
|
||||
const applied = index < cursor;
|
||||
const isCurrent = index === currentIndex;
|
||||
const targetId = detectTargetId(step);
|
||||
const targetName = detectTargetName(step);
|
||||
const entry = { step, index, applied, isCurrent };
|
||||
|
||||
// 仅"单实体 update"参与合并;其它情形(add/remove/多实体 update)始终独立成组。
|
||||
const mergeable = step.opType === 'update' && targetId !== undefined;
|
||||
if (mergeable && current?.opType === 'update' && current.targetId === targetId) {
|
||||
current.steps.push(entry);
|
||||
current.applied = applied;
|
||||
if (isCurrent) current.isCurrent = true;
|
||||
// 保持目标名为最近一次的(重命名时也能反映)
|
||||
if (targetName) current.targetName = targetName;
|
||||
} else {
|
||||
current = {
|
||||
kind,
|
||||
id,
|
||||
opType: step.opType,
|
||||
targetId: mergeable ? targetId : undefined,
|
||||
targetName,
|
||||
steps: [entry],
|
||||
applied,
|
||||
isCurrent,
|
||||
};
|
||||
groups.push(current);
|
||||
}
|
||||
});
|
||||
return groups;
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析 step 中的"目标 id"用于合并:
|
||||
* - 单实体 update:取唯一一项 diff 的快照 id;快照无 id 时(如 CodeBlockContent)回退到 `step.data.id`
|
||||
* (即资源 id),使代码块 / 数据源同样能按资源合并相邻 update;
|
||||
* - 其它情形(多实体 update / add / remove):返回 undefined,表示不参与合并。
|
||||
*/
|
||||
export const detectTargetId = (step: BaseStepValue): Id | undefined => {
|
||||
if (step.opType !== 'update') return undefined;
|
||||
const items = step.diff;
|
||||
if (items?.length !== 1) return undefined;
|
||||
const newSchema = items[0].newSchema as { id?: Id } | undefined;
|
||||
const oldSchema = items[0].oldSchema as { id?: Id } | undefined;
|
||||
return newSchema?.id ?? oldSchema?.id ?? step.data?.id;
|
||||
};
|
||||
|
||||
/** 解析 step 中的目标可读名(用于 UI 展示)。 */
|
||||
export const detectTargetName = (step: BaseStepValue): string | undefined => {
|
||||
const items = step.diff;
|
||||
if (step.opType === 'update') {
|
||||
if (items?.length === 1) {
|
||||
const node = (items[0].newSchema || items[0].oldSchema) as { name?: string; type?: string; id?: Id } | undefined;
|
||||
return (node?.name as string) || (node?.type as string) || (node?.id !== undefined ? `${node.id}` : undefined);
|
||||
}
|
||||
return items?.length ? `${items.length} 个节点` : undefined;
|
||||
}
|
||||
if (step.opType === 'add') {
|
||||
if (items?.length === 1) {
|
||||
const n = items[0].newSchema as { name?: string; type?: string; id?: Id } | undefined;
|
||||
return (n?.name as string) || (n?.type as string) || `${n?.id}`;
|
||||
}
|
||||
return items?.length ? `${items.length} 个节点` : undefined;
|
||||
}
|
||||
if (step.opType === 'remove') {
|
||||
if (items?.length === 1) {
|
||||
const n = items[0].oldSchema as { name?: string; type?: string; id?: Id } | undefined;
|
||||
return (n?.name as string) || (n?.type as string) || `${n?.id}`;
|
||||
}
|
||||
return items?.length ? `${items.length} 个节点` : undefined;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 `Record<Id, UndoRedo>` 整体序列化为 `Record<Id, SerializedUndoRedo>`。
|
||||
*
|
||||
* 序列化(深克隆)的同一趟里,只把每条 step 中可能含函数的 `diff` 用 serialize-javascript 序列化成字符串,
|
||||
* 其余字段(uuid / opType / timestamp / `modifiedNodeIds` Map 等)原样保留,交给 IndexedDB 结构化克隆。
|
||||
* 这样既能写入函数,又避免序列化整份快照的开销;读取时再由 {@link parseStacksStepDiff} 还原 diff。
|
||||
* 不含 `diff` 的元素(如通用栈)原样透传。
|
||||
*/
|
||||
export const serializeStacks = <T extends { diff?: unknown }>(stacks: Record<Id, UndoRedo<T>>) => {
|
||||
const result: Record<Id, ReturnType<UndoRedo<T>['serialize']>> = {};
|
||||
Object.entries(stacks).forEach(([id, undoRedo]) => {
|
||||
if (!undoRedo) return;
|
||||
const serialized = undoRedo.serialize();
|
||||
result[id] = {
|
||||
...serialized,
|
||||
elementList: serialized.elementList.map((step) =>
|
||||
step.diff === undefined ? step : Object.assign({}, step, { diff: serialize(step.diff) }),
|
||||
),
|
||||
};
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 `Record<Id, SerializedUndoRedo>` 整体还原为 `Record<Id, UndoRedo>`。
|
||||
* 还原时把每个栈的游标定位到最近一条已保存(`saved === true`)记录之后。
|
||||
*
|
||||
* 与 {@link serializeStacks} 相反:当传入 `parse`(parseDSL)时,把每条 step 中以字符串形式存储的 `diff`
|
||||
* 解析回真实对象(含函数);不含 `diff` 的元素(如通用栈)原样透传。
|
||||
*/
|
||||
export const deserializeStacks = <T extends { saved?: boolean }>(
|
||||
stacks: Record<Id, ReturnType<UndoRedo<T>['serialize']>> = {},
|
||||
parse?: (serialized: string) => unknown,
|
||||
): Record<Id, UndoRedo<T>> => {
|
||||
const result: Record<Id, UndoRedo<T>> = {};
|
||||
Object.entries(stacks).forEach(([id, serialized]) => {
|
||||
if (!serialized) return;
|
||||
const elementList = parse
|
||||
? serialized.elementList.map((step) => {
|
||||
const { diff } = step as { diff?: unknown };
|
||||
return typeof diff === 'string' ? Object.assign({}, step, { diff: parse(`(${diff})`) }) : step;
|
||||
})
|
||||
: serialized.elementList;
|
||||
result[id] = UndoRedo.fromSerialized<T>(
|
||||
{ ...serialized, elementList },
|
||||
{ isSavedStep: (element) => element.saved === true },
|
||||
);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* 按 id 从「按 id 分栈」的记录表(代码块 / 数据源)中获取(或创建)对应的 UndoRedo 栈。
|
||||
*/
|
||||
export const getOrCreateStack = <T>(stacks: Record<Id, UndoRedo<T>>, id: Id): UndoRedo<T> => {
|
||||
if (!stacks[id]) {
|
||||
stacks[id] = new UndoRedo<T>();
|
||||
}
|
||||
return stacks[id];
|
||||
};
|
||||
|
||||
/**
|
||||
* 撤销下限:当栈 index 0 是 `opType: 'initial'` 的基线 step 时为 1(基线不可被撤销),否则为 0。
|
||||
* 适用于所有历史类型(page / codeBlock / dataSource / 扩展),把 cursor 钉在基线之上,
|
||||
* 保证 undo / canUndo / goto 都不会越过初始基线。
|
||||
*/
|
||||
export const undoFloor = (undoRedo: UndoRedo<any>): number => {
|
||||
return undoRedo.getElementList()[0]?.opType === 'initial' ? 1 : 0;
|
||||
};
|
||||
|
||||
/** 将单次 push 产生的 history uuid(或 null)转为 *AndGetHistoryId 返回用的 uuid 列表。 */
|
||||
export const getLastPushedHistoryIds = (historyId: string | null): string[] => (historyId ? [historyId] : []);
|
||||
@ -27,5 +27,7 @@ export * from './dep/idle-task';
|
||||
export * from './scroll-viewer';
|
||||
export * from './tree';
|
||||
export * from './undo-redo';
|
||||
export * from './indexed-db';
|
||||
export * from './history';
|
||||
export * from './const';
|
||||
export { default as loadMonaco } from './monaco-editor';
|
||||
|
||||
122
packages/editor/src/utils/indexed-db.ts
Normal file
122
packages/editor/src/utils/indexed-db.ts
Normal file
@ -0,0 +1,122 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 一组极简的、基于原生 IndexedDB 的 Promise KV 工具,避免引入额外依赖。
|
||||
* 仅用于浏览器环境;在不支持 IndexedDB 的环境(如 SSR / 部分测试环境)下会 reject。
|
||||
*/
|
||||
|
||||
/** 是否处于支持 IndexedDB 的环境。 */
|
||||
export const isIndexedDBSupported = (): boolean => typeof indexedDB !== 'undefined' && indexedDB !== null;
|
||||
|
||||
/**
|
||||
* 打开(必要时升级)数据库,确保目标 objectStore 存在后返回连接。
|
||||
*
|
||||
* 由于 objectStore 只能在 `onupgradeneeded` 内创建,这里先以当前版本打开,
|
||||
* 若发现 store 不存在则关闭连接、以更高版本重开来按需创建,兼容动态 storeName。
|
||||
*/
|
||||
export const openIndexedDB = (dbName: string, storeName: string): Promise<IDBDatabase> =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (!isIndexedDBSupported()) {
|
||||
reject(new Error('当前环境不支持 IndexedDB'));
|
||||
return;
|
||||
}
|
||||
|
||||
const request = indexedDB.open(dbName);
|
||||
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
db.createObjectStore(storeName);
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
|
||||
request.onsuccess = () => {
|
||||
const db = request.result;
|
||||
if (db.objectStoreNames.contains(storeName)) {
|
||||
resolve(db);
|
||||
return;
|
||||
}
|
||||
|
||||
// store 不存在:以更高版本重开,在 onupgradeneeded 中创建。
|
||||
const nextVersion = db.version + 1;
|
||||
db.close();
|
||||
const upgradeRequest = indexedDB.open(dbName, nextVersion);
|
||||
upgradeRequest.onupgradeneeded = () => {
|
||||
const upgradeDb = upgradeRequest.result;
|
||||
if (!upgradeDb.objectStoreNames.contains(storeName)) {
|
||||
upgradeDb.createObjectStore(storeName);
|
||||
}
|
||||
};
|
||||
upgradeRequest.onerror = () => reject(upgradeRequest.error);
|
||||
upgradeRequest.onsuccess = () => resolve(upgradeRequest.result);
|
||||
};
|
||||
});
|
||||
|
||||
/** 写入(覆盖)一条记录。value 通过结构化克隆存储,支持 Map / Set 等结构。 */
|
||||
export const idbSet = async (dbName: string, storeName: string, key: IDBValidKey, value: unknown): Promise<void> => {
|
||||
const db = await openIndexedDB(dbName, storeName);
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(storeName, 'readwrite');
|
||||
tx.objectStore(storeName).put(value, key);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onabort = () => reject(tx.error);
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** 读取一条记录,不存在时返回 undefined。 */
|
||||
export const idbGet = async <T = unknown>(
|
||||
dbName: string,
|
||||
storeName: string,
|
||||
key: IDBValidKey,
|
||||
): Promise<T | undefined> => {
|
||||
const db = await openIndexedDB(dbName, storeName);
|
||||
try {
|
||||
return await new Promise<T | undefined>((resolve, reject) => {
|
||||
const tx = db.transaction(storeName, 'readonly');
|
||||
const request = tx.objectStore(storeName).get(key);
|
||||
request.onsuccess = () => resolve(request.result as T | undefined);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除一条记录。 */
|
||||
export const idbDelete = async (dbName: string, storeName: string, key: IDBValidKey): Promise<void> => {
|
||||
const db = await openIndexedDB(dbName, storeName);
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction(storeName, 'readwrite');
|
||||
tx.objectStore(storeName).delete(key);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onabort = () => reject(tx.error);
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
};
|
||||
@ -18,8 +18,59 @@
|
||||
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
|
||||
// #region SerializedUndoRedo
|
||||
/**
|
||||
* UndoRedo 栈的可序列化快照,用于持久化(如写入 IndexedDB)后再还原。
|
||||
*/
|
||||
export interface SerializedUndoRedo<T = any> {
|
||||
/** 栈内全部元素(按时间正序,索引 0 为最早一步)。 */
|
||||
elementList: T[];
|
||||
/** 游标位置(已应用步骤数量)。 */
|
||||
listCursor: number;
|
||||
/** 栈容量上限。 */
|
||||
listMaxSize: number;
|
||||
}
|
||||
// #endregion SerializedUndoRedo
|
||||
|
||||
// #region UndoRedo
|
||||
export class UndoRedo<T = any> {
|
||||
/**
|
||||
* 由 {@link UndoRedo.serialize} 产出的快照重建一个 UndoRedo 实例。
|
||||
* 游标会被夹紧到 [0, length] 区间,避免脏数据导致越界。
|
||||
*
|
||||
* @param options.isSavedStep 可选谓词:若提供,则把游标定位到「最近一条满足该谓词的记录」之后
|
||||
* (即恢复到最近一个已保存点);找不到匹配记录时退回快照中的原游标。
|
||||
*/
|
||||
public static fromSerialized<T = any>(
|
||||
data: SerializedUndoRedo<T>,
|
||||
options: { isSavedStep?: (element: T) => boolean } = {},
|
||||
): UndoRedo<T> {
|
||||
const undoRedo = new UndoRedo<T>(data.listMaxSize);
|
||||
const list = Array.isArray(data.elementList) ? data.elementList.map((item) => cloneDeep(item)) : [];
|
||||
let cursor = Number.isFinite(data.listCursor) ? data.listCursor : list.length;
|
||||
|
||||
// 本地数据同样遵循容量上限:超出时裁掉最旧的记录(与 pushElement 的 shift 行为一致),并同步回退游标。
|
||||
const overflow = list.length - undoRedo.listMaxSize;
|
||||
if (overflow > 0) {
|
||||
list.splice(0, overflow);
|
||||
cursor -= overflow;
|
||||
}
|
||||
|
||||
// 若指定了「已保存」谓词,则把游标移动到最近一条已保存记录之后;在裁剪后的 list 上查找以保证索引正确。
|
||||
if (options.isSavedStep) {
|
||||
for (let i = list.length - 1; i >= 0; i--) {
|
||||
if (options.isSavedStep(list[i])) {
|
||||
cursor = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
undoRedo.elementList = list;
|
||||
undoRedo.listCursor = Math.max(0, Math.min(cursor, list.length));
|
||||
return undoRedo;
|
||||
}
|
||||
|
||||
private elementList: T[];
|
||||
private listCursor: number;
|
||||
private listMaxSize: number;
|
||||
@ -31,6 +82,18 @@ export class UndoRedo<T = any> {
|
||||
this.listMaxSize = listMaxSize > minListMaxSize ? listMaxSize : minListMaxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出当前栈的可序列化快照(深克隆,避免外部改动污染内部状态)。
|
||||
* 配合 {@link UndoRedo.fromSerialized} 可在持久化后完整还原撤销/重做栈。
|
||||
*/
|
||||
public serialize(): SerializedUndoRedo<T> {
|
||||
return {
|
||||
elementList: this.elementList.map((item) => cloneDeep(item)),
|
||||
listCursor: this.listCursor,
|
||||
listMaxSize: this.listMaxSize,
|
||||
};
|
||||
}
|
||||
|
||||
public pushElement(element: T): void {
|
||||
// 新元素进来时,把游标之外的元素全部丢弃,并把新元素放进来
|
||||
this.elementList.splice(this.listCursor, this.elementList.length - this.listCursor, cloneDeep(element));
|
||||
@ -76,6 +139,31 @@ export class UndoRedo<T = any> {
|
||||
return cloneDeep(this.elementList[this.listCursor - 1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 `element` 替换当前游标所在元素(cursor - 1),并丢弃其后的重做尾部(与 {@link pushElement} 的丢尾一致),
|
||||
* 游标位置保持不变(元素数量不增)。cursor 为 0(无已应用元素)时不做任何操作并返回 false。
|
||||
* 用于「连续同类记录合并」等就地替换最新一条的场景。
|
||||
*/
|
||||
public replaceCurrentElement(element: T): boolean {
|
||||
if (this.listCursor < 1) return false;
|
||||
this.elementList.splice(this.listCursor - 1, this.elementList.length - (this.listCursor - 1), cloneDeep(element));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对当前游标所在元素(cursor - 1)做就地更新;cursor 为 0(全部已撤销)时不做任何操作。
|
||||
* 用于给「当前步骤」打标记(如标记为已保存)等元数据写入场景。
|
||||
*/
|
||||
public updateCurrentElement(updater: (element: T) => void): void {
|
||||
if (this.listCursor < 1) return;
|
||||
updater(this.elementList[this.listCursor - 1]);
|
||||
}
|
||||
|
||||
/** 对栈内全部元素做就地更新。用于批量清理元数据(如清空所有元素的已保存标记)。 */
|
||||
public updateElements(updater: (element: T, index: number) => void): void {
|
||||
this.elementList.forEach(updater);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回栈内全部元素的浅克隆数组(按时间顺序,索引 0 为最早一步)。
|
||||
* 仅用于历史面板等只读展示场景,不应直接修改返回值。
|
||||
|
||||
237
packages/editor/tests/unit/components/CompareForm.spec.ts
Normal file
237
packages/editor/tests/unit/components/CompareForm.spec.ts
Normal file
@ -0,0 +1,237 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making TMagicEditor available.
|
||||
*
|
||||
* Copyright (C) 2025 Tencent.
|
||||
*/
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import { defineComponent, h, nextTick, ref } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
|
||||
import { HookType } from '@tmagic/core';
|
||||
|
||||
import CompareForm from '@editor/components/CompareForm.vue';
|
||||
|
||||
const propsService = {
|
||||
getPropsConfig: vi.fn(async () => [
|
||||
{
|
||||
type: 'tab',
|
||||
items: [{ title: '样式', items: [{ type: 'text', name: 'color', display: false }] }],
|
||||
},
|
||||
{ type: 'text', name: 'name' },
|
||||
]),
|
||||
};
|
||||
const dataSourceService = {
|
||||
getFormConfig: vi.fn(() => [{ type: 'text', name: 'title' }]),
|
||||
};
|
||||
const codeBlockService = {
|
||||
getParamsColConfig: vi.fn(() => null),
|
||||
};
|
||||
const editorService = {
|
||||
get: vi.fn(() => ({ select: vi.fn() })),
|
||||
};
|
||||
|
||||
const services = {
|
||||
propsService,
|
||||
dataSourceService,
|
||||
codeBlockService,
|
||||
editorService,
|
||||
} as any;
|
||||
|
||||
let capturedShowDiff: ((args: any) => boolean) | undefined;
|
||||
let capturedFormProps: Record<string, any> = {};
|
||||
|
||||
vi.mock('@editor/utils/code-block', () => ({
|
||||
getCodeBlockFormConfig: vi.fn(() => [{ type: 'text', name: 'content' }]),
|
||||
}));
|
||||
|
||||
vi.mock('@tmagic/form', () => ({
|
||||
MForm: defineComponent({
|
||||
name: 'MForm',
|
||||
props: ['config', 'initValues', 'lastValues', 'isCompare', 'disabled', 'labelWidth', 'extendState', 'showDiff'],
|
||||
setup(props, { expose }) {
|
||||
capturedShowDiff = props.showDiff as (args: any) => boolean;
|
||||
capturedFormProps = props as Record<string, any>;
|
||||
expose({ formState: {} });
|
||||
return () => h('div', { class: 'fake-mform' });
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
capturedShowDiff = undefined;
|
||||
capturedFormProps = {};
|
||||
});
|
||||
|
||||
describe('CompareForm.vue', () => {
|
||||
test('node 类别按 type 加载 props 配置并展示 MForm', async () => {
|
||||
const wrapper = mount(CompareForm, {
|
||||
props: {
|
||||
category: 'node',
|
||||
type: 'text',
|
||||
value: { id: 'n1', name: 'new' },
|
||||
lastValue: { id: 'n1', name: 'old' },
|
||||
services,
|
||||
},
|
||||
global: {
|
||||
provide: {
|
||||
codeOptions: { theme: 'vs-dark' },
|
||||
},
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
|
||||
expect(propsService.getPropsConfig).toHaveBeenCalledWith('text', { node: { id: 'n1', name: 'new' } });
|
||||
expect(wrapper.find('.fake-mform').exists()).toBe(true);
|
||||
expect(capturedFormProps.initValues).toEqual({ id: 'n1', name: 'new' });
|
||||
expect(capturedFormProps.lastValues).toEqual({ id: 'n1', name: 'old' });
|
||||
});
|
||||
|
||||
test('node 类别缺少 type 时不渲染 MForm', async () => {
|
||||
const wrapper = mount(CompareForm, {
|
||||
props: {
|
||||
category: 'node',
|
||||
value: { id: 'n1' },
|
||||
services,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
expect(wrapper.find('.fake-mform').exists()).toBe(false);
|
||||
});
|
||||
|
||||
test('data-source 类别加载数据源表单配置', async () => {
|
||||
mount(CompareForm, {
|
||||
props: {
|
||||
category: 'data-source',
|
||||
type: 'http',
|
||||
value: { id: 'ds_1', title: 'A' },
|
||||
lastValue: { id: 'ds_1', title: 'B' },
|
||||
services,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(dataSourceService.getFormConfig).toHaveBeenCalledWith('http');
|
||||
});
|
||||
|
||||
test('code-block 类别会把 content 非字符串值 normalize 成字符串', async () => {
|
||||
mount(CompareForm, {
|
||||
props: {
|
||||
category: 'code-block',
|
||||
value: { id: 'cb_1', content: { toString: () => 'fn-body' } },
|
||||
lastValue: { id: 'cb_1', content: '' },
|
||||
services,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(capturedFormProps.initValues.content).toBe('fn-body');
|
||||
expect(capturedFormProps.lastValues.content).toBe('');
|
||||
});
|
||||
|
||||
test('传入 height 时外层容器启用内部滚动样式', () => {
|
||||
const wrapper = mount(CompareForm, {
|
||||
props: {
|
||||
category: 'node',
|
||||
type: 'text',
|
||||
value: { id: 'n1' },
|
||||
height: '400px',
|
||||
services,
|
||||
},
|
||||
});
|
||||
const style = wrapper.find('.m-editor-compare-form-wrapper').attributes('style') || '';
|
||||
expect(style).toContain('height: 400px');
|
||||
expect(style).toContain('overflow: auto');
|
||||
});
|
||||
|
||||
test('自定义 loadConfig 可接管配置加载', async () => {
|
||||
const loadConfig = vi.fn(async ({ defaultLoadConfig }) => {
|
||||
await defaultLoadConfig();
|
||||
return [{ type: 'text', name: 'custom' }];
|
||||
});
|
||||
const wrapper = mount(CompareForm, {
|
||||
props: {
|
||||
category: 'node',
|
||||
type: 'text',
|
||||
value: { id: 'n1' },
|
||||
loadConfig,
|
||||
services,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(loadConfig).toHaveBeenCalled();
|
||||
expect((wrapper.vm as any).config).toEqual([{ type: 'text', name: 'custom' }]);
|
||||
});
|
||||
|
||||
test('showDiff 对 code-select 的空形态视为相等', async () => {
|
||||
mount(CompareForm, {
|
||||
props: {
|
||||
category: 'node',
|
||||
type: 'text',
|
||||
value: { id: 'n1' },
|
||||
services,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(capturedShowDiff).toBeTypeOf('function');
|
||||
expect(
|
||||
capturedShowDiff!({
|
||||
curValue: '',
|
||||
lastValue: { hookType: HookType.CODE, hookData: [] },
|
||||
config: { type: 'code-select' },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
capturedShowDiff!({
|
||||
curValue: { hookType: HookType.CODE, hookData: [] },
|
||||
lastValue: '',
|
||||
config: { type: 'code-select' },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
capturedShowDiff!({
|
||||
curValue: 'a',
|
||||
lastValue: 'b',
|
||||
config: { type: 'code-select' },
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test('reload 暴露方法会重新加载配置', async () => {
|
||||
const wrapper = mount(CompareForm, {
|
||||
props: {
|
||||
category: 'data-source',
|
||||
type: 'base',
|
||||
value: { id: 'ds_1' },
|
||||
services,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
dataSourceService.getFormConfig.mockClear();
|
||||
await (wrapper.vm as any).reload();
|
||||
expect(dataSourceService.getFormConfig).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('watchEffect 会把 stage / services 写入 MForm.formState', async () => {
|
||||
const stage = ref({ select: vi.fn() });
|
||||
editorService.get.mockReturnValue(stage.value);
|
||||
mount(CompareForm, {
|
||||
props: {
|
||||
category: 'node',
|
||||
type: 'text',
|
||||
value: { id: 'n1' },
|
||||
services,
|
||||
},
|
||||
});
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
stage.value = { select: vi.fn() };
|
||||
await nextTick();
|
||||
expect(editorService.get).toHaveBeenCalledWith('stage');
|
||||
});
|
||||
});
|
||||
@ -9,10 +9,13 @@ import { mount } from '@vue/test-utils';
|
||||
|
||||
import FloatingBox from '@editor/components/FloatingBox.vue';
|
||||
|
||||
const moveableHandlers = new Map<string, (...args: any[]) => void>();
|
||||
const moveableHandlers = new Map<string, ((...args: any[]) => void)[]>();
|
||||
const destroyMock = vi.fn();
|
||||
let lastInstance: any;
|
||||
|
||||
const emitMoveable = (event: string, ...args: any[]) =>
|
||||
(moveableHandlers.get(event) || []).forEach((fn) => fn(...args));
|
||||
|
||||
vi.mock('moveable', () => {
|
||||
class FakeMoveable {
|
||||
public target: any;
|
||||
@ -26,7 +29,9 @@ vi.mock('moveable', () => {
|
||||
moveableHandlers.clear();
|
||||
}
|
||||
public on(event: string, fn: (...args: any[]) => void) {
|
||||
moveableHandlers.set(event, fn);
|
||||
const list = moveableHandlers.get(event) || [];
|
||||
list.push(fn);
|
||||
moveableHandlers.set(event, list);
|
||||
return this;
|
||||
}
|
||||
public destroy() {
|
||||
@ -64,6 +69,18 @@ const services = {
|
||||
},
|
||||
};
|
||||
|
||||
const rect200: DOMRect = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 200,
|
||||
height: 100,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 200,
|
||||
bottom: 100,
|
||||
toJSON: () => '',
|
||||
};
|
||||
|
||||
describe('FloatingBox.vue', () => {
|
||||
beforeEach(() => {
|
||||
moveableHandlers.clear();
|
||||
@ -132,7 +149,7 @@ describe('FloatingBox.vue', () => {
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
const target = document.createElement('div');
|
||||
moveableHandlers.get('resize')?.({
|
||||
emitMoveable('resize', {
|
||||
width: 200,
|
||||
height: 300,
|
||||
target,
|
||||
@ -151,20 +168,67 @@ describe('FloatingBox.vue', () => {
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
const target = document.createElement('div');
|
||||
moveableHandlers.get('drag')?.({ target, transform: 'translate(10px,20px)' });
|
||||
emitMoveable('drag', { target, transform: 'translate(10px,20px)' });
|
||||
expect(target.style.transform.replace(/\s+/g, '')).toBe('translate(10px,20px)');
|
||||
});
|
||||
|
||||
test('left + width 超过 frameworkWidth 时 left 被收敛', async () => {
|
||||
const wrapper = mount(FloatingBox as any, {
|
||||
...services,
|
||||
props: { visible: true, position: { left: 950, top: 0 }, width: 200 },
|
||||
props: { visible: true, position: { left: 950, top: 0 }, width: 200, frameworkWidth: 1000 },
|
||||
attachTo: document.body,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
await wrapper.vm.$nextTick();
|
||||
const box = document.querySelector('.m-editor-float-box') as HTMLElement;
|
||||
expect(box).not.toBeNull();
|
||||
// jsdom 中 getBoundingClientRect 返回 0,width 会被重置为 0,故不触发收敛,left 保持原值
|
||||
expect(box.style.left).toBe('950px');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('当实际宽度使 left + width 超过 frameworkWidth 时 left 收敛到右边界内', async () => {
|
||||
const getBoundingClientRectSpy = vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue(rect200);
|
||||
const wrapper = mount(FloatingBox as any, {
|
||||
props: { visible: true, position: { left: 950, top: 0 }, frameworkWidth: 1000 },
|
||||
attachTo: document.body,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
await wrapper.vm.$nextTick();
|
||||
const box = document.querySelector('.m-editor-float-box') as HTMLElement;
|
||||
expect(box).not.toBeNull();
|
||||
expect(box.style.left).toBe('800px');
|
||||
getBoundingClientRectSpy.mockRestore();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('未传入 frameworkWidth 时默认按视窗宽度收敛 left', async () => {
|
||||
const getBoundingClientRectSpy = vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue(rect200);
|
||||
const innerWidthSpy = vi.spyOn(globalThis, 'window', 'get').mockReturnValue({ innerWidth: 300 } as any);
|
||||
const wrapper = mount(FloatingBox as any, {
|
||||
props: { visible: true, position: { left: 250, top: 0 } },
|
||||
attachTo: document.body,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
await wrapper.vm.$nextTick();
|
||||
const box = document.querySelector('.m-editor-float-box') as HTMLElement;
|
||||
expect(box).not.toBeNull();
|
||||
// 250 + 200 = 450 > 视窗宽度 300,left 收敛为 300 - 200 = 100
|
||||
expect(box.style.left).toBe('100px');
|
||||
getBoundingClientRectSpy.mockRestore();
|
||||
innerWidthSpy.mockRestore();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
test('传入 initialStyle 时合并到浮窗样式', async () => {
|
||||
const wrapper = mount(FloatingBox as any, {
|
||||
props: { visible: true, initialStyle: { backgroundColor: 'rgb(255, 0, 0)' } },
|
||||
attachTo: document.body,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
await wrapper.vm.$nextTick();
|
||||
const box = document.querySelector('.m-editor-float-box') as HTMLElement;
|
||||
expect(box).not.toBeNull();
|
||||
expect(box.style.backgroundColor).toBe('rgb(255, 0, 0)');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
@ -178,4 +242,26 @@ describe('FloatingBox.vue', () => {
|
||||
wrapper.unmount();
|
||||
expect(destroyMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('dragStart 时不显示拖拽遮罩,仅在真正 drag 时显示,dragEnd 时移除', async () => {
|
||||
const wrapper = mount(FloatingBox as any, {
|
||||
props: { visible: true },
|
||||
attachTo: document.body,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// mousedown(dragStart)不应立即盖遮罩,否则会盖住关闭按钮导致点击失效
|
||||
emitMoveable('dragStart');
|
||||
expect(document.querySelector('.m-editor-float-box-drag-mask')).toBeNull();
|
||||
|
||||
// 真正发生位移时才显示遮罩
|
||||
emitMoveable('drag', { target: document.body, transform: 'translate(0,0)' });
|
||||
expect(document.querySelector('.m-editor-float-box-drag-mask')).not.toBeNull();
|
||||
|
||||
// 拖拽结束移除遮罩
|
||||
emitMoveable('dragEnd');
|
||||
expect(document.querySelector('.m-editor-float-box-drag-mask')).toBeNull();
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user