@tmagic/editor 1.8.0-beta.4 → 1.8.0-beta.5

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 (57) hide show
  1. package/dist/es/components/CompareForm.vue_vue_type_script_setup_true_lang.js +1 -1
  2. package/dist/es/components/ToolButton.vue_vue_type_script_setup_true_lang.js +6 -6
  3. package/dist/es/index.js +6 -3
  4. package/dist/es/initService.js +1 -1
  5. package/dist/es/layouts/Framework.vue_vue_type_script_setup_true_lang.js +1 -1
  6. package/dist/es/layouts/history-list/Bucket.vue_vue_type_script_setup_true_lang.js +19 -55
  7. package/dist/es/layouts/history-list/BucketTab.vue_vue_type_script_setup_true_lang.js +22 -39
  8. package/dist/es/layouts/history-list/GroupRow.vue_vue_type_script_setup_true_lang.js +149 -103
  9. package/dist/es/layouts/history-list/HistoryDiffDialog.vue_vue_type_script_setup_true_lang.js +32 -8
  10. package/dist/es/layouts/history-list/HistoryListPanel.vue_vue_type_script_setup_true_lang.js +333 -211
  11. package/dist/es/layouts/history-list/InitialRow.vue_vue_type_script_setup_true_lang.js +28 -7
  12. package/dist/es/layouts/history-list/PageTab.vue_vue_type_script_setup_true_lang.js +47 -60
  13. package/dist/es/layouts/history-list/composables.js +73 -32
  14. package/dist/es/layouts/page-bar/PageBar.vue_vue_type_script_setup_true_lang.js +4 -2
  15. package/dist/es/layouts/sidebar/Sidebar.vue_vue_type_script_setup_true_lang.js +5 -1
  16. package/dist/es/services/codeBlock.js +85 -37
  17. package/dist/es/services/dataSource.js +62 -26
  18. package/dist/es/services/editor.js +243 -100
  19. package/dist/es/services/history.js +270 -206
  20. package/dist/es/services/ui.js +3 -0
  21. package/dist/es/style.css +49 -6
  22. package/dist/es/utils/editor.js +35 -1
  23. package/dist/es/utils/history.js +223 -0
  24. package/dist/es/utils/indexed-db.js +86 -0
  25. package/dist/es/utils/undo-redo.js +60 -1
  26. package/dist/style.css +49 -6
  27. package/dist/tmagic-editor.umd.cjs +1799 -905
  28. package/package.json +7 -7
  29. package/src/components/CompareForm.vue +3 -1
  30. package/src/components/ToolButton.vue +2 -2
  31. package/src/index.ts +1 -0
  32. package/src/initService.ts +1 -1
  33. package/src/layouts/Framework.vue +1 -1
  34. package/src/layouts/history-list/Bucket.vue +34 -71
  35. package/src/layouts/history-list/BucketTab.vue +46 -54
  36. package/src/layouts/history-list/GroupRow.vue +146 -111
  37. package/src/layouts/history-list/HistoryDiffDialog.vue +94 -68
  38. package/src/layouts/history-list/HistoryListPanel.vue +296 -113
  39. package/src/layouts/history-list/InitialRow.vue +25 -9
  40. package/src/layouts/history-list/PageTab.vue +57 -51
  41. package/src/layouts/history-list/composables.ts +157 -36
  42. package/src/layouts/page-bar/PageBar.vue +4 -2
  43. package/src/layouts/sidebar/Sidebar.vue +6 -1
  44. package/src/services/codeBlock.ts +107 -37
  45. package/src/services/dataSource.ts +89 -40
  46. package/src/services/editor.ts +370 -134
  47. package/src/services/history.ts +305 -203
  48. package/src/services/ui.ts +7 -0
  49. package/src/theme/history-list-panel.scss +72 -5
  50. package/src/theme/page-bar.scss +0 -4
  51. package/src/type.ts +167 -63
  52. package/src/utils/editor.ts +41 -1
  53. package/src/utils/history.ts +298 -0
  54. package/src/utils/index.ts +2 -0
  55. package/src/utils/indexed-db.ts +122 -0
  56. package/src/utils/undo-redo.ts +88 -0
  57. package/types/index.d.ts +783 -291
