@tmagic/editor 1.4.7 → 1.4.8

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 (152) hide show
  1. package/dist/style.css +1 -1
  2. package/dist/tmagic-editor.js +314 -452
  3. package/dist/tmagic-editor.umd.cjs +313 -450
  4. package/package.json +15 -11
  5. package/types/layouts/sidebar/layer/use-click.d.ts +1 -1
  6. package/types/services/editor.d.ts +19 -2
  7. package/types/services/props.d.ts +5 -5
  8. package/types/type.d.ts +6 -0
  9. package/types/utils/editor.d.ts +1 -0
  10. package/src/Editor.vue +0 -211
  11. package/src/components/CodeBlockEditor.vue +0 -268
  12. package/src/components/CodeParams.vue +0 -60
  13. package/src/components/ContentMenu.vue +0 -193
  14. package/src/components/FloatingBox.vue +0 -178
  15. package/src/components/Icon.vue +0 -27
  16. package/src/components/Resizer.vue +0 -23
  17. package/src/components/ScrollBar.vue +0 -151
  18. package/src/components/ScrollViewer.vue +0 -128
  19. package/src/components/SearchInput.vue +0 -37
  20. package/src/components/SplitView.vue +0 -186
  21. package/src/components/ToolButton.vue +0 -138
  22. package/src/components/Tree.vue +0 -71
  23. package/src/components/TreeNode.vue +0 -150
  24. package/src/editorProps.ts +0 -117
  25. package/src/fields/Code.vue +0 -50
  26. package/src/fields/CodeLink.vue +0 -80
  27. package/src/fields/CodeSelect.vue +0 -132
  28. package/src/fields/CodeSelectCol.vue +0 -139
  29. package/src/fields/DataSourceFieldSelect.vue +0 -149
  30. package/src/fields/DataSourceFields.vue +0 -323
  31. package/src/fields/DataSourceInput.vue +0 -331
  32. package/src/fields/DataSourceMethodSelect.vue +0 -153
  33. package/src/fields/DataSourceMethods.vue +0 -104
  34. package/src/fields/DataSourceMocks.vue +0 -255
  35. package/src/fields/DataSourceSelect.vue +0 -98
  36. package/src/fields/EventSelect.vue +0 -375
  37. package/src/fields/KeyValue.vue +0 -137
  38. package/src/fields/PageFragmentSelect.vue +0 -63
  39. package/src/fields/UISelect.vue +0 -135
  40. package/src/hooks/index.ts +0 -24
  41. package/src/hooks/use-code-block-edit.ts +0 -83
  42. package/src/hooks/use-data-source-edit.ts +0 -46
  43. package/src/hooks/use-data-source-method.ts +0 -100
  44. package/src/hooks/use-editor-content-height.ts +0 -26
  45. package/src/hooks/use-filter.ts +0 -55
  46. package/src/hooks/use-float-box.ts +0 -76
  47. package/src/hooks/use-getso.ts +0 -35
  48. package/src/hooks/use-next-float-box-position.ts +0 -29
  49. package/src/hooks/use-node-status.ts +0 -48
  50. package/src/hooks/use-stage.ts +0 -129
  51. package/src/hooks/use-window-rect.ts +0 -20
  52. package/src/icons/AppManageIcon.vue +0 -15
  53. package/src/icons/CenterIcon.vue +0 -13
  54. package/src/icons/CodeIcon.vue +0 -28
  55. package/src/icons/FolderMinusIcon.vue +0 -22
  56. package/src/icons/PinIcon.vue +0 -25
  57. package/src/icons/PinnedIcon.vue +0 -25
  58. package/src/index.ts +0 -118
  59. package/src/initService.ts +0 -443
  60. package/src/layouts/AddPageBox.vue +0 -55
  61. package/src/layouts/CodeEditor.vue +0 -226
  62. package/src/layouts/Framework.vue +0 -163
  63. package/src/layouts/NavMenu.vue +0 -200
  64. package/src/layouts/PropsPanel.vue +0 -130
  65. package/src/layouts/page-bar/AddButton.vue +0 -48
  66. package/src/layouts/page-bar/PageBar.vue +0 -159
  67. package/src/layouts/page-bar/PageBarScrollContainer.vue +0 -156
  68. package/src/layouts/page-bar/SwitchTypeButton.vue +0 -45
  69. package/src/layouts/sidebar/ComponentListPanel.vue +0 -134
  70. package/src/layouts/sidebar/Sidebar.vue +0 -278
  71. package/src/layouts/sidebar/code-block/CodeBlockList.vue +0 -160
  72. package/src/layouts/sidebar/code-block/CodeBlockListPanel.vue +0 -70
  73. package/src/layouts/sidebar/data-source/DataSourceConfigPanel.vue +0 -84
  74. package/src/layouts/sidebar/data-source/DataSourceList.vue +0 -172
  75. package/src/layouts/sidebar/data-source/DataSourceListPanel.vue +0 -106
  76. package/src/layouts/sidebar/layer/LayerMenu.vue +0 -128
  77. package/src/layouts/sidebar/layer/LayerNodeTool.vue +0 -32
  78. package/src/layouts/sidebar/layer/LayerPanel.vue +0 -119
  79. package/src/layouts/sidebar/layer/use-click.ts +0 -110
  80. package/src/layouts/sidebar/layer/use-drag.ts +0 -161
  81. package/src/layouts/sidebar/layer/use-keybinding.ts +0 -54
  82. package/src/layouts/sidebar/layer/use-node-status.ts +0 -114
  83. package/src/layouts/workspace/Breadcrumb.vue +0 -35
  84. package/src/layouts/workspace/Workspace.vue +0 -46
  85. package/src/layouts/workspace/viewer/NodeListMenu.vue +0 -115
  86. package/src/layouts/workspace/viewer/Stage.vue +0 -246
  87. package/src/layouts/workspace/viewer/StageOverlay.vue +0 -68
  88. package/src/layouts/workspace/viewer/ViewerMenu.vue +0 -145
  89. package/src/services/BaseService.ts +0 -230
  90. package/src/services/codeBlock.ts +0 -327
  91. package/src/services/componentList.ts +0 -58
  92. package/src/services/dataSource.ts +0 -216
  93. package/src/services/dep.ts +0 -152
  94. package/src/services/editor.ts +0 -1096
  95. package/src/services/events.ts +0 -93
  96. package/src/services/history.ts +0 -126
  97. package/src/services/keybinding.ts +0 -220
  98. package/src/services/props.ts +0 -271
  99. package/src/services/stageOverlay.ts +0 -212
  100. package/src/services/storage.ts +0 -155
  101. package/src/services/ui.ts +0 -156
  102. package/src/shims-vue.d.ts +0 -6
  103. package/src/theme/breadcrumb.scss +0 -6
  104. package/src/theme/code-block.scss +0 -6
  105. package/src/theme/code-editor.scss +0 -38
  106. package/src/theme/common/var.scss +0 -14
  107. package/src/theme/component-list-panel.scss +0 -95
  108. package/src/theme/content-menu.scss +0 -76
  109. package/src/theme/data-source-field.scss +0 -12
  110. package/src/theme/data-source-fields.scss +0 -13
  111. package/src/theme/data-source-input.scss +0 -18
  112. package/src/theme/data-source-methods.scss +0 -13
  113. package/src/theme/data-source.scss +0 -28
  114. package/src/theme/event.scss +0 -37
  115. package/src/theme/floating-box.scss +0 -32
  116. package/src/theme/framework.scss +0 -69
  117. package/src/theme/icon.scss +0 -12
  118. package/src/theme/index.scss +0 -10
  119. package/src/theme/key-value.scss +0 -20
  120. package/src/theme/layer-panel.scss +0 -26
  121. package/src/theme/layout.scss +0 -9
  122. package/src/theme/nav-menu.scss +0 -78
  123. package/src/theme/page-bar.scss +0 -89
  124. package/src/theme/page-fragment-select.scss +0 -14
  125. package/src/theme/props-panel.scss +0 -55
  126. package/src/theme/resizer.scss +0 -66
  127. package/src/theme/ruler.scss +0 -38
  128. package/src/theme/search-input.scss +0 -14
  129. package/src/theme/sidebar.scss +0 -79
  130. package/src/theme/stage.scss +0 -76
  131. package/src/theme/theme.scss +0 -27
  132. package/src/theme/tree.scss +0 -89
  133. package/src/theme/workspace.scss +0 -9
  134. package/src/type.ts +0 -746
  135. package/src/utils/compose.ts +0 -52
  136. package/src/utils/config.ts +0 -29
  137. package/src/utils/content-menu.ts +0 -95
  138. package/src/utils/data-source/formConfigs/base.ts +0 -30
  139. package/src/utils/data-source/formConfigs/http.ts +0 -60
  140. package/src/utils/data-source/index.ts +0 -243
  141. package/src/utils/editor.ts +0 -294
  142. package/src/utils/idle-task.ts +0 -72
  143. package/src/utils/index.ts +0 -24
  144. package/src/utils/keybinding-config.ts +0 -125
  145. package/src/utils/logger.ts +0 -47
  146. package/src/utils/monaco-editor.ts +0 -8
  147. package/src/utils/operator.ts +0 -106
  148. package/src/utils/props.ts +0 -504
  149. package/src/utils/scroll-viewer.ts +0 -165
  150. package/src/utils/tree.ts +0 -15
  151. package/src/utils/undo-redo.ts +0 -76
  152. package/tsconfig.build.json +0 -16
