@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
@@ -1,17 +1,14 @@
1
- import { Layout, canUsePluginMethods } from "../type.js";
1
+ import { Layout, canUsePluginMethods } from "../../type.js";
2
+ import { isFixed } from "../utils/position.js";
3
+ import { COPY_STORAGE_KEY, calcAlignCenterStyle, calcLayerTargetIndex, calcMoveStyle, classifyDragSources, collectRelatedNodes, describeStepForRevert, editorNodeMergeCustomizer, fixNodePosition, getInitPositionStyle, getNodeIndex, getPageFragmentList, getPageList, moveItemsInContainer, resolveSelectedNode, setChildrenLayout, setLayout, toggleFixedPosition } from "../../utils/editor.js";
4
+ import { getLastPushedHistoryIds } from "../../utils/history.js";
2
5
  import BaseService from "./BaseService.js";
3
- import props_default from "./props.js";
4
- import { getLastPushedHistoryIds } from "../utils/history.js";
5
- import history_default from "./history.js";
6
- import storage_default, { Protocol } from "./storage.js";
7
- import { COPY_STORAGE_KEY, calcAlignCenterStyle, calcLayerTargetIndex, calcMoveStyle, classifyDragSources, collectRelatedNodes, describeStepForRevert, editorNodeMergeCustomizer, fixNodePosition, getInitPositionStyle, getNodeIndex, getPageFragmentList, getPageList, moveItemsInContainer, resolveSelectedNode, setChildrenLayout, setLayout, toggleFixedPosition } from "../utils/editor.js";
6
+ import { Protocol } from "./WebStorage.js";
8
7
  import { beforePaste, getAddParent } from "../utils/operator.js";
9
- import { isFixed } from "@tmagic/stage";
10
8
  import { getNodeInfo, getNodePath, getValueByKeyPath, guid, isPage, isPageFragment, isPageOrFragment, setValueByKeyPath, traverseNode } from "@tmagic/utils";
11
9
  import { NodeType } from "@tmagic/core";
12
- import { nextTick, reactive, toRaw } from "vue";
13
10
  import { cloneDeep as cloneDeep$1, isEmpty, isEqual, isObject, mergeWith, uniq } from "lodash-es";
14
- //#region packages/editor/src/services/editor.ts
11
+ //#region packages/editor/src/sdk/services/Editor.ts
15
12
  /** 历史插回时把记录的下标收敛到 [0, length],越界(含未记录)一律追加到末尾 */
16
13
  var clampIndex = (index, length) => typeof index === "number" && index >= 0 && index <= length ? index : length;
17
14
  /**
@@ -25,22 +22,8 @@ var buildUpdateDiff = (items) => items.map(({ oldNode, newNode, changeRecords })
25
22
  ...changeRecords?.length ? { changeRecords } : {}
26
23
  }));
27
24
  var Editor = class extends BaseService {
28
- state = reactive({
29
- root: null,
30
- page: null,
31
- parent: null,
32
- node: null,
33
- nodes: [],
34
- stage: null,
35
- stageLoading: true,
36
- highlightNode: null,
37
- modifiedNodeIds: /* @__PURE__ */ new Map(),
38
- invalidNodeIds: /* @__PURE__ */ new Map(),
39
- pageLength: 0,
40
- pageFragmentLength: 0,
41
- disabledMultiSelect: false,
42
- alwaysMultiSelect: false
43
- });
25
+ ctx;
26
+ state;
44
27
  selectionBeforeOp = null;
45
28
  /**
46
29
  * 操作前的节点校验错误快照,与 selectionBeforeOp 同时在 captureSelectionBeforeOp 中捕获,
@@ -58,7 +41,9 @@ var Editor = class extends BaseService {
58
41
  * 仅在选中节点未变化时复用(连续 add / doNotSelect / 批量粘贴),选中变化后自动失效,无需手动清理。
59
42
  */
60
43
  lastAdded = null;