@@ -0,0 +1,298 @@
1
+ /*
2
+ * Tencent is pleased to support the open source community by making TMagicEditor available.
3
+ *
4
+ * Copyright (C) 2025 Tencent. All rights reserved.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import { cloneDeep } from 'lodash-es';
20
+
21
+ import type { Id } from '@tmagic/core';
22
+ import type { ChangeRecord } from '@tmagic/form';
23
+ import { guid } from '@tmagic/utils';
24
+
25
+ import type {
26
+ BaseStepValue,
27
+ HistoryOpSource,
28
+ HistoryOpType,
29
+ PageHistoryGroup,
30
+ PageHistoryStepEntry,
31
+ StepDiffItem,
32
+ StepValue,
33
+ } from '@editor/type';
34
+
35
+ import { UndoRedo } from './undo-redo';
36
+
37
+ /**
38
+ * 「回滚」生成的新 step 简短描述。代码块 / 数据源共用。
39
+ * 二者逻辑一致,仅展示名取值字段不同(代码块取 `name`,数据源取 `title`),
40
+ * 因此通过 `getLabel` 注入取值方式。
41
+ *
42
+ * @param id 关联的代码块 / 数据源 id
43
+ * @param diff 单条变更 diff(缺省视为空)
44
+ * @param getLabel 从快照取展示名
45
+ */
46
+ export const describeRevertStep = <T extends object>(
47
+ id: Id,
48
+ { oldSchema, newSchema, changeRecords }: StepDiffItem<T> = {},
49
+ getLabel: (schema: T) => string | undefined,
50
+ ): string => {
51
+ const labelOf = (schema: T) => getLabel(schema) || (schema as { id?: Id }).id;
52
+ if (!oldSchema && newSchema) return `撤回新增 ${labelOf(newSchema) || id}`;
53
+ if (oldSchema && !newSchema) return `还原已删除的 ${labelOf(oldSchema) || id}`;
54
+ const label = (newSchema && getLabel(newSchema)) || (oldSchema && getLabel(oldSchema)) || `${id}`;
55
+ const propPath = changeRecords?.[0]?.propPath;
56
+ return propPath ? `还原 ${label} · ${propPath}` : `还原 ${label}`;
57
+ };
58
+
59
+ /**
60
+ * 根据 old/new 是否为 null 推断 opType(与 push 时的约定一致)。
61
+ */
62
+ export const detectStackOpType = (oldVal: unknown, newVal: unknown): 'add' | 'remove' | 'update' => {
63
+ if (oldVal === null && newVal !== null) return 'add';
64
+ if (oldVal !== null && newVal === null) return 'remove';
65
+ return 'update';
66
+ };
67
+
68
+ /**
69
+ * 构造一条代码块 / 数据源「按 id 分栈」的历史记录:两者除 payload 字段命名外完全一致。
70
+ *
71
+ * - `add`:oldValue = null;`remove`:newValue = null;`update`:两者都有,可带 changeRecords 做局部更新。
72
+ * - 内容会做 cloneDeep 防止后续被外部引用篡改;opType 依据 old/new 是否为 null 推断。
73
+ * - 仅负责构造 step 并返回,入栈与事件 emit 由各公共方法(pushCodeBlock / pushDataSource)自行处理。
74
+ * - 不直接驱动业务 service,调用方负责实际写回。
75
+ */
76
+ export const createStackStep = <T, S extends BaseStepValue<T> & { id: Id }>(
77
+ id: Id,
78
+ payload: {
79
+ oldValue: T | null;
80
+ newValue: T | null;
81
+ changeRecords?: ChangeRecord[];
82
+ historyDescription?: string;
83
+ source?: HistoryOpSource;
84
+ },
85
+ ): S | null => {
86
+ if (!id) return null;
87
+
88
+ const oldSchema = payload.oldValue ? cloneDeep(payload.oldValue) : null;
89
+ const newSchema = payload.newValue ? cloneDeep(payload.newValue) : null;
90
+ const changeRecords = payload.changeRecords?.length ? cloneDeep(payload.changeRecords) : undefined;
91
+ const opType = detectStackOpType(payload.oldValue, payload.newValue);
92
+
93
+ const step: BaseStepValue<T> & { id: Id } = {
94
+ uuid: guid(),
95
+ id,
96
+ opType,
97
+ diff: [
98
+ {
99
+ ...(newSchema !== null ? { newSchema } : {}),
100
+ ...(oldSchema !== null ? { oldSchema } : {}),
101
+ ...(opType === 'update' && changeRecords ? { changeRecords } : {}),
102
+ },
103
+ ],
104
+ historyDescription: payload.historyDescription,
105
+ source: payload.source,
106
+ timestamp: Date.now(),
107
+ };
108
+
109
+ return step as S;
110
+ };
111
+
112
+ export const markStackSaved = <S extends { saved?: boolean }>(undoRedo?: UndoRedo<S>): void => {
113
+ if (!undoRedo) return;
114
+ undoRedo.updateElements((element) => {
115
+ element.saved = false;
116
+ });
117
+ undoRedo.updateCurrentElement((element) => {
118
+ element.saved = true;
119
+ });
120
+ };
121
+
122
+ /**
123
+ * 把单个「按 id 分栈」的历史栈(代码块 / 数据源)拆成若干 group:
124
+ * - 把"新增/删除"独立成组(语义上属于一次性事件,不应与 update 合并);
125
+ * - 连续 'update' 合并到同一组,组内 steps 顺序就是发生顺序。
126
+ *
127
+ * 代码块与数据源除 `kind` 外结构完全一致,统一由本方法处理;`kind` 决定返回的具体分组类型。
128
+ */
129
+ export const mergeStackSteps = <S extends BaseStepValue, K extends 'code-block' | 'data-source'>(
130
+ kind: K,
131
+ id: Id,
132
+ list: S[],
133
+ cursor: number,
134
+ ): {
135
+ kind: K;
136
+ id: Id;
137
+ opType: HistoryOpType;
138
+ steps: { step: S; index: number; applied: boolean; isCurrent?: boolean }[];
139
+ applied: boolean;
140
+ isCurrent?: boolean;
141
+ }[] => {
142
+ type Group = {
143
+ kind: K;
144
+ id: Id;
145
+ opType: HistoryOpType;
146
+ steps: { step: S; index: number; applied: boolean; isCurrent?: boolean }[];
147
+ applied: boolean;
148
+ isCurrent?: boolean;
149
+ };
150
+ const groups: Group[] = [];
151
+ let current: Group | null = null;
152
+ const currentIndex = cursor - 1;
153
+ list.forEach((step, index) => {
154
+ const { opType } = step;
155
+ const applied = index < cursor;
156
+ const isCurrent = index === currentIndex;
157
+ if (opType === 'update' && current?.opType === 'update') {
158
+ current.steps.push({ step, index, applied, isCurrent });
159
+ current.applied = applied;
160
+ if (isCurrent) current.isCurrent = true;
161
+ } else {
162
+ current = {
163
+ kind,
164
+ id,
165
+ opType,
166
+ steps: [{ step, index, applied, isCurrent }],
167
+ applied,
168
+ isCurrent,
169
+ };
170
+ groups.push(current);
171
+ }
172
+ });
173
+ return groups;
174
+ };
175
+
176
+ /**
177
+ * 把页面栈拆成若干 group:
178
+ * - 单节点的 'update' 按 targetId 与相邻同 targetId 的 update 合并到一个 group;
179
+ * - 'add' / 'remove' 始终独立成组(语义上是结构变更,不应被收纳进单节点修改组);
180
+ * - 多节点 'update'(如批量改属性)也独立成组(无明确单一目标,避免误合并)。
181
+ */
182
+ export const mergePageSteps = (pageId: Id, list: StepValue[], cursor: number): PageHistoryGroup[] => {
183
+ const groups: PageHistoryGroup[] = [];
184
+ let current: PageHistoryGroup | null = null;
185
+ const currentIndex = cursor - 1;
186
+ list.forEach((step, index) => {
187
+ const applied = index < cursor;
188
+ const isCurrent = index === currentIndex;
189
+ const targetId = detectPageTargetId(step);
190
+ const targetName = detectPageTargetName(step);
191
+ const entry: PageHistoryStepEntry = { step, index, applied, isCurrent };
192
+
193
+ // 仅"单节点 update"参与合并;其它情形(add/remove/多节点 update)始终独立成组。
194
+ const mergeable = step.opType === 'update' && targetId !== undefined;
195
+ if (mergeable && current?.opType === 'update' && current.targetId === targetId) {
196
+ current.steps.push(entry);
197
+ current.applied = applied;
198
+ if (isCurrent) current.isCurrent = true;
199
+ // 保持目标名为最近一次的(节点重命名时也能反映)
200
+ if (targetName) current.targetName = targetName;
201
+ } else {
202
+ current = {
203
+ kind: 'page',
204
+ pageId,
205
+ opType: step.opType,
206
+ targetId: mergeable ? targetId : undefined,
207
+ targetName,
208
+ steps: [entry],
209
+ applied,
210
+ isCurrent,
211
+ };
212
+ groups.push(current);
213
+ }
214
+ });
215
+ return groups;
216
+ };
217
+
218
+ /**
219
+ * 解析 StepValue 中的"目标节点 id"用于合并:
220
+ * - 单节点 update:取唯一一项 updatedItems 的节点 id;
221
+ * - 其它情形(多节点 update / add / remove):返回 undefined,表示不参与合并。
222
+ */
223
+ export const detectPageTargetId = (step: StepValue): Id | undefined => {
224
+ if (step.opType !== 'update') return undefined;
225
+ const items = step.diff;
226
+ if (items?.length !== 1) return undefined;
227
+ return items[0].newSchema?.id ?? items[0].oldSchema?.id;
228
+ };
229
+
230
+ /** 解析 StepValue 中的目标节点可读名(用于 UI 展示)。 */
231
+ export const detectPageTargetName = (step: StepValue): string | undefined => {
232
+ const items = step.diff;
233
+ if (step.opType === 'update') {
234
+ if (items?.length === 1) {
235
+ const node = items[0].newSchema || items[0].oldSchema;
236
+ return (node?.name as string) || (node?.type as string) || (node?.id !== undefined ? `${node.id}` : undefined);
237
+ }
238
+ return items?.length ? `${items.length} 个节点` : undefined;
239
+ }
240
+ if (step.opType === 'add') {
241
+ if (items?.length === 1) {
242
+ const n = items[0].newSchema;
243
+ return (n?.name as string) || (n?.type as string) || `${n?.id}`;
244
+ }
245
+ return items?.length ? `${items.length} 个节点` : undefined;
246
+ }
247
+ if (step.opType === 'remove') {
248
+ if (items?.length === 1) {
249
+ const n = items[0].oldSchema;
250
+ return (n?.name as string) || (n?.type as string) || `${n?.id}`;
251
+ }
252
+ return items?.length ? `${items.length} 个节点` : undefined;
253
+ }
254
+ return undefined;
255
+ };
256
+
257
+ /** 把 `Record<Id, UndoRedo>` 整体序列化为 `Record<Id, SerializedUndoRedo>`。 */
258
+ export const serializeStacks = <T>(stacks: Record<Id, UndoRedo<T>>) => {
259
+ const result: Record<Id, ReturnType<UndoRedo<T>['serialize']>> = {};
260
+ Object.entries(stacks).forEach(([id, undoRedo]) => {
261
+ if (undoRedo) result[id] = undoRedo.serialize();
262
+ });
263
+ return result;
264
+ };
265
+
266
+ /**
267
+ * 把 `Record<Id, SerializedUndoRedo>` 整体还原为 `Record<Id, UndoRedo>`。
268
+ * 还原时把每个栈的游标定位到最近一条已保存(`saved === true`)记录之后。
269
+ */
270
+ export const deserializeStacks = <T extends { saved?: boolean }>(
271
+ stacks: Record<Id, ReturnType<UndoRedo<T>['serialize']>> = {},
272
+ ): Record<Id, UndoRedo<T>> => {
273
+ const result: Record<Id, UndoRedo<T>> = {};
274
+ Object.entries(stacks).forEach(([id, serialized]) => {
275
+ if (serialized) {
276
+ result[id] = UndoRedo.fromSerialized<T>(serialized, { isSavedStep: (element) => element.saved === true });
277
+ }
278
+ });
279
+ return result;
280
+ };
281
+
282
+ /**
283
+ * 按 id 从「按 id 分栈」的记录表(代码块 / 数据源)中获取(或创建)对应的 UndoRedo 栈。
284
+ */
285
+ export const getOrCreateStack = <T>(stacks: Record<Id, UndoRedo<T>>, id: Id): UndoRedo<T> => {
286
+ if (!stacks[id]) {
287
+ stacks[id] = new UndoRedo<T>();
288
+ }
289
+ return stacks[id];
290
+ };
291
+
292
+ /**
293
+ * 撤销下限:当页面栈 index 0 是 `opType: 'initial'` 的基线 step 时为 1(基线不可被撤销),否则为 0。
294
+ * 用于把 cursor 钉在基线之上,保证 undo / canUndo / goto 都不会越过初始基线。
295
+ */
296
+ export const undoFloor = (undoRedo: UndoRedo<StepValue>): number => {
297
+ return undoRedo.getElementList()[0]?.opType === 'initial' ? 1 : 0;
298
+ };
@@ -27,5 +27,7 @@ export * from './dep/idle-task';
27
27
  export * from './scroll-viewer';
