@tmagic/editor 1.8.0-beta.6 → 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 (42) 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 +163 -310
  7. package/dist/es/layouts/history-list/composables.js +47 -128
  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/layouts/sidebar/Sidebar.vue_vue_type_script_setup_true_lang.js +2 -2
  11. package/dist/es/layouts/sidebar/data-source/DataSourceConfigPanel.vue_vue_type_script_setup_true_lang.js +3 -3
  12. package/dist/es/services/codeBlock.js +32 -28
  13. package/dist/es/services/dataSource.js +43 -34
  14. package/dist/es/services/editor.js +31 -26
  15. package/dist/es/services/history.js +268 -384
  16. package/dist/es/style.css +12 -0
  17. package/dist/es/utils/editor.js +2 -2
  18. package/dist/es/utils/history.js +35 -47
  19. package/dist/style.css +12 -0
  20. package/dist/tmagic-editor.umd.cjs +3808 -3090
  21. package/package.json +7 -7
  22. package/src/components/CompareForm.vue +14 -6
  23. package/src/index.ts +2 -0
  24. package/src/layouts/NavMenu.vue +2 -2
  25. package/src/layouts/history-list/GroupRow.vue +10 -0
  26. package/src/layouts/history-list/HistoryDiffDialog.vue +6 -1
  27. package/src/layouts/history-list/HistoryListPanel.vue +60 -270
  28. package/src/layouts/history-list/PageTab.vue +4 -4
  29. package/src/layouts/history-list/composables.ts +82 -180
  30. package/src/layouts/history-list/useHistoryList.ts +60 -0
  31. package/src/layouts/history-list/useHistoryRevert.ts +400 -0
  32. package/src/layouts/sidebar/Sidebar.vue +2 -2
  33. package/src/layouts/sidebar/data-source/DataSourceConfigPanel.vue +5 -4
  34. package/src/services/codeBlock.ts +30 -29
  35. package/src/services/dataSource.ts +37 -37
  36. package/src/services/editor.ts +32 -29
  37. package/src/services/history.ts +340 -431
  38. package/src/theme/history-list-panel.scss +14 -0
  39. package/src/type.ts +179 -100
  40. package/src/utils/editor.ts +2 -2
  41. package/src/utils/history.ts +52 -74
  42. package/types/index.d.ts +435 -309
@@ -17,32 +17,32 @@
17
17
  */
18
18
 
19
19
  import { reactive } from 'vue';
20
+ import type { Writable } from 'type-fest';
20
21
 
21
- import type { CodeBlockContent, DataSourceSchema, Id, MPage, MPageFragment } from '@tmagic/core';
22
- import type { ChangeRecord } from '@tmagic/form';
22
+ import type { Id } from '@tmagic/core';
23
23
  import { guid } from '@tmagic/utils';
24
24
 
25
25
  import type {
26
- CodeBlockHistoryGroup,
26
+ BaseStepValue,
27
27
  CodeBlockStepValue,
28
- DataSourceHistoryGroup,
29
28
  DataSourceStepValue,
29
+ HistoryEvents,
30
+ HistoryGroup,
30
31
  HistoryOpSource,
31
32
  HistoryPersistOptions,
32
33
  HistoryState,
33
- PageHistoryGroup,
34
- PageHistoryStepEntry,
34
+ HistoryStepEntry,
35
+ HistoryStepType,
35
36
  PersistedHistoryState,
36
37
  StepValue,
38
+ SyncHookPlugin,
37
39
  } from '@editor/type';
38
40
  import { getEditorConfig } from '@editor/utils/config';
39
41
  import {
40
- createStackStep,
41
42
  deserializeStacks,
42
43
  getOrCreateStack,
43
44
  markStackSaved,
44
- mergePageSteps,
45
- mergeStackSteps,
45
+ mergeSteps,
46
46
  serializeStacks,
47
47
  undoFloor,
48
48
  } from '@editor/utils/history';
@@ -52,86 +52,110 @@ import { UndoRedo } from '@editor/utils/undo-redo';
52
52
  import BaseService from './BaseService';
53
53
  import editorService from './editor';
54
54
 
55
+ const canUsePluginMethods = {
56
+ sync: ['push', 'undo', 'redo'] as const,
57
+ };
58
+
59
+ /** 各内置历史类型的默认展示名称(用于历史面板 tab / 分组标题等)。扩展类型可通过 registerStepType / setStepName 登记。 */
60
+ const DEFAULT_STEP_NAMES: Record<string, string> = {
61
+ page: '页面',
62
+ codeBlock: '代码块',
63
+ dataSource: '数据源',
64
+ };
65
+
66
+ /** 各历史类型对应的分组 `kind`(展示用):page→page,codeBlock→code-block,dataSource→data-source。扩展类型缺省回退到 stepType 本身。 */
67
+ const STEP_TYPE_KIND: Record<string, string> = {
68
+ page: 'page',
69
+ codeBlock: 'code-block',
70
+ dataSource: 'data-source',
71
+ };
72
+
73
+ type SyncMethodName = Writable<(typeof canUsePluginMethods)['sync']>;
74
+
55
75
  /** 历史记录持久化快照的默认存储位置与结构版本。 */
56
76
  const DEFAULT_DB_NAME = 'tmagic-editor';
57
77
  const DEFAULT_STORE_NAME = 'history';
58
78
  const DEFAULT_KEY: IDBValidKey = 'default';
59
- // v2:仅把每条 step 的 diff 序列化成字符串,其余字段交给 IndexedDB 结构化克隆原生存储(见 saveToIndexedDB)。
60
- const PERSIST_VERSION = 2;
79
+ // 仅把每条 step 的 diff 序列化成字符串,其余字段交给 IndexedDB 结构化克隆原生存储(见 saveToIndexedDB);
80
+ // 全部历史栈统一收敛到 steps 字段(见 HistorySteps)。
81
+ const PERSIST_VERSION = 3;
61
82
 
