@tmagic/editor 1.8.2 → 1.8.3

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 (95) hide show
  1. package/dist/es/Editor.vue_vue_type_script_setup_true_lang.js +16 -24
  2. package/dist/es/fields/CondOpSelect.vue_vue_type_script_setup_true_lang.js +2 -2
  3. package/dist/es/fields/DataSourceFieldSelect/FieldSelect.vue_vue_type_script_setup_true_lang.js +1 -1
  4. package/dist/es/fields/DataSourceFieldSelect/Index.vue_vue_type_script_setup_true_lang.js +1 -1
  5. package/dist/es/fields/DataSourceFields.vue_vue_type_script_setup_true_lang.js +1 -1
  6. package/dist/es/fields/DataSourceInput.vue_vue_type_script_setup_true_lang.js +1 -1
  7. package/dist/es/fields/DataSourceMethodSelect.vue_vue_type_script_setup_true_name_true_lang.js +1 -1
  8. package/dist/es/fields/StyleSetter/configs.js +1 -1
  9. package/dist/es/fields/configs/codeSelect.js +5 -7
  10. package/dist/es/fields/configs/displayConds.js +8 -9
  11. package/dist/es/fields/configs/eventSelect.js +30 -27
  12. package/dist/es/hooks/use-stage.js +18 -18
  13. package/dist/es/index.js +9 -16
  14. package/dist/es/initService.js +33 -106
  15. package/dist/es/layouts/Framework.vue_vue_type_script_setup_true_lang.js +1 -1
  16. package/dist/es/layouts/props-panel/PropsPanel.vue_vue_type_script_setup_true_lang.js +2 -2
  17. package/dist/es/layouts/props-panel/use-style-panel.js +1 -1
  18. package/dist/es/sdk/index.js +151 -0
  19. package/dist/es/{services → sdk/services}/BaseService.js +1 -1
  20. package/dist/es/{services/codeBlock.js → sdk/services/CodeBlock.js} +37 -40
  21. package/dist/es/{services/componentList.js → sdk/services/ComponentList.js} +5 -6
  22. package/dist/es/{services/dataSource.js → sdk/services/DataSource.js} +38 -37
  23. package/dist/es/{services/dep.js → sdk/services/Dep.js} +24 -14
  24. package/dist/es/{services/editor.js → sdk/services/Editor.js} +124 -87
  25. package/dist/es/{services/events.js → sdk/services/Events.js} +13 -13
  26. package/dist/es/{services/history.js → sdk/services/History.js} +86 -33
  27. package/dist/es/{services/props.js → sdk/services/Props.js} +25 -26
  28. package/dist/es/{services/storage.js → sdk/services/WebStorage.js} +31 -8
  29. package/dist/es/sdk/utils/dep.js +100 -0
  30. package/dist/es/sdk/utils/operator.js +70 -0
  31. package/dist/es/sdk/utils/position.js +8 -0
  32. package/dist/es/sdk/utils/props.js +281 -0
  33. package/dist/es/sdk/validate/index.js +286 -0
  34. package/dist/es/sdk/wiring.js +163 -0
  35. package/dist/es/sdk.js +15 -0
  36. package/dist/es/services/keybinding.js +21 -21
  37. package/dist/es/services/sdk-instance.js +37 -0
  38. package/dist/es/services/stageOverlay.js +14 -14
  39. package/dist/es/services/ui.js +6 -6
  40. package/dist/es/utils/data-source/formConfigs/base.js +1 -1
  41. package/dist/es/utils/data-source/formConfigs/http.js +1 -1
  42. package/dist/es/utils/editor.js +2 -2
  43. package/dist/es/utils/event.js +25 -21
  44. package/dist/es/utils/operator.js +11 -57
  45. package/dist/es/utils/props.js +12 -282
  46. package/dist/es/utils/type-match-rules.js +10 -12
  47. package/dist/tmagic-editor-headless.umd.cjs +4690 -2891
  48. package/dist/tmagic-editor-sdk.umd.cjs +9911 -0
  49. package/dist/tmagic-editor.umd.cjs +14126 -13312
  50. package/package.json +12 -7
  51. package/src/Editor.vue +11 -9
  52. package/src/fields/configs/codeSelect.ts +6 -9
  53. package/src/fields/configs/displayConds.ts +10 -9
  54. package/src/fields/configs/eventSelect.ts +40 -25
  55. package/src/hooks/use-stage.ts +1 -1
  56. package/src/index.ts +11 -9
  57. package/src/initService.ts +59 -188
  58. package/src/layouts/Framework.vue +1 -1
  59. package/src/layouts/props-panel/PropsPanel.vue +1 -1
  60. package/src/layouts/props-panel/use-style-panel.ts +1 -1
  61. package/src/sdk/index.ts +264 -0
  62. package/src/{services/codeBlock.ts → sdk/services/CodeBlock.ts} +43 -38
  63. package/src/{services/componentList.ts → sdk/services/ComponentList.ts} +8 -7
  64. package/src/{services/dataSource.ts → sdk/services/DataSource.ts} +38 -32
  65. package/src/{services/dep.ts → sdk/services/Dep.ts} +24 -11
  66. package/src/{services/editor.ts → sdk/services/Editor.ts} +175 -86
  67. package/src/{services/events.ts → sdk/services/Events.ts} +15 -12
  68. package/src/{services/history.ts → sdk/services/History.ts} +100 -28
  69. package/src/{services/props.ts → sdk/services/Props.ts} +25 -25
  70. package/src/{services/storage.ts → sdk/services/WebStorage.ts} +41 -7
  71. package/src/sdk/type.ts +191 -0
  72. package/src/sdk/utils/dep.ts +196 -0
  73. package/src/sdk/utils/operator.ts +114 -0
  74. package/src/sdk/utils/position.ts +23 -0
  75. package/src/sdk/utils/props.ts +368 -0
  76. package/src/sdk/validate/index.ts +501 -0
  77. package/src/sdk/wiring.ts +211 -0
  78. package/src/sdk.ts +19 -0
  79. package/src/services/keybinding.ts +2 -2
  80. package/src/services/sdk-instance.ts +66 -0
  81. package/src/services/stageOverlay.ts +2 -2
  82. package/src/services/ui.ts +3 -3
  83. package/src/type.ts +9 -9
  84. package/src/utils/data-source/formConfigs/base.ts +1 -1
  85. package/src/utils/data-source/formConfigs/http.ts +1 -1
  86. package/src/utils/dep/collect-worker-client.ts +9 -6
  87. package/src/utils/dep/worker.ts +5 -0
  88. package/src/utils/editor.ts +2 -1
  89. package/src/utils/event.ts +36 -18
  90. package/src/utils/operator.ts +21 -87
  91. package/src/utils/props.ts +17 -332
  92. package/src/utils/type-match-rules.ts +1 -3
  93. package/types/index.d.ts +742 -528
  94. package/types/sdk.d.ts +2572 -0
  95. /package/src/{services → sdk/services}/BaseService.ts +0 -0