28
28
  export * from './tree';
29
29
  export * from './undo-redo';
30
+ export * from './indexed-db';
31
+ export * from './history';
30
32
  export * from './const';
31
33
  export { default as loadMonaco } from './monaco-editor';
@@ -0,0 +1,122 @@
1
+ /*
2
+ * Tencent is pleased to support the open source community by making TMagicEditor available.
3
+ *
4
+ * Copyright (C) 2025 Tencent. All rights reserved.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ /**
20
+ * 一组极简的、基于原生 IndexedDB 的 Promise KV 工具,避免引入额外依赖。
21
+ * 仅用于浏览器环境;在不支持 IndexedDB 的环境(如 SSR / 部分测试环境)下会 reject。
22
+ */
23
+
24
+ /** 是否处于支持 IndexedDB 的环境。 */
25
+ export const isIndexedDBSupported = (): boolean => typeof indexedDB !== 'undefined' && indexedDB !== null;
26
+
27
+ /**
28
+ * 打开(必要时升级)数据库,确保目标 objectStore 存在后返回连接。
29
+ *
30
+ * 由于 objectStore 只能在 `onupgradeneeded` 内创建,这里先以当前版本打开,
31
+ * 若发现 store 不存在则关闭连接、以更高版本重开来按需创建,兼容动态 storeName。
32
+ */
33
+ export const openIndexedDB = (dbName: string, storeName: string): Promise<IDBDatabase> =>
34
+ new Promise((resolve, reject) => {
35
+ if (!isIndexedDBSupported()) {
36
+ reject(new Error('当前环境不支持 IndexedDB'));
37
+ return;
38
+ }
39
+
40
+ const request = indexedDB.open(dbName);
41
+
42
+ request.onupgradeneeded = () => {
43
+ const db = request.result;
44
+ if (!db.objectStoreNames.contains(storeName)) {
45
+ db.createObjectStore(storeName);
46
+ }
47
+ };
48
+
49
+ request.onerror = () => reject(request.error);
50
+
51
+ request.onsuccess = () => {
52
+ const db = request.result;
53
+ if (db.objectStoreNames.contains(storeName)) {
54
+ resolve(db);
55
+ return;
56
+ }
57
+
58
+ // store 不存在:以更高版本重开,在 onupgradeneeded 中创建。
59
+ const nextVersion = db.version + 1;
60
+ db.close();
61
+ const upgradeRequest = indexedDB.open(dbName, nextVersion);
62
+ upgradeRequest.onupgradeneeded = () => {
63
+ const upgradeDb = upgradeRequest.result;
64
+ if (!upgradeDb.objectStoreNames.contains(storeName)) {
65
+ upgradeDb.createObjectStore(storeName);
66
+ }
67
+ };
68
+ upgradeRequest.onerror = () => reject(upgradeRequest.error);
69
+ upgradeRequest.onsuccess = () => resolve(upgradeRequest.result);
70
+ };
71
+ });
72
+
73
+ /** 写入(覆盖)一条记录。value 通过结构化克隆存储,支持 Map / Set 等结构。 */
74
+ export const idbSet = async (dbName: string, storeName: string, key: IDBValidKey, value: unknown): Promise<void> => {
75
+ const db = await openIndexedDB(dbName, storeName);
76
+ try {
77
+ await new Promise<void>((resolve, reject) => {
78
+ const tx = db.transaction(storeName, 'readwrite');
79
+ tx.objectStore(storeName).put(value, key);
80
+ tx.oncomplete = () => resolve();
81
+ tx.onabort = () => reject(tx.error);
82
+ tx.onerror = () => reject(tx.error);
83
+ });
84
+ } finally {
85
+ db.close();
86
+ }
87
+ };
88
+
89
+ /** 读取一条记录,不存在时返回 undefined。 */
90
+ export const idbGet = async <T = unknown>(
91
+ dbName: string,
92
+ storeName: string,
93
+ key: IDBValidKey,
94
+ ): Promise<T | undefined> => {
95
+ const db = await openIndexedDB(dbName, storeName);
96
+ try {
97
+ return await new Promise<T | undefined>((resolve, reject) => {
98
+ const tx = db.transaction(storeName, 'readonly');
99
+ const request = tx.objectStore(storeName).get(key);
100
+ request.onsuccess = () => resolve(request.result as T | undefined);
101
+ request.onerror = () => reject(request.error);
102
+ });
103
+ } finally {
104
+ db.close();
105
+ }
106
+ };
107
+
108
+ /** 删除一条记录。 */
109
+ export const idbDelete = async (dbName: string, storeName: string, key: IDBValidKey): Promise<void> => {
110
+ const db = await openIndexedDB(dbName, storeName);
111
+ try {
112
+ await new Promise<void>((resolve, reject) => {
113
+ const tx = db.transaction(storeName, 'readwrite');
114
+ tx.objectStore(storeName).delete(key);
115
+ tx.oncomplete = () => resolve();
116
+ tx.onabort = () => reject(tx.error);
117
+ tx.onerror = () => reject(tx.error);
118
+ });
119
+ } finally {
120
+ db.close();
121
+ }
122
+ };
@@ -18,8 +18,59 @@
18
18
 
