@tmagic/editor 1.8.0-beta.3 → 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 (92) hide show
  1. package/dist/es/components/CompareForm.vue_vue_type_script_setup_true_lang.js +15 -1
  2. package/dist/es/components/ToolButton.vue_vue_type_script_setup_true_lang.js +6 -6
  3. package/dist/es/hooks/use-code-block-edit.js +6 -3
  4. package/dist/es/hooks/use-data-source-edit.js +5 -2
  5. package/dist/es/hooks/use-stage.js +6 -3
  6. package/dist/es/index.js +6 -3
  7. package/dist/es/initService.js +1 -1
  8. package/dist/es/layouts/Framework.vue_vue_type_script_setup_true_lang.js +1 -1
  9. package/dist/es/layouts/NavMenu.vue_vue_type_script_setup_true_lang.js +1 -1
  10. package/dist/es/layouts/history-list/Bucket.vue_vue_type_script_setup_true_lang.js +19 -51
  11. package/dist/es/layouts/history-list/BucketTab.vue_vue_type_script_setup_true_lang.js +22 -36
  12. package/dist/es/layouts/history-list/GroupRow.vue_vue_type_script_setup_true_lang.js +152 -93
  13. package/dist/es/layouts/history-list/HistoryDiffDialog.vue_vue_type_script_setup_true_lang.js +36 -10
  14. package/dist/es/layouts/history-list/HistoryListPanel.vue_vue_type_script_setup_true_lang.js +334 -208
  15. package/dist/es/layouts/history-list/InitialRow.vue_vue_type_script_setup_true_lang.js +28 -7
  16. package/dist/es/layouts/history-list/PageTab.vue_vue_type_script_setup_true_lang.js +47 -57
  17. package/dist/es/layouts/history-list/composables.js +118 -25
  18. package/dist/es/layouts/page-bar/PageBar.vue_vue_type_script_setup_true_lang.js +4 -2
  19. package/dist/es/layouts/props-panel/PropsPanel.vue_vue_type_script_setup_true_lang.js +5 -1
  20. package/dist/es/layouts/sidebar/ComponentListPanel.vue_vue_type_script_setup_true_lang.js +1 -1
  21. package/dist/es/layouts/sidebar/Sidebar.vue_vue_type_script_setup_true_lang.js +5 -1
  22. package/dist/es/layouts/sidebar/code-block/CodeBlockList.vue_vue_type_script_setup_true_lang.js +3 -3
  23. package/dist/es/layouts/sidebar/code-block/CodeBlockListPanel.vue_vue_type_script_setup_true_lang.js +1 -1
  24. package/dist/es/layouts/sidebar/code-block/useContentMenu.js +1 -1
  25. package/dist/es/layouts/sidebar/data-source/DataSourceListPanel.vue_vue_type_script_setup_true_lang.js +1 -1
  26. package/dist/es/layouts/sidebar/data-source/useContentMenu.js +1 -1
  27. package/dist/es/layouts/sidebar/layer/LayerMenu.vue_vue_type_script_setup_true_lang.js +5 -5
  28. package/dist/es/layouts/sidebar/layer/LayerNodeTool.vue_vue_type_script_setup_true_lang.js +1 -1
  29. package/dist/es/layouts/workspace/viewer/Stage.vue_vue_type_script_setup_true_lang.js +1 -1
  30. package/dist/es/layouts/workspace/viewer/ViewerMenu.vue_vue_type_script_setup_true_lang.js +8 -8
  31. package/dist/es/services/codeBlock.js +105 -42
  32. package/dist/es/services/dataSource.js +85 -35
  33. package/dist/es/services/editor.js +317 -122
  34. package/dist/es/services/history.js +270 -204
  35. package/dist/es/services/keybinding.js +3 -3
  36. package/dist/es/services/ui.js +3 -0
  37. package/dist/es/style.css +65 -10
  38. package/dist/es/utils/content-menu.js +17 -9
  39. package/dist/es/utils/editor.js +35 -1
  40. package/dist/es/utils/history.js +223 -0
  41. package/dist/es/utils/indexed-db.js +86 -0
  42. package/dist/es/utils/undo-redo.js +60 -1
  43. package/dist/style.css +65 -10
  44. package/dist/tmagic-editor.umd.cjs +2047 -954
  45. package/package.json +7 -7
  46. package/src/components/CompareForm.vue +21 -1
  47. package/src/components/ToolButton.vue +2 -2
  48. package/src/hooks/use-code-block-edit.ts +4 -3
  49. package/src/hooks/use-data-source-edit.ts +2 -2
  50. package/src/hooks/use-stage.ts +3 -3
  51. package/src/index.ts +1 -0
  52. package/src/initService.ts +1 -1
  53. package/src/layouts/Framework.vue +1 -1
  54. package/src/layouts/NavMenu.vue +1 -1
  55. package/src/layouts/history-list/Bucket.vue +34 -67
  56. package/src/layouts/history-list/BucketTab.vue +46 -51
  57. package/src/layouts/history-list/GroupRow.vue +150 -98
  58. package/src/layouts/history-list/HistoryDiffDialog.vue +96 -69
  59. package/src/layouts/history-list/HistoryListPanel.vue +298 -111
  60. package/src/layouts/history-list/InitialRow.vue +25 -9
  61. package/src/layouts/history-list/PageTab.vue +58 -48
  62. package/src/layouts/history-list/composables.ts +210 -29
  63. package/src/layouts/page-bar/PageBar.vue +4 -2
  64. package/src/layouts/props-panel/PropsPanel.vue +5 -1
  65. package/src/layouts/sidebar/ComponentListPanel.vue +9 -5
  66. package/src/layouts/sidebar/Sidebar.vue +6 -1
  67. package/src/layouts/sidebar/code-block/CodeBlockList.vue +5 -5
  68. package/src/layouts/sidebar/code-block/CodeBlockListPanel.vue +1 -1
  69. package/src/layouts/sidebar/code-block/useContentMenu.ts +1 -1
  70. package/src/layouts/sidebar/data-source/DataSourceListPanel.vue +1 -1
  71. package/src/layouts/sidebar/data-source/useContentMenu.ts +1 -1
  72. package/src/layouts/sidebar/layer/LayerMenu.vue +19 -11
  73. package/src/layouts/sidebar/layer/LayerNodeTool.vue +7 -4
  74. package/src/layouts/workspace/viewer/Stage.vue +1 -1
  75. package/src/layouts/workspace/viewer/ViewerMenu.vue +8 -8
  76. package/src/services/codeBlock.ts +129 -35
  77. package/src/services/dataSource.ts +105 -34
  78. package/src/services/editor.ts +470 -157
  79. package/src/services/history.ts +312 -203
  80. package/src/services/keybinding.ts +3 -3
  81. package/src/services/ui.ts +7 -0
  82. package/src/theme/history-list-panel.scss +87 -6
  83. package/src/theme/page-bar.scss +0 -4
  84. package/src/theme/props-panel.scss +3 -3
  85. package/src/type.ts +221 -61
  86. package/src/utils/content-menu.ts +18 -9
  87. package/src/utils/editor.ts +41 -1
  88. package/src/utils/history.ts +298 -0
  89. package/src/utils/index.ts +2 -0
  90. package/src/utils/indexed-db.ts +122 -0
  91. package/src/utils/undo-redo.ts +88 -0
  92. package/types/index.d.ts +871 -308
