@tmagic/editor 1.8.0-beta.7 → 1.8.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/es/components/CompareForm.vue_vue_type_script_setup_true_lang.js +10 -6
  2. package/dist/es/index.js +6 -4
  3. package/dist/es/layouts/NavMenu.vue_vue_type_script_setup_true_lang.js +2 -2
  4. package/dist/es/layouts/history-list/GroupRow.vue_vue_type_script_setup_true_lang.js +38 -26
  5. package/dist/es/layouts/history-list/HistoryDiffDialog.vue_vue_type_script_setup_true_lang.js +5 -1
  6. package/dist/es/layouts/history-list/HistoryListPanel.vue_vue_type_script_setup_true_lang.js +158 -301
  7. package/dist/es/layouts/history-list/composables.js +23 -55
  8. package/dist/es/layouts/history-list/useHistoryList.js +56 -0
  9. package/dist/es/layouts/history-list/useHistoryRevert.js +304 -0
  10. package/dist/es/services/codeBlock.js +32 -28
  11. package/dist/es/services/dataSource.js +43 -34
  12. package/dist/es/services/editor.js +31 -26
  13. package/dist/es/services/history.js +268 -384
  14. package/dist/es/style.css +12 -0
  15. package/dist/es/utils/history.js +35 -47
  16. package/dist/style.css +12 -0
  17. package/dist/tmagic-editor.umd.cjs +3774 -3003
  18. package/package.json +7 -7
  19. package/src/components/CompareForm.vue +14 -6
  20. package/src/index.ts +2 -0
  21. package/src/layouts/NavMenu.vue +2 -2
  22. package/src/layouts/history-list/GroupRow.vue +10 -0
  23. package/src/layouts/history-list/HistoryDiffDialog.vue +6 -1
  24. package/src/layouts/history-list/HistoryListPanel.vue +53 -250
  25. package/src/layouts/history-list/PageTab.vue +4 -4
  26. package/src/layouts/history-list/composables.ts +52 -90
  27. package/src/layouts/history-list/useHistoryList.ts +60 -0
  28. package/src/layouts/history-list/useHistoryRevert.ts +400 -0
  29. package/src/services/codeBlock.ts +30 -29
  30. package/src/services/dataSource.ts +37 -37
  31. package/src/services/editor.ts +32 -29
  32. package/src/services/history.ts +340 -430
  33. package/src/theme/history-list-panel.scss +14 -0
  34. package/src/type.ts +174 -92
  35. package/src/utils/history.ts +52 -67
  36. package/types/index.d.ts +429 -281
@@ -1,14 +1,12 @@
1
- import { computed, reactive } from 'vue';
2
-
1
+ import { tMagicMessageBox } from '@tmagic/design';
3
2
  import { datetimeFormatter } from '@tmagic/form';
4
3
 
5
- import { useServices } from '@editor/hooks/use-services';
6
4
  import type {
7
5
  BaseStepValue,
6
+ HistoryGroup,
8
7
  HistoryOpSource,
9
8
  HistoryOpType,
10
9
  HistoryRowDescriptor,
11
- PageHistoryGroup,
12
10
  StepValue,
13
11
  } from '@editor/type';
14
12
 
@@ -27,51 +25,49 @@ export interface HistoryBucketGroup<T extends BaseStepValue = BaseStepValue> {
27
25
  steps: { index: number; applied: boolean; isCurrent?: boolean; step: T }[];
28
26
  }
29
27
 