19
19
  import { cloneDeep } from 'lodash-es';
20
20
 
21
+ // #region SerializedUndoRedo
22
+ /**
23
+ * UndoRedo 栈的可序列化快照,用于持久化(如写入 IndexedDB)后再还原。
24
+ */
25
+ export interface SerializedUndoRedo<T = any> {
26
+ /** 栈内全部元素(按时间正序,索引 0 为最早一步)。 */
27
+ elementList: T[];
28
+ /** 游标位置(已应用步骤数量)。 */
29
+ listCursor: number;
30
+ /** 栈容量上限。 */
31
+ listMaxSize: number;
32
+ }
33
+ // #endregion SerializedUndoRedo
34
+
21
35
  // #region UndoRedo
22
36
  export class UndoRedo<T = any> {
37
+ /**
38
+ * 由 {@link UndoRedo.serialize} 产出的快照重建一个 UndoRedo 实例。
39
+ * 游标会被夹紧到 [0, length] 区间,避免脏数据导致越界。
40
+ *
41
+ * @param options.isSavedStep 可选谓词:若提供,则把游标定位到「最近一条满足该谓词的记录」之后
42
+ * (即恢复到最近一个已保存点);找不到匹配记录时退回快照中的原游标。
43
+ */
44
+ public static fromSerialized<T = any>(
45
+ data: SerializedUndoRedo<T>,
46
+ options: { isSavedStep?: (element: T) => boolean } = {},
47
+ ): UndoRedo<T> {
48
+ const undoRedo = new UndoRedo<T>(data.listMaxSize);
49
+ const list = Array.isArray(data.elementList) ? data.elementList.map((item) => cloneDeep(item)) : [];
50
+ let cursor = Number.isFinite(data.listCursor) ? data.listCursor : list.length;
51
+
52
+ // 本地数据同样遵循容量上限:超出时裁掉最旧的记录(与 pushElement 的 shift 行为一致),并同步回退游标。
53
+ const overflow = list.length - undoRedo.listMaxSize;
54
+ if (overflow > 0) {
55
+ list.splice(0, overflow);
56
+ cursor -= overflow;
57
+ }
58
+
59
+ // 若指定了「已保存」谓词,则把游标移动到最近一条已保存记录之后;在裁剪后的 list 上查找以保证索引正确。
60
+ if (options.isSavedStep) {
61
+ for (let i = list.length - 1; i >= 0; i--) {
62
+ if (options.isSavedStep(list[i])) {
63
+ cursor = i + 1;
64
+ break;
65
+ }
66
+ }
67
+ }
68
+
69
+ undoRedo.elementList = list;
70
+ undoRedo.listCursor = Math.max(0, Math.min(cursor, list.length));
71
+ return undoRedo;
72
+ }
73
+
23
74
  private elementList: T[];
24
75
  private listCursor: number;
25
76
  private listMaxSize: number;
@@ -31,6 +82,18 @@ export class UndoRedo<T = any> {
31
82
  this.listMaxSize = listMaxSize > minListMaxSize ? listMaxSize : minListMaxSize;
32
83
  }
33
84
 
85
+ /**
86
+ * 导出当前栈的可序列化快照(深克隆,避免外部改动污染内部状态)。
87
+ * 配合 {@link UndoRedo.fromSerialized} 可在持久化后完整还原撤销/重做栈。
88
+ */
89
+ public serialize(): SerializedUndoRedo<T> {
90
+ return {
91
+ elementList: this.elementList.map((item) => cloneDeep(item)),
92
+ listCursor: this.listCursor,
93
+ listMaxSize: this.listMaxSize,
94
+ };
95
+ }
96
+
34
97
  public pushElement(element: T): void {
35
98
  // 新元素进来时,把游标之外的元素全部丢弃,并把新元素放进来
36
99
  this.elementList.splice(this.listCursor, this.elementList.length - this.listCursor, cloneDeep(element));
@@ -76,6 +139,31 @@ export class UndoRedo<T = any> {
76
139
  return cloneDeep(this.elementList[this.listCursor - 1]);
77
140
  }
78
141
 
142
+ /**
143
+ * 用 `element` 替换当前游标所在元素(cursor - 1),并丢弃其后的重做尾部(与 {@link pushElement} 的丢尾一致),
144
+ * 游标位置保持不变(元素数量不增)。cursor 为 0(无已应用元素)时不做任何操作并返回 false。
145
+ * 用于「连续同类记录合并」等就地替换最新一条的场景。
146
+ */
147
+ public replaceCurrentElement(element: T): boolean {
148
+ if (this.listCursor < 1) return false;
149
+ this.elementList.splice(this.listCursor - 1, this.elementList.length - (this.listCursor - 1), cloneDeep(element));
150
+ return true;
151
+ }
152
+
153
+ /**
154
+ * 对当前游标所在元素(cursor - 1)做就地更新;cursor 为 0(全部已撤销)时不做任何操作。
155
+ * 用于给「当前步骤」打标记(如标记为已保存)等元数据写入场景。
156
+ */
157
+ public updateCurrentElement(updater: (element: T) => void): void {
158
+ if (this.listCursor < 1) return;
159
+ updater(this.elementList[this.listCursor - 1]);
160
+ }
161
+
162
+ /** 对栈内全部元素做就地更新。用于批量清理元数据(如清空所有元素的已保存标记)。 */
163
+ public updateElements(updater: (element: T, index: number) => void): void {
164
+ this.elementList.forEach(updater);
165
+ }
166
+
79
167
  /**
80
168
  * 返回栈内全部元素的浅克隆数组(按时间顺序,索引 0 为最早一步)。
81
169
  * 仅用于历史面板等只读展示场景,不应直接修改返回值。