package/dist/es/style.css CHANGED
@@ -592,7 +592,7 @@ fieldset.m-fieldset .m-form-tip {
592
592
  position: absolute;
593
593
  top: 4px;
594
594
  right: 4px;
595
- z-index: 1;
595
+ z-index: 2;
596
596
  display: flex;
597
597
  align-items: center;
598
598
  height: 40px;
@@ -617,6 +617,23 @@ fieldset.m-fieldset .m-form-tip {
617
617
  padding: 0;
618
618
  list-style: none;
619
619
  }
620
+ .m-editor-history-list-popover .m-editor-history-list-toolbar {
621
+ display: flex;
622
+ align-items: center;
623
+ justify-content: flex-end;
624
+ padding: 0 4px 4px;
625
+ }
626
+ .m-editor-history-list-popover .m-editor-history-list-clear {
627
+ padding: 2px 8px;
628
+ border-radius: 4px;
629
+ font-size: 12px;
630
+ color: #f56c6c;
631
+ cursor: pointer;
632
+ user-select: none;
633
+ }
634
+ .m-editor-history-list-popover .m-editor-history-list-clear:hover {
635
+ background-color: rgba(245, 108, 108, 0.12);
636
+ }
620
637
  .m-editor-history-list-popover .m-editor-history-list-item {
621
638
  display: flex;
622
639
  align-items: center;
@@ -750,12 +767,18 @@ fieldset.m-fieldset .m-form-tip {
750
767
  }
751
768
  .m-editor-history-list-popover .m-editor-history-list-item-index {
752
769
  flex: 0 0 auto;
770
+ min-width: 30px;
771
+ text-align: right;
753
772
  color: #909399;
754
773
  font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
755
774
  font-size: 11px;
756
775
  font-weight: 400;
757
776
  white-space: nowrap;
758
777
  }
778
+ .m-editor-history-list-popover .m-editor-history-list-group.is-merged > .m-editor-history-list-group-head > .m-editor-history-list-item-index {
779
+ min-width: 0;
780
+ text-align: left;
781
+ }
759
782
  .m-editor-history-list-popover .m-editor-history-list-item-time {
760
783
  flex: 0 0 auto;
761
784
  color: #a8abb2;
@@ -804,6 +827,30 @@ fieldset.m-fieldset .m-form-tip {
804
827
  text-overflow: ellipsis;
805
828
  white-space: nowrap;
806
829
  }
830
+ .m-editor-history-list-popover .m-editor-history-list-item-source {
831
+ flex: 0 0 auto;
832
+ padding: 0 6px;
833
+ border: 1px solid #dcdfe6;
834
+ border-radius: 8px;
835
+ font-size: 10px;
836
+ line-height: 14px;
837
+ color: #909399;
838
+ background-color: #f4f4f5;
839
+ white-space: nowrap;
840
+ font-weight: 400;
841
+ }
842
+ .m-editor-history-list-popover .m-editor-history-list-item-saved {
843
+ flex: 0 0 auto;
844
+ padding: 0 6px;
845
+ border-radius: 8px;
846
+ font-size: 10px;
847
+ line-height: 16px;
848
+ color: #fff;
849
+ background-color: #67c23a;
850
+ white-space: nowrap;
851
+ font-weight: 500;
852
+ letter-spacing: 0.2px;
853
+ }
807
854
  .m-editor-history-list-popover .m-editor-history-list-item-merge {
808
855
  flex: 0 0 auto;
809
856
  padding: 0 8px;
@@ -815,6 +862,17 @@ fieldset.m-fieldset .m-form-tip {
815
862
  font-weight: 500;
816
863
  letter-spacing: 0.2px;
817
864
  }
865
+ .m-editor-history-list-popover .m-editor-history-list-item-actions {
866
+ display: none;
867
+ flex: 0 0 auto;
868
+ align-items: center;
869
+ gap: 6px;
870
+ }
871
+ .m-editor-history-list-popover .m-editor-history-list-group-head:hover > .m-editor-history-list-item-actions,
872
+ .m-editor-history-list-popover .m-editor-history-list-substeps > li:hover > .m-editor-history-list-item-actions,
873
+ .m-editor-history-list-popover .m-editor-history-list-initial:hover > .m-editor-history-list-item-actions {
874
+ display: flex;
875
+ }
818
876
  .m-editor-history-list-popover .m-editor-history-list-item-diff {
819
877
  flex: 0 0 auto;
820
878
  padding: 0 6px;
@@ -835,13 +893,13 @@ fieldset.m-fieldset .m-form-tip {
835
893
  border-radius: 2px;
836
894
  font-size: 10px;
837
895
  line-height: 16px;
838
- color: #606266;
839
- background-color: rgba(96, 98, 102, 0.1);
896
+ color: #529b2e;
897
+ background-color: rgba(103, 194, 58, 0.12);
840
898
  cursor: pointer;
841
899
  user-select: none;
842
900
  }
843
901
  .m-editor-history-list-popover .m-editor-history-list-item-goto:hover {
844
- background-color: rgba(96, 98, 102, 0.18);
902
+ background-color: rgba(103, 194, 58, 0.24);
845
903
  }
846
904
  .m-editor-history-list-popover .m-editor-history-list-item-revert {
847
905
  flex: 0 0 auto;
@@ -1384,9 +1442,6 @@ fieldset.m-fieldset .m-form-tip {
1384
1442
  transition: all 0.2s ease 0s;
1385
1443
  padding: 5px 14px;
1386
1444
  }
1387
- .page-bar-popover .menu-item .tmagic-design-button {
1388
- color: #313a40;
1389
- }
1390
1445
  .page-bar-popover .menu-item:hover {
1391
1446
  background-color: #f3f5f9;
1392
1447
  }
@@ -1452,7 +1507,7 @@ fieldset.m-fieldset .m-form-tip {
1452
1507
  position: absolute;
1453
1508
  right: 15px;
1454
1509
  bottom: 15px;
1455
- z-index: 30;
1510
+ z-index: 32;
1456
1511
  opacity: 0.5;
1457
1512
  }
1458
1513
  .m-editor-props-panel .m-editor-props-panel-src-icon:hover {
@@ -1462,7 +1517,7 @@ fieldset.m-fieldset .m-form-tip {
1462
1517
  position: absolute;
1463
1518
  right: 15px;
1464
1519
  bottom: 60px;
1465
- z-index: 30;
1520
+ z-index: 31;
1466
1521
  opacity: 0.5;
1467
1522
  }
1468
1523
  .m-editor-props-panel .m-editor-props-panel-style-icon:hover {
@@ -1472,7 +1527,7 @@ fieldset.m-fieldset .m-form-tip {
1472
1527
  position: absolute;
1473
1528
  left: 0;
1474
1529
  top: 0;
1475
- z-index: 10;
1530
+ z-index: 31;
1476
1531
  }
1477
1532
  .m-editor-props-panel .m-editor-resizer {
1478
1533
  position: absolute;
@@ -4,7 +4,12 @@ import { NodeType, cloneDeep } from "@tmagic/core";
4
4
  import { computed, markRaw } from "vue";
5
5
  import { CopyDocument, Delete, DocumentCopy } from "@element-plus/icons-vue";
6
6
  //#region packages/editor/src/utils/content-menu.ts
7
- var useDeleteMenu = () => ({
7
+ /**
8
+ * 共享的右键菜单项构造器(画布 ViewerMenu 与图层树 LayerMenu 共用)。
9
+ * `historySource` 用于标记本次操作的途径,调用方按所在面板传入:
10
+ * 画布传 `'stage-contextmenu'`,树形面板传 `'tree-contextmenu'`。
11
+ */
12
+ var useDeleteMenu = (historySource) => ({
8
13
  type: "button",
9
14
  text: "删除",
10
15
  icon: Delete,
@@ -14,7 +19,7 @@ var useDeleteMenu = () => ({
14
19
  },
15
20
  handler: ({ editorService }) => {
16
21
  const nodes = editorService.get("nodes");
17
- nodes && editorService.remove(nodes);
22
+ nodes && editorService.remove(nodes, { historySource });
18
23
  }
19
24
  });
20
25
  var useCopyMenu = () => ({
@@ -26,7 +31,7 @@ var useCopyMenu = () => ({
26
31
  nodes && editorService?.copy(nodes);
27
32
  }
28
33
  });
29
- var usePasteMenu = (menu) => ({
34
+ var usePasteMenu = (historySource, menu) => ({
30
35
  type: "button",
31
36
  text: "粘贴",
32
37
  icon: markRaw(DocumentCopy),
@@ -43,17 +48,20 @@ var usePasteMenu = (menu) => ({
43
48
  editorService.paste({
44
49
  left: initialLeft,
45
50
  top: initialTop
46
- });
47
- } else editorService.paste();
51
+ }, void 0, { historySource });
52
+ } else editorService.paste(void 0, void 0, { historySource });
48
53
  }
49
54
  });
50
- var moveTo = async (id, { editorService }) => {
55
+ var moveTo = async (id, { editorService }, historySource) => {
51
56
  const nodes = editorService.get("nodes") || [];
52
57
  const parent = editorService.getNodeById(id);
53
58
  if (!parent || nodes.length === 0) return;
54
- await editorService.moveToContainer(cloneDeep(nodes), parent.id, { doNotSwitchPage: true });
59
+ await editorService.moveToContainer(cloneDeep(nodes), parent.id, {
60
+ doNotSwitchPage: true,
61
+ historySource
62
+ });
55
63
  };
56
- var useMoveToMenu = ({ editorService }) => {
64
+ var useMoveToMenu = ({ editorService }, historySource) => {
57
65
  return {
58
66
  type: "button",
59
67
  text: "移动至",
@@ -66,7 +74,7 @@ var useMoveToMenu = ({ editorService }) => {
66
74
  text: `${page.name}(${page.id})`,
67
75
  type: "button",
68
76
  handler: (services) => {
69
- moveTo(page.id, services);
77
+ moveTo(page.id, services, historySource);
70
78
  }
71
79
  }))
72
80
  };
@@ -431,5 +431,39 @@ var classifyDragSources = (configs, targetParent, getNodeInfo) => {
431
431
  aborted: false
432
432
  };
433
433
  };
434
+ /**
435
+ * 给「回滚」生成的新 step 用的简短描述生成器。
436
+ * 与 UI 层 `describePageStep` 同义,但避免 service 反向依赖 layouts/,故放在此工具函数中。
437
+ */
438
+ var describeStepForRevert = (step) => {
439
+ const items = step.diff ?? [];
440
+ const withId = (node, label) => {
441
+ const id = node?.id;
442
+ if (id === void 0 || id === null || `${id}` === "") return label;
443
+ return label ? `${label}(id: ${id})` : `id: ${id}`;
444
+ };
445
+ switch (step.opType) {
446
+ case "add": {
447
+ const count = items.length;
448
+ const node = items[0]?.newSchema;
449
+ const label = node?.name || node?.type || "";
450
+ return `撤回新增 ${count} 个节点${count === 1 ? `(${withId(node, label)})` : ""}`;
451
+ }
452
+ case "remove": {
453
+ const count = items.length;
454
+ const node = items[0]?.oldSchema;
455
+ const label = node?.name || node?.type || "";
456
+ return `还原已删除的 ${count} 个节点${count === 1 ? `(${withId(node, label)})` : ""}`;
457
+ }
458
+ default:
459
+ if (items.length === 1) {
460
+ const { newSchema, oldSchema, changeRecords } = items[0];
461
+ const target = withId(newSchema || oldSchema, newSchema?.name || newSchema?.type || oldSchema?.name || oldSchema?.type || "");
462
+ const propPath = changeRecords?.[0]?.propPath;
463
+ return propPath ? `还原 ${target} · ${propPath}` : `还原 ${target}`;
464
+ }
465
+ return `还原 ${items.length} 个节点的修改`;
466
+ }
467
+ };
434
468
  //#endregion
435
- export { COPY_CODE_STORAGE_KEY, COPY_DS_STORAGE_KEY, COPY_STORAGE_KEY, Fixed2Other, buildChangeRecords, calcAlignCenterStyle, calcLayerTargetIndex, calcMoveStyle, change2Fixed, classifyDragSources, collectRelatedNodes, editorNodeMergeCustomizer, fixNodeLeft, fixNodePosition, generatePageName, generatePageNameByApp, getGuideLineFromCache, getInitPositionStyle, getNodeIndex, getPageFragmentList, getPageList, getPageNameList, getRelativeStyle, isIncludeDataSource, moveItemsInContainer, resolveSelectedNode, serializeConfig, setChildrenLayout, setLayout, toggleFixedPosition };
469
+ export { COPY_CODE_STORAGE_KEY, COPY_DS_STORAGE_KEY, COPY_STORAGE_KEY, Fixed2Other, buildChangeRecords, calcAlignCenterStyle, calcLayerTargetIndex, calcMoveStyle, change2Fixed, classifyDragSources, collectRelatedNodes, describeStepForRevert, editorNodeMergeCustomizer, fixNodeLeft, fixNodePosition, generatePageName, generatePageNameByApp, getGuideLineFromCache, getInitPositionStyle, getNodeIndex, getPageFragmentList, getPageList, getPageNameList, getRelativeStyle, isIncludeDataSource, moveItemsInContainer, resolveSelectedNode, serializeConfig, setChildrenLayout, setLayout, toggleFixedPosition };
@@ -0,0 +1,223 @@
1
+ import { UndoRedo } from "./undo-redo.js";
2
+ import { guid } from "@tmagic/utils";
3
+ import { cloneDeep } from "lodash-es";
4
+ //#region packages/editor/src/utils/history.ts
5
+ /**
6
+ * 「回滚」生成的新 step 简短描述。代码块 / 数据源共用。
7
+ * 二者逻辑一致,仅展示名取值字段不同(代码块取 `name`,数据源取 `title`),
8
+ * 因此通过 `getLabel` 注入取值方式。
9
+ *
10
+ * @param id 关联的代码块 / 数据源 id
11
+ * @param diff 单条变更 diff(缺省视为空)
12
+ * @param getLabel 从快照取展示名
13
+ */
14
+ var describeRevertStep = (id, { oldSchema, newSchema, changeRecords } = {}, getLabel) => {
15
+ const labelOf = (schema) => getLabel(schema) || schema.id;
16
+ if (!oldSchema && newSchema) return `撤回新增 ${labelOf(newSchema) || id}`;
17
+ if (oldSchema && !newSchema) return `还原已删除的 ${labelOf(oldSchema) || id}`;
18
+ const label = newSchema && getLabel(newSchema) || oldSchema && getLabel(oldSchema) || `${id}`;
19
+ const propPath = changeRecords?.[0]?.propPath;
20
+ return propPath ? `还原 ${label} · ${propPath}` : `还原 ${label}`;
21
+ };
22
+ /**
23
+ * 根据 old/new 是否为 null 推断 opType(与 push 时的约定一致)。
24
+ */
25
+ var detectStackOpType = (oldVal, newVal) => {
26
+ if (oldVal === null && newVal !== null) return "add";
27
+ if (oldVal !== null && newVal === null) return "remove";
28
+ return "update";
29
+ };
30
+ /**
31
+ * 构造一条代码块 / 数据源「按 id 分栈」的历史记录:两者除 payload 字段命名外完全一致。
32
+ *
33
+ * - `add`:oldValue = null;`remove`:newValue = null;`update`:两者都有,可带 changeRecords 做局部更新。
34
+ * - 内容会做 cloneDeep 防止后续被外部引用篡改;opType 依据 old/new 是否为 null 推断。
35
+ * - 仅负责构造 step 并返回,入栈与事件 emit 由各公共方法(pushCodeBlock / pushDataSource)自行处理。
36
+ * - 不直接驱动业务 service,调用方负责实际写回。
37
+ */
38
+ var createStackStep = (id, payload) => {
39
+ if (!id) return null;
40
+ const oldSchema = payload.oldValue ? cloneDeep(payload.oldValue) : null;
41
+ const newSchema = payload.newValue ? cloneDeep(payload.newValue) : null;
42
+ const changeRecords = payload.changeRecords?.length ? cloneDeep(payload.changeRecords) : void 0;
43
+ const opType = detectStackOpType(payload.oldValue, payload.newValue);
44
+ return {
45
+ uuid: guid(),
46
+ id,
47
+ opType,
48
+ diff: [{
49
+ ...newSchema !== null ? { newSchema } : {},
50
+ ...oldSchema !== null ? { oldSchema } : {},
51
+ ...opType === "update" && changeRecords ? { changeRecords } : {}
52
+ }],
53
+ historyDescription: payload.historyDescription,
54
+ source: payload.source,
55
+ timestamp: Date.now()
56
+ };
57
+ };
58
+ var markStackSaved = (undoRedo) => {
59
+ if (!undoRedo) return;
60
+ undoRedo.updateElements((element) => {
61
+ element.saved = false;
62
+ });
63
+ undoRedo.updateCurrentElement((element) => {
64
+ element.saved = true;
65
+ });
66
+ };
67
+ /**
68
+ * 把单个「按 id 分栈」的历史栈(代码块 / 数据源)拆成若干 group:
69
+ * - 把"新增/删除"独立成组(语义上属于一次性事件,不应与 update 合并);
70
+ * - 连续 'update' 合并到同一组,组内 steps 顺序就是发生顺序。
71
+ *
72
+ * 代码块与数据源除 `kind` 外结构完全一致,统一由本方法处理;`kind` 决定返回的具体分组类型。
73
+ */
74
+ var mergeStackSteps = (kind, id, list, cursor) => {
75
+ const groups = [];
76
+ let current = null;
77
+ const currentIndex = cursor - 1;
78
+ list.forEach((step, index) => {
79
+ const { opType } = step;
80
+ const applied = index < cursor;
81
+ const isCurrent = index === currentIndex;
82
+ if (opType === "update" && current?.opType === "update") {
83
+ current.steps.push({
84
+ step,
85
+ index,
86
+ applied,
87
+ isCurrent
88
+ });
89
+ current.applied = applied;
90
+ if (isCurrent) current.isCurrent = true;
91
+ } else {
92
+ current = {
93
+ kind,
94
+ id,
95
+ opType,
96
+ steps: [{
97
+ step,
98
+ index,
99
+ applied,
100
+ isCurrent
101
+ }],
102
+ applied,
103
+ isCurrent
104
+ };
105
+ groups.push(current);
106
+ }
107
+ });
108
+ return groups;
109
+ };
110
+ /**
111
+ * 把页面栈拆成若干 group:
112
+ * - 单节点的 'update' 按 targetId 与相邻同 targetId 的 update 合并到一个 group;
113
+ * - 'add' / 'remove' 始终独立成组(语义上是结构变更,不应被收纳进单节点修改组);
114
+ * - 多节点 'update'(如批量改属性)也独立成组(无明确单一目标,避免误合并)。
115
+ */
116
+ var mergePageSteps = (pageId, list, cursor) => {
117
+ const groups = [];
118
+ let current = null;
119
+ const currentIndex = cursor - 1;
120
+ list.forEach((step, index) => {
121
+ const applied = index < cursor;
122
+ const isCurrent = index === currentIndex;
123
+ const targetId = detectPageTargetId(step);
124
+ const targetName = detectPageTargetName(step);
125
+ const entry = {
126
+ step,
127
+ index,
128
+ applied,
129
+ isCurrent
130
+ };
131
+ const mergeable = step.opType === "update" && targetId !== void 0;
132
+ if (mergeable && current?.opType === "update" && current.targetId === targetId) {
133
+ current.steps.push(entry);
134
+ current.applied = applied;
135
+ if (isCurrent) current.isCurrent = true;
136
+ if (targetName) current.targetName = targetName;
137
+ } else {
138
+ current = {
139
+ kind: "page",
140
+ pageId,
141
+ opType: step.opType,
142
+ targetId: mergeable ? targetId : void 0,
143
+ targetName,
144
+ steps: [entry],
145
+ applied,
146
+ isCurrent
147
+ };
148
+ groups.push(current);
149
+ }
150
+ });
151
+ return groups;
152
+ };
153
+ /**
154
+ * 解析 StepValue 中的"目标节点 id"用于合并:
155
+ * - 单节点 update:取唯一一项 updatedItems 的节点 id;
156
+ * - 其它情形(多节点 update / add / remove):返回 undefined,表示不参与合并。
157
+ */
158
+ var detectPageTargetId = (step) => {
159
+ if (step.opType !== "update") return void 0;
160
+ const items = step.diff;
161
+ if (items?.length !== 1) return void 0;
162
+ return items[0].newSchema?.id ?? items[0].oldSchema?.id;
163
+ };
164
+ /** 解析 StepValue 中的目标节点可读名(用于 UI 展示)。 */
165
+ var detectPageTargetName = (step) => {
166
+ const items = step.diff;
167
+ if (step.opType === "update") {
168
+ if (items?.length === 1) {
169
+ const node = items[0].newSchema || items[0].oldSchema;
170
+ return node?.name || node?.type || (node?.id !== void 0 ? `${node.id}` : void 0);
171
+ }
172
+ return items?.length ? `${items.length} 个节点` : void 0;
173
+ }
174
+ if (step.opType === "add") {
175
+ if (items?.length === 1) {
176
+ const n = items[0].newSchema;
177
+ return n?.name || n?.type || `${n?.id}`;
178
+ }
179
+ return items?.length ? `${items.length} 个节点` : void 0;
180
+ }
181
+ if (step.opType === "remove") {
182
+ if (items?.length === 1) {
183
+ const n = items[0].oldSchema;
184
+ return n?.name || n?.type || `${n?.id}`;
185
+ }
186
+ return items?.length ? `${items.length} 个节点` : void 0;
187
+ }
188
+ };
189
+ /** 把 `Record<Id, UndoRedo>` 整体序列化为 `Record<Id, SerializedUndoRedo>`。 */
190
+ var serializeStacks = (stacks) => {
191
+ const result = {};
192
+ Object.entries(stacks).forEach(([id, undoRedo]) => {
193
+ if (undoRedo) result[id] = undoRedo.serialize();
194
+ });
195
+ return result;
196
+ };
197
+ /**
198
+ * 把 `Record<Id, SerializedUndoRedo>` 整体还原为 `Record<Id, UndoRedo>`。
199
+ * 还原时把每个栈的游标定位到最近一条已保存(`saved === true`)记录之后。
200
+ */
201
+ var deserializeStacks = (stacks = {}) => {
202
+ const result = {};
203
+ Object.entries(stacks).forEach(([id, serialized]) => {
204
+ if (serialized) result[id] = UndoRedo.fromSerialized(serialized, { isSavedStep: (element) => element.saved === true });
205
+ });
206
+ return result;
207
+ };
208
+ /**
209
+ * 按 id 从「按 id 分栈」的记录表(代码块 / 数据源)中获取(或创建)对应的 UndoRedo 栈。
210
+ */
211
+ var getOrCreateStack = (stacks, id) => {
212
+ if (!stacks[id]) stacks[id] = new UndoRedo();
213
+ return stacks[id];
214
+ };
215
+ /**
216
+ * 撤销下限:当页面栈 index 0 是 `opType: 'initial'` 的基线 step 时为 1(基线不可被撤销),否则为 0。
217
+ * 用于把 cursor 钉在基线之上,保证 undo / canUndo / goto 都不会越过初始基线。
218
+ */
219
+ var undoFloor = (undoRedo) => {
220
+ return undoRedo.getElementList()[0]?.opType === "initial" ? 1 : 0;
221
+ };
222
+ //#endregion
223
+ export { createStackStep, describeRevertStep, deserializeStacks, detectPageTargetId, detectPageTargetName, detectStackOpType, getOrCreateStack, markStackSaved, mergePageSteps, mergeStackSteps, serializeStacks, undoFloor };
@@ -0,0 +1,86 @@
1
+ //#region packages/editor/src/utils/indexed-db.ts
2
+ /**
3
+ * 一组极简的、基于原生 IndexedDB 的 Promise KV 工具,避免引入额外依赖。
4
+ * 仅用于浏览器环境;在不支持 IndexedDB 的环境(如 SSR / 部分测试环境)下会 reject。
5
+ */
6
+ /** 是否处于支持 IndexedDB 的环境。 */
7
+ var isIndexedDBSupported = () => typeof indexedDB !== "undefined" && indexedDB !== null;
8
+ /**
9
+ * 打开(必要时升级)数据库,确保目标 objectStore 存在后返回连接。
10
+ *
11
+ * 由于 objectStore 只能在 `onupgradeneeded` 内创建,这里先以当前版本打开,
12
+ * 若发现 store 不存在则关闭连接、以更高版本重开来按需创建,兼容动态 storeName。
13
+ */
14
+ var openIndexedDB = (dbName, storeName) => new Promise((resolve, reject) => {
15
+ if (!isIndexedDBSupported()) {
16
+ reject(/* @__PURE__ */ new Error("当前环境不支持 IndexedDB"));
17
+ return;
18
+ }
19
+ const request = indexedDB.open(dbName);
20
+ request.onupgradeneeded = () => {
21
+ const db = request.result;
22
+ if (!db.objectStoreNames.contains(storeName)) db.createObjectStore(storeName);
23
+ };
24
+ request.onerror = () => reject(request.error);
25
+ request.onsuccess = () => {
26
+ const db = request.result;
27
+ if (db.objectStoreNames.contains(storeName)) {
28
+ resolve(db);
29
+ return;
30
+ }
31
+ const nextVersion = db.version + 1;
32
+ db.close();
33
+ const upgradeRequest = indexedDB.open(dbName, nextVersion);
34
+ upgradeRequest.onupgradeneeded = () => {
35
+ const upgradeDb = upgradeRequest.result;
36
+ if (!upgradeDb.objectStoreNames.contains(storeName)) upgradeDb.createObjectStore(storeName);
37
+ };
38
+ upgradeRequest.onerror = () => reject(upgradeRequest.error);
39
+ upgradeRequest.onsuccess = () => resolve(upgradeRequest.result);
40
+ };
41
+ });
42
+ /** 写入(覆盖)一条记录。value 通过结构化克隆存储,支持 Map / Set 等结构。 */
43
+ var idbSet = async (dbName, storeName, key, value) => {
44
+ const db = await openIndexedDB(dbName, storeName);
45
+ try {
46
+ await new Promise((resolve, reject) => {
47
+ const tx = db.transaction(storeName, "readwrite");
48
+ tx.objectStore(storeName).put(value, key);
49
+ tx.oncomplete = () => resolve();
50
+ tx.onabort = () => reject(tx.error);
51
+ tx.onerror = () => reject(tx.error);
52
+ });
53
+ } finally {
54
+ db.close();
55
+ }
56
+ };
57
+ /** 读取一条记录,不存在时返回 undefined。 */
58
+ var idbGet = async (dbName, storeName, key) => {
59
+ const db = await openIndexedDB(dbName, storeName);
60
+ try {
61
+ return await new Promise((resolve, reject) => {
62
+ const request = db.transaction(storeName, "readonly").objectStore(storeName).get(key);
63
+ request.onsuccess = () => resolve(request.result);
64
+ request.onerror = () => reject(request.error);
65
+ });
66
+ } finally {
67
+ db.close();
68
+ }
69
+ };
70
+ /** 删除一条记录。 */
71
+ var idbDelete = async (dbName, storeName, key) => {
72
+ const db = await openIndexedDB(dbName, storeName);
73
+ try {
74
+ await new Promise((resolve, reject) => {
75
+ const tx = db.transaction(storeName, "readwrite");
76
+ tx.objectStore(storeName).delete(key);
77
+ tx.oncomplete = () => resolve();
78
+ tx.onabort = () => reject(tx.error);
79
+ tx.onerror = () => reject(tx.error);
80
+ });
81
+ } finally {
82
+ db.close();
83
+ }
84
+ };
85
+ //#endregion
86
+ export { idbDelete, idbGet, idbSet, isIndexedDBSupported, openIndexedDB };
@@ -1,6 +1,32 @@
1
1
  import { cloneDeep } from "lodash-es";
2
2
  //#region packages/editor/src/utils/undo-redo.ts
3
- var UndoRedo = class {
3
+ var UndoRedo = class UndoRedo {
4
+ /**
5
+ * 由 {@link UndoRedo.serialize} 产出的快照重建一个 UndoRedo 实例。
6
+ * 游标会被夹紧到 [0, length] 区间,避免脏数据导致越界。
7
+ *
8
+ * @param options.isSavedStep 可选谓词:若提供,则把游标定位到「最近一条满足该谓词的记录」之后
9
+ * (即恢复到最近一个已保存点);找不到匹配记录时退回快照中的原游标。
10
+ */
11
+ static fromSerialized(data, options = {}) {
12
+ const undoRedo = new UndoRedo(data.listMaxSize);
13
+ const list = Array.isArray(data.elementList) ? data.elementList.map((item) => cloneDeep(item)) : [];
14
+ let cursor = Number.isFinite(data.listCursor) ? data.listCursor : list.length;
15
+ const overflow = list.length - undoRedo.listMaxSize;
16
+ if (overflow > 0) {
17
+ list.splice(0, overflow);
18
+ cursor -= overflow;
19
+ }
20
+ if (options.isSavedStep) {
21
+ for (let i = list.length - 1; i >= 0; i--) if (options.isSavedStep(list[i])) {
22
+ cursor = i + 1;
23
+ break;
24
+ }
25
+ }
26
+ undoRedo.elementList = list;
27
+ undoRedo.listCursor = Math.max(0, Math.min(cursor, list.length));
28
+ return undoRedo;
29
+ }
4
30
  elementList;
5
31
  listCursor;
6
32
  listMaxSize;
@@ -10,6 +36,17 @@ var UndoRedo = class {
10
36
  this.listCursor = 0;
11
37
  this.listMaxSize = listMaxSize > minListMaxSize ? listMaxSize : minListMaxSize;
12
38
  }
39
+ /**
40
+ * 导出当前栈的可序列化快照(深克隆,避免外部改动污染内部状态)。
41
+ * 配合 {@link UndoRedo.fromSerialized} 可在持久化后完整还原撤销/重做栈。
42
+ */
43
+ serialize() {
44
+ return {
45
+ elementList: this.elementList.map((item) => cloneDeep(item)),
46
+ listCursor: this.listCursor,
47
+ listMaxSize: this.listMaxSize
48
+ };
49
+ }
13
50
  pushElement(element) {
14
51
  this.elementList.splice(this.listCursor, this.elementList.length - this.listCursor, cloneDeep(element));
15
52
  this.listCursor += 1;
@@ -42,6 +79,28 @@ var UndoRedo = class {
42
79
  return cloneDeep(this.elementList[this.listCursor - 1]);
43
80
  }
44
81
  /**
82
+ * 用 `element` 替换当前游标所在元素(cursor - 1),并丢弃其后的重做尾部(与 {@link pushElement} 的丢尾一致),
83
+ * 游标位置保持不变(元素数量不增)。cursor 为 0(无已应用元素)时不做任何操作并返回 false。
84
+ * 用于「连续同类记录合并」等就地替换最新一条的场景。
85
+ */
86
+ replaceCurrentElement(element) {
87
+ if (this.listCursor < 1) return false;
88
+ this.elementList.splice(this.listCursor - 1, this.elementList.length - (this.listCursor - 1), cloneDeep(element));
89
+ return true;
90
+ }
91
+ /**
92
+ * 对当前游标所在元素(cursor - 1)做就地更新;cursor 为 0(全部已撤销)时不做任何操作。
93
+ * 用于给「当前步骤」打标记(如标记为已保存)等元数据写入场景。
94
+ */
95
+ updateCurrentElement(updater) {
96
+ if (this.listCursor < 1) return;
97
+ updater(this.elementList[this.listCursor - 1]);
98
+ }
99
+ /** 对栈内全部元素做就地更新。用于批量清理元数据(如清空所有元素的已保存标记)。 */
100
+ updateElements(updater) {
101
+ this.elementList.forEach(updater);
102
+ }
103
+ /**
45
104
  * 返回栈内全部元素的浅克隆数组(按时间顺序,索引 0 为最早一步)。
46
105
  * 仅用于历史面板等只读展示场景,不应直接修改返回值。
47
106
  */