61
- constructor() {
44
+ /** 与编辑器 props 中 `disabledPageFragment` / `canDropIn` 对应,供结构合法性校验使用 */
45
+ config = {};
46
+ constructor(ctx) {
62
47
  super(canUsePluginMethods.async.map((methodName) => ({
63
48
  name: methodName,
64
49
  isAsync: true
@@ -67,6 +52,23 @@ var Editor = class extends BaseService {
67
52
  "update",
68
53
  "moveLayer"
69
54
  ]);
55
+ this.ctx = ctx;
56
+ this.state = ctx.reactivity.reactive({
57
+ root: null,
58
+ page: null,
59
+ parent: null,
60
+ node: null,
61
+ nodes: [],
62
+ stage: null,
63
+ stageLoading: true,
64
+ highlightNode: null,
65
+ modifiedNodeIds: /* @__PURE__ */ new Map(),
66
+ invalidNodeIds: /* @__PURE__ */ new Map(),
67
+ pageLength: 0,
68
+ pageFragmentLength: 0,
69
+ disabledMultiSelect: false,
70
+ alwaysMultiSelect: false
71
+ });
70
72
  }
71
73
  /**
72
74
  * 设置当前指点节点配置
@@ -87,7 +89,7 @@ var Editor = class extends BaseService {
87
89
  this.state.stageLoading = this.state.pageLength !== 0;
88
90
  if (preValue && !isEmpty(preValue)) this.pushRootDiffHistory(preValue, app, options.historySource);
89
91
  else app.items?.forEach((pageNode) => {
90
- if (pageNode?.id !== void 0 && !history_default.getMarker("page", pageNode.id)) history_default.setMarker("page", pageNode.id, {
92
+ if (pageNode?.id !== void 0 && !this.ctx.history.getMarker("page", pageNode.id)) this.ctx.history.setMarker("page", pageNode.id, {
91
93
  name: pageNode.name,
92
94
  source: options.historySource
93
95
  });
@@ -117,7 +119,7 @@ var Editor = class extends BaseService {
117
119
  */
118
120
  getNodeInfo(id, raw = true) {
119
121
  let root = this.get("root");
120
- if (raw) root = toRaw(root);
122
+ if (raw) root = this.toRaw(root);
121
123
  if (!root) return {
122
124
  node: null,
123
125
  parent: null,
@@ -199,9 +201,9 @@ var Editor = class extends BaseService {
199
201
  return node;
200
202
  }
201
203
  async selectNextNode() {
202
- const node = toRaw(this.get("node"));
204
+ const node = this.toRaw(this.get("node"));
203
205
  if (!node || isPage(node) || node.type === NodeType.ROOT) return node;
204
- const parent = toRaw(this.getParentById(node.id));
206
+ const parent = this.toRaw(this.getParentById(node.id));
205
207
  if (!parent) return node;
206
208
  const index = getNodeIndex(node.id, parent);
207
209
  const nextNode = parent.items[index + 1] || parent.items[0];
@@ -210,8 +212,8 @@ var Editor = class extends BaseService {
210
212
  return nextNode;
211
213
  }
212
214
  async selectNextPage() {
213
- const root = toRaw(this.get("root"));
214
- const page = toRaw(this.get("page"));
215
+ const root = this.toRaw(this.get("root"));
216
+ const page = this.toRaw(this.get("page"));
215
217
  if (!page) throw new Error("page不能为空");
216
218
  if (!root) throw new Error("root不能为空");
217
219
  const index = getNodeIndex(page.id, root);
@@ -253,6 +255,16 @@ var Editor = class extends BaseService {
253
255
  this.set("stage", null);
254
256
  this.set("highlightNode", null);
255
257
  }
258
+ /** 设置结构合法性校验用到的配置,只覆盖传入的字段 */
259
+ setConfig(config) {
260
+ this.config = {
261
+ ...this.config,
262
+ ...config
263
+ };
264
+ }
265
+ getConfig() {
266
+ return this.config;
267
+ }
256
268
  async doAdd(node, parent, _options = {}) {
257
269
  const root = this.get("root");
258
270
  if (!root) throw new Error("root为空");
@@ -268,7 +280,7 @@ var Editor = class extends BaseService {
268
280
  selectedId: curNode.id,
269
281
  nodeId: node.id
270
282
  };
271
- const layout = await this.getLayout(toRaw(parent), node);
283
+ const layout = await this.getLayout(this.toRaw(parent), node);
272
284
  node.style = getInitPositionStyle(node.style, layout);
273
285
  await stage?.add({
274
286
  config: cloneDeep$1(node),
@@ -304,15 +316,22 @@ var Editor = class extends BaseService {
304
316
  if (!Array.isArray(addNode)) {
305
317
  const { type, inputEvent, ...config } = addNode;
306
318
  if (!type) throw new Error("组件类型不能为空");
307
- addNodes.push({ ...toRaw(await props_default.getPropsValue(type, config)) });
319
+ addNodes.push({ ...this.toRaw(await this.ctx.props.getPropsValue(type, config)) });
308
320
  } else addNodes.push(...addNode);
309
321
  const newNodes = [];
322
+ const targets = [];
310
323
  for (const node of addNodes) {
311
324
  const root = this.get("root");
312
- const parentNode = isPageOrFragment(node) && root ? root : parent ?? getAddParent(node);
325
+ const parentNode = isPageOrFragment(node) && root ? root : parent ?? getAddParent(this.ctx, node);
313
326
  if (!parentNode) throw new Error("未找到父元素");
314
- newNodes.push(await this.doAdd(node, parentNode, options));
327
+ targets.push({
328
+ node,
329
+ parentNode
330
+ });
315
331
  }
332
+ const commitInvalid = await this.runGuard(() => this.ctx.validator.guardAdd(targets));
333
+ for (const { node, parentNode } of targets) newNodes.push(await this.doAdd(node, parentNode, options));
334
+ commitInvalid?.();
316
335
  if (newNodes.length > 1) {
317
336
  const wouldSwitchPage = newNodes.some((n) => this.isOnDifferentPage(n));
318
337
  if (!doNotSelect && !(doNotSwitchPage && wouldSwitchPage)) {
@@ -337,7 +356,7 @@ var Editor = class extends BaseService {
337
356
  const p = this.getParentById(n.id, false);
338
357
  const idx = p ? getNodeIndex(n.id, p) : -1;
339
358
  return {
340
- newSchema: cloneDeep$1(toRaw(n)),
359
+ newSchema: cloneDeep$1(this.toRaw(n)),
341
360
  parentId,
342
361
  index: typeof idx === "number" ? idx : -1
343
362
  };
@@ -362,7 +381,7 @@ var Editor = class extends BaseService {
362
381
  doNotPushHistory
363
382
  });
364
383
  const addedPages = newNodes.filter((node) => isPageOrFragment(node));
365
- if (addedPages.length) history_default.notifyPageStructureChange({
384
+ if (addedPages.length) this.ctx.history.notifyPageStructureChange({
366
385
  add: addedPages,
367
386
  remove: []
368
387
  });
@@ -400,7 +419,7 @@ var Editor = class extends BaseService {
400
419
  if (shouldSwitchPage) {
401
420
  await this.select(rootItems[0]);
402
421
  stage?.select(rootItems[0].id);
403
- await nextTick();
422
+ await this.ctx.reactivity.nextTick();
404
423
  stage?.remove(removeData);
405
424
  } else {
406
425
  stage?.remove(removeData);
@@ -417,7 +436,7 @@ var Editor = class extends BaseService {
417
436
  }
418
437
  if (!rootItems.length) {
419
438
  this.resetModifiedNodeId();
420
- history_default.reset();
439
+ this.ctx.history.reset();
421
440
  }
422
441
  }
423
442
  /**
@@ -447,7 +466,7 @@ var Editor = class extends BaseService {
447
466
  };
448
467
  const idx = getNodeIndex(curNode.id, parent);
449
468
  removedItems.push({
450
- oldSchema: cloneDeep$1(toRaw(curNode)),
469
+ oldSchema: cloneDeep$1(this.toRaw(curNode)),
451
470
  parentId: parent.id,
452
471
  index: typeof idx === "number" ? idx : -1
453
472
  });
@@ -472,7 +491,7 @@ var Editor = class extends BaseService {
472
491
  doNotPushHistory
473
492
  });
474
493
  const removedPages = nodes.filter((node) => isPageOrFragment(node));
475
- if (removedPages.length) history_default.notifyPageStructureChange({
494
+ if (removedPages.length) this.ctx.history.notifyPageStructureChange({
476
495
  add: [],
477
496
  remove: removedPages
478
497
  });
@@ -483,8 +502,8 @@ var Editor = class extends BaseService {
483
502
  if (!config?.id) throw new Error("没有配置或者配置缺少id值");
484
503
  const info = this.getNodeInfo(config.id, false);
485
504
  if (!info.node) throw new Error(`获取不到id为${config.id}的节点`);
486
- const node = toRaw(info.node);
487
- let newConfig = replace ? cloneDeep$1(toRaw(config)) : await toggleFixedPosition(toRaw(config), node, info.path, this.getLayout);
505
+ const node = this.toRaw(info.node);
506
+ let newConfig = replace ? cloneDeep$1(this.toRaw(config)) : await toggleFixedPosition(this.toRaw(config), node, info.path, this.getLayout);
488
507
  if (!replace) newConfig = mergeWith(cloneDeep$1(node), newConfig, editorNodeMergeCustomizer);
489
508
  if (!newConfig.type) throw new Error("配置缺少type值");
490
509
  if (newConfig.type === NodeType.ROOT) {
@@ -534,6 +553,7 @@ var Editor = class extends BaseService {
534
553
  this.captureSelectionBeforeOp();
535
554
  const { doNotPushHistory = false, changeRecordList, changeRecords, historyDescription, historySource, invalidInfo } = data;
536
555
  const nodes = Array.isArray(config) ? config : [config];
556
+ const commitInvalid = await this.runGuard(() => this.ctx.validator.guardUpdate(nodes, { replace: data.replace }));
537
557
  const updateData = await Promise.all(nodes.map((node, index) => {
538
558
  const recordsForNode = changeRecordList ? changeRecordList[index] ?? [] : changeRecords ?? [];
539
559
  return this.doUpdate(node, {
@@ -542,6 +562,7 @@ var Editor = class extends BaseService {
542
562
  });
543
563
  }));
544
564
  this.applyInvalidInfo(config, invalidInfo);
565
+ commitInvalid?.();
545
566
  if (updateData[0].oldNode?.type !== NodeType.ROOT) {
546
567
  if (this.get("nodes").length) {
547
568
  if (!doNotPushHistory) {
@@ -590,7 +611,7 @@ var Editor = class extends BaseService {
590
611
  if (!root) throw new Error("root为空");
591
612
  const node = this.get("node");
592
613
  if (!node) throw new Error("当前节点为空");
593
- const parent = cloneDeep$1(toRaw(this.get("parent")));
614
+ const parent = cloneDeep$1(this.toRaw(this.get("parent")));
594
615
  if (!parent) throw new Error("父节点为空");
595
616
  const index2 = parent.items.findIndex((node) => `${node.id}` === `${id2}`);
596
617
  if (index2 < 0) return;
@@ -613,7 +634,7 @@ var Editor = class extends BaseService {
613
634
  * @returns
614
635
  */
615
636
  copy(config) {
616
- storage_default.setItem(COPY_STORAGE_KEY, Array.isArray(config) ? config : [config], { protocol: Protocol.OBJECT });
637
+ this.ctx.storage.setItem(COPY_STORAGE_KEY, Array.isArray(config) ? config : [config], { protocol: Protocol.OBJECT });
617
638
  }
618
639
  /**
619
640
  * 复制时会带上组件关联的依赖
@@ -623,7 +644,7 @@ var Editor = class extends BaseService {
623
644
  copyWithRelated(config, collectorOptions) {
624
645
  const copyNodes = Array.isArray(config) ? config : [config];
625
646
  if (collectorOptions && typeof collectorOptions.isTarget === "function") collectRelatedNodes(copyNodes, collectorOptions, (id) => this.getNodeById(id));
626
- storage_default.setItem(COPY_STORAGE_KEY, copyNodes, { protocol: Protocol.OBJECT });
647
+ this.ctx.storage.setItem(COPY_STORAGE_KEY, copyNodes, { protocol: Protocol.OBJECT });
627
648
  }
628
649
  /**
629
650
  * 从localStorage中获取节点,然后添加到当前容器中
@@ -636,7 +657,7 @@ var Editor = class extends BaseService {
636
657
  * @returns 添加后的组件节点配置
637
658
  */
638
659
  async paste(position = {}, collectorOptions, { doNotSelect = false, doNotSwitchPage = false, doNotPushHistory = false, historyDescription, historySource } = {}) {
639
- const config = storage_default.getItem(COPY_STORAGE_KEY);
660
+ const config = this.ctx.storage.getItem(COPY_STORAGE_KEY);
640
661
  if (!Array.isArray(config)) return;
641
662
  const node = this.get("node");
642
663
  let parent = null;
@@ -645,7 +666,7 @@ var Editor = class extends BaseService {
645
666
  if (parent?.type === NodeType.ROOT) parent = this.get("page");
646
667
  }
647
668
  const pasteConfigs = await this.doPaste(config, position);
648
- if (collectorOptions && typeof collectorOptions.isTarget === "function") props_default.replaceRelateId(config, pasteConfigs, collectorOptions);
669
+ if (collectorOptions && typeof collectorOptions.isTarget === "function") this.ctx.props.replaceRelateId(config, pasteConfigs, collectorOptions);
649
670
  return this.add(pasteConfigs, parent, {
650
671
  doNotSelect,
651
672
  doNotSwitchPage,
@@ -655,14 +676,14 @@ var Editor = class extends BaseService {
655
676
  });
656
677
  }
657
678
  async doPaste(config, position = {}) {
658
- props_default.clearRelateId();
679
+ this.ctx.props.clearRelateId();
659
680
  const doc = this.get("stage")?.renderer?.contentWindow?.document;
660
- return beforePaste(position, cloneDeep$1(config), doc);
681
+ return beforePaste(this.ctx, position, cloneDeep$1(config), doc);
661
682
  }
662
683
  async doAlignCenter(config) {
663
684
  const parent = this.getParentById(config.id);
664
685
  if (!parent) throw new Error("找不到父节点");
665
- const node = cloneDeep$1(toRaw(config));
686
+ const node = cloneDeep$1(this.toRaw(config));
666
687
  const layout = await this.getLayout(parent, node);
667
688
  const doc = this.get("stage")?.renderer?.contentWindow?.document;
668
689
  const newStyle = calcAlignCenterStyle(node, parent, layout, doc);
@@ -713,12 +734,12 @@ var Editor = class extends BaseService {
713
734
  const isRelative = await this.getLayout(parent, node) === Layout.RELATIVE;
714
735
  const offsetIndex = calcLayerTargetIndex(index, offset, brothers.length, isRelative);
715
736
  if (offsetIndex > 0 && offsetIndex > brothers.length || offsetIndex < 0) return;
716
- const oldParent = cloneDeep$1(toRaw(parent));
737
+ const oldParent = cloneDeep$1(this.toRaw(parent));
717
738
  brothers.splice(index, 1);
718
739
  brothers.splice(offsetIndex, 0, node);
719
740
  const grandparent = this.getParentById(parent.id);
720
741
  this.get("stage")?.update({
721
- config: cloneDeep$1(toRaw(parent)),
742
+ config: cloneDeep$1(this.toRaw(parent)),
722
743
  parentId: grandparent?.id,
723
744
  root: cloneDeep$1(root)
724
745
  });
@@ -728,7 +749,7 @@ var Editor = class extends BaseService {
728
749
  this.pushOpHistory("update", {
729
750
  diff: buildUpdateDiff([{
730
751
  oldNode: oldParent,
731
- newNode: cloneDeep$1(toRaw(parent))
752
+ newNode: cloneDeep$1(this.toRaw(parent))
732
753
  }]),
733
754
  pageData: {
734
755
  name: pageForOp?.name || "",
@@ -771,9 +792,8 @@ var Editor = class extends BaseService {
771
792
  this.captureSelectionBeforeOp();
772
793
  const target = this.getNodeById(targetId, false);
773
794
  if (!target) throw new Error("目标容器不存在");
774
- const root = this.get("root");
775
- const stage = this.get("stage");
776
- if (!root || !stage) throw new Error("root 或 stage为空");
795
+ if (!this.get("root")) throw new Error("root 为空");
796
+ await this.runGuard(() => this.ctx.validator.guardMove(configs.map((item) => item.id), target, "stage-drag"));
777
797
  const moves = [];
778
798
  for (const { id } of configs) {
779
799
  const { node, parent, page } = this.getNodeInfo(id, false);
@@ -789,8 +809,8 @@ var Editor = class extends BaseService {
789
809
  }
790
810
  if (moves.length === 0) throw new Error("没有可移动的节点");
791
811
  const beforeSnapshots = /* @__PURE__ */ new Map();
792
- beforeSnapshots.set(target.id, cloneDeep$1(toRaw(target)));
793
- for (const { parent } of moves) if (!beforeSnapshots.has(parent.id)) beforeSnapshots.set(parent.id, cloneDeep$1(toRaw(parent)));
812
+ beforeSnapshots.set(target.id, cloneDeep$1(this.toRaw(target)));
813
+ for (const { parent } of moves) if (!beforeSnapshots.has(parent.id)) beforeSnapshots.set(parent.id, cloneDeep$1(this.toRaw(parent)));
794
814
  let newConfigs = [];
795
815
  const moveNodes = moves.map(({ node }) => node);
796
816
  await this.remove(moveNodes, {
@@ -806,7 +826,7 @@ var Editor = class extends BaseService {
806
826
  if (!doNotPushHistory) {
807
827
  const updatedItems = Array.from(beforeSnapshots.entries()).map(([id, oldNode]) => ({
808
828
  oldNode,
809
- newNode: cloneDeep$1(toRaw(this.getNodeById(id, false)))
829
+ newNode: cloneDeep$1(this.toRaw(this.getNodeById(id, false)))
810
830
  }));
811
831
  const historyPage = moves[0].pageForOp ?? {
812
832
  name: "",
@@ -825,12 +845,13 @@ var Editor = class extends BaseService {
825
845
  this.captureSelectionBeforeOp();
826
846
  if (!targetParent || !Array.isArray(targetParent.items)) return;
827
847
  const configs = Array.isArray(config) ? config : [config];
848
+ await this.runGuard(() => this.ctx.validator.guardMove(configs.map((item) => item.id), targetParent, "layer"));
828
849
  const beforeSnapshots = /* @__PURE__ */ new Map();
829
850
  for (const cfg of configs) {
830
851
  const { parent } = this.getNodeInfo(cfg.id, false);
831
- if (parent && !beforeSnapshots.has(`${parent.id}`)) beforeSnapshots.set(`${parent.id}`, cloneDeep$1(toRaw(parent)));
852
+ if (parent && !beforeSnapshots.has(`${parent.id}`)) beforeSnapshots.set(`${parent.id}`, cloneDeep$1(this.toRaw(parent)));
832
853
  }
833
- if (!beforeSnapshots.has(`${targetParent.id}`)) beforeSnapshots.set(`${targetParent.id}`, cloneDeep$1(toRaw(targetParent)));
854
+ if (!beforeSnapshots.has(`${targetParent.id}`)) beforeSnapshots.set(`${targetParent.id}`, cloneDeep$1(this.toRaw(targetParent)));
834
855
  const newLayout = await this.getLayout(targetParent);
835
856
  const { sameParentIndices, crossParentConfigs, aborted } = classifyDragSources(configs, targetParent, (id, raw) => this.getNodeInfo(id, raw));
836
857
  if (aborted) return;
@@ -858,7 +879,7 @@ var Editor = class extends BaseService {
858
879
  const newNode = this.getNodeById(oldNode.id, false);
859
880
  if (newNode) updatedItems.push({
860
881
  oldNode,
861
- newNode: cloneDeep$1(toRaw(newNode))
882
+ newNode: cloneDeep$1(this.toRaw(newNode))
862
883
  });
863
884
  }
864
885
  if (!doNotPushHistory) {
@@ -955,7 +976,7 @@ var Editor = class extends BaseService {
955
976
  async undo() {
956
977
  const pageId = this.get("page")?.id;
957
978
  if (pageId === void 0) return null;
958
- const value = history_default.undo("page", pageId);
979
+ const value = this.ctx.history.undo("page", pageId);
959
980
  if (value) await this.applyHistoryOp(value, true);
960
981
  return value;
961
982
  }
@@ -966,7 +987,7 @@ var Editor = class extends BaseService {
966
987
  async redo() {
967
988
  const pageId = this.get("page")?.id;
968
989
  if (pageId === void 0) return null;
969
- const value = history_default.redo("page", pageId);
990
+ const value = this.ctx.history.redo("page", pageId);
970
991
  if (value) await this.applyHistoryOp(value, false);
971
992
  return value;
972
993
  }
@@ -987,7 +1008,7 @@ var Editor = class extends BaseService {
987
1008
  * @returns 反向后产生的新 step;目标不存在 / 未应用 / 反向失败时返回 null
988
1009
  */
989
1010
  async revertPageStep(index) {
990
- const entry = history_default.getStepList("page", this.get("page")?.id)[index];
1011
+ const entry = this.ctx.history.getStepList("page", this.get("page")?.id)[index];
991
1012
  if (!entry?.applied) return null;
992
1013
  const { step } = entry;
993
1014
  if (step.opType === "initial") return null;
@@ -1000,7 +1021,7 @@ var Editor = class extends BaseService {
1000
1021
  const captureRevert = (_pageId, s) => {
1001
1022
  revertedStep = s;
1002
1023
  };
1003
- history_default.once("change", captureRevert);
1024
+ this.ctx.history.once("change", captureRevert);
1004
1025
  const historyDescription = `回滚 #${index + 1}: ${describeStepForRevert(step)}`;
1005
1026
  const opts = {
1006
1027
  doNotSelect: true,
@@ -1052,9 +1073,9 @@ var Editor = class extends BaseService {
1052
1073
  }
1053
1074
  }
1054
1075
  } finally {
1055
- history_default.off("change", captureRevert);
1076
+ this.ctx.history.off("change", captureRevert);
1056
1077
  }
1057
- const page = toRaw(this.get("page"));
1078
+ const page = this.toRaw(this.get("page"));
1058
1079
  if (page) this.emit("history-change", page);
1059
1080
  return revertedStep;
1060
1081
  }
@@ -1069,7 +1090,7 @@ var Editor = class extends BaseService {
1069
1090
  const results = [];
1070
1091
  const pageId = this.get("page")?.id;
1071
1092
  for (const uuid of uuids) {
1072
- const location = history_default.findStepLocationByUuid("page", uuid, pageId);
1093
+ const location = this.ctx.history.findStepLocationByUuid("page", uuid, pageId);
1073
1094
  results.push(!location ? null : await this.revertPageStep(location.index));
1074
1095
  }
1075
1096
  return results;
@@ -1085,8 +1106,8 @@ var Editor = class extends BaseService {
1085
1106
  */
1086
1107
  async gotoPageStep(targetCursor) {
1087
1108
  const pageId = this.get("page")?.id;
1088
- let cursor = history_default.getCursor("page", pageId);
1089
- const { length } = history_default.getStepList("page", pageId);
1109
+ let cursor = this.ctx.history.getCursor("page", pageId);
1110
+ const { length } = this.ctx.history.getStepList("page", pageId);
1090
1111
  const target = Math.max(0, Math.min(targetCursor, length));
1091
1112
  while (cursor > target) {
1092
1113
  if (!await this.undo()) break;
@@ -1099,7 +1120,7 @@ var Editor = class extends BaseService {
1099
1120
  return cursor;
1100
1121
  }
1101
1122
  async move(left, top, { doNotPushHistory = false, historyDescription, historySource } = {}) {
1102
- const node = toRaw(this.get("node"));
1123
+ const node = this.toRaw(this.get("node"));
1103
1124
  if (!node || isPage(node)) return;
1104
1125
  const newStyle = calcMoveStyle(node.style || {}, left, top);
1105
1126
  if (!newStyle) return;
@@ -1243,6 +1264,19 @@ var Editor = class extends BaseService {
1243
1264
  if (node && isPageOrFragment(node)) return node;
1244
1265
  return null;
1245
1266
  }
1267
+ /**
1268
+ * 执行校验。校验不通过(strict 抛错)时操作不会继续,必须清掉 captureSelectionBeforeOp 留下的快照,
1269
+ * 否则下一次成功的操作会沿用这份过期快照,写出错误的 selectedBefore / invalidNodeIdsBefore。
1270
+ */
1271
+ async runGuard(guard) {
1272
+ try {
1273
+ return await guard();
1274
+ } catch (e) {
1275
+ this.selectionBeforeOp = null;
1276
+ this.invalidNodeIdsBeforeOp = null;
1277
+ throw e;
1278
+ }
1279
+ }
1246
1280
  captureSelectionBeforeOp() {
1247
1281
  if (this.selectionBeforeOp) return;
1248
1282
  this.selectionBeforeOp = this.get("nodes").map((n) => n.id);
@@ -1269,27 +1303,27 @@ var Editor = class extends BaseService {
1269
1303
  const prevPage = prevMap.get(`${nextPage.id}`);
1270
1304
  if (!prevPage) {
1271
1305
  this.pushPageDiffStep("add", nextPage, {
1272
- newSchema: cloneDeep$1(toRaw(nextPage)),
1306
+ newSchema: cloneDeep$1(this.toRaw(nextPage)),
1273
1307
  parentId: nextRoot.id,
1274
1308
  index: indexInItems(nextRoot, nextPage.id)
1275
1309
  }, source);
1276
1310
  addedPages.push(nextPage);
1277
- } else if (!isEqual(toRaw(prevPage), toRaw(nextPage))) this.pushPageDiffStep("update", nextPage, {
1278
- oldSchema: cloneDeep$1(toRaw(prevPage)),
1279
- newSchema: cloneDeep$1(toRaw(nextPage))
1311
+ } else if (!isEqual(this.toRaw(prevPage), this.toRaw(nextPage))) this.pushPageDiffStep("update", nextPage, {
1312
+ oldSchema: cloneDeep$1(this.toRaw(prevPage)),
1313
+ newSchema: cloneDeep$1(this.toRaw(nextPage))
1280
1314
  }, source);
1281
1315
  });
1282
1316
  prevPages.forEach((prevPage) => {
1283
1317
  if (!nextMap.has(`${prevPage.id}`)) {
1284
1318
  this.pushPageDiffStep("remove", prevPage, {
1285
- oldSchema: cloneDeep$1(toRaw(prevPage)),
1319
+ oldSchema: cloneDeep$1(this.toRaw(prevPage)),
1286
1320
  parentId: preRoot.id,
1287
1321
  index: indexInItems(preRoot, prevPage.id)
1288
1322
  }, source);
1289
1323
  removedPages.push(prevPage);
1290
1324
  }
1291
1325
  });
1292
- if (addedPages.length || removedPages.length) history_default.notifyPageStructureChange({
1326
+ if (addedPages.length || removedPages.length) this.ctx.history.notifyPageStructureChange({
1293
1327
  add: addedPages,
1294
1328
  remove: removedPages
1295
1329
  });
@@ -1318,9 +1352,9 @@ var Editor = class extends BaseService {
1318
1352
  rootStep: true
1319
1353
  };
1320
1354
  if (source) step.source = source;
1321
- const top = history_default.getCurrentPageStep(page.id);
1322
- if (top?.rootStep && top.source === source) history_default.replaceCurrentStep("page", step, page.id);
1323
- else history_default.push("page", step, page.id);
1355
+ const top = this.ctx.history.getCurrentPageStep(page.id);
1356
+ if (top?.rootStep && top.source === source) this.ctx.history.replaceCurrentStep("page", step, page.id);
1357
+ else this.ctx.history.push("page", step, page.id);
1324
1358
  }
1325
1359
  pushOpHistory(opType, { diff, pageData, historyDescription, source }) {
1326
1360
  const step = {
@@ -1338,7 +1372,7 @@ var Editor = class extends BaseService {
1338
1372
  };
1339
1373
  if (historyDescription) step.historyDescription = historyDescription;
1340
1374
  if (source) step.source = source;
1341
- const historyId = history_default.push("page", step, pageData.id) ? step.uuid : null;
1375
+ const historyId = this.ctx.history.push("page", step, pageData.id) ? step.uuid : null;
1342
1376
  this.lastPushedHistoryId = historyId;
1343
1377
  this.selectionBeforeOp = null;
1344
1378
  this.invalidNodeIdsBeforeOp = null;
@@ -1461,7 +1495,7 @@ var Editor = class extends BaseService {
1461
1495
  const invalidToRestore = (reverse ? step.extra?.invalidNodeIdsBefore : step.extra?.invalidNodeIdsAfter) ?? /* @__PURE__ */ new Map();
1462
1496
  this.set("invalidNodeIds", new Map(invalidToRestore));
1463
1497
  this.emit("invalid-node-change", this.get("invalidNodeIds"));
1464
- const page = toRaw(this.get("page"));
1498
+ const page = this.toRaw(this.get("page"));
1465
1499
  if (page) {
1466
1500
  const selectIds = (reverse ? step.extra?.selectedBefore : step.extra?.selectedAfter) ?? [];
1467
1501
  setTimeout(() => {
@@ -1494,7 +1528,10 @@ var Editor = class extends BaseService {
1494
1528
  doNotPushHistory: true
1495
1529
  });
1496
1530
  }
1531
+ /** 经由 reactivity 注入的 toRaw(默认是 Vue 的 toRaw) */
1532
+ toRaw(value) {
1533
+ return this.ctx.reactivity.toRaw(value);
1534
+ }
1497
1535
  };
1498
- var editor_default = new Editor();
1499
1536
  //#endregion
1500
- export { editor_default as default };
1537
+ export { Editor as default };
@@ -1,8 +1,7 @@
1
1
  import BaseService from "./BaseService.js";
2
2
  import { toLine } from "@tmagic/utils";
3
- import { reactive } from "vue";
4
3
  import { cloneDeep } from "lodash-es";
5
- //#region packages/editor/src/services/events.ts
4
+ //#region packages/editor/src/sdk/services/Events.ts
6
5
  var canUsePluginMethods = {
7
6
  async: [],
8
7
  sync: [
@@ -12,10 +11,10 @@ var canUsePluginMethods = {
12
11
  "getMethod"
13
12
  ]
14
13
  };
15
- var eventMap = reactive({});
16
- var methodMap = reactive({});
17
14
  var Events = class extends BaseService {
18
- constructor() {
15
+ eventMap;
16
+ methodMap;
17
+ constructor(ctx) {
19
18
  super([...canUsePluginMethods.async.map((methodName) => ({
20
19
  name: methodName,
21
20
  isAsync: true
@@ -23,6 +22,8 @@ var Events = class extends BaseService {
23
22
  name: methodName,
24
23
  isAsync: false
25
24
  }))]);
25
+ this.eventMap = ctx.reactivity.reactive({});
26
+ this.methodMap = ctx.reactivity.reactive({});
26
27
  }
27
28
  setEvents(events) {
28
29
  Object.keys(events).forEach((type) => {
@@ -30,10 +31,10 @@ var Events = class extends BaseService {
30
31
  });
31
32
  }
32
33
  setEvent(type, events) {
33
- eventMap[toLine(type)] = [...events];
34
+ this.eventMap[toLine(type)] = [...events];
34
35
  }
35
36
  getEvent(type, _data = {}) {
36
- return cloneDeep(eventMap[toLine(type)]) || [];
37
+ return cloneDeep(this.eventMap[toLine(type)]) || [];
37
38
  }
38
39
  setMethods(methods) {
39
40
  Object.keys(methods).forEach((type) => {
@@ -41,14 +42,14 @@ var Events = class extends BaseService {
41
42
  });
42
43
  }
43
44
  setMethod(type, method) {
44
- methodMap[toLine(type)] = [...method];
45
+ this.methodMap[toLine(type)] = [...method];
45
46
  }
46
47
  getMethod(type, _data = {}) {
47
- return cloneDeep(methodMap[toLine(type)]) || [];
48
+ return cloneDeep(this.methodMap[toLine(type)]) || [];
48
49
  }
49
50
  resetState() {
50
- Object.keys(eventMap).forEach((type) => delete eventMap[type]);
51
- Object.keys(methodMap).forEach((type) => delete methodMap[type]);
51
+ Object.keys(this.eventMap).forEach((type) => delete this.eventMap[type]);
52
+ Object.keys(this.methodMap).forEach((type) => delete this.methodMap[type]);
52
53
  }
53
54
  destroy() {
54
55
  this.resetState();
@@ -59,6 +60,5 @@ var Events = class extends BaseService {
59
60
  super.usePlugin(options);
60
61
  }
61
62
  };
62
- var events_default = new Events();
63
63
  //#endregion
64
- export { events_default as default };
64
+ export { Events as default };