@@ -16,13 +16,11 @@
16
16
  * limitations under the License.
17
17
  */
18
18
 
19
- import { nextTick, reactive, toRaw } from 'vue';
20
19
  import { cloneDeep, isEmpty, isEqual, isObject, mergeWith, uniq } from 'lodash-es';
21
20
 
22
21
  import type { Id, MApp, MContainer, MNode, MPage, MPageFragment, TargetOptions } from '@tmagic/core';
23
22
  import { NodeType } from '@tmagic/core';
24
23
  import type { ChangeRecord } from '@tmagic/form';
25
- import { isFixed } from '@tmagic/stage';
26
24
  import {
27
25
  getNodeInfo,
28
26
  getNodePath,
@@ -35,14 +33,11 @@ import {
35
33
  traverseNode,
36
34
  } from '@tmagic/utils';
37
35
 
38
- import BaseService from '@editor/services//BaseService';
39
- import propsService from '@editor/services//props';
40
- import historyService from '@editor/services/history';
41
- import storageService, { Protocol } from '@editor/services/storage';
42
36
  import type {
43
37
  AddMNode,
44
38
  AsyncHookPlugin,
45
39
  AsyncMethodName,
40
+ CanDropInFunction,
46
41
  DslOpOptions,
47
42
  DslOpWithHistoryIdsResult,
48
43
  EditorEvents,
@@ -80,7 +75,13 @@ import {
80
75
  toggleFixedPosition,
81
76
  } from '@editor/utils/editor';
82
77
  import { getLastPushedHistoryIds } from '@editor/utils/history';
83
- import { beforePaste, getAddParent } from '@editor/utils/operator';
78
+
79
+ import type { SdkContext } from '../type';
80
+ import { beforePaste, getAddParent } from '../utils/operator';
81
+ import { isFixed } from '../utils/position';
82
+
83
+ import BaseService from './BaseService';
84
+ import { Protocol } from './WebStorage';
84
85
 
85
86
  type MoveItem = { node: MNode; parent: MContainer; pageForOp: { name: string; id: Id } | null };
86
87
 
@@ -102,23 +103,13 @@ const buildUpdateDiff = (
102
103
  ...(changeRecords?.length ? { changeRecords } : {}),
103
104
  }));
104
105
 
