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

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 (76) 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/fields/CodeSelectCol.vue_vue_type_script_setup_true_lang.js +4 -1
  4. package/dist/es/fields/DataSourceFieldSelect/FieldSelect.vue_vue_type_script_setup_true_lang.js +8 -2
  5. package/dist/es/fields/DataSourceFields.vue_vue_type_script_setup_true_lang.js +25 -8
  6. package/dist/es/fields/DataSourceMethodSelect.vue_vue_type_script_setup_true_name_true_lang.js +6 -4
  7. package/dist/es/fields/DataSourceMethods.vue_vue_type_script_setup_true_lang.js +25 -12
  8. package/dist/es/fields/StyleSetter/components/Border.vue_vue_type_script_setup_true_lang.js +27 -5
  9. package/dist/es/index.js +6 -3
  10. package/dist/es/initService.js +1 -1
  11. package/dist/es/layouts/Framework.vue_vue_type_script_setup_true_lang.js +1 -1
  12. package/dist/es/layouts/history-list/Bucket.vue_vue_type_script_setup_true_lang.js +19 -55
  13. package/dist/es/layouts/history-list/BucketTab.vue_vue_type_script_setup_true_lang.js +22 -39
  14. package/dist/es/layouts/history-list/GroupRow.vue_vue_type_script_setup_true_lang.js +149 -103
  15. package/dist/es/layouts/history-list/HistoryDiffDialog.vue_vue_type_script_setup_true_lang.js +32 -8
  16. package/dist/es/layouts/history-list/HistoryListPanel.vue_vue_type_script_setup_true_lang.js +335 -213
  17. package/dist/es/layouts/history-list/InitialRow.vue_vue_type_script_setup_true_lang.js +36 -7
  18. package/dist/es/layouts/history-list/PageTab.vue_vue_type_script_setup_true_lang.js +47 -60
  19. package/dist/es/layouts/history-list/composables.js +73 -32
  20. package/dist/es/layouts/page-bar/PageBar.vue_vue_type_script_setup_true_lang.js +4 -2
  21. package/dist/es/layouts/sidebar/Sidebar.vue_vue_type_script_setup_true_lang.js +5 -1
  22. package/dist/es/layouts/sidebar/data-source/DataSourceConfigPanel.vue_vue_type_script_setup_true_lang.js +16 -3
  23. package/dist/es/layouts/sidebar/data-source/DataSourceListPanel.vue_vue_type_script_setup_true_lang.js +23 -1
  24. package/dist/es/services/codeBlock.js +96 -37
  25. package/dist/es/services/dataSource.js +70 -26
  26. package/dist/es/services/editor.js +266 -104
  27. package/dist/es/services/history.js +271 -212
  28. package/dist/es/services/ui.js +3 -0
  29. package/dist/es/style.css +53 -7
  30. package/dist/es/utils/data-source/index.js +2 -0
  31. package/dist/es/utils/editor.js +103 -49
  32. package/dist/es/utils/history.js +232 -0
  33. package/dist/es/utils/indexed-db.js +86 -0
  34. package/dist/es/utils/undo-redo.js +60 -1
  35. package/dist/style.css +53 -7
  36. package/dist/tmagic-editor.umd.cjs +2064 -1000
  37. package/package.json +7 -7
  38. package/src/components/CompareForm.vue +3 -1
  39. package/src/components/ToolButton.vue +2 -2
  40. package/src/fields/CodeSelectCol.vue +7 -1
  41. package/src/fields/DataSourceFieldSelect/FieldSelect.vue +16 -2
  42. package/src/fields/DataSourceFields.vue +37 -8
  43. package/src/fields/DataSourceMethodSelect.vue +9 -4
  44. package/src/fields/DataSourceMethods.vue +42 -21
  45. package/src/fields/StyleSetter/components/Border.vue +15 -6
  46. package/src/index.ts +1 -0
  47. package/src/initService.ts +1 -1
  48. package/src/layouts/Framework.vue +1 -1
  49. package/src/layouts/history-list/Bucket.vue +34 -71
  50. package/src/layouts/history-list/BucketTab.vue +46 -54
  51. package/src/layouts/history-list/GroupRow.vue +146 -111
  52. package/src/layouts/history-list/HistoryDiffDialog.vue +94 -68
  53. package/src/layouts/history-list/HistoryListPanel.vue +298 -115
  54. package/src/layouts/history-list/InitialRow.vue +28 -9
  55. package/src/layouts/history-list/PageTab.vue +57 -51
  56. package/src/layouts/history-list/composables.ts +157 -36
  57. package/src/layouts/page-bar/PageBar.vue +4 -2
  58. package/src/layouts/sidebar/Sidebar.vue +6 -1
  59. package/src/layouts/sidebar/data-source/DataSourceConfigPanel.vue +30 -2
  60. package/src/layouts/sidebar/data-source/DataSourceListPanel.vue +26 -1
  61. package/src/services/codeBlock.ts +113 -37
  62. package/src/services/dataSource.ts +94 -40
  63. package/src/services/editor.ts +376 -136
  64. package/src/services/history.ts +306 -209
  65. package/src/services/ui.ts +7 -0
  66. package/src/theme/history-list-panel.scss +72 -5
  67. package/src/theme/page-bar.scss +0 -4
  68. package/src/theme/style-setter/border.scss +4 -1
  69. package/src/type.ts +183 -64
  70. package/src/utils/data-source/index.ts +2 -0
  71. package/src/utils/editor.ts +166 -60
  72. package/src/utils/history.ts +308 -0
  73. package/src/utils/index.ts +2 -0
  74. package/src/utils/indexed-db.ts +122 -0
  75. package/src/utils/undo-redo.ts +88 -0
  76. package/types/index.d.ts +813 -302