62
83
  class History extends BaseService {
63
84
  public state = reactive<HistoryState>({
64
- pageSteps: {},
65
- pageId: undefined,
66
- canRedo: false,
67
- canUndo: false,
68
- codeBlockState: {},
69
- dataSourceState: {},
85
+ steps: {
86
+ page: {},
87
+ codeBlock: {},
88
+ dataSource: {},
89
+ },
90
+ stepNames: { ...DEFAULT_STEP_NAMES },
70
91
  });
71
92
 
72
93
  constructor() {
73
- super([]);
74
-
75
- this.on('change', this.setCanUndoRedo);
94
+ super([...canUsePluginMethods.sync.map((methodName) => ({ name: methodName, isAsync: false }))]);
76
95
  }
77
96
 
78
- public reset() {
79
- this.state.pageSteps = {};
80
- this.state.codeBlockState = {};
81
- this.state.dataSourceState = {};
82
- this.resetPage();
97
+ /**
98
+ * 注册一个扩展历史类型,使其可与内置 `page` / `codeBlock` / `dataSource` 一样走统一的
99
+ * {@link push} / {@link undo} / {@link redo}(按 id 分栈、独立 undo/redo)。
100
+ *
101
+ * @param stepType 自定义历史类型标识(勿与内置类型重名)
102
+ * @param options.event push/undo/redo 后派发的事件名,缺省为 `${stepType}-history-change`
103
+ * @param options.name 历史面板中的展示名称(tab / 分组标题等),缺省回退到 stepType 本身
104
+ */
105
+ public registerStepType(stepType: string, options: { event?: string; name?: string } = {}): void {
106
+ this.getStepBucket(stepType);
107
+ if (options.name !== undefined) this.state.stepNames[stepType] = options.name;
83
108
  }
84
109
 
85
- public resetPage() {
86
- this.state.pageId = undefined;
87
- this.state.canRedo = false;
88
- this.state.canUndo = false;
110
+ /**
111
+ * 读取指定历史类型的展示名称(用于历史面板 tab / 分组标题等)。
112
+ * 未登记名称时回退到 stepType 本身。
113
+ */
114
+ public getStepName(stepType: HistoryStepType): string {
115
+ return this.state.stepNames[stepType] ?? `${stepType}`;
89
116
  }
90
117
 
91
- public changePage(page: MPage | MPageFragment): void {
92
- if (!page) return;
93
-
94
- this.state.pageId = page.id;
95
-
96
- if (!this.state.pageSteps[this.state.pageId]) {
97
- this.state.pageSteps[this.state.pageId] = new UndoRedo<StepValue>();
98
- }
99
-
100
- this.setCanUndoRedo();
118
+ /**
119
+ * 设置指定历史类型的展示名称(用于历史面板 tab / 分组标题等)。
120
+ * 内置 `page` / `codeBlock` / `dataSource` 也可在此覆盖默认中文名。
121
+ */
122
+ public setStepName(stepType: HistoryStepType, name: string): void {
123
+ this.state.stepNames[stepType] = name;
124
+ }
101
125
 
102
- this.emit('page-change', this.state.pageSteps[this.state.pageId]);
126
+ public reset() {
127
+ this.clearAllSteps();
103
128
  }
104
129
 
105
130
  public resetState(): void {
106
- this.state.pageId = undefined;
107
- this.state.pageSteps = {};
108
- this.state.canRedo = false;
109
- this.state.canUndo = false;
110
- this.state.codeBlockState = {};
111
- this.state.dataSourceState = {};
131
+ this.clearAllSteps();
112
132
  }
113
133
 
114
134
  /**
115
- * 为指定页面 / 页面片种入一条「初始基线」记录(如加载 DSL 时的「初始 / 加载」基线)。
135
+ * 为指定历史栈(默认 `page`,也适用于 codeBlock / dataSource / 扩展类型)种入一条「初始基线」记录。
116
136
  *
117
- * 该记录是一条 `opType: 'initial'` 的 {@link StepValue},作为页面历史栈 **index 0 的固定底线**:
137
+ * 该记录是一条 `opType: 'initial'` 的 step,作为对应栈 **index 0 的固定底线**:
118
138
  * - 它是一条真实入栈的 step(随栈一起持久化),但被钉为撤销/回滚的下限——cursor 永不低于它,
119
- * 因此不会被 undo / goto / revert 触达(详见 {@link undo} / {@link setCanUndoRedo});
120
- * - 历史面板把它过滤出分组列表(见 {@link getPageHistoryGroups}),改由底部「初始」行展示。
139
+ * 因此不会被 undo / goto / revert 触达(详见 {@link undo} / {@link undoFloor});
140
+ * - 历史面板把它过滤出分组列表(见 {@link getHistoryGroups}),改由底部「初始」行展示。
141
+ *
142
+ * 仅当目标栈为空时种入(保证 initial 一定位于 index 0);已存在 initial 底线时不重复种入。
121
143
  *
122
- * 仅当目标页面栈为空时种入(保证 initial 一定位于 index 0);已存在 initial 底线时默认不重复种入,
123
- * `force=true` 且栈为空时按新基线种入。
144
+ * @param stepType 历史类型
145
+ * @param id 目标栈 id(page 为 pageId,其余类型为对应资源 id)
146
+ * @param options 基线展示信息(名称 / 描述 / 来源)
124
147
  */
125
- public setPageMarker(
126
- pageId: Id,
127
- options: { name?: string; description?: string; source?: HistoryOpSource } = {},
148
+ public setMarker(
149
+ stepType: HistoryStepType,
150
+ id: Id,
151
+ options: { name?: string; description?: string; source?: HistoryOpSource; extra?: Record<string, any> } = {},
128
152
  ): StepValue | null {
129
- if (pageId === undefined || pageId === null || `${pageId}` === '') return null;
153
+ if (!this.isValidStackId(id)) return null;
130
154
 
131
- const existing = this.getPageMarker(pageId);
155
+ const existing = this.getMarker(stepType, id);
132
156
  if (existing) return existing;
133
157
 
134
- const stack = getOrCreateStack(this.state.pageSteps, pageId);
158
+ const stack = getOrCreateStack(this.getStepBucket(stepType), id);
135
159
  // initial 必须是 index 0;栈非空(已有真实记录、却无 initial,如旧数据)时不强行前插,优雅降级为无基线。
136
160
  if (stack.getLength() > 0) return null;
137
161
 
@@ -139,205 +163,141 @@ class History extends BaseService {
139
163
  uuid: guid(),
140
164
  opType: 'initial',
141
165
  diff: [],
142
- data: { name: options.name || '', id: pageId },
143
- selectedBefore: [],
144
- selectedAfter: [],
145
- modifiedNodeIds: new Map(),
166
+ data: { name: options.name || '', id },
167
+ extra: {
168
+ ...(options.extra || {}),
169
+ ...(stepType === 'page'
170
+ ? {
171
+ selectedBefore: [],
172
+ selectedAfter: [],
173
+ modifiedNodeIds: new Map(),
174
+ }
175
+ : {}),
176
+ },
146
177
  historyDescription: options.description || '未修改的初始状态',
147
178
  timestamp: Date.now(),
148
179
  ...(options.source ? { source: options.source } : {}),
149
180
  };
150
181
  stack.pushElement(marker);
151
- if (`${pageId}` === `${this.state.pageId}`) this.setCanUndoRedo();
152
- this.emit('page-marker-change', marker);
182
+ this.emit('marker-change', { id, marker, stepType });
153
183
  return marker;
154
184
  }
155
185
 
156
186
  /**
157
- * 读取指定页面(缺省当前活动页)的初始基线 step(页面栈 index 0 且 `opType: 'initial'`);
158
- * 不存在时返回 undefined。
187
+ * 读取指定历史栈的初始基线 step(栈 index 0 且 `opType: 'initial'`);
188
+ * 不存在或 id 缺省时返回 undefined。
159
189
  */
160
- public getPageMarker(pageId?: Id): StepValue | undefined {
161
- const targetPageId = pageId ?? this.state.pageId;
162
- if (!targetPageId) return undefined;
163
- const first = this.state.pageSteps[targetPageId]?.getElementList()[0];
164
- return first?.opType === 'initial' ? first : undefined;
190
+ public getMarker(stepType: HistoryStepType, id?: Id): StepValue | undefined {
191
+ if (!this.isValidStackId(id)) return undefined;
192
+ const first = this.state.steps[stepType]?.[id]?.getElementList()[0];
193
+ return first?.opType === 'initial' ? (first as StepValue) : undefined;
165
194
  }
166
195
 
167
196
  /**
168
- * 把一条步骤推入指定页面的栈;不指定 pageId 时落到当前活动页。
197
+ * 把一条步骤推入指定历史栈。统一入口,所有类型(page / codeBlock / dataSource / 扩展)行为完全一致:
198
+ * 按 `stepType` 选择目标栈类型,按 `id`(必填)选择具体栈,按需建栈后入栈,并派发对应的历史变更事件
199
+ * (`page` 为 `change`,其余见 {@link registerStepType}),回调签名统一为 `(id, step)`。
169
200
  *
170
- * 跨页操作(例如 `moveToContainer` 把节点搬到其它页)必须显式传入 `pageId`,
171
- * 否则会把记录错误地落到操作发起页 / 当前激活页,破坏目标页 / 源页的撤销栈语义。
172
- */
173
- public push(state: StepValue, pageId?: Id): StepValue | null {
174
- const undoRedo = this.getUndoRedo(pageId);
175
- if (!undoRedo) return null;
176
- if (state.uuid === undefined) state.uuid = guid();
177
- if (state.timestamp === undefined) state.timestamp = Date.now();
178
- undoRedo.pushElement(state);
179
- // 仅当推入的是当前活动页时才需要刷新 canUndo/canRedo —— 其它页栈对当前 UI 状态没影响。
180
- if (pageId === undefined || `${pageId}` === `${this.state.pageId}`) {
181
- this.emit('change', state);
182
- }
183
- return state;
184
- }
185
-
186
- /** 读取指定页面(缺省当前活动页)历史栈当前游标所在的 step(cursor - 1);无则返回 null。 */
187
- public getCurrentPageStep(pageId?: Id): StepValue | null {
188
- const targetPageId = pageId ?? this.state.pageId;
189
- if (!targetPageId) return null;
190
- return this.state.pageSteps[targetPageId]?.getCurrentElement() ?? null;
191
- }
192
-
193
- /**
194
- * 用 `state` 替换指定页面栈当前游标所在的 step(并丢弃其后的重做尾部),游标不变。
195
- * 用于「连续 set root 记录合并」等就地替换最新一条的场景;替换成功后按需刷新 / 通知。
196
- */
197
- public replaceCurrentPageStep(state: StepValue, pageId?: Id): StepValue | null {
198
- const undoRedo = this.getUndoRedo(pageId);
199
- if (!undoRedo) return null;
200
- if (state.uuid === undefined) state.uuid = guid();
201
- if (state.timestamp === undefined) state.timestamp = Date.now();
202
- if (!undoRedo.replaceCurrentElement(state)) return null;
203
- this.emit('change', state);
204
- return state;
205
- }
206
-
207
- /**
208
- * 推入一条代码块变更记录(与页面/节点完全无关),按 `codeBlockId` 维度独立一份 UndoRedo 栈。
201
+ * 跨页 / 跨资源操作(如 `moveToContainer` 把节点搬到其它页)必须显式传入目标 id,
202
+ * 否则无法落到正确的栈。step 可由 `createStackStep` 等构造后传入。
209
203
  *
210
- * - 新增:oldContent = null,newContent = 新内容
211
- * - 更新:oldContent / newContent 都为对应内容
212
- * - 删除:newContent = null,oldContent = 删除前内容
213
- * - `changeRecords` 来自 form 端,撤销/重做时若有则按 propPath 局部覆盖;缺省才退化为整内容替换。
214
- * - 不直接驱动 codeBlockService,调用方负责实际写回。
204
+ * @param stepType 历史类型
205
+ * @param step 已构造好的历史记录(缺省自动补全 uuid / timestamp)
206
+ * @param id 目标栈 id(page pageId,其余类型为对应资源 id),必填
215
207
  */
216
- public pushCodeBlock(
217
- codeBlockId: Id,
218
- payload: {
219
- oldContent: CodeBlockContent | null;
220
- newContent: CodeBlockContent | null;
221
- changeRecords?: ChangeRecord[];
222
- /** 可选的人类可读描述(如「修改按钮颜色」),仅用于历史面板展示。 */
223
- historyDescription?: string;
224
- /** 可选的操作途径(配置面板 / 菜单 / 接口等),仅用于历史面板展示与埋点。 */
225
- source?: HistoryOpSource;
226
- },
227
- ): CodeBlockStepValue | null {
228
- const step = createStackStep<CodeBlockContent, CodeBlockStepValue>(codeBlockId, {
229
- oldValue: payload.oldContent,
230
- newValue: payload.newContent,
231
- changeRecords: payload.changeRecords,
232
- historyDescription: payload.historyDescription,
233
- source: payload.source,
234
- });
235
- if (!step) return null;
236
- getOrCreateStack(this.state.codeBlockState, codeBlockId).pushElement(step);
237
- this.emit('code-block-history-change', codeBlockId, step);
208
+ public push(stepType: 'page', step: StepValue, id: Id): StepValue | null;
209
+ public push(stepType: 'codeBlock', step: CodeBlockStepValue, id: Id): CodeBlockStepValue | null;
210
+ public push(stepType: 'dataSource', step: DataSourceStepValue, id: Id): DataSourceStepValue | null;
211
+ public push<T extends BaseStepValue>(stepType: string, step: T, id: Id): T | null;
212
+ public push(stepType: HistoryStepType, step: BaseStepValue, id: Id): BaseStepValue | null {
213
+ if (!this.isValidStackId(id)) return null;
214
+ this.fillStepMeta(step);
215
+ getOrCreateStack(this.getStepBucket(stepType), id).pushElement(step);
216
+ this.emit('change', step, stepType, id);
238
217
  return step;
239
218
  }
240
219
 
241
220
  /**
242
- * 推入一条数据源变更记录(与页面/节点完全无关),按 `dataSourceId` 维度独立一份 UndoRedo 栈。
243
- * 行为同 pushCodeBlock(新增 oldSchema=null;删除 newSchema=null)。
221
+ * 撤销指定历史栈的最近一次变更。统一入口,所有类型行为一致:
222
+ * `id`(必填)+ `stepType` 定位栈,不会越过 index 0 的 initial 基线(所有类型同等适用),
223
+ * 仅在确有可撤销 step 时派发对应的历史变更事件(`page` 为 `change`,回调签名 `(id, step)`)。
224
+ *
225
+ * @param stepType 历史类型
226
+ * @param id 目标栈 id(page 为 pageId,其余类型为对应资源 id),必填
244
227
  */
245
- public pushDataSource(
246
- dataSourceId: Id,
247
- payload: {
248
- oldSchema: DataSourceSchema | null;
249
- newSchema: DataSourceSchema | null;
250
- changeRecords?: ChangeRecord[];
251
- /** 可选的人类可读描述,仅用于历史面板展示。 */
252
- historyDescription?: string;
253
- /** 可选的操作途径(配置面板 / 菜单 / 接口等),仅用于历史面板展示与埋点。 */
254
- source?: HistoryOpSource;
255
- },
256
- ): DataSourceStepValue | null {
257
- const step = createStackStep<DataSourceSchema, DataSourceStepValue>(dataSourceId, {
258
- oldValue: payload.oldSchema,
259
- newValue: payload.newSchema,
260
- changeRecords: payload.changeRecords,
261
- historyDescription: payload.historyDescription,
262
- source: payload.source,
263
- });
264
- if (!step) return null;
265
- getOrCreateStack(this.state.dataSourceState, dataSourceId).pushElement(step);
266
- this.emit('data-source-history-change', dataSourceId, step);
267
- return step;
268
- }
269
-
270
- /** 撤销指定代码块的最近一次变更。 */
271
- public undoCodeBlock(codeBlockId: Id): CodeBlockStepValue | null {
272
- const undoRedo = this.state.codeBlockState[codeBlockId];
228
+ public undo(stepType: 'page', id: Id): StepValue | null;
229
+ public undo(stepType: 'codeBlock', id: Id): CodeBlockStepValue | null;
230
+ public undo(stepType: 'dataSource', id: Id): DataSourceStepValue | null;
231
+ public undo<T extends BaseStepValue>(stepType: string, id: Id): T | null;
232
+ public undo(stepType: HistoryStepType, id: Id): BaseStepValue | null {
233
+ if (!this.isValidStackId(id)) return null;
234
+ const undoRedo = this.state.steps[stepType]?.[id];
273
235
  if (!undoRedo) return null;
236
+ // 不允许撤销越过初始基线(index 0 的 initial step);无基线时 floor 为 0。
237
+ if (undoRedo.getCursor() <= undoFloor(undoRedo)) return null;
274
238
  const step = undoRedo.undo();
275
- if (step) this.emit('code-block-history-change', codeBlockId, step);
239
+ if (step) this.emit('change', step, stepType, id);
276
240
  return step;
277
241
  }
278
242
 
279
- /** 重做指定代码块的下一次变更。 */
280
- public redoCodeBlock(codeBlockId: Id): CodeBlockStepValue | null {
281
- const undoRedo = this.state.codeBlockState[codeBlockId];
243
+ /**
244
+ * 重做指定历史栈的下一次变更。语义与 {@link undo} 对称,详见其说明。
245
+ *
246
+ * @param stepType 历史类型
247
+ * @param id 目标栈 id(page 为 pageId,其余类型为对应资源 id),必填
248
+ */
249
+ public redo(stepType: 'page', id: Id): StepValue | null;
250
+ public redo(stepType: 'codeBlock', id: Id): CodeBlockStepValue | null;
251
+ public redo(stepType: 'dataSource', id: Id): DataSourceStepValue | null;
252
+ public redo<T extends BaseStepValue>(stepType: string, id: Id): T | null;
253
+ public redo(stepType: HistoryStepType, id: Id): BaseStepValue | null {
254
+ if (!this.isValidStackId(id)) return null;
255
+ const undoRedo = this.state.steps[stepType]?.[id];
282
256
  if (!undoRedo) return null;
283
257
  const step = undoRedo.redo();
284
- if (step) this.emit('code-block-history-change', codeBlockId, step);
258
+ if (step) this.emit('change', step, stepType, id);
285
259
  return step;
286
260
  }
287
261
 
288
- /** 是否可对指定代码块撤销。 */
289
- public canUndoCodeBlock(codeBlockId: Id): boolean {
290
- return this.state.codeBlockState[codeBlockId]?.canUndo() ?? false;
291
- }
292
-
293
- /** 是否可对指定代码块重做。 */
294
- public canRedoCodeBlock(codeBlockId: Id): boolean {
295
- return this.state.codeBlockState[codeBlockId]?.canRedo() ?? false;
296
- }
297
-
298
- /** 撤销指定数据源的最近一次变更。 */
299
- public undoDataSource(dataSourceId: Id): DataSourceStepValue | null {
300
- const undoRedo = this.state.dataSourceState[dataSourceId];
301
- if (!undoRedo) return null;
302
- const step = undoRedo.undo();
303
- if (step) this.emit('data-source-history-change', dataSourceId, step);
304
- return step;
262
+ /**
263
+ * 是否可对指定历史栈撤销(cursor 高于 initial 基线底线)。
264
+ * @param stepType 历史类型
265
+ * @param id 目标栈 id;缺省 / 无效时返回 false
266
+ */
267
+ public canUndo(stepType: HistoryStepType, id?: Id): boolean {
268
+ if (!this.isValidStackId(id)) return false;
269
+ const undoRedo = this.state.steps[stepType]?.[id];
270
+ return undoRedo ? undoRedo.getCursor() > undoFloor(undoRedo) : false;
305
271
  }
306
272
 
307
- /** 重做指定数据源的下一次变更。 */
308
- public redoDataSource(dataSourceId: Id): DataSourceStepValue | null {
309
- const undoRedo = this.state.dataSourceState[dataSourceId];
310
- if (!undoRedo) return null;
311
- const step = undoRedo.redo();
312
- if (step) this.emit('data-source-history-change', dataSourceId, step);
313
- return step;
273
+ /**
274
+ * 是否可对指定历史栈重做。
275
+ * @param stepType 历史类型
276
+ * @param id 目标栈 id;缺省 / 无效时返回 false
277
+ */
278
+ public canRedo(stepType: HistoryStepType, id?: Id): boolean {
279
+ if (!this.isValidStackId(id)) return false;
280
+ return this.state.steps[stepType]?.[id]?.canRedo() ?? false;
314
281
  }
315
282
 
316
- /** 是否可对指定数据源撤销。 */
317
- public canUndoDataSource(dataSourceId: Id): boolean {
318
- return this.state.dataSourceState[dataSourceId]?.canUndo() ?? false;
283
+ /** 读取指定页面历史栈当前游标所在的 step(cursor - 1);无则返回 null。 */
284
+ public getCurrentPageStep(pageId: Id): StepValue | null {
285
+ if (!this.isValidStackId(pageId)) return null;
286
+ return this.state.steps.page[pageId]?.getCurrentElement() ?? null;
319
287
  }
320
288
 
321
- /** 是否可对指定数据源重做。 */
322
- public canRedoDataSource(dataSourceId: Id): boolean {
323
- return this.state.dataSourceState[dataSourceId]?.canRedo() ?? false;
324
- }
289
+ /**
290
+ * `state` 替换指定页面栈当前游标所在的 step(并丢弃其后的重做尾部),游标不变。
291
+ * 用于「连续 set root 记录合并」等就地替换最新一条的场景;替换成功后派发 `change`。
292
+ */
293
+ public replaceCurrentStep(stepType: HistoryStepType, state: StepValue, id: Id): StepValue | null {
294
+ if (!this.isValidStackId(id)) return null;
295
+ const undoRedo = getOrCreateStack(this.getStepBucket(stepType), id);
325
296
 
326
- public undo(): StepValue | null {
327
- const undoRedo = this.getUndoRedo();
328
- if (!undoRedo) return null;
329
- // 不允许撤销越过初始基线(index 0 的 initial step)。
330
- if (undoRedo.getCursor() <= undoFloor(undoRedo)) return null;
331
- const state = undoRedo.undo();
332
- this.emit('change', state);
333
- return state;
334
- }
297
+ this.fillStepMeta(state);
335
298
 
336
- public redo(): StepValue | null {
337
- const undoRedo = this.getUndoRedo();
338
- if (!undoRedo) return null;
339
- const state = undoRedo.redo();
340
- this.emit('change', state);
299
+ if (!undoRedo.replaceCurrentElement(state)) return null;
300
+ this.emit('change', state, stepType, id);
341
301
  return state;
342
302
  }
343
303
 
@@ -348,91 +308,53 @@ class History extends BaseService {
348
308
  }
349
309
 
350
310
  /**
351
- * 清空指定页面(缺省当前活动页)的历史记录栈。
352
- * 仅删除撤销/重做记录,不会改动当前 DSL;清空后该页将无法再撤销/重做之前的操作。
353
- */
354
- public clearPage(pageId?: Id): void {
355
- const targetPageId = pageId ?? this.state.pageId;
356
- if (!targetPageId) return;
357
- // 保留该页原 initial 基线的文案 / 来源(仅清空其后的真实操作记录),无基线时清空成空栈。
358
- const marker = this.getPageMarker(targetPageId);
359
- this.state.pageSteps[targetPageId] = new UndoRedo<StepValue>();
360
- if (marker) {
361
- this.setPageMarker(targetPageId, {
362
- name: marker.data?.name,
363
- description: marker.historyDescription,
364
- source: marker.source,
365
- });
366
- }
367
- if (`${targetPageId}` === `${this.state.pageId}`) {
368
- this.setCanUndoRedo();
369
- this.emit('clear-page', null);
370
- }
371
- }
372
-
373
- /**
374
- * 清空数据源历史记录栈:传入 `dataSourceId` 仅清空该数据源,缺省清空全部数据源。
375
- * 仅删除撤销/重做记录,不会改动数据源本身。
311
+ * 清空历史记录栈。统一入口,所有类型(page / codeBlock / dataSource / 扩展)行为一致:
312
+ * - 传入 `id`:仅清空 `stepType` 下该 id 对应的栈;
313
+ * - 缺省 `id`:清空 `stepType` 下的全部栈。
314
+ *
315
+ * 仅删除撤销/重做记录,不会改动 DSL / 代码块 / 数据源本身。清空时会**保留各栈原有的
316
+ * initial 基线**(文案 / 来源),无基线时清空成空栈。清空后派发 `clear`(签名 `(id, stepType)`)。
317
+ *
318
+ * @param stepType 历史类型
319
+ * @param id 目标栈 id;缺省表示清空该类型下全部栈
376
320
  */
377
- public clearDataSource(dataSourceId?: Id): void {
378
- if (dataSourceId !== undefined) {
379
- delete this.state.dataSourceState[dataSourceId];
321
+ public clear(stepType: HistoryStepType, id?: Id): void {
322
+ const bucket = this.state.steps[stepType];
323
+ if (!bucket) return;
324
+
325
+ if (this.isValidStackId(id)) {
326
+ this.clearStack(stepType, id);
327
+ } else if (id === undefined) {
328
+ Object.keys(bucket).forEach((stackId) => this.clearStack(stepType, stackId as Id));
380
329
  } else {
381
- this.state.dataSourceState = {};
330
+ return;
382
331
  }
332
+ this.emit('clear', { id: id as Id, stepType });
383
333
  }
384
334
 
385
335
  /**
386
- * 清空代码块历史记录栈:传入 `codeBlockId` 仅清空该代码块,缺省清空全部代码块。
387
- * 仅删除撤销/重做记录,不会改动代码块本身。
336
+ * 标记历史记录为「已保存」(把对应栈当前游标所在的记录标为 `saved`)。统一入口:
337
+ * - 缺省 `id`:标记**全部类型、全部栈**(整份 DSL 落库场景),派发 `mark-saved` 且 `kind: 'all'`;
338
+ * - 传入 `id`:仅标记 `stepType` 下该 id 对应的栈,派发 `mark-saved` 且 `kind` 为 `stepType`。
339
+ *
340
+ * 同一栈内任意时刻最多只有一条记录为 `saved`;从 IndexedDB 恢复时游标会被定位到最近一条已保存记录之后。
341
+ *
342
+ * @param stepType 历史类型
343
+ * @param id 目标栈 id;缺省表示标记全部类型 / 全部栈
388
344
  */
389
- public clearCodeBlock(codeBlockId?: Id): void {
390
- if (codeBlockId !== undefined) {
391
- delete this.state.codeBlockState[codeBlockId];
392
- } else {
393
- this.state.codeBlockState = {};
345
+ public markSaved(stepType: HistoryStepType, id?: Id): void {
346
+ if (id === undefined) {
347
+ Object.values(this.state.steps).forEach((bucket) => Object.values(bucket).forEach(markStackSaved));
348
+ this.emit('mark-saved', { kind: 'all' });
349
+ return;
394
350
  }
351
+ if (!this.isValidStackId(id)) return;
352
+ markStackSaved(this.state.steps[stepType]?.[id]);
353
+ this.emit('mark-saved', { kind: stepType, id });
395
354
  }
396
355
 
397
356
  /**
398
- * 标记「整份 DSL 已保存」:把页面 / 代码块 / 数据源所有栈当前游标所在的记录都标为 `saved`。
399
- * 适用于「整体落库」场景;若只保存了其中一类,请改用更细粒度的
400
- * {@link markPageSaved} / {@link markCodeBlockSaved} / {@link markDataSourceSaved}。
401
- */
402
- public markSaved(): void {
403
- Object.values(this.state.pageSteps).forEach(markStackSaved);
404
- Object.values(this.state.codeBlockState).forEach(markStackSaved);
405
- Object.values(this.state.dataSourceState).forEach(markStackSaved);
406
- this.emit('mark-saved', { kind: 'all' });
407
- }
408
-
409
- /**
410
- * 标记指定页面(缺省为当前活动页)的历史栈当前记录为已保存。
411
- * 仅影响该页面自己的栈,不波及代码块 / 数据源 / 其它页面。
412
- */
413
- public markPageSaved(pageId?: Id): void {
414
- const targetPageId = pageId ?? this.state.pageId;
415
- if (!targetPageId) return;
416
- markStackSaved(this.state.pageSteps[targetPageId]);
417
- this.emit('mark-saved', { kind: 'page', id: targetPageId });
418
- }
419
-
420
- /** 标记指定代码块的历史栈当前记录为已保存,仅影响该代码块自己的栈。 */
421
- public markCodeBlockSaved(codeBlockId: Id): void {
422
- if (!codeBlockId) return;
423
- markStackSaved(this.state.codeBlockState[codeBlockId]);
424
- this.emit('mark-saved', { kind: 'code-block', id: codeBlockId });
425
- }
426
-
427
- /** 标记指定数据源的历史栈当前记录为已保存,仅影响该数据源自己的栈。 */
428
- public markDataSourceSaved(dataSourceId: Id): void {
429
- if (!dataSourceId) return;
430
- markStackSaved(this.state.dataSourceState[dataSourceId]);
431
- this.emit('mark-saved', { kind: 'data-source', id: dataSourceId });
432
- }
433
-
434
- /**
435
- * 把当前内存中的全部历史栈(页面 / 代码块 / 数据源)序列化后写入本地 IndexedDB。
357
+ * 把当前内存中的全部历史栈(页面 / 代码块 / 数据源 / 扩展类型)序列化后写入本地 IndexedDB。
436
358
  *
437
359
  * - 每个 UndoRedo 栈连同其游标、容量一并保存,恢复后可继续 undo/redo;
438
360
  * - `key` 用于区分不同活动页 / 项目(同一 store 下可保存多份快照),缺省为 `default`;
@@ -444,12 +366,14 @@ class History extends BaseService {
444
366
 
445
367
  // serializeStacks 会在序列化各栈时只把每条 step 的 diff(可能含函数)序列化成字符串,其余字段原样保留,
446
368
  // 因此整份快照可直接按对象写入 IndexedDB(结构化克隆),避免序列化整份快照的开销;读取时再用 parseDSL 还原 diff。
369
+ const steps: PersistedHistoryState['steps'] = { page: {}, codeBlock: {}, dataSource: {} };
370
+ Object.entries(this.state.steps).forEach(([stepType, bucket]) => {
371
+ steps[stepType] = serializeStacks(bucket);
372
+ });
373
+
447
374
  const snapshot: PersistedHistoryState = {
448
375
  version: PERSIST_VERSION,
449
- pageId: this.state.pageId,
450
- pageSteps: serializeStacks(this.state.pageSteps),
451
- codeBlockState: serializeStacks(this.state.codeBlockState),
452
- dataSourceState: serializeStacks(this.state.dataSourceState),
376
+ steps,
453
377
  savedAt: Date.now(),
454
378
  };
455
379
 
@@ -462,7 +386,7 @@ class History extends BaseService {
462
386
  * 从本地 IndexedDB 读取此前保存的历史快照并重建全部撤销/重做栈。
463
387
  *
464
388
  * - 读取到的每个栈都会经 {@link UndoRedo.fromSerialized} 还原(含游标),随后可直接 undo/redo;
465
- * - 会整体覆盖当前内存中的历史状态,并把活动页恢复为快照中的 pageId;
389
+ * - 会整体覆盖当前内存中的历史状态(活动页由 editorService 维护,不在此恢复);
466
390
  * - 找不到对应记录时返回 null,且不改动当前状态;
467
391
  * - 不支持 IndexedDB 的环境(如 SSR)会 reject。
468
392
  */
@@ -474,176 +398,168 @@ class History extends BaseService {
474
398
 
475
399
  // 各 step 的 diff 以序列化字符串存储(含函数),由 deserializeStacks 逐条用 parseDSL 还原。
476
400
  const parseDSL = getEditorConfig('parseDSL');
477
- this.state.pageSteps = deserializeStacks(snapshot.pageSteps, parseDSL);
478
- this.state.codeBlockState = deserializeStacks(snapshot.codeBlockState, parseDSL);
479
- this.state.dataSourceState = deserializeStacks(snapshot.dataSourceState, parseDSL);
480
- // initial 基线作为页面栈 index 0 的 step 随 pageSteps 一并还原,无需单独恢复。
481
- this.state.pageId = snapshot.pageId;
482
401
 
483
- this.setCanUndoRedo();
402
+ const steps: HistoryState['steps'] = { page: {}, codeBlock: {}, dataSource: {} };
403
+ Object.entries(snapshot.steps).forEach(([stepType, bucket]) => {
404
+ steps[stepType] = deserializeStacks(bucket, parseDSL);
405
+ });
406
+ this.state.steps = steps;
407
+ // initial 基线作为各栈 index 0 的 step 随 steps 一并还原,无需单独恢复;活动页由 editorService 维护。
484
408
  this.emit('restore-from-indexed-db', snapshot);
485
409
  return snapshot;
486
410
  }
487
411
 
488
412
  /**
489
- * 取出当前活动页的历史步骤平铺列表(包含已应用 + 已撤销)。
490
- * 列表按时间正序,最早一步在最前面。
491
- * 通常 UI 应使用 `getPageHistoryGroups` 取已合并分组的版本;本方法仅为兼容/调试保留。
413
+ * 取出指定历史类型(页面 / 代码块 / 数据源 / 扩展类型)某个栈的平铺步骤列表(含 applied 标记)。
414
+ * 统一入口,替代旧的 `getPageStepList` / `getCodeBlockStepList` / `getDataSourceStepList`。
415
+ *
416
+ * 列表按时间正序,最早一步在最前面;`applied` 表示该步骤处于栈游标之前(已应用)。
417
+ * 供 revert / goto 等按 index 索引步骤的场景使用。通常 UI 应使用
418
+ * {@link getHistoryGroups} 取已合并分组的版本;本方法仅为兼容/调试保留。
419
+ *
420
+ * @param stepType 历史类型
421
+ * @param id 目标栈 id(page 为 pageId,其余类型为对应资源 id);缺省 / 无效时返回空数组
492
422
  */
493
- public getPageStepList(pageId?: Id): PageHistoryStepEntry[] {
494
- const targetPageId = pageId ?? this.state.pageId;
495
- if (!targetPageId) return [];
496
- const undoRedo = this.state.pageSteps[targetPageId];
423
+ public getStepList(stepType: 'page', id?: Id): HistoryStepEntry<StepValue>[];
424
+ public getStepList(stepType: 'codeBlock', id: Id): HistoryStepEntry<CodeBlockStepValue>[];
425
+ public getStepList(stepType: 'dataSource', id: Id): HistoryStepEntry<DataSourceStepValue>[];
426
+ public getStepList<T extends BaseStepValue>(stepType: HistoryStepType, id?: Id): HistoryStepEntry<T>[];
427
+ public getStepList(stepType: HistoryStepType, id?: Id): HistoryStepEntry<any>[] {
428
+ if (!this.isValidStackId(id)) return [];
429
+ const undoRedo = this.state.steps[stepType]?.[id];
497
430
  if (!undoRedo) return [];
498
431
  const list = undoRedo.getElementList();
499
432
  const cursor = undoRedo.getCursor();
500
- return list.map((step, index) => ({
501
- step,
502
- index,
503
- applied: index < cursor,
504
- }));
433
+ return list.map((step, index) => ({ step, index, applied: index < cursor }));
505
434
  }
506
435
 
507
436
  /**
508
- * 取出当前活动页的历史栈,按"目标节点"做相邻合并:
509
- * - 连续修改同一节点(单节点 update)的多步合并为一个 group,组内可展开查看每步;
510
- * - add / remove / 多节点 update 始终独立成组。
511
- * 用于历史面板的"页面"tab 展示。
437
+ * 取出指定历史类型的历史分组(页面 / 代码块 / 数据源 / 扩展类型统一入口)。
438
+ *
439
+ * 把目标栈的步骤列表按"目标"做相邻合并(连续修改同一目标的 update 合并为一组,组内可展开查看每步;
440
+ * add / remove / 多实体 update 始终独立成组),并过滤掉 index 0 的 initial 基线(底部「初始」行由
441
+ * {@link getMarker} 驱动)。各类型行为完全一致,仅 `kind` 与 step 快照类型不同。
442
+ *
443
+ * 作用域:
444
+ * - 传入 `id`:仅取该 id 对应的单个栈(页面历史按活动页查看,传入 pageId);
445
+ * - 缺省 `id`:遍历该类型下全部栈并汇总(代码块 / 数据源按全部资源分桶展示)。
446
+ *
447
+ * @param stepType 历史类型,缺省 `page`
448
+ * @param id 目标栈 id;缺省表示遍历该类型下全部栈
512
449
  */
513
- public getPageHistoryGroups(pageId?: Id): PageHistoryGroup[] {
514
- const targetPageId = pageId ?? this.state.pageId;
515
- if (!targetPageId) return [];
516
- const undoRedo = this.state.pageSteps[targetPageId];
517
- if (!undoRedo) return [];
518
- const list = undoRedo.getElementList();
519
- if (!list.length) return [];
520
- const cursor = undoRedo.getCursor();
521
- // initial 基线(index 0)不作为普通操作组展示,过滤掉;其余真实 step index 保持不变,
522
- // 以便面板 goto(index+1) / revert(index) 仍直接对应栈内位置。底部「初始」行由 getPageMarker 驱动。
523
- return mergePageSteps(targetPageId, list, cursor).filter((group) => group.opType !== 'initial');
450
+ public getHistoryGroups(stepType: 'page', id?: Id): HistoryGroup<StepValue>[];
451
+ public getHistoryGroups(stepType: 'codeBlock', id?: Id): HistoryGroup<CodeBlockStepValue>[];
452
+ public getHistoryGroups(stepType: 'dataSource', id?: Id): HistoryGroup<DataSourceStepValue>[];
453
+ public getHistoryGroups<T extends BaseStepValue>(stepType: HistoryStepType, id?: Id): HistoryGroup<T>[];
454
+ public getHistoryGroups(stepType: HistoryStepType, id?: Id): HistoryGroup[] {
455
+ const bucket = this.state.steps[stepType];
456
+ if (!bucket) return [];
457
+ const kind = STEP_TYPE_KIND[stepType] ?? stepType;
458
+ const collect = (stackId: Id): HistoryGroup[] => {
459
+ const undoRedo = bucket[stackId];
460
+ if (!undoRedo) return [];
461
+ const list = undoRedo.getElementList();
462
+ if (!list.length) return [];
463
+ // initial 基线(index 0)不作为普通操作组展示,过滤掉;其余真实 step 的 index 保持不变,
464
+ // 以便面板 goto(index+1) / revert(index) 仍直接对应栈内位置。
465
+ return mergeSteps(kind, stackId, list, undoRedo.getCursor()).filter((group) => group.opType !== 'initial');
466
+ };
467
+ if (this.isValidStackId(id)) return collect(id);
468
+ return Object.keys(bucket).flatMap((stackId) => collect(stackId as Id));
524
469
  }
525
470
 
526
471
  /**
527
- * 取出全部代码块的历史栈,按 codeBlockId 分桶展示。
528
- * 同一栈内每条操作记录独立成组,不做相邻 update 合并。
472
+ * 读取指定历史栈的当前游标(已应用步骤数量)。统一入口,替代旧的
473
+ * `getPageCursor` / `getCodeBlockCursor` / `getDataSourceCursor`。
474
+ * - `id` 缺省或非法、或对应栈不存在时返回 0;
475
+ * - `stepType` 支持 `page` / `codeBlock` / `dataSource` / 扩展类型。
529
476
  */
530
- public getCodeBlockHistoryGroups(): CodeBlockHistoryGroup[] {
531
- const groups: CodeBlockHistoryGroup[] = [];
532
- Object.entries(this.state.codeBlockState).forEach(([id, undoRedo]) => {
533
- if (!undoRedo) return;
534
- const list = undoRedo.getElementList();
535
- if (!list.length) return;
536
- const cursor = undoRedo.getCursor();
537
- groups.push(...mergeStackSteps('code-block', id, list, cursor));
538
- });
539
- return groups;
477
+ public getCursor(stepType: HistoryStepType, id?: Id): number {
478
+ if (!this.isValidStackId(id)) return 0;
479
+ return this.state.steps[stepType]?.[id]?.getCursor() ?? 0;
540
480
  }
541
481
 
542
482
  /**
543
- * 读取指定页面历史栈的当前游标(已应用步骤数量)。不传则取当前活动页。
544
- * 没有对应栈时返回 0。
483
+ * 按历史记录 uuid 在指定历史类型的栈中查找其所属 id 与索引,统一入口,替代旧的
484
+ * `getPageStepIndexByUuid` / `findCodeBlockStepLocationByUuid` / `findDataSourceStepLocationByUuid`。
485
+ *
486
+ * - 传入 `id`:仅在该 id 对应的单个栈中查找(如页面历史按活动页查看,传入 pageId);
487
+ * - 缺省 `id`:遍历该类型下全部栈查找(代码块 / 数据源等按全部资源分桶的场景)。
488
+ *
489
+ * 找不到时返回 null。供「按 uuid 回滚」等需要把 uuid 映射回 (id, index) 的场景使用。
490
+ *
491
+ * @param stepType 历史类型
492
+ * @param uuid 目标历史记录的 uuid
493
+ * @param id 目标栈 id;缺省表示遍历该类型下全部栈
545
494
  */
546
- public getPageCursor(pageId?: Id): number {
547
- const targetPageId = pageId ?? this.state.pageId;
548
- if (!targetPageId) return 0;
549
- return this.state.pageSteps[targetPageId]?.getCursor() ?? 0;
550
- }
495
+ public findStepLocationByUuid(stepType: HistoryStepType, uuid: string, id?: Id): { id: Id; index: number } | null {
496
+ if (!uuid) return null;
497
+ const bucket = this.state.steps[stepType];
498
+ if (!bucket) return null;
551
499
 
552
- /** 读取指定代码块历史栈的当前游标。 */
553
- public getCodeBlockCursor(codeBlockId: Id): number {
554
- return this.state.codeBlockState[codeBlockId]?.getCursor() ?? 0;
555
- }
500
+ if (this.isValidStackId(id)) {
501
+ const index = this.getStepList(stepType, id).findIndex((entry) => entry.step.uuid === uuid);
502
+ return index >= 0 ? { id, index } : null;
503
+ }
556
504
 
557
- /** 读取指定数据源历史栈的当前游标。 */
558
- public getDataSourceCursor(dataSourceId: Id): number {
559
- return this.state.dataSourceState[dataSourceId]?.getCursor() ?? 0;
505
+ for (const stackId of Object.keys(bucket)) {
506
+ const index = this.getStepList(stepType, stackId as Id).findIndex((entry) => entry.step.uuid === uuid);
507
+ if (index >= 0) return { id: stackId as Id, index };
508
+ }
509
+ return null;
560
510
  }
561
511
 
562
- /**
563
- * 取出指定代码块历史栈的平铺步骤列表(含 applied 标记)。供 revert 等按 index 索引步骤使用。
564
- */
565
- public getCodeBlockStepList(codeBlockId: Id): { step: CodeBlockStepValue; index: number; applied: boolean }[] {
566
- const undoRedo = this.state.codeBlockState[codeBlockId];
567
- if (!undoRedo) return [];
568
- const list = undoRedo.getElementList();
569
- const cursor = undoRedo.getCursor();
570
- return list.map((step, index) => ({ step, index, applied: index < cursor }));
512
+ public usePlugin(options: SyncHookPlugin<SyncMethodName, History>): void {
513
+ super.usePlugin(options);
571
514
  }
572
515
 
573
- /**
574
- * 取出指定数据源历史栈的平铺步骤列表(含 applied 标记)。供 revert 等按 index 索引步骤使用。
575
- */
576
- public getDataSourceStepList(dataSourceId: Id): { step: DataSourceStepValue; index: number; applied: boolean }[] {
577
- const undoRedo = this.state.dataSourceState[dataSourceId];
578
- if (!undoRedo) return [];
579
- const list = undoRedo.getElementList();
580
- const cursor = undoRedo.getCursor();
581
- return list.map((step, index) => ({ step, index, applied: index < cursor }));
516
+ public emit<Name extends keyof HistoryEvents, Param extends HistoryEvents[Name]>(eventName: Name, ...args: Param) {
517
+ return super.emit(eventName, ...args);
582
518
  }
583
519
 
584
520
  /**
585
- * 按历史记录 uuid 在指定页面(默认当前活动页)的栈中查找其索引。
586
- * 找不到时返回 -1。供「按 uuid 回滚」等需要把 uuid 映射回 index 的场景使用。
521
+ * 取出指定历史类型的栈桶(`Record<id, UndoRedo>`);不存在时按需创建空桶,
522
+ * 从而支持通过 {@link registerStepType} 或首次 push 动态扩展历史类型。
587
523
  */
588
- public getPageStepIndexByUuid(uuid: string, pageId?: Id): number {
589
- if (!uuid) return -1;
590
- return this.getPageStepList(pageId).findIndex((entry) => entry.step.uuid === uuid);
524
+ private getStepBucket(stepType: string): Record<Id, UndoRedo<any>> {
525
+ if (!this.state.steps[stepType]) {
526
+ this.state.steps[stepType] = {};
527
+ }
528
+ return this.state.steps[stepType];
591
529
  }
592
530
 
593
531
  /**
594
- * 按历史记录 uuid 在全部代码块栈中查找其所属 codeBlockId 与索引。
595
- * 找不到时返回 null。
532
+ * 清空单个历史栈并按需重建其 initial 基线(保留原基线的文案 / 来源)。
596
533
  */
597
- public findCodeBlockStepLocationByUuid(uuid: string): { id: Id; index: number } | null {
598
- if (!uuid) return null;
599
- for (const id of Object.keys(this.state.codeBlockState)) {
600
- const index = this.getCodeBlockStepList(id).findIndex((entry) => entry.step.uuid === uuid);
601
- if (index >= 0) return { id, index };
534
+ private clearStack(stepType: HistoryStepType, id: Id): void {
535
+ // 保留原 initial 基线的文案 / 来源(仅清空其后的真实操作记录),无基线时清空成空栈。
536
+ const marker = this.getMarker(stepType, id);
537
+ this.getStepBucket(stepType)[id] = new UndoRedo<any>();
538
+ if (marker) {
539
+ this.setMarker(stepType, id, {
540
+ name: marker.data?.name,
541
+ description: marker.historyDescription,
542
+ source: marker.source,
543
+ });
602
544
  }
603
- return null;
604
545
  }
605
546
 
606
- /**
607
- * 按历史记录 uuid 在全部数据源栈中查找其所属 dataSourceId 与索引。
608
- * 找不到时返回 null。
609
- */
610
- public findDataSourceStepLocationByUuid(uuid: string): { id: Id; index: number } | null {
611
- if (!uuid) return null;
612
- for (const id of Object.keys(this.state.dataSourceState)) {
613
- const index = this.getDataSourceStepList(id).findIndex((entry) => entry.step.uuid === uuid);
614
- if (index >= 0) return { id, index };
615
- }
616
- return null;
547
+ /** 入栈前补全 step 的 uuid / timestamp(调用方未指定时)。 */
548
+ private fillStepMeta(step: BaseStepValue): void {
549
+ if (step.uuid === undefined) step.uuid = guid();
550
+ if (step.timestamp === undefined) step.timestamp = Date.now();
617
551
  }
618
552
 
619
- /**
620
- * 取出全部数据源的历史栈,按 dataSourceId 分桶展示。同上,每条操作独立成组。
621
- */
622
- public getDataSourceHistoryGroups(): DataSourceHistoryGroup[] {
623
- const groups: DataSourceHistoryGroup[] = [];
624
- Object.entries(this.state.dataSourceState).forEach(([id, undoRedo]) => {
625
- if (!undoRedo) return;
626
- const list = undoRedo.getElementList();
627
- if (!list.length) return;
628
- const cursor = undoRedo.getCursor();
629
- groups.push(...mergeStackSteps('data-source', id, list, cursor));
630
- });
631
- return groups;
553
+ /** 校验「按 id 分栈」类型(codeBlock / dataSource / 扩展)的 id 是否有效。 */
554
+ private isValidStackId(id?: Id): id is Id {
555
+ return id !== undefined && id !== null && `${id}` !== '';
632
556
  }
633
557
 
634
- /**
635
- * 取出指定页面的栈;不传 pageId 时按当前活动页取。
636
- *
637
- * 跨页 push 时如果目标页的栈尚不存在(用户从未进入过该页),会按需创建一条空栈,
638
- * 这样切到目标页时 Ctrl+Z 也能撤回该步骤。
639
- */
640
- private getUndoRedo(pageId?: Id) {
641
- const targetPageId = pageId ?? this.state.pageId;
642
- if (!targetPageId) return null;
643
- if (!this.state.pageSteps[targetPageId]) {
644
- this.state.pageSteps[targetPageId] = new UndoRedo<StepValue>();
645
- }
646
- return this.state.pageSteps[targetPageId];
558
+ /** 清空全部历史栈内容(保留已注册的类型键,使扩展类型在 reset 后仍可用)。 */
559
+ private clearAllSteps(): void {
560
+ Object.keys(this.state.steps).forEach((stepType) => {
561
+ this.state.steps[stepType] = {};
562
+ });
647
563
  }
648
564
 
649
565
  /**
@@ -655,13 +571,6 @@ class History extends BaseService {
655
571
  const resolvedAppId = appId ?? editorService.get('root')?.id;
656
572
  return resolvedAppId ? `${dbName}-${resolvedAppId}` : dbName;
657
573
  }
658
-
659
- private setCanUndoRedo(): void {
660
- const undoRedo = this.getUndoRedo();
661
- this.state.canRedo = undoRedo?.canRedo() || false;
662
- // 初始基线之上才可撤销:cursor 必须高于底线(有 initial 时为 1)。
663
- this.state.canUndo = undoRedo ? undoRedo.getCursor() > undoFloor(undoRedo) : false;
664
- }
665
574
  }
666
575
 
667
576
  export type HistoryService = History;