@@ -1,1096 +0,0 @@
1
- /*
2
- * Tencent is pleased to support the open source community by making TMagicEditor available.
3
- *
4
- * Copyright (C) 2023 THL A29 Limited, a Tencent company. All rights reserved.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
-
19
- import { reactive, toRaw } from 'vue';
20
- import { cloneDeep, get, isObject, mergeWith, uniq } from 'lodash-es';
21
- import { Writable } from 'type-fest';
22
-
23
- import { Target, type TargetOptions, Watcher } from '@tmagic/dep';
24
- import type { Id, MApp, MComponent, MContainer, MNode, MPage, MPageFragment } from '@tmagic/schema';
25
- import { NodeType } from '@tmagic/schema';
26
- import { calcValueByFontsize, getNodePath, isNumber, isPage, isPageFragment, isPop } from '@tmagic/utils';
27
-
28
- import BaseService from '@editor/services//BaseService';
29
- import propsService from '@editor/services//props';
30
- import historyService from '@editor/services/history';
31
- import storageService, { Protocol } from '@editor/services/storage';
32
- import type {
33
- AddMNode,
34
- AsyncHookPlugin,
35
- EditorNodeInfo,
36
- PastePosition,
37
- StepValue,
38
- StoreState,
39
- StoreStateKey,
40
- } from '@editor/type';
41
- import { LayerOffset, Layout } from '@editor/type';
42
- import {
43
- change2Fixed,
44
- COPY_STORAGE_KEY,
45
- Fixed2Other,
46
- fixNodePosition,
47
- getInitPositionStyle,
48
- getNodeIndex,
49
- getPageFragmentList,
50
- getPageList,
51
- isFixed,
52
- setChildrenLayout,
53
- setLayout,
54
- } from '@editor/utils/editor';
55
- import { beforePaste, getAddParent } from '@editor/utils/operator';
56
-
57
- const canUsePluginMethods = {
58
- async: [
59
- 'getLayout',
60
- 'highlight',
61
- 'select',
62
- 'multiSelect',
63
- 'doAdd',
64
- 'add',
65
- 'doRemove',
66
- 'remove',
67
- 'doUpdate',
68
- 'update',
69
- 'sort',
70
- 'copy',
71
- 'paste',
72
- 'doPaste',
73
- 'doAlignCenter',
74
- 'alignCenter',
75
- 'moveLayer',
76
- 'moveToContainer',
77
- 'dragTo',
78
- 'undo',
79
- 'redo',
80
- 'move',
81
- ] as const,
82
- sync: [],
83
- };
84
-
85
- type AsyncMethodName = Writable<(typeof canUsePluginMethods)['async']>;
86
-
87
- class Editor extends BaseService {
88
- public state: StoreState = reactive({
89
- root: null,
90
- page: null,
91
- parent: null,
92
- node: null,
93
- nodes: [],
94
- stage: null,
95
- stageLoading: true,
96
- highlightNode: null,
97
- modifiedNodeIds: new Map(),
98
- pageLength: 0,
99
- pageFragmentLength: 0,
100
- disabledMultiSelect: false,
101
- });
102
- private isHistoryStateChange = false;
103
-
104
- constructor() {
105
- super(
106
- canUsePluginMethods.async.map((methodName) => ({ name: methodName, isAsync: true })),
107
- // 需要注意循环依赖问题,如果函数间有相互调用的话,不能设置为串行调用
108
- ['select', 'update', 'moveLayer'],
109
- );
110
- }
111
-
112
- /**
113
- * 设置当前指点节点配置
114
- * @param name 'root' | 'page' | 'parent' | 'node' | 'highlightNode' | 'nodes' | 'stage' | 'modifiedNodeIds' | 'pageLength' | 'pageFragmentLength
115
- * @param value MNode
116
- */
117
- public set<K extends StoreStateKey, T extends StoreState[K]>(name: K, value: T) {
118
- const preValue = this.state[name];
119
- this.state[name] = value;
120
-
121
- // set nodes时将node设置为nodes第一个元素
122
- if (name === 'nodes' && Array.isArray(value)) {
123
- this.set('node', value[0]);
124
- }
125
-
126
- if (name === 'root') {
127
- if (Array.isArray(value)) {
128
- throw new Error('root 不能为数组');
129
- }
130
-
131
- if (value && isObject(value)) {
132
- const app = value as MApp;
133
- this.state.pageLength = getPageList(app).length || 0;
134
- this.state.pageFragmentLength = getPageFragmentList(app).length || 0;
135
- this.state.stageLoading = this.state.pageLength !== 0;
136
- } else {
137
- this.state.pageLength = 0;
138
- this.state.pageFragmentLength = 0;
139
- this.state.stageLoading = false;
140
- }
141
-
142
- this.emit('root-change', value, preValue);
143
- }
144
- }
145
-
146
- /**
147
- * 获取当前指点节点配置
148
- * @param name 'root' | 'page' | 'parent' | 'node' | 'highlightNode' | 'nodes' | 'stage' | 'modifiedNodeIds' | 'pageLength' | 'pageFragmentLength'
149
- * @returns MNode
150
- */
151
- public get<K extends StoreStateKey>(name: K): StoreState[K] {
152
- return this.state[name];
153
- }
154
-
155
- /**
156
- * 根据id获取组件、组件的父组件以及组件所属的页面节点
157
- * @param {number | string} id 组件id
158
- * @param {boolean} raw 是否使用toRaw
159
- * @returns {EditorNodeInfo}
160
- */
161
- public getNodeInfo(id: Id, raw = true): EditorNodeInfo {
162
- let root = this.get('root');
163
- if (raw) {
164
- root = toRaw(root);
165
- }
166
-
167
- const info: EditorNodeInfo = {
168
- node: null,
169
- parent: null,
170
- page: null,
171
- };
172
-
173
- if (!root) return info;
174
-
175
- if (id === root.id) {
176
- info.node = root;
177
- return info;
178
- }
179
-
180
- const path = getNodePath(id, root.items);
181
-
182
- if (!path.length) return info;
183
-
184
- path.unshift(root);
185
-
186
- info.node = path[path.length - 1] as MComponent;
187
- info.parent = path[path.length - 2] as MContainer;
188
-
189
- path.forEach((item) => {
190
- if (isPage(item) || isPageFragment(item)) {
191
- info.page = item as MPage | MPageFragment;
192
- return;
193
- }
194
- });
195
-
196
- return info;
197
- }
198
-
199
- /**
200
- * 根据ID获取指点节点配置
201
- * @param id 组件ID
202
- * @param {boolean} raw 是否使用toRaw
203
- * @returns 组件节点配置
204
- */
205
- public getNodeById(id: Id, raw = true): MNode | null {
206
- const { node } = this.getNodeInfo(id, raw);
207
- return node;
208
- }
209
-
210
- /**
211
- * 根据ID获取指点节点的父节点配置
212
- * @param id 组件ID
213
- * @param {boolean} raw 是否使用toRaw
214
- * @returns 指点组件的父节点配置
215
- */
216
- public getParentById(id: Id, raw = true): MContainer | null {
217
- const { parent } = this.getNodeInfo(id, raw);
218
- return parent;
219
- }
220
-
221
- /**
222
- * 只有容器拥有布局
223
- */
224
- public async getLayout(parent: MNode, node?: MNode | null): Promise<Layout> {
225
- if (node && typeof node !== 'function' && isFixed(node)) return Layout.FIXED;
226
-
227
- if (parent.layout) {
228
- return parent.layout;
229
- }
230
-
231
- // 如果该节点没有设置position,则认为是流式布局,例如获取root的布局时
232
- if (!parent.style?.position) {
233
- return Layout.RELATIVE;
234
- }
235
-
236
- return Layout.ABSOLUTE;
237
- }
238
-
239
- /**
240
- * 选中指定节点(将指定节点设置成当前选中状态)
241
- * @param config 指定节点配置或者ID
242
- * @returns 当前选中的节点配置
243
- */
244
- public async select(config: MNode | Id): Promise<MNode> | never {
245
- const { node, page, parent } = this.selectedConfigExceptionHandler(config);
246
- this.set('nodes', node ? [node] : []);
247
- this.set('page', page);
248
- this.set('parent', parent);
249
-
250
- if (page) {
251
- historyService.changePage(toRaw(page));
252
- } else {
253
- historyService.resetState();
254
- }
255
-
256
- if (node?.id) {
257
- this.get('stage')
258
- ?.renderer.runtime?.getApp?.()
259
- ?.page?.emit(
260
- 'editor:select',
261
- {
262
- node,
263
- page,
264
- parent,
265
- },
266
- getNodePath(node.id, this.get('root')?.items),
267
- );
268
- }
269
-
270
- this.emit('select', node);
271
-
272
- return node!;
273
- }
274
-
275
- public async selectNextNode(): Promise<MNode | null> | never {
276
- const node = toRaw(this.get('node'));
277
-
278
- if (!node || isPage(node) || node.type === NodeType.ROOT) return node;
279
-
280
- const parent = toRaw(this.getParentById(node.id));
281
-
282
- if (!parent) return node;
283
-
284
- const index = getNodeIndex(node.id, parent);
285
-
286
- const nextNode = parent.items[index + 1] || parent.items[0];
287
-
288
- await this.select(nextNode);
289
- this.get('stage')?.select(nextNode.id);
290
-
291
- return nextNode;
292
- }
293
-
294
- public async selectNextPage(): Promise<MNode> | never {
295
- const root = toRaw(this.get('root'));
296
- const page = toRaw(this.get('page'));
297
-
298
- if (!page) throw new Error('page不能为空');
299
- if (!root) throw new Error('root不能为空');
300
-
301
- const index = getNodeIndex(page.id, root);
302
-
303
- const nextPage = root.items[index + 1] || root.items[0];
304
-
305
- await this.select(nextPage);
306
- this.get('stage')?.select(nextPage.id);
307
-
308
- return nextPage;
309
- }
310
-
311
- /**
312
- * 高亮指定节点
313
- * @param config 指定节点配置或者ID
314
- * @returns 当前高亮的节点配置
315
- */
316
- public highlight(config: MNode | Id): void {
317
- const { node } = this.selectedConfigExceptionHandler(config);
318
- const currentHighlightNode = this.get('highlightNode');
319
- if (currentHighlightNode === node) return;
320
- this.set('highlightNode', node);
321
- }
322
-
323
- /**
324
- * 多选
325
- * @param ids 指定节点ID
326
- * @returns 加入多选的节点配置
327
- */
328
- public multiSelect(ids: Id[]): void {
329
- const nodes: MNode[] = [];
330
- const idsUnique = uniq(ids);
331
- idsUnique.forEach((id) => {
332
- const { node } = this.getNodeInfo(id);
333
- if (!node) return;
334
- nodes.push(node);
335
- });
336
- this.set('nodes', nodes);
337
- }
338
-
339
- public selectRoot() {
340
- const root = this.get('root');
341
- if (!root) return;
342
-
343
- this.set('nodes', [root]);
344
- this.set('parent', null);
345
- this.set('page', null);
346
- this.set('stage', null);
347
- this.set('highlightNode', null);
348
- }
349
-
350
- public async doAdd(node: MNode, parent: MContainer): Promise<MNode> {
351
- const root = this.get('root');
352
-
353
- if (!root) throw new Error('root为空');
354
-
355
- const curNode = this.get('node');
356
- const stage = this.get('stage');
357
-
358
- if (!curNode) throw new Error('当前选中节点为空');
359
-
360
- if ((parent.type === NodeType.ROOT || curNode?.type === NodeType.ROOT) && !(isPage(node) || isPageFragment(node))) {
361
- throw new Error('app下不能添加组件');
362
- }
363
-
364
- if (parent.id !== curNode.id && !(isPage(node) || isPageFragment(node))) {
365
- const index = parent.items.indexOf(curNode);
366
- parent.items?.splice(index + 1, 0, node);
367
- } else {
368
- // 新增节点添加到配置中
369
- parent.items?.push(node);
370
- }
371
-
372
- const layout = await this.getLayout(toRaw(parent), node as MNode);
373
- node.style = getInitPositionStyle(node.style, layout);
374
-
375
- await stage?.add({
376
- config: cloneDeep(node),
377
- parent: cloneDeep(parent),
378
- parentId: parent.id,
379
- root: cloneDeep(root),
380
- });
381
-
382
- const newStyle = fixNodePosition(node, parent, stage);
383
-
384
- if (newStyle && (newStyle.top !== node.style.top || newStyle.left !== node.style.left)) {
385
- node.style = newStyle;
386
- await stage?.update({ config: cloneDeep(node), parentId: parent.id, root: cloneDeep(root) });
387
- }
388
-
389
- this.addModifiedNodeId(node.id);
390
-
391
- return node;
392
- }
393
-
394
- /**
395
- * 向指点容器添加组件节点
396
- * @param addConfig 将要添加的组件节点配置
397
- * @param parent 要添加到的容器组件节点配置,如果不设置,默认为当前选中的组件的父节点
398
- * @returns 添加后的节点
399
- */
400
- public async add(addNode: AddMNode | MNode[], parent?: MContainer | null): Promise<MNode | MNode[]> {
401
- const stage = this.get('stage');
402
-
403
- // 新增多个组件只存在于粘贴多个组件,粘贴的是一个完整的config,所以不再需要getPropsValue
404
- const addNodes = [];
405
- if (!Array.isArray(addNode)) {
406
- const { type, inputEvent, ...config } = addNode;
407
-
408
- if (!type) throw new Error('组件类型不能为空');
409
-
410
- addNodes.push({ ...toRaw(await propsService.getPropsValue(type, config)) });
411
- } else {
412
- addNodes.push(...addNode);
413
- }
414
-
415
- const newNodes = await Promise.all(
416
- addNodes.map((node) => {
417
- const root = this.get('root');
418
- if ((isPage(node) || isPageFragment(node)) && root) {
419
- return this.doAdd(node, root);
420
- }
421
- const parentNode = parent && typeof parent !== 'function' ? parent : getAddParent(node);
422
- if (!parentNode) throw new Error('未找到父元素');
423
- return this.doAdd(node, parentNode);
424
- }),
425
- );
426
-
427
- if (newNodes.length > 1) {
428
- const newNodeIds = newNodes.map((node) => node.id);
429
- // 触发选中样式
430
- stage?.multiSelect(newNodeIds);
431
- await this.multiSelect(newNodeIds);
432
- } else {
433
- await this.select(newNodes[0]);
434
-
435
- if (isPage(newNodes[0])) {
436
- this.state.pageLength += 1;
437
- } else if (isPageFragment(newNodes[0])) {
438
- this.state.pageFragmentLength += 1;
439
- } else {
440
- // 新增页面,这个时候页面还有渲染出来,此时select会出错,在runtime-ready的时候回去select
441
- stage?.select(newNodes[0].id);
442
- }
443
- }
444
-
445
- if (!(isPage(newNodes[0]) || isPageFragment(newNodes[0]))) {
446
- this.pushHistoryState();
447
- }
448
-
449
- this.emit('add', newNodes);
450
-
451
- return Array.isArray(addNode) ? newNodes : newNodes[0];
452
- }
453
-
454
- public async doRemove(node: MNode): Promise<void> {
455
- const root = this.get('root');
456
- if (!root) throw new Error('root不能为空');
457
-
458
- const { parent, node: curNode } = this.getNodeInfo(node.id, false);
459
-
460
- if (!parent || !curNode) throw new Error('找不要删除的节点');
461
-
462
- const index = getNodeIndex(curNode.id, parent);
463
-
464
- if (typeof index !== 'number' || index === -1) throw new Error('找不要删除的节点');
465
-
466
- parent.items?.splice(index, 1);
467
- const stage = this.get('stage');
468
- stage?.remove({ id: node.id, parentId: parent.id, root: cloneDeep(root) });
469
-
470
- const selectDefault = async (pages: MNode[]) => {
471
- if (pages[0]) {
472
- await this.select(pages[0]);
473
- stage?.select(pages[0].id);
474
- } else {
475
- this.selectRoot();
476
-
477
- historyService.resetPage();
478
- }
479
- };
480
-
481
- const rootItems = root.items || [];
482
-
483
- if (isPage(node)) {
484
- this.state.pageLength -= 1;
485
-
486
- await selectDefault(getPageList(root));
487
- } else if (isPageFragment(node)) {
488
- this.state.pageFragmentLength -= 1;
489
-
490
- await selectDefault(getPageFragmentList(root));
491
- } else {
492
- await this.select(parent);
493
- stage?.select(parent.id);
494
-
495
- this.addModifiedNodeId(parent.id);
496
- }
497
-
498
- if (!rootItems.length) {
499
- this.resetModifiedNodeId();
500
- historyService.reset();
501
- }
502
- }
503
-
504
- /**
505
- * 删除组件
506
- * @param {Object} node
507
- */
508
- public async remove(nodeOrNodeList: MNode | MNode[]): Promise<void> {
509
- const nodes = Array.isArray(nodeOrNodeList) ? nodeOrNodeList : [nodeOrNodeList];
510
-
511
- await Promise.all(nodes.map((node) => this.doRemove(node)));
512
-
513
- if (!(isPage(nodes[0]) || isPageFragment(nodes[0]))) {
514
- // 更新历史记录
515
- this.pushHistoryState();
516
- }
517
-
518
- this.emit('remove', nodes);
519
- }
520
-
521
- public async doUpdate(config: MNode) {
522
- const root = this.get('root');
523
- if (!root) throw new Error('root为空');
524
-
525
- if (!config?.id) throw new Error('没有配置或者配置缺少id值');
526
-
527
- const info = this.getNodeInfo(config.id, false);
528
-
529
- if (!info.node) throw new Error(`获取不到id为${config.id}的节点`);
530
-
531
- const node = cloneDeep(toRaw(info.node));
532
-
533
- let newConfig = await this.toggleFixedPosition(toRaw(config), node, root);
534
-
535
- newConfig = mergeWith(cloneDeep(node), newConfig, (objValue, srcValue, key) => {
536
- if (typeof srcValue === 'undefined' && Object.hasOwn(newConfig, key)) {
537
- return '';
538
- }
539
-
540
- if (isObject(srcValue) && Array.isArray(objValue)) {
541
- // 原来的配置是数组,新的配置是对象,则直接使用新的值
542
- return srcValue;
543
- }
544
- if (Array.isArray(srcValue)) {
545
- return srcValue;
546
- }
547
- });
548
-
549
- if (!newConfig.type) throw new Error('配置缺少type值');
550
-
551
- if (newConfig.type === NodeType.ROOT) {
552
- this.set('root', newConfig as MApp);
553
- return newConfig;
554
- }
555
-
556
- const { parent } = info;
557
- if (!parent) throw new Error('获取不到父级节点');
558
-
559
- const parentNodeItems = parent.items;
560
- const index = getNodeIndex(newConfig.id, parent);
561
-
562
- if (!parentNodeItems || typeof index === 'undefined' || index === -1) throw new Error('更新的节点未找到');
563
-
564
- const newLayout = await this.getLayout(newConfig);
565
- const layout = await this.getLayout(node);
566
- if (Array.isArray(newConfig.items) && newLayout !== layout) {
567
- newConfig = setChildrenLayout(newConfig as MContainer, newLayout);
568
- }
569
-
570
- parentNodeItems[index] = newConfig;
571
-
572
- // 将update后的配置更新到nodes中
573
- const nodes = this.get('nodes');
574
- const targetIndex = nodes.findIndex((nodeItem: MNode) => `${nodeItem.id}` === `${newConfig.id}`);
575
- nodes.splice(targetIndex, 1, newConfig);
576
- this.set('nodes', [...nodes]);
577
-
578
- this.get('stage')?.update({
579
- config: cloneDeep(newConfig),
580
- parentId: parent.id,
581
- root: cloneDeep(root),
582
- });
583
-
584
- if (isPage(newConfig) || isPageFragment(newConfig)) {
585
- this.set('page', newConfig as MPage | MPageFragment);
586
- }
587
-
588
- this.addModifiedNodeId(newConfig.id);
589
-
590
- return newConfig;
591
- }
592
-
593
- /**
594
- * 更新节点
595
- * @param config 新的节点配置,配置中需要有id信息
596
- * @returns 更新后的节点配置
597
- */
598
- public async update(config: MNode | MNode[]): Promise<MNode | MNode[]> {
599
- const nodes = Array.isArray(config) ? config : [config];
600
-
601
- const newNodes = await Promise.all(nodes.map((node) => this.doUpdate(node)));
602
-
603
- if (newNodes[0]?.type !== NodeType.ROOT) {
604
- this.pushHistoryState();
605
- }
606
-
607
- this.emit('update', newNodes);
608
- return Array.isArray(config) ? newNodes : newNodes[0];
609
- }
610
-
611
- /**
612
- * 将id为id1的组件移动到id为id2的组件位置上,例如:[1,2,3,4] -> sort(1,3) -> [2,1,3,4]
613
- * @param id1 组件ID
614
- * @param id2 组件ID
615
- * @returns void
616
- */
617
- public async sort(id1: Id, id2: Id): Promise<void> {
618
- const root = this.get('root');
619
- if (!root) throw new Error('root为空');
620
-
621
- const node = this.get('node');
622
- if (!node) throw new Error('当前节点为空');
623
-
624
- const parent = cloneDeep(toRaw(this.get('parent')));
625
- if (!parent) throw new Error('父节点为空');
626
-
627
- const index2 = parent.items.findIndex((node: MNode) => `${node.id}` === `${id2}`);
628
- // 在 id1 的兄弟组件中若无 id2 则直接 return
629
- if (index2 < 0) return;
630
- const index1 = parent.items.findIndex((node: MNode) => `${node.id}` === `${id1}`);
631
-
632
- parent.items.splice(index2, 0, ...parent.items.splice(index1, 1));
633
-
634
- await this.update(parent);
635
- await this.select(node);
636
-
637
- this.get('stage')?.update({
638
- config: cloneDeep(node),
639
- parentId: parent.id,
640
- root: cloneDeep(root),
641
- });
642
-
643
- this.addModifiedNodeId(parent.id);
644
- this.pushHistoryState();
645
- }
646
-
647
- /**
648
- * 将组件节点配置存储到localStorage中
649
- * @param config 组件节点配置
650
- * @returns
651
- */
652
- public copy(config: MNode | MNode[]): void {
653
- storageService.setItem(COPY_STORAGE_KEY, Array.isArray(config) ? config : [config], {
654
- protocol: Protocol.OBJECT,
655
- });
656
- }
657
-
658
- /**
659
- * 复制时会带上组件关联的依赖
660
- * @param config 组件节点配置
661
- * @returns
662
- */
663
- public copyWithRelated(config: MNode | MNode[], collectorOptions?: TargetOptions): void {
664
- const copyNodes: MNode[] = Array.isArray(config) ? config : [config];
665
-
666
- // 初始化复制组件相关的依赖收集器
667
- if (collectorOptions && typeof collectorOptions.isTarget === 'function') {
668
- const customTarget = new Target({
669
- ...collectorOptions,
670
- });
671
-
672
- const coperWatcher = new Watcher();
673
-
674
- coperWatcher.addTarget(customTarget);
675
-
676
- coperWatcher.collect(copyNodes, {}, true, collectorOptions.type);
677
- Object.keys(customTarget.deps).forEach((nodeId: Id) => {
678
- const node = this.getNodeById(nodeId);
679
- if (!node) return;
680
- customTarget!.deps[nodeId].keys.forEach((key) => {
681
- const relateNodeId = get(node, key);
682
- const isExist = copyNodes.find((node) => node.id === relateNodeId);
683
- if (!isExist) {
684
- const relateNode = this.getNodeById(relateNodeId);
685
- if (relateNode) {
686
- copyNodes.push(relateNode);
687
- }
688
- }
689
- });
690
- });
691
- }
692
-
693
- storageService.setItem(COPY_STORAGE_KEY, copyNodes, {
694
- protocol: Protocol.OBJECT,
695
- });
696
- }
697
-
698
- /**
699
- * 从localStorage中获取节点,然后添加到当前容器中
700
- * @param position 粘贴的坐标
701
- * @returns 添加后的组件节点配置
702
- */
703
- public async paste(position: PastePosition = {}, collectorOptions?: TargetOptions): Promise<MNode | MNode[] | void> {
704
- const config: MNode[] = storageService.getItem(COPY_STORAGE_KEY);
705
- if (!Array.isArray(config)) return;
706
-
707
- const node = this.get('node');
708
-
709
- let parent: MContainer | null = null;
710
- // 粘贴的组件为当前选中组件的副本时,则添加到当前选中组件的父组件中
711
- if (config.length === 1 && config[0].id === node?.id) {
712
- parent = this.get('parent');
713
- if (parent?.type === NodeType.ROOT) {
714
- parent = this.get('page');
715
- }
716
- }
717
- const pasteConfigs = await this.doPaste(config, position);
718
-
719
- if (collectorOptions && typeof collectorOptions.isTarget === 'function') {
720
- propsService.replaceRelateId(config, pasteConfigs, collectorOptions);
721
- }
722
-
723
- return this.add(pasteConfigs, parent);
724
- }
725
-
726
- public async doPaste(config: MNode[], position: PastePosition = {}): Promise<MNode[]> {
727
- propsService.clearRelateId();
728
- const doc = this.get('stage')?.renderer.contentWindow?.document;
729
- const pasteConfigs = beforePaste(position, cloneDeep(config), doc);
730
- return pasteConfigs;
731
- }
732
-
733
- public async doAlignCenter(config: MNode): Promise<MNode> {
734
- const parent = this.getParentById(config.id);
735
-
736
- if (!parent) throw new Error('找不到父节点');
737
-
738
- const node = cloneDeep(toRaw(config));
739
- const layout = await this.getLayout(parent, node);
740
- if (layout === Layout.RELATIVE) {
741
- return config;
742
- }
743
-
744
- if (!node.style) return config;
745
-
746
- const stage = this.get('stage');
747
- const doc = stage?.renderer.contentWindow?.document;
748
-
749
- if (doc) {
750
- const el = doc.getElementById(`${node.id}`);
751
- const parentEl = layout === Layout.FIXED ? doc.body : el?.offsetParent;
752
- if (parentEl && el) {
753
- node.style.left = calcValueByFontsize(doc, (parentEl.clientWidth - el.clientWidth) / 2);
754
- node.style.right = '';
755
- }
756
- } else if (parent.style && isNumber(parent.style?.width) && isNumber(node.style?.width)) {
757
- node.style.left = (parent.style.width - node.style.width) / 2;
758
- node.style.right = '';
759
- }
760
-
761
- return node;
762
- }
763
-
764
- /**
765
- * 将指点节点设置居中
766
- * @param config 组件节点配置
767
- * @returns 当前组件节点配置
768
- */
769
- public async alignCenter(config: MNode | MNode[]): Promise<MNode | MNode[]> {
770
- const nodes = Array.isArray(config) ? config : [config];
771
- const stage = this.get('stage');
772
-
773
- const newNodes = await Promise.all(nodes.map((node) => this.doAlignCenter(node)));
774
-
775
- const newNode = await this.update(newNodes);
776
-
777
- if (newNodes.length > 1) {
778
- await stage?.multiSelect(newNodes.map((node) => node.id));
779
- } else {
780
- await stage?.select(newNodes[0].id);
781
- }
782
-
783
- return newNode;
784
- }
785
-
786
- /**
787
- * 移动当前选中节点位置
788
- * @param offset 偏移量
789
- */
790
- public async moveLayer(offset: number | LayerOffset): Promise<void> {
791
- const root = this.get('root');
792
- if (!root) throw new Error('root为空');
793
-
794
- const parent = this.get('parent');
795
- if (!parent) throw new Error('父节点为空');
796
-
797
- const node = this.get('node');
798
- if (!node) throw new Error('当前节点为空');
799
-
800
- const brothers: MNode[] = parent.items || [];
801
- const index = brothers.findIndex((item) => `${item.id}` === `${node?.id}`);
802
-
803
- // 流式布局与绝对定位布局操作的相反的
804
- const layout = await this.getLayout(parent, node);
805
- const isRelative = layout === Layout.RELATIVE;
806
-
807
- let offsetIndex: number;
808
- if (offset === LayerOffset.TOP) {
809
- offsetIndex = isRelative ? 0 : brothers.length;
810
- } else if (offset === LayerOffset.BOTTOM) {
811
- offsetIndex = isRelative ? brothers.length : 0;
812
- } else {
813
- offsetIndex = index + (isRelative ? -offset : offset);
814
- }
815
-
816
- if ((offsetIndex > 0 && offsetIndex > brothers.length) || offsetIndex < 0) {
817
- return;
818
- }
819
- brothers.splice(index, 1);
820
- brothers.splice(offsetIndex, 0, node);
821
-
822
- const grandparent = this.getParentById(parent.id);
823
-
824
- this.get('stage')?.update({
825
- config: cloneDeep(toRaw(parent)),
826
- parentId: grandparent?.id,
827
- root: cloneDeep(root),
828
- });
829
-
830
- this.addModifiedNodeId(parent.id);
831
- this.pushHistoryState();
832
-
833
- this.emit('move-layer', offset);
834
- }
835
-
836
- /**
837
- * 移动到指定容器中
838
- * @param config 需要移动的节点
839
- * @param targetId 容器ID
840
- */
841
- public async moveToContainer(config: MNode, targetId: Id): Promise<MNode | undefined> {
842
- const root = this.get('root');
843
- const { node, parent } = this.getNodeInfo(config.id, false);
844
- const target = this.getNodeById(targetId, false) as MContainer;
845
-
846
- const stage = this.get('stage');
847
- if (root && node && parent && stage) {
848
- const index = getNodeIndex(node.id, parent);
849
- parent.items?.splice(index, 1);
850
-
851
- await stage.remove({ id: node.id, parentId: parent.id, root: cloneDeep(root) });
852
-
853
- const layout = await this.getLayout(target);
854
-
855
- const newConfig = mergeWith(cloneDeep(node), config, (objValue, srcValue) => {
856
- if (Array.isArray(srcValue)) {
857
- return srcValue;
858
- }
859
- });
860
- newConfig.style = getInitPositionStyle(newConfig.style, layout);
861
-
862
- target.items.push(newConfig);
863
-
864
- await stage.select(targetId);
865
-
866
- const targetParent = this.getParentById(target.id);
867
- await stage.update({ config: cloneDeep(target), parentId: targetParent?.id, root: cloneDeep(root) });
868
-
869
- await this.select(newConfig);
870
- stage.select(newConfig.id);
871
-
872
- this.addModifiedNodeId(target.id);
873
- this.addModifiedNodeId(parent.id);
874
- this.pushHistoryState();
875
-
876
- return newConfig;
877
- }
878
- }
879
-
880
- public async dragTo(config: MNode, targetParent: MContainer, targetIndex: number) {
881
- if (!targetParent || !Array.isArray(targetParent.items)) return;
882
-
883
- const { parent, node: curNode } = this.getNodeInfo(config.id, false);
884
- if (!parent || !curNode) throw new Error('找不要删除的节点');
885
-
886
- const index = getNodeIndex(curNode.id, parent);
887
-
888
- if (typeof index !== 'number' || index === -1) throw new Error('找不要删除的节点');
889
-
890
- if (parent.id === targetParent.id) {
891
- if (index === targetIndex) return;
892
-
893
- if (index < targetIndex) {
894
- targetIndex -= 1;
895
- }
896
- }
897
-
898
- const layout = await this.getLayout(parent);
899
- const newLayout = await this.getLayout(targetParent);
900
-
901
- if (newLayout !== layout) {
902
- setLayout(config, newLayout);
903
- }
904
-
905
- parent.items?.splice(index, 1);
906
-
907
- targetParent.items?.splice(targetIndex, 0, config);
908
-
909
- const page = this.get('page');
910
- const root = this.get('root');
911
- const stage = this.get('stage');
912
-
913
- if (stage && page && root) {
914
- stage.update({
915
- config: cloneDeep(page),
916
- parentId: root.id,
917
- root: cloneDeep(root),
918
- });
919
- }
920
-
921
- this.addModifiedNodeId(config.id);
922
- this.addModifiedNodeId(parent.id);
923
-
924
- this.pushHistoryState();
925
-
926
- this.emit('drag-to', { index, targetIndex, config, parent, targetParent });
927
- }
928
-
929
- /**
930
- * 撤销当前操作
931
- * @returns 上一次数据
932
- */
933
- public async undo(): Promise<StepValue | null> {
934
- const value = historyService.undo();
935
- await this.changeHistoryState(value);
936
- return value;
937
- }
938
-
939
- /**
940
- * 恢复到下一步
941
- * @returns 下一步数据
942
- */
943
- public async redo(): Promise<StepValue | null> {
944
- const value = historyService.redo();
945
- await this.changeHistoryState(value);
946
- return value;
947
- }
948
-
949
- public async move(left: number, top: number) {
950
- const node = toRaw(this.get('node'));
951
- if (!node || isPage(node)) return;
952
-
953
- const { style, id, type } = node;
954
- if (!style || !['absolute', 'fixed'].includes(style.position)) return;
955
-
956
- const update = (style: { [key: string]: any }) =>
957
- this.update({
958
- id,
959
- type,
960
- style,
961
- });
962
-
963
- if (top) {
964
- if (isNumber(style.top)) {
965
- update({
966
- ...style,
967
- top: Number(style.top) + Number(top),
968
- bottom: '',
969
- });
970
- } else if (isNumber(style.bottom)) {
971
- update({
972
- ...style,
973
- bottom: Number(style.bottom) - Number(top),
974
- top: '',
975
- });
976
- }
977
- }
978
-
979
- if (left) {
980
- if (isNumber(style.left)) {
981
- update({
982
- ...style,
983
- left: Number(style.left) + Number(left),
984
- right: '',
985
- });
986
- } else if (isNumber(style.right)) {
987
- update({
988
- ...style,
989
- right: Number(style.right) - Number(left),
990
- left: '',
991
- });
992
- }
993
- }
994
- }
995
-
996
- public resetState() {
997
- this.set('root', null);
998
- this.set('node', null);
999
- this.set('nodes', []);
1000
- this.set('page', null);
1001
- this.set('parent', null);
1002
- this.set('stage', null);
1003
- this.set('highlightNode', null);
1004
- this.set('modifiedNodeIds', new Map());
1005
- this.set('pageLength', 0);
1006
- }
1007
-
1008
- public destroy() {
1009
- this.removeAllListeners();
1010
- this.resetState();
1011
- this.removeAllPlugins();
1012
- }
1013
-
1014
- public resetModifiedNodeId() {
1015
- this.get('modifiedNodeIds').clear();
1016
- }
1017
-
1018
- public usePlugin(options: AsyncHookPlugin<AsyncMethodName, Editor>): void {
1019
- super.usePlugin(options);
1020
- }
1021
-
1022
- private addModifiedNodeId(id: Id) {
1023
- if (!this.isHistoryStateChange) {
1024
- this.get('modifiedNodeIds').set(id, id);
1025
- }
1026
- }
1027
-
1028
- private pushHistoryState() {
1029
- const curNode = cloneDeep(toRaw(this.get('node')));
1030
- const page = this.get('page');
1031
- if (!this.isHistoryStateChange && curNode && page) {
1032
- historyService.push({
1033
- data: cloneDeep(toRaw(page)),
1034
- modifiedNodeIds: this.get('modifiedNodeIds'),
1035
- nodeId: curNode.id,
1036
- });
1037
- }
1038
- this.isHistoryStateChange = false;
1039
- }
1040
-
1041
- private async changeHistoryState(value: StepValue | null) {
1042
- if (!value) return;
1043
-
1044
- this.isHistoryStateChange = true;
1045
- await this.update(value.data);
1046
- this.set('modifiedNodeIds', value.modifiedNodeIds);
1047
- setTimeout(async () => {
1048
- if (!value.nodeId) return;
1049
- await this.select(value.nodeId);
1050
- this.get('stage')?.select(value.nodeId);
1051
- }, 0);
1052
- this.emit('history-change', value.data);
1053
- }
1054
-
1055
- private async toggleFixedPosition(dist: MNode, src: MNode, root: MApp) {
1056
- const newConfig = cloneDeep(dist);
1057
-
1058
- if (!isPop(src) && newConfig.style?.position) {
1059
- if (isFixed(newConfig) && !isFixed(src)) {
1060
- newConfig.style = change2Fixed(newConfig, root);
1061
- } else if (!isFixed(newConfig) && isFixed(src)) {
1062
- newConfig.style = await Fixed2Other(newConfig, root, this.getLayout);
1063
- }
1064
- }
1065
-
1066
- return newConfig;
1067
- }
1068
-
1069
- private selectedConfigExceptionHandler(config: MNode | Id): EditorNodeInfo {
1070
- let id: Id;
1071
- if (typeof config === 'string' || typeof config === 'number') {
1072
- id = config;
1073
- } else {
1074
- id = config.id;
1075
- }
1076
- if (!id) {
1077
- throw new Error('没有ID,无法选中');
1078
- }
1079
-
1080
- const { node, parent, page } = this.getNodeInfo(id);
1081
- if (!node) throw new Error('获取不到组件信息');
1082
-
1083
- if (node.id === this.state.root?.id) {
1084
- throw new Error('不能选根节点');
1085
- }
1086
- return {
1087
- node,
1088
- parent,
1089
- page,
1090
- };
1091
- }
1092
- }
1093
-
1094
- export type EditorService = Editor;
1095
-
1096
- export default new Editor();