106
+ export interface EditorServiceConfig {
107
+ disabledPageFragment?: boolean;
108
+ canDropIn?: CanDropInFunction;
109
+ }
110
+
105
111
  class Editor extends BaseService {
106
- public state: StoreState = reactive({
107
- root: null,
108
- page: null,
109
- parent: null,
110
- node: null,
111
- nodes: [],
112
- stage: null,
113
- stageLoading: true,
114
- highlightNode: null,
115
- modifiedNodeIds: new Map(),
116
- invalidNodeIds: new Map(),
117
- pageLength: 0,
118
- pageFragmentLength: 0,
119
- disabledMultiSelect: false,
120
- alwaysMultiSelect: false,
121
- });
112
+ public state: StoreState;
122
113
  private selectionBeforeOp: Id[] | null = null;
123
114
  /**
124
115
  * 操作前的节点校验错误快照,与 selectionBeforeOp 同时在 captureSelectionBeforeOp 中捕获,
@@ -137,12 +128,32 @@ class Editor extends BaseService {
137
128
  */
138
129
  private lastAdded: { selectedId: Id; nodeId: Id } | null = null;
139
130
 
140
- constructor() {
131
+ /** 与编辑器 props 中 `disabledPageFragment` / `canDropIn` 对应,供结构合法性校验使用 */
132
+ private config: EditorServiceConfig = {};
133
+
134
+ constructor(private ctx: SdkContext) {
141
135
  super(
142
136
  canUsePluginMethods.async.map((methodName) => ({ name: methodName, isAsync: true })),
143
137
  // 需要注意循环依赖问题,如果函数间有相互调用的话,不能设置为串行调用
144
138
  ['select', 'update', 'moveLayer'],
145
139
  );
140
+
141
+ this.state = ctx.reactivity.reactive<StoreState>({
142
+ root: null,
143
+ page: null,
144
+ parent: null,
145
+ node: null,
146
+ nodes: [],
147
+ stage: null,
148
+ stageLoading: true,
149
+ highlightNode: null,
150
+ modifiedNodeIds: new Map(),
151
+ invalidNodeIds: new Map(),
152
+ pageLength: 0,
153
+ pageFragmentLength: 0,
154
+ disabledMultiSelect: false,
155
+ alwaysMultiSelect: false,
156
+ });
146
157
  }
147
158
 
148
159
  /**
@@ -185,8 +196,8 @@ class Editor extends BaseService {
185
196
  // 重复创建,set root 不额外产生记录,由恢复出的历史栈作为当前状态来源。
186
197
  // 标记不进入撤销/重做栈,仅作为该页历史列表底部的初始基线展示。
187
198
  app.items?.forEach((pageNode) => {
188
- if (pageNode?.id !== undefined && !historyService.getMarker('page', pageNode.id)) {
189
- historyService.setMarker('page', pageNode.id, {
199
+ if (pageNode?.id !== undefined && !this.ctx.history.getMarker('page', pageNode.id)) {
200
+ this.ctx.history.setMarker('page', pageNode.id, {
190
201
  name: pageNode.name,
191
202
  source: options.historySource,
192
203
  });
@@ -224,7 +235,7 @@ class Editor extends BaseService {
224
235
  public getNodeInfo(id: Id, raw = true): EditorNodeInfo {
225
236
  let root = this.get('root');
226
237
  if (raw) {
227
- root = toRaw(root);
238
+ root = this.toRaw(root);
228
239
  }
229
240
 
230
241
  if (!root) {
@@ -340,11 +351,11 @@ class Editor extends BaseService {
340
351
  }
341
352
 
342
353
  public async selectNextNode(): Promise<MNode | null> | never {
343
- const node = toRaw(this.get('node'));
354
+ const node = this.toRaw(this.get('node'));
344
355
 
345
356
  if (!node || isPage(node) || node.type === NodeType.ROOT) return node;
346
357
 
347
- const parent = toRaw(this.getParentById(node.id));
358
+ const parent = this.toRaw(this.getParentById(node.id));
348
359
 
349
360
  if (!parent) return node;
350
361
 
@@ -359,8 +370,8 @@ class Editor extends BaseService {
359
370
  }
360
371
 
361
372
  public async selectNextPage(): Promise<MNode> | never {
362
- const root = toRaw(this.get('root'));
363
- const page = toRaw(this.get('page'));
373
+ const root = this.toRaw(this.get('root'));
374
+ const page = this.toRaw(this.get('page'));
364
375
 
365
376
  if (!page) throw new Error('page不能为空');
366
377
  if (!root) throw new Error('root不能为空');
@@ -414,6 +425,15 @@ class Editor extends BaseService {
414
425
  this.set('highlightNode', null);
415
426
  }
416
427
 
428
+ /** 设置结构合法性校验用到的配置,只覆盖传入的字段 */
429
+ public setConfig(config: Partial<EditorServiceConfig>): void {
430
+ this.config = { ...this.config, ...config };
431
+ }
432
+
433
+ public getConfig(): Readonly<EditorServiceConfig> {
434
+ return this.config;
435
+ }
436
+
417
437
  public async doAdd(node: MNode, parent: MContainer, _options: DslOpOptions = {}): Promise<MNode> {
418
438
  const root = this.get('root');
419
439
 
@@ -439,7 +459,7 @@ class Editor extends BaseService {
439
459
  parent.items.splice(insertIndex, 0, node);
440
460
  this.lastAdded = { selectedId: curNode.id, nodeId: node.id };
441
461
 
442
- const layout = await this.getLayout(toRaw(parent), node as MNode);
462
+ const layout = await this.getLayout(this.toRaw(parent), node as MNode);
443
463
  node.style = getInitPositionStyle(node.style, layout);
444
464
 
445
465
  await stage?.add({
@@ -493,7 +513,7 @@ class Editor extends BaseService {
493
513
 
494
514
  if (!type) throw new Error('组件类型不能为空');
495
515
 
496
- addNodes.push({ ...toRaw(await propsService.getPropsValue(type, config)) });
516
+ addNodes.push({ ...this.toRaw(await this.ctx.props.getPropsValue(type, config)) });
497
517
  } else {
498
518
  addNodes.push(...addNode);
499
519
  }
@@ -501,13 +521,24 @@ class Editor extends BaseService {
501
521
  // 必须串行:每个节点的插入位置依赖上一个已插入的节点,并行时插入顺序会受
502
522
  // doAdd 前置耗时(如异步 beforeDoAdd 插件钩子)影响而错乱
503
523
  const newNodes: MNode[] = [];
524
+ const targets: { node: MNode; parentNode: MContainer }[] = [];
504
525
  for (const node of addNodes) {
505
526
  const root = this.get('root');
506
- const parentNode = isPageOrFragment(node) && root ? root : (parent ?? getAddParent(node));
527
+ const parentNode = isPageOrFragment(node) && root ? root : (parent ?? getAddParent(this.ctx, node));
507
528
  if (!parentNode) throw new Error('未找到父元素');
529
+ targets.push({ node, parentNode });
530
+ }
531
+
532
+ // 校验放在真正修改 DSL 之前,strict 模式下校验不通过则整批都不会被添加
533
+ const commitInvalid = await this.runGuard(() => this.ctx.validator.guardAdd(targets));
534
+
535
+ for (const { node, parentNode } of targets) {
508
536
  newNodes.push(await this.doAdd(node, parentNode, options));
509
537
  }
510
538
 
539
+ // record 模式:在写入历史记录之前落库,使历史快照包含本次的错误状态
540
+ commitInvalid?.();
541
+
511
542
  if (newNodes.length > 1) {
512
543
  // 多选时只要任一新增节点位于非当前页面,触发的 multiSelect 就会引起页面切换
513
544
  const wouldSwitchPage = newNodes.some((n) => this.isOnDifferentPage(n));
@@ -544,7 +575,7 @@ class Editor extends BaseService {
544
575
  const p = this.getParentById(n.id, false) as MContainer;
545
576
  const idx = p ? getNodeIndex(n.id, p) : -1;
546
577
  return {
547
- newSchema: cloneDeep(toRaw(n)),
578
+ newSchema: cloneDeep(this.toRaw(n)),
548
579
  parentId,
549
580
  index: typeof idx === 'number' ? idx : -1,
550
581
  };
@@ -569,7 +600,7 @@ class Editor extends BaseService {
569
600
  // 页面 / 页面片新增不入历史栈(见上方 isPageOrFragment 分支),这里合并补发一次结构变更通知
570
601
  const addedPages = newNodes.filter((node) => isPageOrFragment(node)) as (MPage | MPageFragment)[];
571
602
  if (addedPages.length) {
572
- historyService.notifyPageStructureChange({ add: addedPages, remove: [] });
603
+ this.ctx.history.notifyPageStructureChange({ add: addedPages, remove: [] });
573
604
  }
574
605
 
575
606
  return Array.isArray(addNode) ? newNodes : newNodes[0];
@@ -626,7 +657,7 @@ class Editor extends BaseService {
626
657
  // nextTick 用于等 Stage 的 page watch 把新页面 id 同步给 runtime。
627
658
  await this.select(rootItems[0]);
628
659
  stage?.select(rootItems[0].id);
629
- await nextTick();
660
+ await this.ctx.reactivity.nextTick();
630
661
  stage?.remove(removeData);
631
662
  } else {
632
663
  // page 置空会让 Workspace 卸载 Stage 并销毁 renderer,删除通知必须在卸载前发出,
@@ -653,7 +684,7 @@ class Editor extends BaseService {
653
684
 
654
685
  if (!rootItems.length) {
655
686
  this.resetModifiedNodeId();
656
- historyService.reset();
687
+ this.ctx.history.reset();
657
688
  }
658
689
  }
659
690
 
@@ -685,7 +716,7 @@ class Editor extends BaseService {
685
716
  }
686
717
  const idx = getNodeIndex(curNode.id, parent);
687
718
  removedItems.push({
688
- oldSchema: cloneDeep(toRaw(curNode)),
719
+ oldSchema: cloneDeep(this.toRaw(curNode)),
689
720
  parentId: parent.id,
690
721
  index: typeof idx === 'number' ? idx : -1,
691
722
  });
@@ -717,7 +748,7 @@ class Editor extends BaseService {
717
748
  // 页面 / 页面片删除不入历史栈(见上方 isPageOrFragment 分支),这里合并补发一次结构变更通知
718
749
  const removedPages = nodes.filter((node) => isPageOrFragment(node)) as (MPage | MPageFragment)[];
719
750
  if (removedPages.length) {
720
- historyService.notifyPageStructureChange({ add: [], remove: removedPages });
751
+ this.ctx.history.notifyPageStructureChange({ add: [], remove: removedPages });
721
752
  }
722
753
  }
723
754
 
@@ -735,12 +766,12 @@ class Editor extends BaseService {
735
766
 
736
767
  if (!info.node) throw new Error(`获取不到id为${config.id}的节点`);
737
768
 
738
- const node = toRaw(info.node);
769
+ const node = this.toRaw(info.node);
739
770
 
740
771
  // replace=true 时跳过 toggleFixedPosition / mergeWith / setChildrenLayout,直接用传入配置整节点替换
741
772
  let newConfig = replace
742
- ? cloneDeep(toRaw(config))
743
- : await toggleFixedPosition(toRaw(config), node, info.path, this.getLayout);
773
+ ? cloneDeep(this.toRaw(config))
774
+ : await toggleFixedPosition(this.toRaw(config), node, info.path, this.getLayout);
744
775
 
745
776
  if (!replace) {
746
777
  newConfig = mergeWith(cloneDeep(node), newConfig, editorNodeMergeCustomizer);
@@ -821,6 +852,8 @@ class Editor extends BaseService {
821
852
 
822
853
  const nodes = Array.isArray(config) ? config : [config];
823
854
 
855
+ const commitInvalid = await this.runGuard(() => this.ctx.validator.guardUpdate(nodes, { replace: data.replace }));
856
+
824
857
  // 多节点必须使用 changeRecordList 为每个节点提供独立的记录;
825
858
  // 否则同一份 changeRecords 会被复用到每个节点上,nodeUpdateHandler / 历史回放都会按错误的 propPath 处理。
826
859
  const updateData = await Promise.all(
@@ -832,6 +865,7 @@ class Editor extends BaseService {
832
865
 
833
866
  // 校验错误信息在 pushOpHistory 之前落库,保证历史快照包含本次变更对应的错误状态。
834
867
  this.applyInvalidInfo(config, invalidInfo);
868
+ commitInvalid?.();
835
869
 
836
870
  if (updateData[0].oldNode?.type !== NodeType.ROOT) {
837
871
  const curNodes = this.get('nodes');
@@ -891,7 +925,7 @@ class Editor extends BaseService {
891
925
  const node = this.get('node');
892
926
  if (!node) throw new Error('当前节点为空');
893
927
 
894
- const parent = cloneDeep(toRaw(this.get('parent')));
928
+ const parent = cloneDeep(this.toRaw(this.get('parent')));
895
929
  if (!parent) throw new Error('父节点为空');
896
930
 
897
931
  const index2 = parent.items.findIndex((node: MNode) => `${node.id}` === `${id2}`);
@@ -919,7 +953,7 @@ class Editor extends BaseService {
919
953
  * @returns
920
954
  */
921
955
  public copy(config: MNode | MNode[]): void {
922
- storageService.setItem(COPY_STORAGE_KEY, Array.isArray(config) ? config : [config], {
956
+ this.ctx.storage.setItem(COPY_STORAGE_KEY, Array.isArray(config) ? config : [config], {
923
957
  protocol: Protocol.OBJECT,
924
958
  });
925
959
  }
@@ -936,7 +970,7 @@ class Editor extends BaseService {
936
970
  collectRelatedNodes(copyNodes, collectorOptions, (id) => this.getNodeById(id));
937
971
  }
938
972
 
939
- storageService.setItem(COPY_STORAGE_KEY, copyNodes, {
973
+ this.ctx.storage.setItem(COPY_STORAGE_KEY, copyNodes, {
940
974
  protocol: Protocol.OBJECT,
941
975
  });
942
976
  }
@@ -962,7 +996,7 @@ class Editor extends BaseService {
962
996
  historySource,
963
997
  }: DslOpOptions = {},
964
998
  ): Promise<MNode | MNode[] | void> {
965
- const config: MNode[] = storageService.getItem(COPY_STORAGE_KEY);
999
+ const config: MNode[] = this.ctx.storage.getItem(COPY_STORAGE_KEY);
966
1000
  if (!Array.isArray(config)) return;
967
1001
 
968
1002
  const node = this.get('node');
@@ -978,7 +1012,7 @@ class Editor extends BaseService {
978
1012
  const pasteConfigs = await this.doPaste(config, position);
979
1013
 
980
1014
  if (collectorOptions && typeof collectorOptions.isTarget === 'function') {
981
- propsService.replaceRelateId(config, pasteConfigs, collectorOptions);
1015
+ this.ctx.props.replaceRelateId(config, pasteConfigs, collectorOptions);
982
1016
  }
983
1017
 
984
1018
  return this.add(pasteConfigs, parent, {
@@ -991,9 +1025,9 @@ class Editor extends BaseService {
991
1025
  }
992
1026
 
993
1027
  public async doPaste(config: MNode[], position: PastePosition = {}): Promise<MNode[]> {
994
- propsService.clearRelateId();
1028
+ this.ctx.props.clearRelateId();
995
1029
  const doc = this.get('stage')?.renderer?.contentWindow?.document;
996
- const pasteConfigs = beforePaste(position, cloneDeep(config), doc);
1030
+ const pasteConfigs = beforePaste(this.ctx, position, cloneDeep(config), doc);
997
1031
  return pasteConfigs;
998
1032
  }
999
1033
 
@@ -1001,7 +1035,7 @@ class Editor extends BaseService {
1001
1035
  const parent = this.getParentById(config.id);
1002
1036
  if (!parent) throw new Error('找不到父节点');
1003
1037
 
1004
- const node = cloneDeep(toRaw(config));
1038
+ const node = cloneDeep(this.toRaw(config));
1005
1039
  const layout = await this.getLayout(parent, node);
1006
1040
  const doc = this.get('stage')?.renderer?.contentWindow?.document;
1007
1041
  const newStyle = calcAlignCenterStyle(node, parent, layout, doc);
@@ -1030,7 +1064,11 @@ class Editor extends BaseService {
1030
1064
 
1031
1065
  const newNodes = await Promise.all(nodes.map((node) => this.doAlignCenter(node)));
1032
1066
 
1033
- const newNode = await this.update(newNodes, { doNotPushHistory, historyDescription, historySource });
1067
+ const newNode = await this.update(newNodes, {
1068
+ doNotPushHistory,
1069
+ historyDescription,
1070
+ historySource,
1071
+ });
1034
1072
 
1035
1073
  if (!doNotSelect) {
1036
1074
  if (newNodes.length > 1) {
@@ -1075,7 +1113,7 @@ class Editor extends BaseService {
1075
1113
  return;
1076
1114
  }
1077
1115
 
1078
- const oldParent = cloneDeep(toRaw(parent));
1116
+ const oldParent = cloneDeep(this.toRaw(parent));
1079
1117
 
1080
1118
  brothers.splice(index, 1);
1081
1119
  brothers.splice(offsetIndex, 0, node);
@@ -1083,7 +1121,7 @@ class Editor extends BaseService {
1083
1121
  const grandparent = this.getParentById(parent.id);
1084
1122
 
1085
1123
  this.get('stage')?.update({
1086
- config: cloneDeep(toRaw(parent)),
1124
+ config: cloneDeep(this.toRaw(parent)),
1087
1125
  parentId: grandparent?.id,
1088
1126
  root: cloneDeep(root),
1089
1127
  });
@@ -1095,7 +1133,7 @@ class Editor extends BaseService {
1095
1133
  'update',
1096
1134
 
1097
1135
  {
1098
- diff: buildUpdateDiff([{ oldNode: oldParent, newNode: cloneDeep(toRaw(parent)) }]),
1136
+ diff: buildUpdateDiff([{ oldNode: oldParent, newNode: cloneDeep(this.toRaw(parent)) }]),
1099
1137
  pageData: { name: pageForOp?.name || '', id: pageForOp!.id },
1100
1138
  historyDescription,
1101
1139
  source: historySource,
@@ -1156,12 +1194,20 @@ class Editor extends BaseService {
1156
1194
  }
1157
1195
 
1158
1196
  const root = this.get('root');
1159
- const stage = this.get('stage');
1160
1197
 
1161
- if (!root || !stage) {
1162
- throw new Error('root 或 stage为空');
1198
+ if (!root) {
1199
+ throw new Error('root 为空');
1163
1200
  }
1164
1201
 
1202
+ // 校验放在过滤之前:源节点不存在也要作为校验错误报出
1203
+ await this.runGuard(() =>
1204
+ this.ctx.validator.guardMove(
1205
+ configs.map((item) => item.id),
1206
+ target,
1207
+ 'stage-drag',
1208
+ ),
1209
+ );
1210
+
1165
1211
  // 收集 (节点, 源父) 信息,过滤掉异常节点(找不到父或源父等于目标本身)
1166
1212
  const moves: MoveItem[] = [];
1167
1213
  for (const { id } of configs) {
@@ -1176,10 +1222,10 @@ class Editor extends BaseService {
1176
1222
 
1177
1223
  // 记录所有涉及的源父容器(按 id 去重)+ 目标容器的前置快照;同一父容器只快照一次。
1178
1224
  const beforeSnapshots = new Map<Id, MNode>();
1179
- beforeSnapshots.set(target.id, cloneDeep(toRaw(target)));
1225
+ beforeSnapshots.set(target.id, cloneDeep(this.toRaw(target)));
1180
1226
  for (const { parent } of moves) {
1181
1227
  if (!beforeSnapshots.has(parent.id)) {
1182
- beforeSnapshots.set(parent.id, cloneDeep(toRaw(parent)));
1228
+ beforeSnapshots.set(parent.id, cloneDeep(this.toRaw(parent)));
1183
1229
  }
1184
1230
  }
1185
1231
 
@@ -1198,7 +1244,7 @@ class Editor extends BaseService {
1198
1244
  // 整批只入栈一条历史:updatedItems 包含所有源父容器 + 目标容器的前后快照(撤销/重做最小依赖)。
1199
1245
  const updatedItems = Array.from(beforeSnapshots.entries()).map(([id, oldNode]) => ({
1200
1246
  oldNode,
1201
- newNode: cloneDeep(toRaw(this.getNodeById(id, false))) as MNode,
1247
+ newNode: cloneDeep(this.toRaw(this.getNodeById(id, false))) as MNode,
1202
1248
  }));
1203
1249
  const historyPage = moves[0].pageForOp ?? { name: '', id: target.id };
1204
1250
  this.pushOpHistory('update', {
@@ -1226,15 +1272,23 @@ class Editor extends BaseService {
1226
1272
 
1227
1273
  const configs = Array.isArray(config) ? config : [config];
1228
1274
 
1275
+ await this.runGuard(() =>
1276
+ this.ctx.validator.guardMove(
1277
+ configs.map((item) => item.id),
1278
+ targetParent,
1279
+ 'layer',
1280
+ ),
1281
+ );
1282
+
1229
1283
  const beforeSnapshots = new Map<string, MNode>();
1230
1284
  for (const cfg of configs) {
1231
1285
  const { parent } = this.getNodeInfo(cfg.id, false);
1232
1286
  if (parent && !beforeSnapshots.has(`${parent.id}`)) {
1233
- beforeSnapshots.set(`${parent.id}`, cloneDeep(toRaw(parent)));
1287
+ beforeSnapshots.set(`${parent.id}`, cloneDeep(this.toRaw(parent)));
1234
1288
  }
1235
1289
  }
1236
1290
  if (!beforeSnapshots.has(`${targetParent.id}`)) {
1237
- beforeSnapshots.set(`${targetParent.id}`, cloneDeep(toRaw(targetParent)));
1291
+ beforeSnapshots.set(`${targetParent.id}`, cloneDeep(this.toRaw(targetParent)));
1238
1292
  }
1239
1293
 
1240
1294
  const newLayout = await this.getLayout(targetParent);
@@ -1276,7 +1330,7 @@ class Editor extends BaseService {
1276
1330
  for (const oldNode of beforeSnapshots.values()) {
1277
1331
  const newNode = this.getNodeById(oldNode.id, false);
1278
1332
  if (newNode) {
1279
- updatedItems.push({ oldNode, newNode: cloneDeep(toRaw(newNode)) });
1333
+ updatedItems.push({ oldNode, newNode: cloneDeep(this.toRaw(newNode)) });
1280
1334
  }
1281
1335
  }
1282
1336
  if (!doNotPushHistory) {
@@ -1383,7 +1437,7 @@ class Editor extends BaseService {
1383
1437
  public async undo(): Promise<StepValue | null> {
1384
1438
  const pageId = this.get('page')?.id;
1385
1439
  if (pageId === undefined) return null;
1386
- const value = historyService.undo('page', pageId);
1440
+ const value = this.ctx.history.undo('page', pageId);
1387
1441
  if (value) {
1388
1442
  await this.applyHistoryOp(value, true);
1389
1443
  }
@@ -1397,7 +1451,7 @@ class Editor extends BaseService {
1397
1451
  public async redo(): Promise<StepValue | null> {
1398
1452
  const pageId = this.get('page')?.id;
1399
1453
  if (pageId === undefined) return null;
1400
- const value = historyService.redo('page', pageId);
1454
+ const value = this.ctx.history.redo('page', pageId);
1401
1455
  if (value) {
1402
1456
  await this.applyHistoryOp(value, false);
1403
1457
  }
@@ -1421,7 +1475,7 @@ class Editor extends BaseService {
1421
1475
  * @returns 反向后产生的新 step;目标不存在 / 未应用 / 反向失败时返回 null
1422
1476
  */
1423
1477
  public async revertPageStep(index: number): Promise<StepValue | null> {
1424
- const list = historyService.getStepList('page', this.get('page')?.id);
1478
+ const list = this.ctx.history.getStepList('page', this.get('page')?.id);
1425
1479
  const entry = list[index];
1426
1480
  if (!entry?.applied) return null;
1427
1481
 
@@ -1443,11 +1497,16 @@ class Editor extends BaseService {
1443
1497
  const captureRevert = (_pageId: Id, s: StepValue) => {
1444
1498
  revertedStep = s;
1445
1499
  };
1446
- historyService.once('change', captureRevert);
1500
+ this.ctx.history.once('change', captureRevert);
1447
1501
 
1448
1502
  const historyDescription = `回滚 #${index + 1}: ${describeStepForRevert(step)}`;
1449
1503
  // revert 走 public add/remove/update,让操作以一条普通新 step 入栈;不要切换选区与页面,避免打断用户。
1450
- const opts = { doNotSelect: true, doNotSwitchPage: true, historyDescription, historySource: 'rollback' } as const;
1504
+ const opts = {
1505
+ doNotSelect: true,
1506
+ doNotSwitchPage: true,
1507
+ historyDescription,
1508
+ historySource: 'rollback',
1509
+ } as const;
1451
1510
 
1452
1511
  try {
1453
1512
  switch (step.opType) {
@@ -1506,11 +1565,11 @@ class Editor extends BaseService {
1506
1565
  }
1507
1566
  }
1508
1567
  } finally {
1509
- historyService.off('change', captureRevert);
1568
+ this.ctx.history.off('change', captureRevert);
1510
1569
  }
1511
1570
 
1512
1571
  // 通知一次 history-change,让上层(如属性面板)按当前最新 DSL 刷新
1513
- const page = toRaw(this.get('page'));
1572
+ const page = this.toRaw(this.get('page'));
1514
1573
  if (page) {
1515
1574
  this.emit('history-change', page as MPage | MPageFragment);
1516
1575
  }
@@ -1529,7 +1588,7 @@ class Editor extends BaseService {
1529
1588
  const results: (StepValue | null)[] = [];
1530
1589
  const pageId = this.get('page')?.id;
1531
1590
  for (const uuid of uuids) {
1532
- const location = historyService.findStepLocationByUuid('page', uuid, pageId);
1591
+ const location = this.ctx.history.findStepLocationByUuid('page', uuid, pageId);
1533
1592
  results.push(!location ? null : await this.revertPageStep(location.index));
1534
1593
  }
1535
1594
  return results;
@@ -1546,8 +1605,8 @@ class Editor extends BaseService {
1546
1605
  */
1547
1606
  public async gotoPageStep(targetCursor: number): Promise<number> {
1548
1607
  const pageId = this.get('page')?.id;
1549
- let cursor = historyService.getCursor('page', pageId);
1550
- const { length } = historyService.getStepList('page', pageId);
1608
+ let cursor = this.ctx.history.getCursor('page', pageId);
1609
+ const { length } = this.ctx.history.getStepList('page', pageId);
1551
1610
  const target = Math.max(0, Math.min(targetCursor, length));
1552
1611
  while (cursor > target) {
1553
1612
  const step = await this.undo();
@@ -1567,7 +1626,7 @@ class Editor extends BaseService {
1567
1626
  top: number,
1568
1627
  { doNotPushHistory = false, historyDescription, historySource }: DslOpOptions = {},
1569
1628
  ) {
1570
- const node = toRaw(this.get('node'));
1629
+ const node = this.toRaw(this.get('node'));
1571
1630
  if (!node || isPage(node)) return;
1572
1631
 
1573
1632
  const newStyle = calcMoveStyle(node.style || {}, left, top);
@@ -1760,6 +1819,20 @@ class Editor extends BaseService {
1760
1819
  return null;
1761
1820
  }
1762
1821
 
1822
+ /**
1823
+ * 执行校验。校验不通过(strict 抛错)时操作不会继续,必须清掉 captureSelectionBeforeOp 留下的快照,
1824
+ * 否则下一次成功的操作会沿用这份过期快照,写出错误的 selectedBefore / invalidNodeIdsBefore。
1825
+ */
1826
+ private async runGuard<T>(guard: () => Promise<T>): Promise<T> {
1827
+ try {
1828
+ return await guard();
1829
+ } catch (e) {
1830
+ this.selectionBeforeOp = null;
1831
+ this.invalidNodeIdsBeforeOp = null;
1832
+ throw e;
1833
+ }
1834
+ }
1835
+
1763
1836
  private captureSelectionBeforeOp() {
1764
1837
  if (this.selectionBeforeOp) return;
1765
1838
  this.selectionBeforeOp = this.get('nodes').map((n) => n.id);
@@ -1794,15 +1867,22 @@ class Editor extends BaseService {
1794
1867
  this.pushPageDiffStep(
1795
1868
  'add',
1796
1869
  nextPage,
1797
- { newSchema: cloneDeep(toRaw(nextPage)), parentId: nextRoot.id, index: indexInItems(nextRoot, nextPage.id) },
1870
+ {
1871
+ newSchema: cloneDeep(this.toRaw(nextPage)),
1872
+ parentId: nextRoot.id,
1873
+ index: indexInItems(nextRoot, nextPage.id),
1874
+ },
1798
1875
  source,
1799
1876
  );
1800
1877
  addedPages.push(nextPage);
1801
- } else if (!isEqual(toRaw(prevPage), toRaw(nextPage))) {
1878
+ } else if (!isEqual(this.toRaw(prevPage), this.toRaw(nextPage))) {
1802
1879
  this.pushPageDiffStep(
1803
1880
  'update',
1804
1881
  nextPage,
1805
- { oldSchema: cloneDeep(toRaw(prevPage)), newSchema: cloneDeep(toRaw(nextPage)) },
1882
+ {
1883
+ oldSchema: cloneDeep(this.toRaw(prevPage)),
1884
+ newSchema: cloneDeep(this.toRaw(nextPage)),
1885
+ },
1806
1886
  source,
1807
1887
  );
1808
1888
  }
@@ -1813,7 +1893,11 @@ class Editor extends BaseService {
1813
1893
  this.pushPageDiffStep(
1814
1894
  'remove',
1815
1895
  prevPage,
1816
- { oldSchema: cloneDeep(toRaw(prevPage)), parentId: preRoot.id, index: indexInItems(preRoot, prevPage.id) },
1896
+ {
1897
+ oldSchema: cloneDeep(this.toRaw(prevPage)),
1898
+ parentId: preRoot.id,
1899
+ index: indexInItems(preRoot, prevPage.id),
1900
+ },
1817
1901
  source,
1818
1902
  );
1819
1903
  removedPages.push(prevPage);
@@ -1821,7 +1905,7 @@ class Editor extends BaseService {
1821
1905
  });
1822
1906
 
1823
1907
  if (addedPages.length || removedPages.length) {
1824
- historyService.notifyPageStructureChange({ add: addedPages, remove: removedPages });
1908
+ this.ctx.history.notifyPageStructureChange({ add: addedPages, remove: removedPages });
1825
1909
  }
1826
1910
  }
1827
1911
 
@@ -1852,11 +1936,11 @@ class Editor extends BaseService {
1852
1936
  };
1853
1937
  if (source) step.source = source;
1854
1938
 
1855
- const top = historyService.getCurrentPageStep(page.id);
1939
+ const top = this.ctx.history.getCurrentPageStep(page.id);
1856
1940
  if (top?.rootStep && top.source === source) {
1857
- historyService.replaceCurrentStep('page', step, page.id);
1941
+ this.ctx.history.replaceCurrentStep('page', step, page.id);
1858
1942
  } else {
1859
- historyService.push('page', step, page.id);
1943
+ this.ctx.history.push('page', step, page.id);
1860
1944
  }
1861
1945
  }
1862
1946
 
@@ -1892,7 +1976,7 @@ class Editor extends BaseService {
1892
1976
  if (source) step.source = source;
1893
1977
  // 显式按 step.data.id 入栈:跨页操作(如 moveToContainer 从源页搬到目标页)
1894
1978
  // 必须落到正确的页面栈,否则会把记录错误地推到当前活动页 / 操作发起页。
1895
- const pushed = historyService.push('page', step, pageData.id);
1979
+ const pushed = this.ctx.history.push('page', step, pageData.id);
1896
1980
  // push 返回 null 表示当前没有可写入的页面栈(未真正入栈),此时不应返回 uuid。
1897
1981
  const historyId = pushed ? step.uuid : null;
1898
1982
  this.lastPushedHistoryId = historyId;
@@ -2051,7 +2135,7 @@ class Editor extends BaseService {
2051
2135
  this.set('invalidNodeIds', new Map(invalidToRestore));
2052
2136
  this.emit('invalid-node-change', this.get('invalidNodeIds'));
2053
2137
 
2054
- const page = toRaw(this.get('page'));
2138
+ const page = this.toRaw(this.get('page'));
2055
2139
  if (page) {
2056
2140
  const selectIds = (reverse ? step.extra?.selectedBefore : step.extra?.selectedAfter) ?? [];
2057
2141
  setTimeout(() => {
@@ -2089,8 +2173,13 @@ class Editor extends BaseService {
2089
2173
  doNotPushHistory: true,
2090
2174
  });
2091
2175
  }
2176
+
2177
+ /** 经由 reactivity 注入的 toRaw(默认是 Vue 的 toRaw) */
2178
+ private toRaw<T>(value: T): T {
2179
+ return this.ctx.reactivity.toRaw(value);
2180
+ }
2092
2181
  }
2093
2182
 
2094
2183
  export type EditorService = Editor;
2095
2184
 
2096
- export default new Editor();
2185
+ export default Editor;