@@ -35,7 +35,7 @@ import {
35
35
  isValueIncludeDataSource,
36
36
  } from '@tmagic/utils';
37
37
 
38
- import type { EditorNodeInfo } from '@editor/type';
38
+ import type { EditorNodeInfo, StepValue } from '@editor/type';
39
39
  import { LayerOffset, Layout } from '@editor/type';
40
40
 
41
41
  export const COPY_STORAGE_KEY = '$MagicEditorCopyData';
@@ -132,6 +132,34 @@ const getMiddleTop = (node: MNode, parentNode: MNode, stage: StageCore | null) =
132
132
  return (Math.min(parentHeight, wrapperHeightDeal) - height) / 2;
133
133
  };
134
134
 
135
+ // 同时存在一对相反的定位属性(如 left/right)时只保留一个,避免元素被拉伸
136
+ const removeConflictPosition = (style: Record<string, any>, primary: string, secondary: string) => {
137
+ // '' / 0 / undefined / null 视为无效值
138
+ const isInvalid = (value: any) => value === '' || value === 0 || value === undefined || value === null;
139
+
140
+ if (!(primary in style) || !(secondary in style)) {
141
+ return;
142
+ }
143
+
144
+ const primaryValue = style[primary];
145
+ const secondaryValue = style[secondary];
146
+ const primaryInvalid = isInvalid(primaryValue);
147
+ const secondaryInvalid = isInvalid(secondaryValue);
148
+
149
+ if (primaryInvalid && !secondaryInvalid) {
150
+ delete style[primary];
151
+ } else if (secondaryInvalid && !primaryInvalid) {
152
+ delete style[secondary];
153
+ } else if (primaryInvalid && secondaryInvalid) {
154
+ // 都是无效值时优先保留 0,否则保留 primary(left/top)
155
+ if (secondaryValue === 0 && primaryValue !== 0) {
156
+ delete style[primary];
157
+ } else {
158
+ delete style[secondary];
159
+ }
160
+ }
161
+ };
162
+
135
163
  export const getInitPositionStyle = (style: Record<string, any> = {}, layout: Layout) => {
136
164
  if (layout === Layout.ABSOLUTE) {
137
165
  const newStyle: Record<string, any> = {
@@ -139,6 +167,9 @@ export const getInitPositionStyle = (style: Record<string, any> = {}, layout: La
139
167
  position: 'absolute',
140
168
  };
141
169
 
170
+ removeConflictPosition(newStyle, 'left', 'right');
171
+ removeConflictPosition(newStyle, 'top', 'bottom');
172
+
142
173
  if (typeof newStyle.left === 'undefined' && typeof newStyle.right === 'undefined') {
143
174
  newStyle.left = 0;
144
175
  }
@@ -178,43 +209,68 @@ export const setLayout = (node: MNode, layout: Layout) => {
178
209
  return node;
179
210
  };
180
211
 
181
- export const change2Fixed = (node: MNode, root: MApp) => {
182
- const style = {
183
- ...(node.style || {}),
184
- };
212
+ type PositionKey = 'left' | 'top' | 'right' | 'bottom';
185
213
 
186
- const path = getNodePath(node.id, root.items);
187
- const offset = {
188
- left: 0,
189
- top: 0,
190
- };
214
+ // 判断 style 是否显式设置了某个定位属性,使用 typeof 判断以避免将 0(如 right: 0)误判为未设置
215
+ const hasPositionValue = (style: Record<string, any> | undefined, key: PositionKey): boolean =>
216
+ typeof style?.[key] !== 'undefined' && style?.[key] !== '';
191
217
 
192
- if (!node.style?.right && isNumber(node.style?.left || 0)) {
193
- for (const value of path) {
194
- if (value.style?.right || !isNumber(value.style?.left || 0)) {
195
- offset.left = 0;
196
- break;
197
- }
198
- offset.left = offset.left + Number(value.style?.left || 0);
218
+ /**
219
+ * 沿节点路径累加(或抵消)某一方向上的定位偏移量
220
+ * 当路径上的祖先使用了反方向定位(例如计算 left 时祖先用了 right)或非数值定位时,
221
+ * 无法简单地通过求和换算坐标,此时返回 0 表示放弃补偿、保持原值
222
+ * @param path 从根到目标节点的路径(含节点自身)
223
+ * @param dir 需要累加的定位方向
224
+ * @param opposite 反方向定位属性
225
+ * @param sign change2Fixed 取 1(累加祖先偏移),Fixed2Other 取 -1(抵消祖先偏移)
226
+ * @param init 偏移量初始值
227
+ */
228
+ const accumulatePositionOffset = (
229
+ path: MNode[],
230
+ dir: PositionKey,
231
+ opposite: PositionKey,
232
+ sign: 1 | -1,
233
+ init = 0,
234
+ ): number => {
235
+ let offset = init;
236
+ for (const value of path) {
237
+ if (hasPositionValue(value.style, opposite) || !isNumber(value.style?.[dir] || 0)) {
238
+ return 0;
199
239
  }
240
+ offset = offset + sign * Number(value.style?.[dir] || 0);
200
241
  }
242
+ return offset;
243
+ };
201
244
 
202
- if (!node.style?.bottom && isNumber(node.style?.top || 0)) {
203
- for (const value of path) {
204
- if (value.style?.bottom || !isNumber(value.style?.top || 0)) {
205
- offset.top = 0;
206
- break;
207
- }
208
- offset.top = offset.top + Number(value.style?.top || 0);
209
- }
210
- }
245
+ export const change2Fixed = (node: MNode, path: MNode[]) => {
246
+ const style = {
247
+ ...(node.style || {}),
248
+ };
211
249
 
212
- if (offset.left) {
213
- style.left = offset.left;
250
+ // 水平方向:以 left 锚定则累加祖先 left,以 right 锚定则累加祖先 right
251
+ if (!hasPositionValue(node.style, 'right') && isNumber(node.style?.left || 0)) {
252
+ const left = accumulatePositionOffset(path, 'left', 'right', 1);
253
+ if (left) {
254
+ style.left = left;
255
+ }
256
+ } else if (hasPositionValue(node.style, 'right') && isNumber(node.style?.right || 0)) {
257
+ const right = accumulatePositionOffset(path, 'right', 'left', 1);
258
+ if (right) {
259
+ style.right = right;
260
+ }
214
261
  }
215
262
 
216
- if (offset.top) {
217
- style.top = offset.top;
263
+ // 垂直方向:以 top 锚定则累加祖先 top,以 bottom 锚定则累加祖先 bottom
264
+ if (!hasPositionValue(node.style, 'bottom') && isNumber(node.style?.top || 0)) {
265
+ const top = accumulatePositionOffset(path, 'top', 'bottom', 1);
266
+ if (top) {
267
+ style.top = top;
268
+ }
269
+ } else if (hasPositionValue(node.style, 'bottom') && isNumber(node.style?.bottom || 0)) {
270
+ const bottom = accumulatePositionOffset(path, 'bottom', 'top', 1);
271
+ if (bottom) {
272
+ style.bottom = bottom;
273
+ }
218
274
  }
219
275
 
220
276
  return style;
@@ -222,34 +278,29 @@ export const change2Fixed = (node: MNode, root: MApp) => {
222
278
 
223
279
  export const Fixed2Other = async (
224
280
  node: MNode,
225
- root: MApp,
281
+ path: MNode[],
226
282
  getLayout: (parent: MNode, node?: MNode) => Promise<Layout>,
227
283
  ) => {
228
- const path = getNodePath(node.id, root.items);
229
284
  const cur = path.pop();
230
285
  const offset = {
231
- left: cur?.style?.left || 0,
232
- top: cur?.style?.top || 0,
286
+ left: 0,
287
+ top: 0,
288
+ right: 0,
289
+ bottom: 0,
233
290
  };
234
291
 
235
- if (!node.style?.right && isNumber(node.style?.left || 0)) {
236
- for (const value of path) {
237
- if (value.style?.right || !isNumber(value.style?.left || 0)) {
238
- offset.left = 0;
239
- break;
240
- }
241
- offset.left = offset.left - Number(value.style?.left || 0);
242
- }
292
+ // 水平方向:抵消祖先在对应锚定方向上的偏移量,初始值为节点自身的偏移
293
+ if (!hasPositionValue(node.style, 'right') && isNumber(node.style?.left || 0)) {
294
+ offset.left = accumulatePositionOffset(path, 'left', 'right', -1, Number(cur?.style?.left || 0));
295
+ } else if (hasPositionValue(node.style, 'right') && isNumber(node.style?.right || 0)) {
296
+ offset.right = accumulatePositionOffset(path, 'right', 'left', -1, Number(cur?.style?.right || 0));
243
297
  }
244
298
 
245
- if (!node.style?.bottom && isNumber(node.style?.top || 0)) {
246
- for (const value of path) {
247
- if (value.style?.bottom || !isNumber(value.style?.top || 0)) {
248
- offset.top = 0;
249
- break;
250
- }
251
- offset.top = offset.top - Number(value.style?.top || 0);
252
- }
299
+ // 垂直方向:同上
300
+ if (!hasPositionValue(node.style, 'bottom') && isNumber(node.style?.top || 0)) {
301
+ offset.top = accumulatePositionOffset(path, 'top', 'bottom', -1, Number(cur?.style?.top || 0));
302
+ } else if (hasPositionValue(node.style, 'bottom') && isNumber(node.style?.bottom || 0)) {
303
+ offset.bottom = accumulatePositionOffset(path, 'bottom', 'top', -1, Number(cur?.style?.bottom || 0));
253
304
  }
254
305
 
255
306
  const style = node.style || {};
@@ -269,6 +320,14 @@ export const Fixed2Other = async (
269
320
  style.top = offset.top;
270
321
  }
271
322
 
323
+ if (offset.right) {
324
+ style.right = offset.right;
325
+ }
326
+
327
+ if (offset.bottom) {
328
+ style.bottom = offset.bottom;
329
+ }
330
+
272
331
  return {
273
332
  ...style,
274
333
  position: 'absolute',
@@ -316,11 +375,18 @@ export const fixNodePosition = (config: MNode, parent: MContainer, stage: StageC
316
375
  return config.style;
317
376
  }
318
377
 
319
- return {
320
- ...(config.style || {}),
321
- top: getMiddleTop(config, parent, stage),
322
- left: fixNodeLeft(config, parent, stage?.renderer?.contentWindow?.document),
323
- };
378
+ const style = { ...(config.style || {}) };
379
+ const baseStyle = config.style || {};
380
+
381
+ if ('left' in baseStyle && !('right' in baseStyle)) {
382
+ style.left = fixNodeLeft(config, parent, stage?.renderer?.contentWindow?.document);
383
+ }
384
+
385
+ if ('top' in baseStyle && !('bottom' in baseStyle)) {
386
+ style.top = getMiddleTop(config, parent, stage);
387
+ }
388
+
389
+ return style;
324
390
  };
325
391
 
326
392
  // 序列化配置
@@ -460,11 +526,11 @@ export const resolveSelectedNode = (
460
526
  throw new Error('没有ID,无法选中');
461
527
  }
462
528
 
463
- const { node, parent, page } = getNodeInfoFn(id);
529
+ const { node, parent, page, path } = getNodeInfoFn(id);
464
530
  if (!node) throw new Error('获取不到组件信息');
465
531
  if (node.id === rootId) throw new Error('不能选根节点');
466
532
 
467
- return { node, parent, page };
533
+ return { node, parent, page, path };
468
534
  };
469
535
 
470
536
  /**
@@ -479,16 +545,16 @@ export const resolveSelectedNode = (
479
545
  export const toggleFixedPosition = async (
480
546
  dist: MNode,
481
547
  src: MNode,
482
- root: MApp,
548
+ path: MNode[],
483
549
  getLayoutFn: (parent: MNode, node?: MNode | null) => Promise<Layout>,
484
550
  ): Promise<MNode> => {
485
551
  const newConfig = cloneDeep(dist);
486
552
 
487
553
  if (!isPop(src) && newConfig.style?.position) {
488
554
  if (isFixed(newConfig.style) && !isFixed(src.style || {})) {
489
- newConfig.style = change2Fixed(newConfig, root);
555
+ newConfig.style = change2Fixed(newConfig, path);
490
556
  } else if (!isFixed(newConfig.style) && isFixed(src.style || {})) {
491
- newConfig.style = await Fixed2Other(newConfig, root, getLayoutFn);
557
+ newConfig.style = await Fixed2Other(newConfig, path, getLayoutFn);
492
558
  }
493
559
  }
494
560
 
@@ -684,3 +750,43 @@ export const classifyDragSources = (
684
750
 
685
751
  return { sameParentIndices, crossParentConfigs, aborted: false };
686
752
  };
753
+
754
+ /**
755
+ * 给「回滚」生成的新 step 用的简短描述生成器。
756
+ * 与 UI 层 `describePageStep` 同义,但避免 service 反向依赖 layouts/,故放在此工具函数中。
757
+ */
758
+ export const describeStepForRevert = (step: StepValue): string => {
759
+ const items = step.diff ?? [];
760
+ // 在可读名后拼接组件 id,便于在历史面板中精确定位被回滚的组件;id 缺失时退化为仅展示名称。
761
+ const withId = (node: MNode | undefined, label: string): string => {
762
+ const id = node?.id;
763
+ if (id === undefined || id === null || `${id}` === '') return label;
764
+ return label ? `${label}(id: ${id})` : `id: ${id}`;
765
+ };
766
+ switch (step.opType) {
767
+ case 'add': {
768
+ const count = items.length;
769
+ const node = items[0]?.newSchema;
770
+ const label = node?.name || node?.type || '';
771
+ return `撤回新增 ${count} 个节点${count === 1 ? `(${withId(node, label)})` : ''}`;
772
+ }
773
+ case 'remove': {
774
+ const count = items.length;
775
+ const node = items[0]?.oldSchema;
776
+ const label = node?.name || node?.type || '';
777
+ return `还原已删除的 ${count} 个节点${count === 1 ? `(${withId(node, label)})` : ''}`;
778
+ }
779
+ case 'update':
780
+ default: {
781
+ if (items.length === 1) {
782
+ const { newSchema, oldSchema, changeRecords } = items[0];
783
+ const node = newSchema || oldSchema;
784
+ const label = newSchema?.name || newSchema?.type || oldSchema?.name || oldSchema?.type || '';
785
+ const target = withId(node, label);
786
+ const propPath = changeRecords?.[0]?.propPath;
787
+ return propPath ? `还原 ${target} · ${propPath}` : `还原 ${target}`;
788
+ }
789
+ return `还原 ${items.length} 个节点的修改`;
790
+ }
791
+ }
792
+ };
@@ -0,0 +1,308 @@
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
+ import serialize from 'serialize-javascript';
21
+
22
+ import type { Id } from '@tmagic/core';
23
+ import type { ChangeRecord } from '@tmagic/form';
24
+ import { guid } from '@tmagic/utils';
25
+
26
+ import type {
27
+ BaseStepValue,
28
+ HistoryOpSource,
29
+ HistoryOpType,
30
+ PageHistoryGroup,
31
+ PageHistoryStepEntry,
32
+ StepDiffItem,
33
+ StepValue,
34
+ } from '@editor/type';
35
+
36
+ import { UndoRedo } from './undo-redo';
37
+
38
+ /**
39
+ * 「回滚」生成的新 step 简短描述。代码块 / 数据源共用。
40
+ * 二者逻辑一致,仅展示名取值字段不同(代码块取 `name`,数据源取 `title`),
41
+ * 因此通过 `getLabel` 注入取值方式。
42
+ *
43
+ * @param id 关联的代码块 / 数据源 id
44
+ * @param diff 单条变更 diff(缺省视为空)
45
+ * @param getLabel 从快照取展示名
46
+ */
47
+ export const describeRevertStep = <T extends object>(
48
+ id: Id,
49
+ { oldSchema, newSchema, changeRecords }: StepDiffItem<T> = {},
50
+ getLabel: (schema: T) => string | undefined,
51
+ ): string => {
52
+ const labelOf = (schema: T) => getLabel(schema) || (schema as { id?: Id }).id;
53
+ if (!oldSchema && newSchema) return `撤回新增 ${labelOf(newSchema) || id}`;
54
+ if (oldSchema && !newSchema) return `还原已删除的 ${labelOf(oldSchema) || id}`;
55
+ const label = (newSchema && getLabel(newSchema)) || (oldSchema && getLabel(oldSchema)) || `${id}`;
56
+ const propPath = changeRecords?.[0]?.propPath;
57
+ return propPath ? `还原 ${label} · ${propPath}` : `还原 ${label}`;
58
+ };
59
+
60
+ /**
61
+ * 根据 old/new 是否为 null 推断 opType(与 push 时的约定一致)。
62
+ */
63
+ export const detectStackOpType = (oldVal: unknown, newVal: unknown): 'add' | 'remove' | 'update' => {
64
+ if (oldVal === null && newVal !== null) return 'add';
65
+ if (oldVal !== null && newVal === null) return 'remove';
66
+ return 'update';
67
+ };
68
+
69
+ /**
70
+ * 构造一条代码块 / 数据源「按 id 分栈」的历史记录:两者除 payload 字段命名外完全一致。
71
+ *
72
+ * - `add`:oldValue = null;`remove`:newValue = null;`update`:两者都有,可带 changeRecords 做局部更新。
73
+ * - 内容会做 cloneDeep 防止后续被外部引用篡改;opType 依据 old/new 是否为 null 推断。
74
+ * - 仅负责构造 step 并返回,入栈与事件 emit 由各公共方法(pushCodeBlock / pushDataSource)自行处理。
75
+ * - 不直接驱动业务 service,调用方负责实际写回。
76
+ */
77
+ export const createStackStep = <T, S extends BaseStepValue<T> & { id: Id }>(
78
+ id: Id,
79
+ payload: {
80
+ oldValue: T | null;
81
+ newValue: T | null;
82
+ changeRecords?: ChangeRecord[];
83
+ historyDescription?: string;
84
+ source?: HistoryOpSource;
85
+ },
86
+ ): S | null => {
87
+ if (!id) return null;
88
+
89
+ const oldSchema = payload.oldValue ? cloneDeep(payload.oldValue) : null;
90
+ const newSchema = payload.newValue ? cloneDeep(payload.newValue) : null;
91
+ const changeRecords = payload.changeRecords?.length ? cloneDeep(payload.changeRecords) : undefined;
92
+ const opType = detectStackOpType(payload.oldValue, payload.newValue);
93
+
94
+ const step: BaseStepValue<T> & { id: Id } = {
95
+ uuid: guid(),
96
+ id,
97
+ opType,
98
+ diff: [
99
+ {
100
+ ...(newSchema !== null ? { newSchema } : {}),
101
+ ...(oldSchema !== null ? { oldSchema } : {}),
102
+ ...(opType === 'update' && changeRecords ? { changeRecords } : {}),
103
+ },
104
+ ],
105
+ historyDescription: payload.historyDescription,
106
+ source: payload.source,
107
+ timestamp: Date.now(),
108
+ };
109
+
110
+ return step as S;
111
+ };
112
+
113
+ export const markStackSaved = <S extends { saved?: boolean }>(undoRedo?: UndoRedo<S>): void => {
114
+ if (!undoRedo) return;
115
+ undoRedo.updateElements((element) => {
116
+ element.saved = false;
117
+ });
118
+ undoRedo.updateCurrentElement((element) => {
119
+ element.saved = true;
120
+ });
121
+ };
122
+
123
+ /**
124
+ * 把单个「按 id 分栈」的历史栈(代码块 / 数据源)拆成若干 group:
125
+ * 每条操作记录独立成组,不做相邻 update 合并(与页面历史的合并策略不同)。
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
+ const currentIndex = cursor - 1;
143
+ return list.map((step, index) => {
144
+ const applied = index < cursor;
145
+ const isCurrent = index === currentIndex;
146
+ return {
147
+ kind,
148
+ id,
149
+ opType: step.opType,
150
+ steps: [{ step, index, applied, isCurrent }],
151
+ applied,
152
+ isCurrent,
153
+ };
154
+ });
155
+ };
156
+
157
+ /**
158
+ * 把页面栈拆成若干 group:
159
+ * - 单节点的 'update' 按 targetId 与相邻同 targetId 的 update 合并到一个 group;
160
+ * - 'add' / 'remove' 始终独立成组(语义上是结构变更,不应被收纳进单节点修改组);
161
+ * - 多节点 'update'(如批量改属性)也独立成组(无明确单一目标,避免误合并)。
162
+ */
163
+ export const mergePageSteps = (pageId: Id, list: StepValue[], cursor: number): PageHistoryGroup[] => {
164
+ const groups: PageHistoryGroup[] = [];
165
+ let current: PageHistoryGroup | null = null;
166
+ const currentIndex = cursor - 1;
167
+ list.forEach((step, index) => {
168
+ const applied = index < cursor;
169
+ const isCurrent = index === currentIndex;
170
+ const targetId = detectPageTargetId(step);
171
+ const targetName = detectPageTargetName(step);
172
+ const entry: PageHistoryStepEntry = { step, index, applied, isCurrent };
173
+
174
+ // 仅"单节点 update"参与合并;其它情形(add/remove/多节点 update)始终独立成组。
175
+ const mergeable = step.opType === 'update' && targetId !== undefined;
176
+ if (mergeable && current?.opType === 'update' && current.targetId === targetId) {
177
+ current.steps.push(entry);
178
+ current.applied = applied;
179
+ if (isCurrent) current.isCurrent = true;
180
+ // 保持目标名为最近一次的(节点重命名时也能反映)
181
+ if (targetName) current.targetName = targetName;
182
+ } else {
183
+ current = {
184
+ kind: 'page',
185
+ pageId,
186
+ opType: step.opType,
187
+ targetId: mergeable ? targetId : undefined,
188
+ targetName,
189
+ steps: [entry],
190
+ applied,
191
+ isCurrent,
192
+ };
193
+ groups.push(current);
194
+ }
195
+ });
196
+ return groups;
197
+ };
198
+
199
+ /**
200
+ * 解析 StepValue 中的"目标节点 id"用于合并:
201
+ * - 单节点 update:取唯一一项 updatedItems 的节点 id;
202
+ * - 其它情形(多节点 update / add / remove):返回 undefined,表示不参与合并。
203
+ */
204
+ export const detectPageTargetId = (step: StepValue): Id | undefined => {
205
+ if (step.opType !== 'update') return undefined;
206
+ const items = step.diff;
207
+ if (items?.length !== 1) return undefined;
208
+ return items[0].newSchema?.id ?? items[0].oldSchema?.id;
209
+ };
210
+
211
+ /** 解析 StepValue 中的目标节点可读名(用于 UI 展示)。 */
212
+ export const detectPageTargetName = (step: StepValue): string | undefined => {
213
+ const items = step.diff;
214
+ if (step.opType === 'update') {
215
+ if (items?.length === 1) {
216
+ const node = items[0].newSchema || items[0].oldSchema;
217
+ return (node?.name as string) || (node?.type as string) || (node?.id !== undefined ? `${node.id}` : undefined);
218
+ }
219
+ return items?.length ? `${items.length} 个节点` : undefined;
220
+ }
221
+ if (step.opType === 'add') {
222
+ if (items?.length === 1) {
223
+ const n = items[0].newSchema;
224
+ return (n?.name as string) || (n?.type as string) || `${n?.id}`;
225
+ }
226
+ return items?.length ? `${items.length} 个节点` : undefined;
227
+ }
228
+ if (step.opType === 'remove') {
229
+ if (items?.length === 1) {
230
+ const n = items[0].oldSchema;
231
+ return (n?.name as string) || (n?.type as string) || `${n?.id}`;
232
+ }
233
+ return items?.length ? `${items.length} 个节点` : undefined;
234
+ }
235
+ return undefined;
236
+ };
237
+
238
+ /**
239
+ * 把 `Record<Id, UndoRedo>` 整体序列化为 `Record<Id, SerializedUndoRedo>`。
240
+ *
241
+ * 序列化(深克隆)的同一趟里,只把每条 step 中可能含函数的 `diff` 用 serialize-javascript 序列化成字符串,
242
+ * 其余字段(uuid / opType / timestamp / `modifiedNodeIds` Map 等)原样保留,交给 IndexedDB 结构化克隆。
243
+ * 这样既能写入函数,又避免序列化整份快照的开销;读取时再由 {@link parseStacksStepDiff} 还原 diff。
244
+ * 不含 `diff` 的元素(如通用栈)原样透传。
245
+ */
246
+ export const serializeStacks = <T extends { diff?: unknown }>(stacks: Record<Id, UndoRedo<T>>) => {
247
+ const result: Record<Id, ReturnType<UndoRedo<T>['serialize']>> = {};
248
+ Object.entries(stacks).forEach(([id, undoRedo]) => {
249
+ if (!undoRedo) return;
250
+ const serialized = undoRedo.serialize();
251
+ result[id] = {
252
+ ...serialized,
253
+ elementList: serialized.elementList.map((step) =>
254
+ step.diff === undefined ? step : Object.assign({}, step, { diff: serialize(step.diff) }),
255
+ ),
256
+ };
257
+ });
258
+ return result;
259
+ };
260
+
261
+ /**
262
+ * 把 `Record<Id, SerializedUndoRedo>` 整体还原为 `Record<Id, UndoRedo>`。
263
+ * 还原时把每个栈的游标定位到最近一条已保存(`saved === true`)记录之后。
264
+ *
265
+ * 与 {@link serializeStacks} 相反:当传入 `parse`(parseDSL)时,把每条 step 中以字符串形式存储的 `diff`
266
+ * 解析回真实对象(含函数);不含 `diff` 的元素(如通用栈)原样透传。
267
+ */
268
+ export const deserializeStacks = <T extends { saved?: boolean }>(
269
+ stacks: Record<Id, ReturnType<UndoRedo<T>['serialize']>> = {},
270
+ parse?: (serialized: string) => unknown,
271
+ ): Record<Id, UndoRedo<T>> => {
272
+ const result: Record<Id, UndoRedo<T>> = {};
273
+ Object.entries(stacks).forEach(([id, serialized]) => {
274
+ if (!serialized) return;
275
+ const elementList = parse
276
+ ? serialized.elementList.map((step) => {
277
+ const { diff } = step as { diff?: unknown };
278
+ return typeof diff === 'string' ? Object.assign({}, step, { diff: parse(`(${diff})`) }) : step;
279
+ })
280
+ : serialized.elementList;
281
+ result[id] = UndoRedo.fromSerialized<T>(
282
+ { ...serialized, elementList },
283
+ { isSavedStep: (element) => element.saved === true },
284
+ );
285
+ });
286
+ return result;
287
+ };
288
+
289
+ /**
290
+ * 按 id 从「按 id 分栈」的记录表(代码块 / 数据源)中获取(或创建)对应的 UndoRedo 栈。
291
+ */
292
+ export const getOrCreateStack = <T>(stacks: Record<Id, UndoRedo<T>>, id: Id): UndoRedo<T> => {
293
+ if (!stacks[id]) {
294
+ stacks[id] = new UndoRedo<T>();
295
+ }
296
+ return stacks[id];
297
+ };
298
+
299
+ /**
300
+ * 撤销下限:当页面栈 index 0 是 `opType: 'initial'` 的基线 step 时为 1(基线不可被撤销),否则为 0。
301
+ * 用于把 cursor 钉在基线之上,保证 undo / canUndo / goto 都不会越过初始基线。
302
+ */
303
+ export const undoFloor = (undoRedo: UndoRedo<StepValue>): number => {
304
+ return undoRedo.getElementList()[0]?.opType === 'initial' ? 1 : 0;
305
+ };
306
+
307
+ /** 将单次 push 产生的 history uuid(或 null)转为 *AndGetHistoryId 返回用的 uuid 列表。 */
308
+ export const getLastPushedHistoryIds = (historyId: string | null): string[] => (historyId ? [historyId] : []);
@@ -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';