30
- /** GroupRow 渲染所需的单个子步视图模型(已由 {@link toRowGroup} 预先派生,组件内部不再触碰原始 step)。 */
31
- export interface HistoryRowStep {
32
- /** 该子步在所属栈中的稳定索引。 */
33
- index: number;
28
+ /**
29
+ * GroupRow 的组头部与子步共用的展示字段(均由 {@link toRowGroup} 预先派生)。
30
+ * 抽出公共部分避免 {@link HistoryRowStep} / {@link HistoryRowGroup} 重复声明,
31
+ * 也便于消费方用本类型收窄「组头 / 子步」通用渲染逻辑的入参。
32
+ */
33
+ export interface HistoryRowDisplay {
34
34
  /** 是否已应用(false 表示已被 undo,UI 灰态)。 */
35
35
  applied: boolean;
36
- /** 是否为当前所在步骤。 */
37
- isCurrent?: boolean;
38
- /** 是否为最近一次保存的记录。 */
39
- saved?: boolean;
40
- /** 子步描述文案。 */
36
+ /** 是否为当前所在步骤 / 分组。 */
37
+ isCurrent: boolean;
38
+ /** 描述文案。 */
41
39
  desc: string;
42
- /** 是否可查看差异。 */
43
- diffable?: boolean;
44
- /** 是否可回滚。 */
45
- revertable?: boolean;
46
40
  /** 操作途径。 */
47
41
  source?: HistoryOpSource;
42
+ /** 操作人。 */
43
+ operator?: string;
48
44
  /** 时间文案。 */
49
45
  time?: string;
50
46
  /** 时间的完整 title 提示。 */
51
47
  timeTitle?: string;
52
48
  }
53
49
 
50
+ /** GroupRow 渲染所需的单个子步视图模型(已由 {@link toRowGroup} 预先派生,组件内部不再触碰原始 step)。 */
51
+ export interface HistoryRowStep extends HistoryRowDisplay {
52
+ /** 该子步在所属栈中的稳定索引。 */
53
+ index: number;
54
+ /** 是否为最近一次保存的记录。 */
55
+ saved?: boolean;
56
+ /** 是否可查看差异。 */
57
+ diffable?: boolean;
58
+ /** 是否可回滚。 */
59
+ revertable?: boolean;
60
+ }
61
+
54
62
  /**
55
63
  * GroupRow 渲染所需的整组视图模型(由 {@link toRowGroup} 统一派生)。
56
64
  * 把原先 GroupRow 上十多个扁平 props 收敛为单一对象,header 信息与子步列表一并携带。
57
65
  */
58
- export interface HistoryRowGroup {
66
+ export interface HistoryRowGroup extends HistoryRowDisplay {
59
67
  /** 分组的稳定 key,作为 toggle 事件 payload 与折叠状态的索引。 */
60
68
  key: string;
61
- /** 组内最后一步是否已应用。 */
62
- applied: boolean;
63
- /** 是否为当前所在分组。 */
64
- isCurrent: boolean;
65
69
  /** 操作类型,用于徽标颜色与文案。 */
66
70
  opType: HistoryOpType;
67
- /** 组整体描述文案。 */
68
- desc: string;
69
- /** 组的操作途径(取组内最近一步)。 */
70
- source?: HistoryOpSource;
71
- /** 组头部时间文案(取组内最近一步)。 */
72
- time?: string;
73
- /** 组头部时间的完整 title 提示。 */
74
- timeTitle?: string;
75
71
  /** 子步列表(时间正序);其长度即合并步数,length > 1 即为合并组。 */
76
72
  subSteps: HistoryRowStep[];
77
73
  }
@@ -79,63 +75,6 @@ export interface HistoryRowGroup {
79
75
  /** 合并组默认展开;仅当 expanded[key] === false 时为收起。 */
80
76
  export const isHistoryGroupExpanded = (expanded: Record<string, boolean>, key: string) => expanded[key] !== false;
81
77
 
82
- /**
83
- * 历史记录面板共享逻辑:
84
- * - 暴露三类历史的聚合数据(页面 / 数据源 / 代码块);
85
- * - 提供折叠状态管理;
86
- * - 提供操作描述文案生成器。
87
- *
88
- * 所有数据基于 historyService 的 reactive state 派生,自动跟随历史变化刷新。
89
- */
90
- export const useHistoryList = () => {
91
- const { historyService } = useServices();
92
-
93
- /**
94
- * 折叠状态:key 形如 `pg-${组内首步 index}` / `ds-${id}-${组内首步 index}` / `cb-${id}-${组内首步 index}`。
95
- * 用组内首步的稳定 index(而非展示位置)作为 key,确保历史数据更新后已展开的分组状态保持不变。
96
- * 合并组默认展开;仅当值为 `false` 时表示收起。
97
- */
98
- const expanded = reactive<Record<string, boolean>>({});
99
- const toggleGroup = (key: string) => {
100
- expanded[key] = expanded[key] === false;
101
- };
102
-
103
- const pageGroups = computed(() => historyService.getPageHistoryGroups());
104
- const dataSourceGroups = computed(() => historyService.getDataSourceHistoryGroups());
105
- const codeBlockGroups = computed(() => historyService.getCodeBlockHistoryGroups());
106
-
107
- /** 页面 tab 倒序展示(最新一组在最上面)。 */
108
- const pageGroupsDisplay = computed(() => pageGroups.value.slice().reverse());
109
-
110
- /**
111
- * 把按时间正序的 group 列表,再按 id 聚拢成 bucket(同 id 的所有分组放一起)。
112
- * 每个 bucket 内部仍然按时间倒序展示(最近的操作最先看到)。
113
- */
114
- const groupByTarget = <G extends { id: string | number }>(groups: G[]) => {
115
- const map = new Map<string | number, G[]>();
116
- groups.forEach((g) => {
117
- const list = map.get(g.id) ?? [];
118
- list.push(g);
119
- map.set(g.id, list);
120
- });
121
- return Array.from(map.entries()).map(([id, gs]) => ({ id, groups: gs.slice().reverse() }));
122
- };
123
-
124
- const dataSourceGroupsByTarget = computed(() => groupByTarget(dataSourceGroups.value));
125
- const codeBlockGroupsByTarget = computed(() => groupByTarget(codeBlockGroups.value));
126
-
127
- return {
128
- expanded,
129
- toggleGroup,
130
- pageGroups,
131
- dataSourceGroups,
132
- codeBlockGroups,
133
- pageGroupsDisplay,
134
- dataSourceGroupsByTarget,
135
- codeBlockGroupsByTarget,
136
- };
137
- };
138
-
139
78
  /**
140
79
  * 历史面板的时间展示:
141
80
  * - 当天的记录只显示 `HH:mm:ss`;
@@ -203,7 +142,11 @@ export const sourceLabel = (source: HistoryOpSource = 'unknown'): string => {
203
142
  export const groupSource = (group: { steps: { step: { source?: HistoryOpSource } }[] }): HistoryOpSource | undefined =>
204
143
  group.steps[group.steps.length - 1]?.step.source;
205
144
 
206
- /** {@link toRowGroup} 接受的最小分组结构,PageHistoryGroup 与 HistoryBucketGroup 均满足。 */
145
+ /** 取一组历史步骤里最后一步(最近一次)的操作人,用于组头部展示。 */
146
+ export const groupOperator = (group: { steps: { step: { operator?: string } }[] }): string | undefined =>
147
+ group.steps[group.steps.length - 1]?.step.operator;
148
+
149
+ /** {@link toRowGroup} 接受的最小分组结构 */
207
150
  interface RowGroupInput<T extends BaseStepValue = BaseStepValue> {
208
151
  applied: boolean;
209
152
  isCurrent?: boolean;
@@ -232,17 +175,19 @@ export const toRowGroup = <T extends BaseStepValue = BaseStepValue>(
232
175
  opType: group.opType,
233
176
  desc: describeGroup ? describeGroup(group) : describeStep(lastStep),
234
177
  source: groupSource(group),
178
+ operator: groupOperator(group),
235
179
  time: formatHistoryTime(timestamp),
236
180
  timeTitle: formatHistoryFullTime(timestamp),
237
181
  subSteps: group.steps.map((s) => ({
238
182
  index: s.index,
239
183
  applied: s.applied,
240
- isCurrent: s.isCurrent,
184
+ isCurrent: Boolean(s.isCurrent),
241
185
  saved: s.step.saved,
242
186
  desc: describeStep(s.step),
243
187
  diffable: isStepDiffable ? isStepDiffable(s.step) : false,
244
188
  revertable: s.applied && (isStepRevertable ? isStepRevertable(s.step) : true),
245
189
  source: s.step.source,
190
+ operator: s.step.operator,
246
191
  time: formatHistoryTime(s.step.timestamp),
247
192
  timeTitle: formatHistoryFullTime(s.step.timestamp),
248
193
  })),
@@ -314,7 +259,7 @@ export const describePageStep = (step: StepValue): string => describeStep(step,
314
259
  * - 单步组:复用 describePageStep;
315
260
  * - 多步组(连续修改同一节点):展示节点名 + 涉及的前几个 propPath。
316
261
  */
317
- export const describePageGroup = (group: PageHistoryGroup) => {
262
+ export const describePageGroup = (group: HistoryGroup<StepValue>) => {
318
263
  const lastDesc = pickLastDescription(group.steps.map((s) => s.step.historyDescription));
319
264
  if (lastDesc) return lastDesc;
320
265
  if (group.steps.length === 1) return describePageStep(group.steps[0].step);
@@ -345,3 +290,20 @@ export const isSingleDiffStepRevertable = (step: BaseStepValue): boolean => {
345
290
  if (!item?.oldSchema || !item?.newSchema) return true;
346
291
  return Boolean(item.changeRecords?.length);
347
292
  };
293
+
294
+ /**
295
+ * 通用二次确认弹窗:清空历史 / 无法差异对比的回滚等会改变状态的操作,先弹出确认框,
296
+ * 用户点击「确定」返回 true,取消(confirm reject)时返回 false 并静默忽略。
297
+ */
298
+ export const confirmHistoryAction = async (message: string): Promise<boolean> => {
299
+ try {
300
+ await tMagicMessageBox.confirm(message, '提示', {
301
+ confirmButtonText: '确定',
302
+ cancelButtonText: '取消',
303
+ type: 'warning',
304
+ });
305
+ return true;
306
+ } catch {
307
+ return false;
308
+ }
309
+ };
@@ -0,0 +1,60 @@
1
+ import { computed, reactive } from 'vue';
2
+
3
+ import { useServices } from '@editor/hooks/use-services';
4
+
5
+ /**
6
+ * 历史记录面板共享逻辑:
7
+ * - 暴露三类历史的聚合数据(页面 / 数据源 / 代码块);
8
+ * - 提供折叠状态管理;
9
+ * - 提供操作描述文案生成器。
10
+ *
11
+ * 所有数据基于 historyService 的 reactive state 派生,自动跟随历史变化刷新。
12
+ */
13
+ export const useHistoryList = () => {
14
+ const { editorService, historyService } = useServices();
15
+
16
+ /**
17
+ * 折叠状态:key 形如 `pg-${组内首步 index}` / `ds-${id}-${组内首步 index}` / `cb-${id}-${组内首步 index}`。
18
+ * 用组内首步的稳定 index(而非展示位置)作为 key,确保历史数据更新后已展开的分组状态保持不变。
19
+ * 合并组默认展开;仅当值为 `false` 时表示收起。
20
+ */
21
+ const expanded = reactive<Record<string, boolean>>({});
22
+ const toggleGroup = (key: string) => {
23
+ expanded[key] = expanded[key] === false;
24
+ };
25
+
26
+ const pageGroups = computed(() => historyService.getHistoryGroups('page', editorService.get('page')?.id));
27
+ const dataSourceGroups = computed(() => historyService.getHistoryGroups('dataSource'));
28
+ const codeBlockGroups = computed(() => historyService.getHistoryGroups('codeBlock'));
29
+
30
+ /** 页面 tab 倒序展示(最新一组在最上面)。 */
31
+ const pageGroupsDisplay = computed(() => pageGroups.value.slice().reverse());
32
+
33
+ /**
34
+ * 把按时间正序的 group 列表,再按 id 聚拢成 bucket(同 id 的所有分组放一起)。
35
+ * 每个 bucket 内部仍然按时间倒序展示(最近的操作最先看到)。
36
+ */
37
+ const groupByTarget = <G extends { id: string | number }>(groups: G[]) => {
38
+ const map = new Map<string | number, G[]>();
39
+ groups.forEach((g) => {
40
+ const list = map.get(g.id) ?? [];
41
+ list.push(g);
42
+ map.set(g.id, list);
43
+ });
44
+ return Array.from(map.entries()).map(([id, gs]) => ({ id, groups: gs.slice().reverse() }));
45
+ };
46
+
47
+ const dataSourceGroupsByTarget = computed(() => groupByTarget(dataSourceGroups.value));
48
+ const codeBlockGroupsByTarget = computed(() => groupByTarget(codeBlockGroups.value));
49
+
50
+ return {
51
+ expanded,
52
+ toggleGroup,
53
+ pageGroups,
54
+ dataSourceGroups,
55
+ codeBlockGroups,
56
+ pageGroupsDisplay,
57
+ dataSourceGroupsByTarget,
58
+ codeBlockGroupsByTarget,
59
+ };
60
+ };
@@ -0,0 +1,400 @@
1
+ import { createApp, getCurrentInstance } from 'vue';
2
+
3
+ import { tMagicMessage } from '@tmagic/design';
4
+
5
+ import type {
6
+ ConfirmAndRevertOptions,
7
+ CustomDiffFormOptions,
8
+ DiffDialogPayload,
9
+ Services,
10
+ UseHistoryRevertOptions,
11
+ } from '@editor/type';
12
+
13
+ import { confirmHistoryAction } from './composables';
14
+
15
+ /**
16
+ * 三类历史(页面 / 数据源 / 代码块)差异弹窗入参的构造差异,收敛为一份配置:
17
+ * 仅「分组来源、当前值读取、类型 / 展示名提取」不同,定位 step、校验前后值、组装 payload 的流程共用。
18
+ */
19
+ interface DiffPayloadSource {
20
+ /** 表单类别:节点 / 数据源 / 代码块。 */
21
+ category: DiffDialogPayload['category'];
22
+ /** 该类别按时间正序的历史分组列表(含已撤销)。 */
23
+ groups: () => { id?: string | number; steps: { index: number; step: { diff?: any[] } }[] }[];
24
+ /** 读取目标当前实际值,用于「与当前对比」;不存在时返回空即禁用对比。 */
25
+ getCurrent: (_id: string | number) => Record<string, any> | null | undefined;
26
+ /** 由新/旧快照提取展示名(含各自的兜底,如节点回退 type、数据源 / 代码块回退 id)。 */
27
+ resolveLabel: (_newSchema: Record<string, any>, _oldSchema: Record<string, any>, _id: string | number) => string;
28
+ /** 由新/旧快照提取类型;代码块无 type 字段则不传。 */
29
+ resolveType?: (_newSchema: Record<string, any>, _oldSchema: Record<string, any>) => string;
30
+ }
31
+
32
+ /**
33
+ * 构造差异弹窗入参:仅 update(前后值都存在)可对比。
34
+ * - 页面(无 id):在全部分组中按 index 定位 step,目标 id 取自快照;
35
+ * - 数据源 / 代码块(带 id):先匹配分组 id 再按 index 定位。
36
+ * 无可对比内容(多节点 / add / remove)或定位不到时返回 null。
37
+ */
38
+ const buildDiffPayload = (source: DiffPayloadSource, index: number, id?: string | number): DiffDialogPayload | null => {
39
+ for (const group of source.groups()) {
40
+ if (id !== undefined && group.id !== id) continue;
41
+ const step = group.steps.find((s) => s.index === index)?.step;
42
+ if (!step) continue;
43
+ const oldSchema = step.diff?.[0]?.oldSchema as Record<string, any> | undefined;
44
+ const newSchema = step.diff?.[0]?.newSchema as Record<string, any> | undefined;
45
+ if (!oldSchema || !newSchema) return null;
46
+ const targetId = id ?? newSchema.id ?? oldSchema.id;
47
+ const type = source.resolveType?.(newSchema, oldSchema);
48
+ return {
49
+ category: source.category,
50
+ ...(type !== undefined ? { type } : {}),
51
+ lastValue: oldSchema,
52
+ value: newSchema,
53
+ currentValue: (targetId !== undefined ? source.getCurrent(targetId) : null) || null,
54
+ targetLabel: source.resolveLabel(newSchema, oldSchema, targetId),
55
+ id: targetId,
56
+ };
57
+ }
58
+ return null;
59
+ };
60
+
61
+ interface MountedDiffDialog {
62
+ instance: {
63
+ open: (_payload: DiffDialogPayload) => void;
64
+ confirm: (_payload: DiffDialogPayload) => Promise<boolean>;
65
+ };
66
+ /** 卸载弹窗并清理容器(延迟以等待关闭过渡播放完成,避免动画被强行打断)。 */
67
+ destroy: () => void;
68
+ }
69
+
70
+ /**
71
+ * 按需动态 import 并挂载一个游离的 HistoryDiffDialog,返回其实例与清理函数。
72
+ * 通过继承 appContext 复用全局组件 / 指令 / provide / 插件(Element Plus、@tmagic/form 字段组件等),
73
+ * 弹窗组件动态 import,避免拖累其它消费者。供「确认回滚」与「查看差异」两种交互共用。
74
+ */
75
+ const mountHistoryDiffDialog = async (
76
+ options: Pick<UseHistoryRevertOptions, 'appContext' | 'extendState'> &
77
+ CustomDiffFormOptions & {
78
+ services: Pick<Services, 'editorService' | 'dataSourceService' | 'codeBlockService' | 'historyService'>;
79
+ isConfirm?: boolean;
80
+ onClose?: () => void;
81
+ },
82
+ ): Promise<MountedDiffDialog> => {
83
+ const { default: historyDiffDialog } = await import('./HistoryDiffDialog.vue');
84
+
85
+ const container = document.createElement('div');
86
+ container.style.display = 'none';
87
+ document.body.appendChild(container);
88
+
89
+ const app = createApp(historyDiffDialog, {
90
+ services: options.services,
91
+ isConfirm: options.isConfirm,
92
+ extendState: options.extendState,
93
+ loadConfig: options.loadConfig,
94
+ selfDiffFieldTypes: options.selfDiffFieldTypes,
95
+ onClose: options.onClose,
96
+ });
97
+ if (options.appContext) {
98
+ Object.assign(app._context, options.appContext);
99
+ }
100
+
101
+ const instance = app.mount(container) as unknown as MountedDiffDialog['instance'];
102
+
103
+ const destroy = () => {
104
+ setTimeout(() => {
105
+ try {
106
+ app.unmount();
107
+ } catch {
108
+ // ignore
109
+ }
110
+ container.parentNode?.removeChild(container);
111
+ }, 300);
112
+ };
113
+
114
+ return { instance, destroy };
115
+ };
116
+
117
+ /**
118
+ * 动态挂载一个「确认回滚」模式的 HistoryDiffDialog,等待用户确认:
119
+ * - 用户点「确定回滚」resolve(true),取消 / 关闭 resolve(false);
120
+ * - 确认流程结束后自动卸载。
121
+ */
122
+ const confirmRevertWithDiffDialog = async (
123
+ payload: DiffDialogPayload,
124
+ options: Pick<UseHistoryRevertOptions, 'appContext' | 'extendState'> &
125
+ CustomDiffFormOptions & {
126
+ services: Pick<Services, 'editorService' | 'dataSourceService' | 'codeBlockService' | 'historyService'>;
127
+ },
128
+ ): Promise<boolean> => {
129
+ const { instance, destroy } = await mountHistoryDiffDialog({
130
+ ...options,
131
+ isConfirm: true,
132
+ });
133
+ try {
134
+ return await instance.confirm(payload);
135
+ } finally {
136
+ destroy();
137
+ }
138
+ };
139
+
140
+ /**
141
+ * 动态挂载一个「查看差异」模式(只读)的 HistoryDiffDialog 并打开:
142
+ * 弹窗保持打开直到用户关闭,关闭(close 事件)后自动卸载并清理容器。
143
+ */
144
+ const viewHistoryDiffDialog = async (
145
+ payload: DiffDialogPayload,
146
+ options: Pick<UseHistoryRevertOptions, 'appContext' | 'extendState'> &
147
+ CustomDiffFormOptions & {
148
+ services: Pick<Services, 'editorService' | 'dataSourceService' | 'codeBlockService' | 'historyService'>;
149
+ },
150
+ ): Promise<void> => {
151
+ // onClose 在用户关闭弹窗时才触发,此时 handle.destroy 早已赋值。
152
+ const handle: { destroy?: () => void } = {};
153
+ const { instance, destroy } = await mountHistoryDiffDialog({
154
+ ...options,
155
+ isConfirm: false,
156
+ onClose: () => handle.destroy?.(),
157
+ });
158
+ handle.destroy = destroy;
159
+ instance.open(payload);
160
+ };
161
+
162
+ /**
163
+ * 历史记录「单步回滚」与「查看差异」的完整交互流程,供历史面板与业务方共用。
164
+ *
165
+ * 单步回滚(类 git revert):
166
+ * 1. 前置校验:目标数据已被删除(update 写回目标 / 页面 remove 的原父容器缺失)时给出「回滚失败」提示并中止;
167
+ * 2. 二次确认:可差异对比的步骤(单实体 update)弹出差异确认弹窗,其余步骤弹普通二次确认框;
168
+ * 3. 用户确认后执行对应 service 的 revert(页面 / 数据源 / 代码块)。
169
+ *
170
+ * 查看差异:可差异对比的步骤动态挂载只读 HistoryDiffDialog 展示前后值差异。
171
+ *
172
+ * 上述弹窗均按需动态挂载 HistoryDiffDialog 实现,业务方无需自行挂载任何弹窗。
173
+ *
174
+ * 返回的能力分三组:
175
+ * - 内置三类(页面 / 数据源 / 代码块):`onPageRevert` / `onDataSourceRevert` / `onCodeBlockRevert` 单步回滚,
176
+ * `onPageDiff` / `onDataSourceDiff` / `onCodeBlockDiff` 查看差异,及配套的 `buildXxxDiffPayload` / `isXxxRevertTargetMissing`;
177
+ * - 业务自有历史(如管理台「模块」):`confirmAndRevert` / `viewDiff` 复用同一套交互流程,由业务方自行构造差异入参;
178
+ * 即上述内置三类本质上是它们各自预置好 payload 构造与 service.revert 的特例。
179
+ *
180
+ * 业务方可在拿到 Editor 实例暴露的 `services` 后直接 import 调用:
181
+ *
182
+ * ```ts
183
+ * import { useHistoryRevert } from '@tmagic/editor';
184
+ *
185
+ * const { onPageRevert, onPageDiff } = useHistoryRevert(editorRef.value); // editorRef.value 即 Editor 暴露的 services
186
+ * await onPageRevert(index); // 弹出差异 / 二次确认弹窗后回滚
187
+ * onPageDiff(index); // 弹出只读差异弹窗查看前后值差异
188
+ * ```
189
+ */
190
+ export const useHistoryRevert = (
191
+ services: Pick<Services, 'editorService' | 'dataSourceService' | 'codeBlockService' | 'historyService'>,
192
+ options: UseHistoryRevertOptions = {},
193
+ ) => {
194
+ const { editorService, dataSourceService, codeBlockService, historyService } = services;
195
+ // 自动捕获调用方所在组件的 appContext(在 setup 中调用时),业务方亦可显式覆盖。
196
+ const appContext = options.appContext ?? getCurrentInstance()?.appContext ?? null;
197
+ const { extendState } = options;
198
+
199
+ /** 目标数据已被删除、无法回滚时的统一提示。 */
200
+ const showRevertTargetMissing = () => {
201
+ tMagicMessage.error('回滚失败:该记录对应的数据已被删除');
202
+ };
203
+
204
+ /**
205
+ * 「回滚」二次确认:新增 / 删除 / 多节点更新等无法做差异对比的步骤,
206
+ * 不弹差异弹窗,改用一个普通确认框替代「确定回滚」按钮,避免点击后无任何提示直接执行。
207
+ * 用户取消时返回 false,调用方据此中止回滚。
208
+ */
209
+ const confirmRevert = (): Promise<boolean> =>
210
+ confirmHistoryAction(
211
+ '确定回滚该步骤吗?回滚会将该操作作为一条新记录反向应用(新增将被删除、删除将被还原),不影响后续历史记录。',
212
+ );
213
+
214
+ /**
215
+ * 「回滚」统一确认入口:可差异对比的步骤动态挂载 HistoryDiffDialog 走差异确认弹窗,
216
+ * 无法对比的步骤(add / remove / 多节点更新)回退到普通二次确认框。
217
+ * `extra` 供业务自有历史(如模块)透传自定义表单配置加载等渲染入参。
218
+ */
219
+ const runRevert = (payload: DiffDialogPayload | null, extra?: CustomDiffFormOptions): Promise<boolean> => {
220
+ if (payload) {
221
+ return confirmRevertWithDiffDialog(payload, { appContext, extendState, services, ...extra });
222
+ }
223
+ return confirmRevert();
224
+ };
225
+
226
+ const buildPageDiffPayload = (index: number): DiffDialogPayload | null =>
227
+ buildDiffPayload(
228
+ {
229
+ category: 'node',
230
+ groups: () => historyService.getHistoryGroups('page', editorService.get('page')?.id),
231
+ getCurrent: (id) => editorService.getNodeById(id) as Record<string, any> | null,
232
+ resolveType: (n, o) => n.type || o.type || '',
233
+ resolveLabel: (n, o) => n.name || o.name || n.type || o.type || '',
234
+ },
235
+ index,
236
+ );
237
+
238
+ const buildDataSourceDiffPayload = (id: string | number, index: number): DiffDialogPayload | null =>
239
+ buildDiffPayload(
240
+ {
241
+ category: 'data-source',
242
+ groups: () => historyService.getHistoryGroups('dataSource'),
243
+ getCurrent: (id) => dataSourceService.getDataSourceById(`${id}`) as Record<string, any> | null,
244
+ resolveType: (n, o) => n.type || o.type || 'base',
245
+ resolveLabel: (n, o, id) => n.title || o.title || `${id}`,
246
+ },
247
+ index,
248
+ id,
249
+ );
250
+
251
+ const buildCodeBlockDiffPayload = (id: string | number, index: number): DiffDialogPayload | null =>
252
+ buildDiffPayload(
253
+ {
254
+ category: 'code-block',
255
+ groups: () => historyService.getHistoryGroups('codeBlock'),
256
+ getCurrent: (id) => codeBlockService.getCodeContentById(id) as Record<string, any> | null,
257
+ resolveLabel: (n, o, id) => n.name || o.name || `${id}`,
258
+ },
259
+ index,
260
+ id,
261
+ );
262
+
263
+ /**
264
+ * 回滚前置校验:若该历史步骤回滚所依赖的目标数据已被删除,则无法回滚。
265
+ * - update(把旧值写回):被修改的目标必须仍存在;
266
+ * - 页面 remove(还原被删节点):被删节点的原父容器必须仍存在,否则无处插回;
267
+ * add(回滚即删除)即使目标已不在,也已达成「删除」目的,不视为失败。
268
+ */
269
+ const isPageRevertTargetMissing = (index: number): boolean => {
270
+ const step = historyService.getStepList('page', editorService.get('page')?.id)[index]?.step;
271
+ if (!step) return false;
272
+ if (step.opType === 'update') {
273
+ return (step.diff ?? []).some((item) => {
274
+ const id = item.newSchema?.id ?? item.oldSchema?.id;
275
+ return id !== undefined && !editorService.getNodeById(id, false);
276
+ });
277
+ }
278
+ if (step.opType === 'remove') {
279
+ return (step.diff ?? []).some(
280
+ (item) => item.parentId !== undefined && !editorService.getNodeById(item.parentId, false),
281
+ );
282
+ }
283
+ return false;
284
+ };
285
+
286
+ /** 数据源 update 步骤回滚时,对应数据源必须仍存在(已删除则无处写回旧值)。 */
287
+ const isDataSourceRevertTargetMissing = (id: string | number, index: number): boolean => {
288
+ const step = historyService.getStepList('dataSource', id)[index]?.step;
289
+ return Boolean(step?.opType === 'update' && !dataSourceService.getDataSourceById(`${id}`));
290
+ };
291
+
292
+ /** 代码块 update 步骤回滚时,对应代码块必须仍存在(已删除则无处写回旧值)。 */
293
+ const isCodeBlockRevertTargetMissing = (id: string | number, index: number): boolean => {
294
+ const step = historyService.getStepList('codeBlock', id)[index]?.step;
295
+ return Boolean(step?.opType === 'update' && !codeBlockService.getCodeContentById(id));
296
+ };
297
+
298
+ const onPageRevert = (index: number) => {
299
+ if (isPageRevertTargetMissing(index)) {
300
+ showRevertTargetMissing();
301
+ return Promise.resolve(null);
302
+ }
303
+ return runRevert(buildPageDiffPayload(index)).then((result) =>
304
+ result ? editorService.revertPageStep(index) : null,
305
+ );
306
+ };
307
+
308
+ const onDataSourceRevert = (id: string | number, index: number) => {
309
+ if (isDataSourceRevertTargetMissing(id, index)) {
310
+ showRevertTargetMissing();
311
+ return Promise.resolve(null);
312
+ }
313
+ return runRevert(buildDataSourceDiffPayload(id, index)).then((result) =>
314
+ result ? dataSourceService.revert(id, index) : null,
315
+ );
316
+ };
317
+
318
+ const onCodeBlockRevert = (id: string | number, index: number) => {
319
+ if (isCodeBlockRevertTargetMissing(id, index)) {
320
+ showRevertTargetMissing();
321
+ return Promise.resolve(null);
322
+ }
323
+ return runRevert(buildCodeBlockDiffPayload(id, index)).then((result) =>
324
+ result ? codeBlockService.revert(id, index) : null,
325
+ );
326
+ };
327
+
328
+ /**
329
+ * 「查看差异」:可差异对比的步骤(单实体 update)动态挂载只读 HistoryDiffDialog 展示前后值差异,
330
+ * 无可对比内容(add / remove / 多节点更新)时不弹窗、静默返回。
331
+ */
332
+ const onPageDiff = (index: number): Promise<void> | void => {
333
+ const payload = buildPageDiffPayload(index);
334
+ if (payload) return viewHistoryDiffDialog(payload, { appContext, extendState, services });
335
+ };
336
+
337
+ const onDataSourceDiff = (id: string | number, index: number): Promise<void> | void => {
338
+ const payload = buildDataSourceDiffPayload(id, index);
339
+ if (payload) return viewHistoryDiffDialog(payload, { appContext, extendState, services });
340
+ };
341
+
342
+ const onCodeBlockDiff = (id: string | number, index: number): Promise<void> | void => {
343
+ const payload = buildCodeBlockDiffPayload(id, index);
344
+ if (payload) return viewHistoryDiffDialog(payload, { appContext, extendState, services });
345
+ };
346
+
347
+ /**
348
+ * 业务自有历史(如管理台「模块」)的「单步回滚」统一入口:
349
+ * 复用与页面/数据源/代码块一致的「目标校验 → 差异/二次确认弹窗 → 反向回滚」流程,
350
+ * 内置三类只是它的特例(各自预置了 buildXxxDiffPayload + service.revert)。
351
+ *
352
+ * 用户取消或前置校验未过时返回 null,确认并执行回滚后返回 `revert()` 的结果。
353
+ *
354
+ * ```ts
355
+ * await confirmAndRevert({
356
+ * diffPayload: oldSchema && newSchema ? { category: 'module', lastValue: oldSchema, value: newSchema, ... } : null,
357
+ * loadConfig: (ctx) => loadModFormConfig(modTypeId, values),
358
+ * selfDiffFieldTypes: ['mod-cond'],
359
+ * revert: () => moduleHistoryStore.revert(id, index),
360
+ * });
361
+ * ```
362
+ */
363
+ const confirmAndRevert = async <T = unknown>(revertOptions: ConfirmAndRevertOptions<T>): Promise<T | null> => {
364
+ if (revertOptions.isTargetMissing?.()) {
365
+ showRevertTargetMissing();
366
+ return null;
367
+ }
368
+ const confirmed = await runRevert(revertOptions.diffPayload ?? null, {
369
+ loadConfig: revertOptions.loadConfig,
370
+ selfDiffFieldTypes: revertOptions.selfDiffFieldTypes,
371
+ });
372
+ if (!confirmed) return null;
373
+ return await revertOptions.revert();
374
+ };
375
+
376
+ /**
377
+ * 业务自有历史的「查看差异」统一入口:传入自行构造的差异入参即弹出只读差异弹窗,
378
+ * 可透传 `loadConfig` / `selfDiffFieldTypes`。payload 为 null(不可对比)时静默返回。
379
+ */
380
+ const viewDiff = (payload: DiffDialogPayload | null, extra?: CustomDiffFormOptions): Promise<void> | void => {
381
+ if (payload) return viewHistoryDiffDialog(payload, { appContext, extendState, services, ...extra });
382
+ };
383
+
384
+ return {
385
+ onPageRevert,
386
+ onDataSourceRevert,
387
+ onCodeBlockRevert,
388
+ onPageDiff,
389
+ onDataSourceDiff,
390
+ onCodeBlockDiff,
391
+ buildPageDiffPayload,
392
+ buildDataSourceDiffPayload,
393
+ buildCodeBlockDiffPayload,
394
+ isPageRevertTargetMissing,
395
+ isDataSourceRevertTargetMissing,
396
+ isCodeBlockRevertTargetMissing,
397
+ confirmAndRevert,
398
+ viewDiff,
399
+ };
400
+ };