@plait/core 0.24.0-next.1 → 0.24.0-next.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 (103) hide show
  1. package/board/board.component.d.ts +1 -1
  2. package/core/children/children.component.d.ts +1 -1
  3. package/core/element/element.component.d.ts +1 -1
  4. package/core/element/plugin-element.d.ts +1 -1
  5. package/core/island/island-base.component.d.ts +1 -1
  6. package/{esm2020 → esm2022}/board/board.component.mjs +6 -6
  7. package/{esm2020 → esm2022}/core/children/children.component.mjs +6 -6
  8. package/{esm2020 → esm2022}/core/element/element.component.mjs +4 -4
  9. package/{esm2020 → esm2022}/core/element/plugin-element.mjs +4 -4
  10. package/{esm2020 → esm2022}/core/island/island-base.component.mjs +7 -7
  11. package/esm2022/interfaces/rectangle-client.mjs +56 -0
  12. package/{esm2020 → esm2022}/plait.module.mjs +5 -5
  13. package/esm2022/plugins/with-moving.mjs +98 -0
  14. package/{esm2020 → esm2022}/services/image-context.service.mjs +4 -4
  15. package/esm2022/utils/dom/common.mjs +68 -0
  16. package/esm2022/utils/element.mjs +53 -0
  17. package/esm2022/utils/math.mjs +128 -0
  18. package/{fesm2020 → fesm2022}/plait-core.mjs +199 -80
  19. package/fesm2022/plait-core.mjs.map +1 -0
  20. package/interfaces/rectangle-client.d.ts +2 -0
  21. package/package.json +14 -14
  22. package/utils/dom/common.d.ts +4 -0
  23. package/utils/element.d.ts +1 -0
  24. package/utils/math.d.ts +6 -0
  25. package/esm2020/interfaces/rectangle-client.mjs +0 -40
  26. package/esm2020/plugins/with-moving.mjs +0 -97
  27. package/esm2020/utils/dom/common.mjs +0 -53
  28. package/esm2020/utils/element.mjs +0 -44
  29. package/esm2020/utils/math.mjs +0 -48
  30. package/fesm2015/plait-core.mjs +0 -3454
  31. package/fesm2015/plait-core.mjs.map +0 -1
  32. package/fesm2020/plait-core.mjs.map +0 -1
  33. /package/{esm2020 → esm2022}/board/board.component.interface.mjs +0 -0
  34. /package/{esm2020 → esm2022}/constants/index.mjs +0 -0
  35. /package/{esm2020 → esm2022}/constants/keycodes.mjs +0 -0
  36. /package/{esm2020 → esm2022}/constants/resize.mjs +0 -0
  37. /package/{esm2020 → esm2022}/constants/selection.mjs +0 -0
  38. /package/{esm2020 → esm2022}/core/children/effect.mjs +0 -0
  39. /package/{esm2020 → esm2022}/core/element/context-change.mjs +0 -0
  40. /package/{esm2020 → esm2022}/core/element/context.mjs +0 -0
  41. /package/{esm2020 → esm2022}/interfaces/board.mjs +0 -0
  42. /package/{esm2020 → esm2022}/interfaces/custom-types.mjs +0 -0
  43. /package/{esm2020 → esm2022}/interfaces/element.mjs +0 -0
  44. /package/{esm2020 → esm2022}/interfaces/history.mjs +0 -0
  45. /package/{esm2020 → esm2022}/interfaces/index.mjs +0 -0
  46. /package/{esm2020 → esm2022}/interfaces/node.mjs +0 -0
  47. /package/{esm2020 → esm2022}/interfaces/operation.mjs +0 -0
  48. /package/{esm2020 → esm2022}/interfaces/path-ref.mjs +0 -0
  49. /package/{esm2020 → esm2022}/interfaces/path.mjs +0 -0
  50. /package/{esm2020 → esm2022}/interfaces/plugin-key.mjs +0 -0
  51. /package/{esm2020 → esm2022}/interfaces/plugin.mjs +0 -0
  52. /package/{esm2020 → esm2022}/interfaces/point.mjs +0 -0
  53. /package/{esm2020 → esm2022}/interfaces/pointer.mjs +0 -0
  54. /package/{esm2020 → esm2022}/interfaces/selection.mjs +0 -0
  55. /package/{esm2020 → esm2022}/interfaces/theme.mjs +0 -0
  56. /package/{esm2020 → esm2022}/interfaces/viewport.mjs +0 -0
  57. /package/{esm2020 → esm2022}/plait-core.mjs +0 -0
  58. /package/{esm2020 → esm2022}/plugins/create-board.mjs +0 -0
  59. /package/{esm2020 → esm2022}/plugins/with-board.mjs +0 -0
  60. /package/{esm2020 → esm2022}/plugins/with-hand.mjs +0 -0
  61. /package/{esm2020 → esm2022}/plugins/with-history.mjs +0 -0
  62. /package/{esm2020 → esm2022}/plugins/with-hotkey.mjs +0 -0
  63. /package/{esm2020 → esm2022}/plugins/with-options.mjs +0 -0
  64. /package/{esm2020 → esm2022}/plugins/with-selection.mjs +0 -0
  65. /package/{esm2020 → esm2022}/plugins/with-viewport.mjs +0 -0
  66. /package/{esm2020 → esm2022}/public-api.mjs +0 -0
  67. /package/{esm2020 → esm2022}/testing/core/create-board.mjs +0 -0
  68. /package/{esm2020 → esm2022}/testing/core/fake-weak-map.mjs +0 -0
  69. /package/{esm2020 → esm2022}/testing/core/index.mjs +0 -0
  70. /package/{esm2020 → esm2022}/testing/fake-events/event-objects.mjs +0 -0
  71. /package/{esm2020 → esm2022}/testing/fake-events/index.mjs +0 -0
  72. /package/{esm2020 → esm2022}/testing/index.mjs +0 -0
  73. /package/{esm2020 → esm2022}/testing/test-element.mjs +0 -0
  74. /package/{esm2020 → esm2022}/transforms/board.mjs +0 -0
  75. /package/{esm2020 → esm2022}/transforms/general.mjs +0 -0
  76. /package/{esm2020 → esm2022}/transforms/index.mjs +0 -0
  77. /package/{esm2020 → esm2022}/transforms/node.mjs +0 -0
  78. /package/{esm2020 → esm2022}/transforms/selection.mjs +0 -0
  79. /package/{esm2020 → esm2022}/transforms/theme.mjs +0 -0
  80. /package/{esm2020 → esm2022}/transforms/viewport.mjs +0 -0
  81. /package/{esm2020 → esm2022}/utils/board.mjs +0 -0
  82. /package/{esm2020 → esm2022}/utils/clipboard.mjs +0 -0
  83. /package/{esm2020 → esm2022}/utils/common.mjs +0 -0
  84. /package/{esm2020 → esm2022}/utils/dom/environment.mjs +0 -0
  85. /package/{esm2020 → esm2022}/utils/dom/foreign.mjs +0 -0
  86. /package/{esm2020 → esm2022}/utils/dom/index.mjs +0 -0
  87. /package/{esm2020 → esm2022}/utils/draw/arrow.mjs +0 -0
  88. /package/{esm2020 → esm2022}/utils/draw/circle.mjs +0 -0
  89. /package/{esm2020 → esm2022}/utils/draw/line.mjs +0 -0
  90. /package/{esm2020 → esm2022}/utils/draw/rectangle.mjs +0 -0
  91. /package/{esm2020 → esm2022}/utils/environment.mjs +0 -0
  92. /package/{esm2020 → esm2022}/utils/helper.mjs +0 -0
  93. /package/{esm2020 → esm2022}/utils/history.mjs +0 -0
  94. /package/{esm2020 → esm2022}/utils/hotkeys.mjs +0 -0
  95. /package/{esm2020 → esm2022}/utils/id-creator.mjs +0 -0
  96. /package/{esm2020 → esm2022}/utils/index.mjs +0 -0
  97. /package/{esm2020 → esm2022}/utils/moving-element.mjs +0 -0
  98. /package/{esm2020 → esm2022}/utils/selected-element.mjs +0 -0
  99. /package/{esm2020 → esm2022}/utils/to-image.mjs +0 -0
  100. /package/{esm2020 → esm2022}/utils/touch.mjs +0 -0
  101. /package/{esm2020 → esm2022}/utils/tree.mjs +0 -0
  102. /package/{esm2020 → esm2022}/utils/viewport.mjs +0 -0
  103. /package/{esm2020 → esm2022}/utils/weak-maps.mjs +0 -0
@@ -1,3454 +0,0 @@
1
- import * as i0 from '@angular/core';
2
- import { Directive, Input, Injectable, Component, ChangeDetectionStrategy, EventEmitter, ElementRef, Output, HostBinding, ViewChild, ContentChildren, NgModule } from '@angular/core';
3
- import rough from 'roughjs/bin/rough';
4
- import { timer, Subject, fromEvent } from 'rxjs';
5
- import { takeUntil, filter, tap } from 'rxjs/operators';
6
- import produce, { createDraft, finishDraft, isDraft } from 'immer';
7
- import { isKeyHotkey, isHotkey } from 'is-hotkey';
8
- import { __awaiter } from 'tslib';
9
- import * as i1 from '@angular/common';
10
- import { CommonModule } from '@angular/common';
11
-
12
- // record richtext type status
13
- const IS_BOARD_CACHE = new WeakMap();
14
- const FLUSHING = new WeakMap();
15
- const NODE_TO_INDEX = new WeakMap();
16
- const NODE_TO_PARENT = new WeakMap();
17
- const IS_TEXT_EDITABLE = new WeakMap();
18
- const BOARD_TO_ON_CHANGE = new WeakMap();
19
- const BOARD_TO_COMPONENT = new WeakMap();
20
- const BOARD_TO_ROUGH_SVG = new WeakMap();
21
- const BOARD_TO_HOST = new WeakMap();
22
- const BOARD_TO_ELEMENT_HOST = new WeakMap();
23
- const BOARD_TO_SELECTED_ELEMENT = new WeakMap();
24
- const BOARD_TO_MOVING_POINT_IN_BOARD = new WeakMap();
25
- const BOARD_TO_MOVING_POINT = new WeakMap();
26
- const BOARD_TO_VIEWPORT_ORIGINATION = new WeakMap();
27
- const BOARD_TO_IS_SELECTION_MOVING = new WeakMap();
28
- // save no standard selected elements
29
- const BOARD_TO_TEMPORARY_ELEMENTS = new WeakMap();
30
- const BOARD_TO_MOVING_ELEMENT = new WeakMap();
31
- const IS_PREVENT_TOUCH_MOVE = new WeakMap();
32
- const PATH_REFS = new WeakMap();
33
-
34
- function depthFirstRecursion(node, callback, recursion, isReverse) {
35
- if (!recursion || recursion(node)) {
36
- let children = [];
37
- if (node.children) {
38
- children = [...node.children];
39
- }
40
- children = isReverse ? children.reverse() : children;
41
- children.forEach(child => {
42
- depthFirstRecursion(child, callback, recursion);
43
- });
44
- }
45
- callback(node);
46
- }
47
- const getIsRecursionFunc = (board) => {
48
- return (element) => {
49
- if (PlaitBoard.isBoard(element) || board.isRecursion(element)) {
50
- return true;
51
- }
52
- else {
53
- return false;
54
- }
55
- };
56
- };
57
-
58
- function getRectangleByElements(board, elements, recursion) {
59
- const boundaryBox = {
60
- left: Number.MAX_VALUE,
61
- top: Number.MAX_VALUE,
62
- right: Number.NEGATIVE_INFINITY,
63
- bottom: Number.NEGATIVE_INFINITY
64
- };
65
- const calcRectangleClient = (node) => {
66
- const nodeRectangle = board.getRectangle(node);
67
- if (nodeRectangle) {
68
- boundaryBox.left = Math.min(boundaryBox.left, nodeRectangle.x);
69
- boundaryBox.top = Math.min(boundaryBox.top, nodeRectangle.y);
70
- boundaryBox.right = Math.max(boundaryBox.right, nodeRectangle.x + nodeRectangle.width);
71
- boundaryBox.bottom = Math.max(boundaryBox.bottom, nodeRectangle.y + nodeRectangle.height);
72
- }
73
- };
74
- elements.forEach(element => {
75
- if (recursion) {
76
- depthFirstRecursion(element, node => calcRectangleClient(node), node => board.isRecursion(node));
77
- }
78
- else {
79
- calcRectangleClient(element);
80
- }
81
- });
82
- if (boundaryBox.left === Number.MAX_VALUE) {
83
- return {
84
- x: 0,
85
- y: 0,
86
- width: 0,
87
- height: 0
88
- };
89
- }
90
- return {
91
- x: boundaryBox.left,
92
- y: boundaryBox.top,
93
- width: boundaryBox.right - boundaryBox.left,
94
- height: boundaryBox.bottom - boundaryBox.top
95
- };
96
- }
97
- function getBoardRectangle(board) {
98
- return getRectangleByElements(board, board.children, true);
99
- }
100
-
101
- var ThemeColorMode;
102
- (function (ThemeColorMode) {
103
- ThemeColorMode["default"] = "default";
104
- ThemeColorMode["colorful"] = "colorful";
105
- ThemeColorMode["soft"] = "soft";
106
- ThemeColorMode["retro"] = "retro";
107
- ThemeColorMode["dark"] = "dark";
108
- ThemeColorMode["starry"] = "starry";
109
- })(ThemeColorMode || (ThemeColorMode = {}));
110
- const DefaultThemeColor = {
111
- mode: ThemeColorMode.default,
112
- boardBackground: '#ffffff',
113
- textColor: '#333333'
114
- };
115
- const ColorfulThemeColor = {
116
- mode: ThemeColorMode.colorful,
117
- boardBackground: '#ffffff',
118
- textColor: '#333333'
119
- };
120
- const SoftThemeColor = {
121
- mode: ThemeColorMode.soft,
122
- boardBackground: '#f5f5f5',
123
- textColor: '#333333'
124
- };
125
- const RetroThemeColor = {
126
- mode: ThemeColorMode.retro,
127
- boardBackground: '#f9f8ed',
128
- textColor: '#333333'
129
- };
130
- const DarkThemeColor = {
131
- mode: ThemeColorMode.dark,
132
- boardBackground: '#141414',
133
- textColor: '#FFFFFF'
134
- };
135
- const StarryThemeColor = {
136
- mode: ThemeColorMode.starry,
137
- boardBackground: '#0d2537',
138
- textColor: '#FFFFFF'
139
- };
140
- const ThemeColors = [
141
- DefaultThemeColor,
142
- ColorfulThemeColor,
143
- SoftThemeColor,
144
- RetroThemeColor,
145
- DarkThemeColor,
146
- StarryThemeColor
147
- ];
148
-
149
- // https://stackoverflow.com/a/6853926/232122
150
- function distanceBetweenPointAndSegment(x, y, x1, y1, x2, y2) {
151
- const A = x - x1;
152
- const B = y - y1;
153
- const C = x2 - x1;
154
- const D = y2 - y1;
155
- const dot = A * C + B * D;
156
- const lenSquare = C * C + D * D;
157
- let param = -1;
158
- if (lenSquare !== 0) {
159
- // in case of 0 length line
160
- param = dot / lenSquare;
161
- }
162
- let xx, yy;
163
- if (param < 0) {
164
- xx = x1;
165
- yy = y1;
166
- }
167
- else if (param > 1) {
168
- xx = x2;
169
- yy = y2;
170
- }
171
- else {
172
- xx = x1 + param * C;
173
- yy = y1 + param * D;
174
- }
175
- const dx = x - xx;
176
- const dy = y - yy;
177
- return Math.hypot(dx, dy);
178
- }
179
- function rotate(x1, y1, x2, y2, angle) {
180
- // 𝑎′𝑥=(𝑎𝑥−𝑐𝑥)cos𝜃−(𝑎𝑦−𝑐𝑦)sin𝜃+𝑐𝑥
181
- // 𝑎′𝑦=(𝑎𝑥−𝑐𝑥)sin𝜃+(𝑎𝑦−𝑐𝑦)cos𝜃+𝑐𝑦.
182
- // https://math.stackexchange.com/questions/2204520/how-do-i-rotate-a-line-segment-in-a-specific-point-on-the-line
183
- return [(x1 - x2) * Math.cos(angle) - (y1 - y2) * Math.sin(angle) + x2, (x1 - x2) * Math.sin(angle) + (y1 - y2) * Math.cos(angle) + y2];
184
- }
185
- function distanceBetweenPointAndPoint(x1, y1, x2, y2) {
186
- const dx = x1 - x2;
187
- const dy = y1 - y2;
188
- return Math.hypot(dx, dy);
189
- }
190
- // https://stackoverflow.com/questions/5254838/calculating-distance-between-a-point-and-a-rectangular-box-nearest-point
191
- function distanceBetweenPointAndRectangle(x, y, rect) {
192
- var dx = Math.max(rect.x - x, 0, x - (rect.x + rect.width));
193
- var dy = Math.max(rect.y - y, 0, y - (rect.y + rect.height));
194
- return Math.sqrt(dx * dx + dy * dy);
195
- }
196
-
197
- const PlaitBoard = {
198
- isBoard(value) {
199
- const cachedIsBoard = IS_BOARD_CACHE.get(value);
200
- if (cachedIsBoard !== undefined) {
201
- return cachedIsBoard;
202
- }
203
- const isBoard = typeof value.onChange === 'function' && typeof value.apply === 'function';
204
- IS_BOARD_CACHE.set(value, isBoard);
205
- return isBoard;
206
- },
207
- findPath(board, node) {
208
- const path = [];
209
- let child = node;
210
- while (true) {
211
- const parent = NODE_TO_PARENT.get(child);
212
- if (parent == null) {
213
- if (PlaitBoard.isBoard(child)) {
214
- return path;
215
- }
216
- else {
217
- break;
218
- }
219
- }
220
- const i = NODE_TO_INDEX.get(child);
221
- if (i == null) {
222
- break;
223
- }
224
- path.unshift(i);
225
- child = parent;
226
- }
227
- throw new Error(`Unable to find the path for Plait node: ${JSON.stringify(node)}`);
228
- },
229
- getHost(board) {
230
- return BOARD_TO_HOST.get(board);
231
- },
232
- getElementHost(board) {
233
- var _a;
234
- return (_a = BOARD_TO_ELEMENT_HOST.get(board)) === null || _a === void 0 ? void 0 : _a.host;
235
- },
236
- getElementUpperHost(board) {
237
- var _a;
238
- return (_a = BOARD_TO_ELEMENT_HOST.get(board)) === null || _a === void 0 ? void 0 : _a.upperHost;
239
- },
240
- getElementActiveHost(board) {
241
- var _a;
242
- return (_a = BOARD_TO_ELEMENT_HOST.get(board)) === null || _a === void 0 ? void 0 : _a.activeHost;
243
- },
244
- getRoughSVG(board) {
245
- return BOARD_TO_ROUGH_SVG.get(board);
246
- },
247
- getComponent(board) {
248
- return BOARD_TO_COMPONENT.get(board);
249
- },
250
- getBoardContainer(board) {
251
- return PlaitBoard.getComponent(board).nativeElement;
252
- },
253
- getRectangle(board) {
254
- return getRectangleByElements(board, board.children, true);
255
- },
256
- getViewportContainer(board) {
257
- return PlaitBoard.getHost(board).parentElement;
258
- },
259
- isFocus(board) {
260
- return !!board.selection;
261
- },
262
- isReadonly(board) {
263
- return board.options.readonly;
264
- },
265
- hasBeenTextEditing(board) {
266
- return !!IS_TEXT_EDITABLE.get(board);
267
- },
268
- getPointer(board) {
269
- return board.pointer;
270
- },
271
- isPointer(board, pointer) {
272
- return board.pointer === pointer;
273
- },
274
- isInPointer(board, pointers) {
275
- const point = board.pointer;
276
- return pointers.includes(point);
277
- },
278
- getMovingPointInBoard(board) {
279
- return BOARD_TO_MOVING_POINT_IN_BOARD.get(board);
280
- },
281
- isMovingPointInBoard(board) {
282
- const point = BOARD_TO_MOVING_POINT.get(board);
283
- const rect = PlaitBoard.getBoardContainer(board).getBoundingClientRect();
284
- if (point && distanceBetweenPointAndRectangle(point[0], point[1], rect) === 0) {
285
- return true;
286
- }
287
- return false;
288
- },
289
- getThemeColors(board) {
290
- return (board.options.themeColors || ThemeColors);
291
- }
292
- };
293
-
294
- var PlaitPointerType;
295
- (function (PlaitPointerType) {
296
- PlaitPointerType["hand"] = "hand";
297
- PlaitPointerType["selection"] = "selection";
298
- })(PlaitPointerType || (PlaitPointerType = {}));
299
-
300
- function isNullOrUndefined(value) {
301
- return value === null || value === undefined;
302
- }
303
- /**
304
- * 规范 point
305
- * @param point
306
- * @returns point
307
- */
308
- function normalizePoint(point) {
309
- return Array.isArray(point)
310
- ? {
311
- x: point[0],
312
- y: point[1]
313
- }
314
- : point;
315
- }
316
-
317
- const Viewport = {
318
- isViewport: (value) => {
319
- return !isNullOrUndefined(value.zoom) && !isNullOrUndefined(value.viewBackgroundColor);
320
- },
321
- };
322
-
323
- const Path = {
324
- /**
325
- * Get a list of ancestor paths for a given path.
326
- *
327
- * The paths are sorted from shallowest to deepest ancestor. However, if the
328
- * `reverse: true` option is passed, they are reversed.
329
- */
330
- ancestors(path, options = {}) {
331
- const { reverse = false } = options;
332
- let paths = Path.levels(path, options);
333
- if (reverse) {
334
- paths = paths.slice(1);
335
- }
336
- else {
337
- paths = paths.slice(0, -1);
338
- }
339
- return paths;
340
- },
341
- /**
342
- * Get a list of paths at every level down to a path. Note: this is the same
343
- * as `Path.ancestors`, but including the path itself.
344
- *
345
- * The paths are sorted from shallowest to deepest. However, if the `reverse:
346
- * true` option is passed, they are reversed.
347
- */
348
- levels(path, options = {}) {
349
- const { reverse = false } = options;
350
- const list = [];
351
- for (let i = 0; i <= path.length; i++) {
352
- list.push(path.slice(0, i));
353
- }
354
- if (reverse) {
355
- list.reverse();
356
- }
357
- return list;
358
- },
359
- parent(path) {
360
- if (path.length === 0) {
361
- throw new Error(`Cannot get the parent path of the root path [${path}].`);
362
- }
363
- return path.slice(0, -1);
364
- },
365
- next(path) {
366
- if (path.length === 0) {
367
- throw new Error(`Cannot get the next path of a root path [${path}], because it has no next index.`);
368
- }
369
- const last = path[path.length - 1];
370
- return path.slice(0, -1).concat(last + 1);
371
- },
372
- hasPrevious(path) {
373
- return path[path.length - 1] > 0;
374
- },
375
- previous(path) {
376
- if (path.length === 0) {
377
- throw new Error(`Cannot get the next path of a root path [${path}], because it has no previous index.`);
378
- }
379
- const last = path[path.length - 1];
380
- return path.slice(0, -1).concat(last - 1);
381
- },
382
- /**
383
- * Check if a path is an ancestor of another.
384
- */
385
- isAncestor(path, another) {
386
- return path.length < another.length && Path.compare(path, another) === 0;
387
- },
388
- /**
389
- * Compare a path to another, returning an integer indicating whether the path
390
- * was before, at, or after the other.
391
- *
392
- * Note: Two paths of unequal length can still receive a `0` result if one is
393
- * directly above or below the other. If you want exact matching, use
394
- * [[Path.equals]] instead.
395
- */
396
- compare(path, another) {
397
- const min = Math.min(path.length, another.length);
398
- for (let i = 0; i < min; i++) {
399
- if (path[i] < another[i])
400
- return -1;
401
- if (path[i] > another[i])
402
- return 1;
403
- }
404
- return 0;
405
- },
406
- /**
407
- * Check if a path is exactly equal to another.
408
- */
409
- equals(path, another) {
410
- return path.length === another.length && path.every((n, i) => n === another[i]);
411
- },
412
- /**
413
- * Check if a path ends before one of the indexes in another.
414
- */
415
- endsBefore(path, another) {
416
- const i = path.length - 1;
417
- const as = path.slice(0, i);
418
- const bs = another.slice(0, i);
419
- const av = path[i];
420
- const bv = another[i];
421
- return Path.equals(as, bs) && av < bv;
422
- },
423
- /**
424
- * Check if a path is a sibling of another.
425
- */
426
- isSibling(path, another) {
427
- if (path.length !== another.length) {
428
- return false;
429
- }
430
- const as = path.slice(0, -1);
431
- const bs = another.slice(0, -1);
432
- const al = path[path.length - 1];
433
- const bl = another[another.length - 1];
434
- return al !== bl && Path.equals(as, bs);
435
- },
436
- transform(path, operation) {
437
- return produce(path, p => {
438
- // PERF: Exit early if the operation is guaranteed not to have an effect.
439
- if (!path || (path === null || path === void 0 ? void 0 : path.length) === 0) {
440
- return;
441
- }
442
- if (p === null) {
443
- return null;
444
- }
445
- switch (operation.type) {
446
- case 'insert_node': {
447
- const { path: op } = operation;
448
- if (Path.equals(op, p) || Path.endsBefore(op, p) || Path.isAncestor(op, p)) {
449
- p[op.length - 1] += 1;
450
- }
451
- break;
452
- }
453
- case 'remove_node': {
454
- const { path: op } = operation;
455
- if (Path.equals(op, p) || Path.isAncestor(op, p)) {
456
- return null;
457
- }
458
- else if (Path.endsBefore(op, p)) {
459
- p[op.length - 1] -= 1;
460
- }
461
- break;
462
- }
463
- case 'move_node': {
464
- const { path: op, newPath: onp } = operation;
465
- // If the old and new path are the same, it's a no-op.
466
- if (Path.equals(op, onp)) {
467
- return;
468
- }
469
- if (Path.isAncestor(op, p) || Path.equals(op, p)) {
470
- const copy = onp.slice();
471
- // op.length <= onp.length is different for slate
472
- // resolve drag from [0, 0] to [0, 3] issue
473
- if (Path.endsBefore(op, onp) && op.length <= onp.length) {
474
- copy[op.length - 1] -= 1;
475
- }
476
- return copy.concat(p.slice(op.length));
477
- }
478
- else if (Path.isSibling(op, onp) && (Path.isAncestor(onp, p) || Path.equals(onp, p))) {
479
- if (Path.endsBefore(op, p)) {
480
- p[op.length - 1] -= 1;
481
- }
482
- else {
483
- p[op.length - 1] += 1;
484
- }
485
- }
486
- else if (Path.endsBefore(onp, p) || Path.equals(onp, p) || Path.isAncestor(onp, p)) {
487
- if (Path.endsBefore(op, p)) {
488
- p[op.length - 1] -= 1;
489
- }
490
- p[onp.length - 1] += 1;
491
- }
492
- else if (Path.endsBefore(op, p)) {
493
- if (Path.equals(onp, p)) {
494
- p[onp.length - 1] += 1;
495
- }
496
- p[op.length - 1] -= 1;
497
- }
498
- break;
499
- }
500
- }
501
- return p;
502
- });
503
- }
504
- };
505
-
506
- const PlaitNode = {
507
- parent: (board, path) => {
508
- const parentPath = Path.parent(path);
509
- const p = PlaitNode.get(board, parentPath);
510
- return p;
511
- },
512
- /**
513
- * Return a generator of all the ancestor nodes above a specific path.
514
- *
515
- * By default the order is top-down, from highest to lowest ancestor in
516
- * the tree, but you can pass the `reverse: true` option to go bottom-up.
517
- */
518
- *parents(root, path, options = {}) {
519
- for (const p of Path.ancestors(path, options)) {
520
- const n = PlaitNode.get(root, p);
521
- yield n;
522
- }
523
- },
524
- get(root, path) {
525
- let node = root;
526
- for (let i = 0; i < path.length; i++) {
527
- const p = path[i];
528
- if (!node || !node.children || !node.children[p]) {
529
- throw new Error(`Cannot find a descendant at path [${path}]`);
530
- }
531
- node = node.children[p];
532
- }
533
- return node;
534
- },
535
- last(board, path) {
536
- let n = PlaitNode.get(board, path);
537
- while (n && n.children && n.children.length > 0) {
538
- const i = n.children.length - 1;
539
- n = n.children[i];
540
- }
541
- return n;
542
- }
543
- };
544
-
545
- const applyToDraft = (board, selection, viewport, theme, op) => {
546
- var _a, _b;
547
- switch (op.type) {
548
- case 'insert_node': {
549
- const { path, node } = op;
550
- const parent = PlaitNode.parent(board, path);
551
- const index = path[path.length - 1];
552
- if (!parent.children || index > parent.children.length) {
553
- throw new Error(`Cannot apply an "insert_node" operation at path [${path}] because the destination is past the end of the node.`);
554
- }
555
- parent.children.splice(index, 0, node);
556
- break;
557
- }
558
- case 'remove_node': {
559
- const { path } = op;
560
- const parent = PlaitNode.parent(board, path);
561
- const index = path[path.length - 1];
562
- if (!parent.children || index > parent.children.length) {
563
- throw new Error(`Cannot apply an "insert_node" operation at path [${path}] because the destination is past the end of the node.`);
564
- }
565
- parent.children.splice(index, 1);
566
- break;
567
- }
568
- case 'move_node': {
569
- const { path, newPath } = op;
570
- if (Path.isAncestor(path, newPath)) {
571
- throw new Error(`Cannot move a path [${path}] to new path [${newPath}] because the destination is inside itself.`);
572
- }
573
- const node = PlaitNode.get(board, path);
574
- const parent = PlaitNode.parent(board, path);
575
- const index = path[path.length - 1];
576
- // This is tricky, but since the `path` and `newPath` both refer to
577
- // the same snapshot in time, there's a mismatch. After either
578
- // removing the original position, the second step's path can be out
579
- // of date. So instead of using the `op.newPath` directly, we
580
- // transform `op.path` to ascertain what the `newPath` would be after
581
- // the operation was applied.
582
- (_a = parent.children) === null || _a === void 0 ? void 0 : _a.splice(index, 1);
583
- const truePath = Path.transform(path, op);
584
- const newParent = PlaitNode.get(board, Path.parent(truePath));
585
- const newIndex = truePath[truePath.length - 1];
586
- (_b = newParent.children) === null || _b === void 0 ? void 0 : _b.splice(newIndex, 0, node);
587
- break;
588
- }
589
- case 'set_node': {
590
- const { path, properties, newProperties } = op;
591
- if (path.length === 0) {
592
- throw new Error(`Cannot set properties on the root node!`);
593
- }
594
- const node = PlaitNode.get(board, path);
595
- for (const key in newProperties) {
596
- const value = newProperties[key];
597
- if (value == null) {
598
- delete node[key];
599
- }
600
- else {
601
- node[key] = value;
602
- }
603
- }
604
- // properties that were previously defined, but are now missing, must be deleted
605
- for (const key in properties) {
606
- if (!newProperties.hasOwnProperty(key)) {
607
- delete node[key];
608
- }
609
- }
610
- break;
611
- }
612
- case 'set_viewport': {
613
- const { newProperties } = op;
614
- if (newProperties == null) {
615
- viewport = newProperties;
616
- }
617
- else {
618
- if (viewport == null) {
619
- if (!Viewport.isViewport(newProperties)) {
620
- throw new Error(`Cannot apply an incomplete "set_viewport" operation properties ${JSON.stringify(newProperties)} when there is no current viewport.`);
621
- }
622
- viewport = Object.assign({}, newProperties);
623
- }
624
- for (const key in newProperties) {
625
- const value = newProperties[key];
626
- if (value == null) {
627
- delete viewport[key];
628
- }
629
- else {
630
- viewport[key] = value;
631
- }
632
- }
633
- }
634
- break;
635
- }
636
- case 'set_selection': {
637
- const { newProperties } = op;
638
- if (newProperties == null) {
639
- selection = newProperties;
640
- }
641
- else {
642
- if (selection === null) {
643
- selection = op.newProperties;
644
- }
645
- else {
646
- selection.ranges = newProperties.ranges;
647
- }
648
- }
649
- break;
650
- }
651
- case 'set_theme': {
652
- const { newProperties } = op;
653
- theme = newProperties;
654
- break;
655
- }
656
- }
657
- return { selection, viewport, theme };
658
- };
659
- const GeneralTransforms = {
660
- /**
661
- * Transform the board by an operation.
662
- */
663
- transform(board, op) {
664
- board.children = createDraft(board.children);
665
- let viewport = board.viewport && createDraft(board.viewport);
666
- let selection = board.selection && createDraft(board.selection);
667
- let theme = board.theme && createDraft(board.theme);
668
- try {
669
- const state = applyToDraft(board, selection, viewport, theme, op);
670
- viewport = state.viewport;
671
- selection = state.selection;
672
- theme = state.theme;
673
- }
674
- finally {
675
- board.children = finishDraft(board.children);
676
- if (selection) {
677
- board.selection = isDraft(selection) ? finishDraft(selection) : selection;
678
- }
679
- else {
680
- board.selection = null;
681
- }
682
- board.viewport = isDraft(viewport) ? finishDraft(viewport) : viewport;
683
- board.theme = isDraft(theme) ? finishDraft(theme) : theme;
684
- }
685
- }
686
- };
687
-
688
- function insertNode(board, node, path) {
689
- const operation = { type: 'insert_node', node, path };
690
- board.apply(operation);
691
- }
692
- function setNode(board, props, path) {
693
- const properties = {};
694
- const newProperties = {};
695
- const node = PlaitNode.get(board, path);
696
- for (const k in props) {
697
- if (node[k] !== props[k]) {
698
- if (node.hasOwnProperty(k)) {
699
- properties[k] = node[k];
700
- }
701
- if (props[k] != null)
702
- newProperties[k] = props[k];
703
- }
704
- }
705
- const operation = { type: 'set_node', properties, newProperties, path };
706
- board.apply(operation);
707
- }
708
- function removeNode(board, path) {
709
- const node = PlaitNode.get(board, path);
710
- const operation = { type: 'remove_node', path, node };
711
- board.apply(operation);
712
- }
713
- function moveNode(board, path, newPath) {
714
- const operation = { type: 'move_node', path, newPath };
715
- board.apply(operation);
716
- }
717
- const NodeTransforms = {
718
- insertNode,
719
- setNode,
720
- removeNode,
721
- moveNode
722
- };
723
-
724
- function setSelection(board, selection) {
725
- const operation = { type: 'set_selection', properties: board.selection, newProperties: selection };
726
- board.apply(operation);
727
- }
728
- const SelectionTransforms = {
729
- setSelection,
730
- setSelectionWithTemporaryElements
731
- };
732
- function setSelectionWithTemporaryElements(board, elements) {
733
- setTimeout(() => {
734
- BOARD_TO_TEMPORARY_ELEMENTS.set(board, elements);
735
- setSelection(board, { ranges: [] });
736
- });
737
- }
738
-
739
- function setViewport(board, viewport) {
740
- const operation = { type: 'set_viewport', properties: board.viewport, newProperties: viewport };
741
- board.apply(operation);
742
- }
743
- const ViewportTransforms$1 = {
744
- setViewport
745
- };
746
-
747
- /**
748
- * @license
749
- * Copyright Google LLC All Rights Reserved.
750
- *
751
- * Use of this source code is governed by an MIT-style license that can be
752
- * found in the LICENSE file at https://angular.io/license
753
- */
754
- const MAC_ENTER = 3;
755
- const BACKSPACE = 8;
756
- const TAB = 9;
757
- const NUM_CENTER = 12;
758
- const ENTER = 13;
759
- const SHIFT = 16;
760
- const CONTROL = 17;
761
- const ALT = 18;
762
- const PAUSE = 19;
763
- const CAPS_LOCK = 20;
764
- const ESCAPE = 27;
765
- const SPACE = 32;
766
- const PAGE_UP = 33;
767
- const PAGE_DOWN = 34;
768
- const END = 35;
769
- const HOME = 36;
770
- const LEFT_ARROW = 37;
771
- const UP_ARROW = 38;
772
- const RIGHT_ARROW = 39;
773
- const DOWN_ARROW = 40;
774
- const PLUS_SIGN = 43;
775
- const PRINT_SCREEN = 44;
776
- const INSERT = 45;
777
- const DELETE = 46;
778
- const ZERO = 48;
779
- const ONE = 49;
780
- const TWO = 50;
781
- const THREE = 51;
782
- const FOUR = 52;
783
- const FIVE = 53;
784
- const SIX = 54;
785
- const SEVEN = 55;
786
- const EIGHT = 56;
787
- const NINE = 57;
788
- const FF_SEMICOLON = 59; // Firefox (Gecko) fires this for semicolon instead of 186
789
- const FF_EQUALS = 61; // Firefox (Gecko) fires this for equals instead of 187
790
- const QUESTION_MARK = 63;
791
- const AT_SIGN = 64;
792
- const A = 65;
793
- const B = 66;
794
- const C = 67;
795
- const D = 68;
796
- const E = 69;
797
- const F = 70;
798
- const G = 71;
799
- const H = 72;
800
- const I = 73;
801
- const J = 74;
802
- const K = 75;
803
- const L = 76;
804
- const M = 77;
805
- const N = 78;
806
- const O = 79;
807
- const P = 80;
808
- const Q = 81;
809
- const R = 82;
810
- const S = 83;
811
- const T = 84;
812
- const U = 85;
813
- const V = 86;
814
- const W = 87;
815
- const X = 88;
816
- const Y = 89;
817
- const Z = 90;
818
- const META = 91; // WIN_KEY_LEFT
819
- const MAC_WK_CMD_LEFT = 91;
820
- const MAC_WK_CMD_RIGHT = 93;
821
- const CONTEXT_MENU = 93;
822
- const NUMPAD_ZERO = 96;
823
- const NUMPAD_ONE = 97;
824
- const NUMPAD_TWO = 98;
825
- const NUMPAD_THREE = 99;
826
- const NUMPAD_FOUR = 100;
827
- const NUMPAD_FIVE = 101;
828
- const NUMPAD_SIX = 102;
829
- const NUMPAD_SEVEN = 103;
830
- const NUMPAD_EIGHT = 104;
831
- const NUMPAD_NINE = 105;
832
- const NUMPAD_MULTIPLY = 106;
833
- const NUMPAD_PLUS = 107;
834
- const NUMPAD_MINUS = 109;
835
- const NUMPAD_PERIOD = 110;
836
- const NUMPAD_DIVIDE = 111;
837
- const F1 = 112;
838
- const F2 = 113;
839
- const F3 = 114;
840
- const F4 = 115;
841
- const F5 = 116;
842
- const F6 = 117;
843
- const F7 = 118;
844
- const F8 = 119;
845
- const F9 = 120;
846
- const F10 = 121;
847
- const F11 = 122;
848
- const F12 = 123;
849
- const NUM_LOCK = 144;
850
- const SCROLL_LOCK = 145;
851
- const FIRST_MEDIA = 166;
852
- const FF_MINUS = 173;
853
- const MUTE = 173; // Firefox (Gecko) fires 181 for MUTE
854
- const VOLUME_DOWN = 174; // Firefox (Gecko) fires 182 for VOLUME_DOWN
855
- const VOLUME_UP = 175; // Firefox (Gecko) fires 183 for VOLUME_UP
856
- const FF_MUTE = 181;
857
- const FF_VOLUME_DOWN = 182;
858
- const LAST_MEDIA = 183;
859
- const FF_VOLUME_UP = 183;
860
- const SEMICOLON = 186; // Firefox (Gecko) fires 59 for SEMICOLON
861
- const EQUALS = 187; // Firefox (Gecko) fires 61 for EQUALS
862
- const COMMA = 188;
863
- const DASH = 189; // Firefox (Gecko) fires 173 for DASH/MINUS
864
- const PERIOD = 190;
865
- const SLASH = 191;
866
- const APOSTROPHE = 192;
867
- const TILDE = 192;
868
- const OPEN_SQUARE_BRACKET = 219;
869
- const BACKSLASH = 220;
870
- const CLOSE_SQUARE_BRACKET = 221;
871
- const SINGLE_QUOTE = 222;
872
- const MAC_META = 224;
873
-
874
- var ResizeCursorClass;
875
- (function (ResizeCursorClass) {
876
- ResizeCursorClass["ew-resize"] = "ew-resize";
877
- })(ResizeCursorClass || (ResizeCursorClass = {}));
878
-
879
- const ATTACHED_ELEMENT_CLASS_NAME = 'plait-board-attached';
880
-
881
- const CLIP_BOARD_FORMAT_KEY = 'x-plait-fragment';
882
- const HOST_CLASS_NAME = 'plait-board-container';
883
- const SCROLL_BAR_WIDTH = 20;
884
- const MAX_RADIUS = 16;
885
- const POINTER_BUTTON = {
886
- MAIN: 0,
887
- WHEEL: 1,
888
- SECONDARY: 2,
889
- TOUCH: -1
890
- };
891
- const PRESS_AND_MOVE_BUFFER = 5;
892
-
893
- const NS = 'http://www.w3.org/2000/svg';
894
- function toPoint(x, y, container) {
895
- const rect = container.getBoundingClientRect();
896
- return [x - rect.x, y - rect.y];
897
- }
898
- function createG() {
899
- const newG = document.createElementNS(NS, 'g');
900
- return newG;
901
- }
902
- function createPath() {
903
- const newG = document.createElementNS(NS, 'path');
904
- return newG;
905
- }
906
- function createSVG() {
907
- const svg = document.createElementNS(NS, 'svg');
908
- return svg;
909
- }
910
- function createText(x, y, fill, textContent) {
911
- var text = document.createElementNS(NS, 'text');
912
- text.setAttribute('x', `${x}`);
913
- text.setAttribute('y', `${y}`);
914
- text.setAttribute('fill', fill);
915
- text.textContent = textContent;
916
- return text;
917
- }
918
- /**
919
- * Check if a DOM node is an element node.
920
- */
921
- const isDOMElement = (value) => {
922
- return isDOMNode(value) && value.nodeType === 1;
923
- };
924
- /**
925
- * Check if a value is a DOM node.
926
- */
927
- const isDOMNode = (value) => {
928
- return value instanceof window.Node;
929
- };
930
- const hasInputOrTextareaTarget = (target) => {
931
- if (isDOMElement(target)) {
932
- if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
933
- return true;
934
- }
935
- }
936
- return false;
937
- };
938
- const isSecondaryPointer = (event) => {
939
- return event.button === POINTER_BUTTON.SECONDARY;
940
- };
941
- const isMainPointer = (event) => {
942
- return event.button === POINTER_BUTTON.MAIN;
943
- };
944
-
945
- const SELECTION_BORDER_COLOR = '#6698FF';
946
- const SELECTION_FILL_COLOR = '#6698FF19'; // 主色 0.1 透明度
947
- const Selection = {
948
- isCollapsed(selection) {
949
- if (selection.anchor[0] == selection.focus[0] && selection.anchor[1] === selection.focus[1]) {
950
- return true;
951
- }
952
- else {
953
- return false;
954
- }
955
- }
956
- };
957
-
958
- const getHitElements = (board, selection, match = () => true) => {
959
- const realSelection = selection || board.selection;
960
- const selectedElements = [];
961
- const isCollapsed = realSelection && realSelection.ranges.length === 1 && Selection.isCollapsed(realSelection.ranges[0]);
962
- depthFirstRecursion(board, node => {
963
- if (selectedElements.length > 0 && isCollapsed) {
964
- return;
965
- }
966
- if (!PlaitBoard.isBoard(node) &&
967
- match(node) &&
968
- realSelection &&
969
- realSelection.ranges.some(range => {
970
- return board.isHitSelection(node, range);
971
- })) {
972
- selectedElements.push(node);
973
- }
974
- }, getIsRecursionFunc(board), true);
975
- return selectedElements;
976
- };
977
- const getHitElementOfRoot = (board, rootElements, range) => {
978
- const newRootElements = [...rootElements].reverse();
979
- return newRootElements.find(item => {
980
- return board.isHitSelection(item, range);
981
- });
982
- };
983
- const isHitElements = (board, elements, ranges) => {
984
- let isIntersectionElements = false;
985
- if (elements.length) {
986
- elements.map(item => {
987
- if (!isIntersectionElements) {
988
- isIntersectionElements = ranges.some(range => {
989
- return board.isHitSelection(item, range);
990
- });
991
- }
992
- });
993
- }
994
- return isIntersectionElements;
995
- };
996
- const cacheSelectedElements = (board, selectedElements) => {
997
- BOARD_TO_SELECTED_ELEMENT.set(board, selectedElements);
998
- };
999
- const getSelectedElements = (board) => {
1000
- return BOARD_TO_SELECTED_ELEMENT.get(board) || [];
1001
- };
1002
- const addSelectedElement = (board, element) => {
1003
- const selectedElements = getSelectedElements(board);
1004
- cacheSelectedElements(board, [...selectedElements, element]);
1005
- };
1006
- const removeSelectedElement = (board, element) => {
1007
- const selectedElements = getSelectedElements(board);
1008
- const newSelectedElements = selectedElements.filter(value => value !== element);
1009
- cacheSelectedElements(board, newSelectedElements);
1010
- };
1011
- const clearSelectedElement = (board) => {
1012
- cacheSelectedElements(board, []);
1013
- };
1014
- const isSelectedElement = (board, element) => {
1015
- const selectedElements = getSelectedElements(board);
1016
- return !!selectedElements.find(value => value === element);
1017
- };
1018
-
1019
- function hasBeforeContextChange(value) {
1020
- if (value.beforeContextChange) {
1021
- return true;
1022
- }
1023
- return false;
1024
- }
1025
- function hasOnContextChanged(value) {
1026
- if (value.onContextChanged) {
1027
- return true;
1028
- }
1029
- return false;
1030
- }
1031
-
1032
- class PlaitPluginElementComponent {
1033
- set context(value) {
1034
- if (hasBeforeContextChange(this)) {
1035
- this.beforeContextChange(value);
1036
- }
1037
- const previousContext = this._context;
1038
- this._context = value;
1039
- if (this.element) {
1040
- ELEMENT_TO_COMPONENT.set(this.element, this);
1041
- }
1042
- if (this.initialized) {
1043
- this.cdr.markForCheck();
1044
- if (hasOnContextChanged(this)) {
1045
- this.onContextChanged(value, previousContext);
1046
- }
1047
- }
1048
- else {
1049
- if (PlaitElement.isRootElement(this.element) && this.element.children) {
1050
- this.g = createG();
1051
- this.rootG = createG();
1052
- this.rootG.append(this.g);
1053
- }
1054
- else {
1055
- this.g = createG();
1056
- }
1057
- }
1058
- }
1059
- get context() {
1060
- return this._context;
1061
- }
1062
- get element() {
1063
- return this.context && this.context.element;
1064
- }
1065
- get board() {
1066
- return this.context && this.context.board;
1067
- }
1068
- get selected() {
1069
- return this.context && this.context.selected;
1070
- }
1071
- get effect() {
1072
- return this.context && this.context.effect;
1073
- }
1074
- constructor(cdr) {
1075
- this.cdr = cdr;
1076
- this.initialized = false;
1077
- }
1078
- ngOnInit() {
1079
- if (this.element.type) {
1080
- (this.rootG || this.g).setAttribute(`plait-${this.element.type}`, 'true');
1081
- }
1082
- this.initialized = true;
1083
- }
1084
- ngOnDestroy() {
1085
- if (ELEMENT_TO_COMPONENT.get(this.element) === this) {
1086
- ELEMENT_TO_COMPONENT.delete(this.element);
1087
- }
1088
- removeSelectedElement(this.board, this.element);
1089
- (this.rootG || this.g).remove();
1090
- }
1091
- }
1092
- PlaitPluginElementComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitPluginElementComponent, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive });
1093
- PlaitPluginElementComponent.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.2.5", type: PlaitPluginElementComponent, inputs: { context: "context" }, ngImport: i0 });
1094
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitPluginElementComponent, decorators: [{
1095
- type: Directive
1096
- }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }]; }, propDecorators: { context: [{
1097
- type: Input
1098
- }] } });
1099
- const ELEMENT_TO_COMPONENT = new WeakMap();
1100
-
1101
- function transformPoints(board, points) {
1102
- const newPoints = points.map(point => {
1103
- return transformPoint(board, point);
1104
- });
1105
- return newPoints;
1106
- }
1107
- function transformPoint(board, point) {
1108
- const { width, height } = PlaitBoard.getHost(board).getBoundingClientRect();
1109
- const viewBox = PlaitBoard.getHost(board).viewBox.baseVal;
1110
- const x = (point[0] / width) * viewBox.width + viewBox.x;
1111
- const y = (point[1] / height) * viewBox.height + viewBox.y;
1112
- const newPoint = [x, y];
1113
- return newPoint;
1114
- }
1115
- function isInPlaitBoard(board, x, y) {
1116
- const plaitBoardElement = PlaitBoard.getBoardContainer(board);
1117
- const plaitBoardRect = plaitBoardElement.getBoundingClientRect();
1118
- const distances = distanceBetweenPointAndRectangle(x, y, plaitBoardRect);
1119
- return distances === 0;
1120
- }
1121
- function getRealScrollBarWidth(board) {
1122
- const { hideScrollbar } = board.options;
1123
- let scrollBarWidth = 0;
1124
- if (!hideScrollbar) {
1125
- const viewportContainer = PlaitBoard.getViewportContainer(board);
1126
- scrollBarWidth = viewportContainer.offsetWidth - viewportContainer.clientWidth;
1127
- }
1128
- return scrollBarWidth;
1129
- }
1130
-
1131
- function createForeignObject(x, y, width, height) {
1132
- var newForeignObject = document.createElementNS(NS, 'foreignObject');
1133
- newForeignObject.setAttribute('x', `${x}`);
1134
- newForeignObject.setAttribute('y', `${y}`);
1135
- newForeignObject.setAttribute('width', `${width}`);
1136
- newForeignObject.setAttribute('height', `${height}`);
1137
- return newForeignObject;
1138
- }
1139
- function updateForeignObject(g, width, height, x, y) {
1140
- const foreignObject = g.querySelector('foreignObject');
1141
- if (foreignObject) {
1142
- foreignObject.setAttribute('width', `${width}`);
1143
- foreignObject.setAttribute('height', `${height}`);
1144
- foreignObject.setAttribute('x', `${x}`);
1145
- foreignObject.setAttribute('y', `${y}`);
1146
- }
1147
- }
1148
-
1149
- const IS_MAC = typeof window != 'undefined' && /Mac|iPod|iPhone|iPad/.test(window.navigator.platform);
1150
-
1151
- const IS_IOS = typeof navigator !== 'undefined' &&
1152
- typeof window !== 'undefined' &&
1153
- /iPad|iPhone|iPod/.test(navigator.userAgent) &&
1154
- !window.MSStream;
1155
- const IS_APPLE = typeof navigator !== 'undefined' && /Mac OS X/.test(navigator.userAgent);
1156
- const IS_FIREFOX = typeof navigator !== 'undefined' && /^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent);
1157
- const IS_SAFARI = typeof navigator !== 'undefined' && /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
1158
- // "modern" Edge was released at 79.x
1159
- const IS_EDGE_LEGACY = typeof navigator !== 'undefined' && /Edge?\/(?:[0-6][0-9]|[0-7][0-8])/i.test(navigator.userAgent);
1160
- const IS_CHROME = typeof navigator !== 'undefined' && /Chrome/i.test(navigator.userAgent);
1161
- // Native beforeInput events don't work well with react on Chrome 75 and older, Chrome 76+ can use beforeInput
1162
- const IS_CHROME_LEGACY = typeof navigator !== 'undefined' && /Chrome?\/(?:[0-7][0-5]|[0-6][0-9])/i.test(navigator.userAgent);
1163
-
1164
- /**
1165
- * Check whether to merge an operation into the previous operation.
1166
- */
1167
- const shouldMerge = (op, prev) => {
1168
- if (op.type === 'set_viewport' && op.type === (prev === null || prev === void 0 ? void 0 : prev.type)) {
1169
- return true;
1170
- }
1171
- return false;
1172
- };
1173
- /**
1174
- * Check whether an operation needs to be saved to the history.
1175
- */
1176
- const shouldSave = (op, prev) => {
1177
- if (op.type === 'set_selection' || op.type === 'set_viewport') {
1178
- return false;
1179
- }
1180
- return true;
1181
- };
1182
- /**
1183
- * Check whether an operation should clear the redos stack.
1184
- */
1185
- const shouldClear = (op) => {
1186
- if (op.type === 'set_selection') {
1187
- return false;
1188
- }
1189
- return true;
1190
- };
1191
- const PlaitHistoryBoard = {
1192
- /**
1193
- * Get the saving flag's current value.
1194
- */
1195
- isSaving(board) {
1196
- return SAVING.get(board);
1197
- },
1198
- /**
1199
- * Get the merge flag's current value.
1200
- */
1201
- isMerging(board) {
1202
- return MERGING.get(board);
1203
- },
1204
- /**
1205
- * Apply a series of changes inside a synchronous `fn`, without merging any of
1206
- * the new operations into previous save point in the history.
1207
- */
1208
- withoutMerging(board, fn) {
1209
- const prev = PlaitHistoryBoard.isMerging(board);
1210
- MERGING.set(board, false);
1211
- fn();
1212
- MERGING.set(board, prev);
1213
- },
1214
- /**
1215
- * Apply a series of changes inside a synchronous `fn`, without saving any of
1216
- * their operations into the history.
1217
- */
1218
- withoutSaving(board, fn) {
1219
- const prev = PlaitHistoryBoard.isSaving(board);
1220
- SAVING.set(board, false);
1221
- fn();
1222
- SAVING.set(board, prev);
1223
- }
1224
- };
1225
-
1226
- /**
1227
- * Hotkey mappings for each platform.
1228
- */
1229
- const HOTKEYS = {
1230
- bold: 'mod+b',
1231
- compose: ['down', 'left', 'right', 'up', 'backspace', 'enter'],
1232
- moveBackward: 'left',
1233
- moveForward: 'right',
1234
- moveUp: 'up',
1235
- moveDown: 'down',
1236
- moveWordBackward: 'ctrl+left',
1237
- moveWordForward: 'ctrl+right',
1238
- deleteBackward: 'shift?+backspace',
1239
- deleteForward: 'shift?+delete',
1240
- extendBackward: 'shift+left',
1241
- extendForward: 'shift+right',
1242
- italic: 'mod+i',
1243
- splitBlock: 'shift?+enter',
1244
- undo: 'mod+z'
1245
- };
1246
- const APPLE_HOTKEYS = {
1247
- moveLineBackward: 'opt+up',
1248
- moveLineForward: 'opt+down',
1249
- moveWordBackward: 'opt+left',
1250
- moveWordForward: 'opt+right',
1251
- deleteBackward: ['ctrl+backspace', 'ctrl+h'],
1252
- deleteForward: ['ctrl+delete', 'ctrl+d'],
1253
- deleteLineBackward: 'cmd+shift?+backspace',
1254
- deleteLineForward: ['cmd+shift?+delete', 'ctrl+k'],
1255
- deleteWordBackward: 'opt+shift?+backspace',
1256
- deleteWordForward: 'opt+shift?+delete',
1257
- extendLineBackward: 'opt+shift+up',
1258
- extendLineForward: 'opt+shift+down',
1259
- redo: 'cmd+shift+z',
1260
- transposeCharacter: 'ctrl+t'
1261
- };
1262
- const WINDOWS_HOTKEYS = {
1263
- deleteWordBackward: 'ctrl+shift?+backspace',
1264
- deleteWordForward: 'ctrl+shift?+delete',
1265
- redo: ['ctrl+y', 'ctrl+shift+z']
1266
- };
1267
- /**
1268
- * Create a platform-aware hotkey checker.
1269
- */
1270
- const create = (key) => {
1271
- const generic = HOTKEYS[key];
1272
- const apple = APPLE_HOTKEYS[key];
1273
- const windows = WINDOWS_HOTKEYS[key];
1274
- const isGeneric = generic && isKeyHotkey(generic);
1275
- const isApple = apple && isKeyHotkey(apple);
1276
- const isWindows = windows && isKeyHotkey(windows);
1277
- return (event) => {
1278
- if (isGeneric && isGeneric(event)) {
1279
- return true;
1280
- }
1281
- if (IS_APPLE && isApple && isApple(event)) {
1282
- return true;
1283
- }
1284
- if (!IS_APPLE && isWindows && isWindows(event)) {
1285
- return true;
1286
- }
1287
- return false;
1288
- };
1289
- };
1290
- /**
1291
- * Hotkeys.
1292
- */
1293
- const hotkeys = {
1294
- isBold: create('bold'),
1295
- isCompose: create('compose'),
1296
- isMoveBackward: create('moveBackward'),
1297
- isMoveForward: create('moveForward'),
1298
- isMoveUp: create('moveUp'),
1299
- isMoveDown: create('moveDown'),
1300
- isDeleteBackward: create('deleteBackward'),
1301
- isDeleteForward: create('deleteForward'),
1302
- isDeleteLineBackward: create('deleteLineBackward'),
1303
- isDeleteLineForward: create('deleteLineForward'),
1304
- isDeleteWordBackward: create('deleteWordBackward'),
1305
- isDeleteWordForward: create('deleteWordForward'),
1306
- isExtendBackward: create('extendBackward'),
1307
- isExtendForward: create('extendForward'),
1308
- isExtendLineBackward: create('extendLineBackward'),
1309
- isExtendLineForward: create('extendLineForward'),
1310
- isItalic: create('italic'),
1311
- isMoveLineBackward: create('moveLineBackward'),
1312
- isMoveLineForward: create('moveLineForward'),
1313
- isMoveWordBackward: create('moveWordBackward'),
1314
- isMoveWordForward: create('moveWordForward'),
1315
- isRedo: create('redo'),
1316
- isSplitBlock: create('splitBlock'),
1317
- isTransposeCharacter: create('transposeCharacter'),
1318
- isUndo: create('undo')
1319
- };
1320
-
1321
- function idCreator(length = 5) {
1322
- // remove numeral
1323
- const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
1324
- const maxPosition = $chars.length;
1325
- let key = '';
1326
- for (let i = 0; i < length; i++) {
1327
- key += $chars.charAt(Math.floor(Math.random() * maxPosition));
1328
- }
1329
- return key;
1330
- }
1331
-
1332
- /**
1333
- * drawRoundRectangle
1334
- */
1335
- function drawRoundRectangle(rs, x1, y1, x2, y2, options, outline = false, borderRadius) {
1336
- const width = Math.abs(x1 - x2);
1337
- const height = Math.abs(y1 - y2);
1338
- let radius = borderRadius || 0;
1339
- if (radius === 0) {
1340
- const defaultRadius = Math.min(width, height) / 8;
1341
- let radius = defaultRadius;
1342
- if (defaultRadius > MAX_RADIUS) {
1343
- radius = outline ? MAX_RADIUS + 2 : MAX_RADIUS;
1344
- }
1345
- }
1346
- const point1 = [x1 + radius, y1];
1347
- const point2 = [x2 - radius, y1];
1348
- const point3 = [x2, y1 + radius];
1349
- const point4 = [x2, y2 - radius];
1350
- const point5 = [x2 - radius, y2];
1351
- const point6 = [x1 + radius, y2];
1352
- const point7 = [x1, y2 - radius];
1353
- const point8 = [x1, y1 + radius];
1354
- return rs.path(`M${point2[0]} ${point2[1]} A ${radius} ${radius}, 0, 0, 1, ${point3[0]} ${point3[1]} L ${point4[0]} ${point4[1]} A ${radius} ${radius}, 0, 0, 1, ${point5[0]} ${point5[1]} L ${point6[0]} ${point6[1]} A ${radius} ${radius}, 0, 0, 1, ${point7[0]} ${point7[1]} L ${point8[0]} ${point8[1]} A ${radius} ${radius}, 0, 0, 1, ${point1[0]} ${point1[1]} Z`, options);
1355
- }
1356
-
1357
- function arrowPoints(start, end, maxHypotenuseLength = 10, degree = 40) {
1358
- const width = Math.abs(start[0] - end[0]);
1359
- const height = Math.abs(start[1] - end[1]);
1360
- let hypotenuse = Math.hypot(width, height); // 斜边
1361
- const realRotateLine = hypotenuse > maxHypotenuseLength * 2 ? maxHypotenuseLength : hypotenuse / 2;
1362
- const rotateWidth = (realRotateLine / hypotenuse) * width;
1363
- const rotateHeight = (realRotateLine / hypotenuse) * height;
1364
- const rotatePoint = [
1365
- end[0] > start[0] ? end[0] - rotateWidth : end[0] + rotateWidth,
1366
- end[1] > start[1] ? end[1] - rotateHeight : end[1] + rotateHeight
1367
- ];
1368
- const pointRight = rotate(rotatePoint[0], rotatePoint[1], end[0], end[1], (degree * Math.PI) / 180);
1369
- const pointLeft = rotate(rotatePoint[0], rotatePoint[1], end[0], end[1], (-degree * Math.PI) / 180);
1370
- return { pointLeft, pointRight };
1371
- }
1372
- function drawArrow(rs, start, end, options, maxHypotenuseLength = 10, degree = 40) {
1373
- const { pointLeft, pointRight } = arrowPoints(start, end, maxHypotenuseLength, degree);
1374
- const arrowLineLeft = rs.linearPath([pointLeft, end], options);
1375
- const arrowLineRight = rs.linearPath([pointRight, end], options);
1376
- return [arrowLineLeft, arrowLineRight];
1377
- }
1378
-
1379
- function drawCircle(roughSVG, point, diameter, options) {
1380
- return roughSVG.circle(point[0], point[1], diameter, options);
1381
- }
1382
-
1383
- function drawLine(rs, start, end, options) {
1384
- return rs.linearPath([start, end], options);
1385
- }
1386
- function drawLinearPath(points, options) {
1387
- const g = createG();
1388
- const path = createPath();
1389
- let polylinePath = '';
1390
- points.forEach((point, index) => {
1391
- if (index === 0) {
1392
- polylinePath += `M ${point[0]} ${point[1]} `;
1393
- }
1394
- else {
1395
- polylinePath += `L ${point[0]} ${point[1]} `;
1396
- }
1397
- });
1398
- path.setAttribute('d', polylinePath);
1399
- path.setAttribute('stroke', `${options === null || options === void 0 ? void 0 : options.stroke}`);
1400
- path.setAttribute('stroke-width', `${options === null || options === void 0 ? void 0 : options.strokeWidth}`);
1401
- path.setAttribute('fill', `none`);
1402
- g.appendChild(path);
1403
- return g;
1404
- }
1405
- function drawBezierPath(points, options) {
1406
- const g = createG();
1407
- const path = createPath();
1408
- let polylinePath = '';
1409
- for (let i = 0; i < points.length - 3; i += 3) {
1410
- if (i === 0) {
1411
- polylinePath += `M ${points[0][0]} ${points[0][1]} `;
1412
- }
1413
- else {
1414
- polylinePath += `C ${points[i + 1][0]} ${points[i + 1][1]}, ${points[i + 2][0]} ${points[i + 2][1]}, ${points[i + 3][0]} ${points[i + 3][1]}`;
1415
- }
1416
- }
1417
- path.setAttribute('d', polylinePath);
1418
- path.setAttribute('stroke', `${options === null || options === void 0 ? void 0 : options.stroke}`);
1419
- path.setAttribute('stroke-width', `${options === null || options === void 0 ? void 0 : options.strokeWidth}`);
1420
- path.setAttribute('fill', `none`);
1421
- g.appendChild(path);
1422
- return g;
1423
- }
1424
-
1425
- let timerId = null;
1426
- const throttleRAF = (fn) => {
1427
- const scheduleFunc = () => {
1428
- timerId = requestAnimationFrame(() => {
1429
- timerId = null;
1430
- fn();
1431
- });
1432
- };
1433
- if (timerId !== null) {
1434
- cancelAnimationFrame(timerId);
1435
- timerId = null;
1436
- }
1437
- scheduleFunc();
1438
- };
1439
- const debounce = (func, wait, options) => {
1440
- let timerSubscription = null;
1441
- return () => {
1442
- if (timerSubscription && !timerSubscription.closed) {
1443
- timerSubscription.unsubscribe();
1444
- timerSubscription = timer(wait).subscribe(() => {
1445
- func();
1446
- });
1447
- }
1448
- else {
1449
- if (options === null || options === void 0 ? void 0 : options.leading) {
1450
- func();
1451
- }
1452
- timerSubscription = timer(wait).subscribe();
1453
- }
1454
- };
1455
- };
1456
-
1457
- const getMovingElements = (board) => {
1458
- return BOARD_TO_MOVING_ELEMENT.get(board) || [];
1459
- };
1460
- const addMovingElements = (board, elements) => {
1461
- const movingElements = getMovingElements(board);
1462
- const newElements = elements.filter(item => !movingElements.find(movingElement => movingElement.key === item.key));
1463
- cacheMovingElements(board, [...movingElements, ...newElements]);
1464
- };
1465
- const removeMovingElements = (board) => {
1466
- BOARD_TO_MOVING_ELEMENT.delete(board);
1467
- };
1468
- const cacheMovingElements = (board, elements) => {
1469
- BOARD_TO_MOVING_ELEMENT.set(board, elements);
1470
- };
1471
-
1472
- function cloneCSSStyle(nativeNode, clonedNode) {
1473
- const targetStyle = clonedNode.style;
1474
- if (!targetStyle) {
1475
- return;
1476
- }
1477
- const sourceStyle = window.getComputedStyle(nativeNode);
1478
- if (sourceStyle.cssText) {
1479
- targetStyle.cssText = sourceStyle.cssText;
1480
- targetStyle.transformOrigin = sourceStyle.transformOrigin;
1481
- }
1482
- else {
1483
- Array.from(sourceStyle).forEach(name => {
1484
- let value = sourceStyle.getPropertyValue(name);
1485
- targetStyle.setProperty(name, value, sourceStyle.getPropertyPriority(name));
1486
- });
1487
- }
1488
- }
1489
- function createCanvas(width, height, fillStyle) {
1490
- const canvas = document.createElement('canvas');
1491
- const ctx = canvas.getContext('2d');
1492
- canvas.width = width;
1493
- canvas.height = height;
1494
- canvas.style.width = `${width}px`;
1495
- canvas.style.height = `${height}px`;
1496
- ctx.strokeStyle = '#ffffff';
1497
- ctx.fillStyle = fillStyle;
1498
- ctx.fillRect(0, 0, width, height);
1499
- return {
1500
- canvas,
1501
- ctx
1502
- };
1503
- }
1504
- function isElementNode(node) {
1505
- return node.nodeType === Node.ELEMENT_NODE;
1506
- }
1507
- function cloneSvg(board, options) {
1508
- const elementHostBox = getRectangleByElements(board, board.children, true);
1509
- const { width, height, x, y } = elementHostBox;
1510
- const { padding = 4, inlineStyleClassNames } = options;
1511
- const sourceSvg = PlaitBoard.getHost(board);
1512
- const cloneSvgElement = sourceSvg.cloneNode(true);
1513
- cloneSvgElement.style.width = `${width}px`;
1514
- cloneSvgElement.style.height = `${height}px`;
1515
- cloneSvgElement.style.backgroundColor = '';
1516
- cloneSvgElement.setAttribute('width', `${width}`);
1517
- cloneSvgElement.setAttribute('height', `${height}`);
1518
- cloneSvgElement.setAttribute('viewBox', [x - padding, y - padding, width + 2 * padding, height + 2 * padding].join(','));
1519
- if (inlineStyleClassNames) {
1520
- const sourceNodes = Array.from(sourceSvg.querySelectorAll(inlineStyleClassNames));
1521
- const cloneNodes = Array.from(cloneSvgElement.querySelectorAll(inlineStyleClassNames));
1522
- sourceNodes.forEach((node, index) => {
1523
- const cloneNode = cloneNodes[index];
1524
- const childElements = Array.from(node.querySelectorAll('*')).filter(isElementNode);
1525
- const cloneChildElements = Array.from(cloneNode.querySelectorAll('*')).filter(isElementNode);
1526
- sourceNodes.push(...childElements);
1527
- cloneNodes.push(...cloneChildElements);
1528
- });
1529
- sourceNodes.forEach((node, index) => {
1530
- const cloneNode = cloneNodes[index];
1531
- cloneCSSStyle(node, cloneNode);
1532
- });
1533
- }
1534
- return cloneSvgElement;
1535
- }
1536
- function loadImage(src) {
1537
- return new Promise((resolve, reject) => {
1538
- const img = new Image();
1539
- img.onload = () => resolve(img);
1540
- img.onerror = () => reject(new Error('Failed to load image'));
1541
- img.src = src;
1542
- });
1543
- }
1544
- function toImage(board, options) {
1545
- return __awaiter(this, void 0, void 0, function* () {
1546
- if (!board) {
1547
- return undefined;
1548
- }
1549
- const elementHostBox = getRectangleByElements(board, board.children, true);
1550
- const { ratio = 2, fillStyle = 'transparent' } = options;
1551
- const { width, height } = elementHostBox;
1552
- const ratioWidth = width * ratio;
1553
- const ratioHeight = height * ratio;
1554
- const cloneSvgElement = cloneSvg(board, options);
1555
- const { canvas, ctx } = createCanvas(ratioWidth, ratioHeight, fillStyle);
1556
- const svgStr = new XMLSerializer().serializeToString(cloneSvgElement);
1557
- const imgSrc = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgStr)}`;
1558
- try {
1559
- const img = yield loadImage(imgSrc);
1560
- ctx.drawImage(img, 0, 0, ratioWidth, ratioHeight);
1561
- const url = canvas.toDataURL('image/png');
1562
- return url;
1563
- }
1564
- catch (error) {
1565
- console.error('Error converting SVG to image:', error);
1566
- return undefined;
1567
- }
1568
- });
1569
- }
1570
- function downloadImage(url, name) {
1571
- const a = document.createElement('a');
1572
- a.href = url;
1573
- a.download = name;
1574
- a.click();
1575
- a.remove();
1576
- }
1577
-
1578
- const getClipboardByKey = (key) => {
1579
- return `application/x-plait-${key}-fragment`;
1580
- };
1581
- const setClipboardData = (data, elements) => {
1582
- const result = [...elements];
1583
- const pluginContextResult = getDataFromClipboard(data);
1584
- if (pluginContextResult) {
1585
- result.push(...pluginContextResult);
1586
- }
1587
- const stringObj = JSON.stringify(result);
1588
- const encoded = window.btoa(encodeURIComponent(stringObj));
1589
- data === null || data === void 0 ? void 0 : data.setData(`application/${CLIP_BOARD_FORMAT_KEY}`, encoded);
1590
- };
1591
- const setClipboardDataByText = (data, text) => {
1592
- const pluginContextResult = getTextFromClipboard(data);
1593
- data === null || data === void 0 ? void 0 : data.setData(`text/plain`, text + '\n' + pluginContextResult);
1594
- };
1595
- const setClipboardDataByMedia = (data, media, key) => {
1596
- const stringObj = JSON.stringify(media);
1597
- const encoded = window.btoa(encodeURIComponent(stringObj));
1598
- data === null || data === void 0 ? void 0 : data.setData(getClipboardByKey(key), encoded);
1599
- };
1600
- const getDataFromClipboard = (data) => {
1601
- const encoded = data === null || data === void 0 ? void 0 : data.getData(`application/${CLIP_BOARD_FORMAT_KEY}`);
1602
- let nodesData = [];
1603
- if (encoded) {
1604
- const decoded = decodeURIComponent(window.atob(encoded));
1605
- nodesData = JSON.parse(decoded);
1606
- }
1607
- return nodesData;
1608
- };
1609
- const getTextFromClipboard = (data) => {
1610
- return (data ? data.getData(`text/plain`) : '');
1611
- };
1612
- const getClipboardDataByMedia = (data, key) => {
1613
- const encoded = data === null || data === void 0 ? void 0 : data.getData(getClipboardByKey(key));
1614
- let imageItem = null;
1615
- if (encoded) {
1616
- const decoded = decodeURIComponent(window.atob(encoded));
1617
- imageItem = JSON.parse(decoded);
1618
- }
1619
- return imageItem;
1620
- };
1621
-
1622
- const isPreventTouchMove = (board) => {
1623
- return !!IS_PREVENT_TOUCH_MOVE.get(board);
1624
- };
1625
- const preventTouchMove = (board, state) => {
1626
- IS_PREVENT_TOUCH_MOVE.set(board, state);
1627
- };
1628
-
1629
- const PlaitElement = {
1630
- isRootElement(value) {
1631
- const parent = NODE_TO_PARENT.get(value);
1632
- if (parent && PlaitBoard.isBoard(parent)) {
1633
- return true;
1634
- }
1635
- else {
1636
- return false;
1637
- }
1638
- },
1639
- getComponent(value) {
1640
- return ELEMENT_TO_COMPONENT.get(value);
1641
- }
1642
- };
1643
-
1644
- const RectangleClient = {
1645
- isHit: (origin, target) => {
1646
- const minX = origin.x < target.x ? origin.x : target.x;
1647
- const maxX = origin.x + origin.width > target.x + target.width ? origin.x + origin.width : target.x + target.width;
1648
- const minY = origin.y < target.y ? origin.y : target.y;
1649
- const maxY = origin.y + origin.height > target.y + target.height ? origin.y + origin.height : target.y + target.height;
1650
- // float calculate error( eg: 1.4210854715202004e-14 > 0)
1651
- if (Math.floor(maxX - minX - origin.width - target.width) <= 0 && Math.floor(maxY - minY - origin.height - target.height) <= 0) {
1652
- return true;
1653
- }
1654
- else {
1655
- return false;
1656
- }
1657
- },
1658
- toRectangleClient: (points) => {
1659
- const xArray = points.map(ele => ele[0]);
1660
- const yArray = points.map(ele => ele[1]);
1661
- const xMin = Math.min(...xArray);
1662
- const xMax = Math.max(...xArray);
1663
- const yMin = Math.min(...yArray);
1664
- const yMax = Math.max(...yArray);
1665
- const rect = { x: xMin, y: yMin, width: xMax - xMin, height: yMax - yMin };
1666
- return rect;
1667
- },
1668
- getOutlineRectangle: (rectangle, offset) => {
1669
- return {
1670
- x: rectangle.x + offset,
1671
- y: rectangle.y + offset,
1672
- width: rectangle.width + Math.abs(offset) * 2,
1673
- height: rectangle.height + Math.abs(offset) * 2
1674
- };
1675
- },
1676
- isEqual: (rectangle, otherRectangle) => {
1677
- return (rectangle.x === otherRectangle.x &&
1678
- rectangle.y === otherRectangle.y &&
1679
- rectangle.width === otherRectangle.width &&
1680
- rectangle.height === otherRectangle.height);
1681
- }
1682
- };
1683
-
1684
- const isSetViewportOperation = (value) => {
1685
- return value.type === 'set_viewport';
1686
- };
1687
- const inverse = (op) => {
1688
- switch (op.type) {
1689
- case 'insert_node': {
1690
- return Object.assign(Object.assign({}, op), { type: 'remove_node' });
1691
- }
1692
- case 'remove_node': {
1693
- return Object.assign(Object.assign({}, op), { type: 'insert_node' });
1694
- }
1695
- case 'move_node': {
1696
- const { newPath, path } = op;
1697
- // PERF: in this case the move operation is a no-op anyways.
1698
- if (Path.equals(newPath, path)) {
1699
- return op;
1700
- }
1701
- // when operation path is [0,0] -> [0,2], should exec Path.transform to get [0,1] -> [0,0]
1702
- // shoud not return [0,2] -> [0,0] #WIK-8981
1703
- // if (Path.isSibling(path, newPath)) {
1704
- // return { ...op, path: newPath, newPath: path };
1705
- // }
1706
- // If the move does not happen within a single parent it is possible
1707
- // for the move to impact the true path to the location where the node
1708
- // was removed from and where it was inserted. We have to adjust for this
1709
- // and find the original path. We can accomplish this (only in non-sibling)
1710
- // moves by looking at the impact of the move operation on the node
1711
- // after the original move path.
1712
- const inversePath = Path.transform(path, op);
1713
- const inverseNewPath = Path.transform(Path.next(path), op);
1714
- return Object.assign(Object.assign({}, op), { path: inversePath, newPath: inverseNewPath });
1715
- }
1716
- case 'set_node': {
1717
- const { properties, newProperties } = op;
1718
- return Object.assign(Object.assign({}, op), { properties: newProperties, newProperties: properties });
1719
- }
1720
- case 'set_selection': {
1721
- const { properties, newProperties } = op;
1722
- if (properties == null) {
1723
- return Object.assign(Object.assign({}, op), { properties: newProperties, newProperties: null });
1724
- }
1725
- else if (newProperties == null) {
1726
- return Object.assign(Object.assign({}, op), { properties: null, newProperties: properties });
1727
- }
1728
- else {
1729
- return Object.assign(Object.assign({}, op), { properties: newProperties, newProperties: properties });
1730
- }
1731
- }
1732
- case 'set_viewport': {
1733
- const { properties, newProperties } = op;
1734
- if (properties == null) {
1735
- return Object.assign(Object.assign({}, op), { properties: newProperties, newProperties: newProperties });
1736
- }
1737
- else if (newProperties == null) {
1738
- return Object.assign(Object.assign({}, op), { properties: properties, newProperties: properties });
1739
- }
1740
- else {
1741
- return Object.assign(Object.assign({}, op), { properties: newProperties, newProperties: properties });
1742
- }
1743
- }
1744
- case 'set_theme': {
1745
- const { properties, newProperties } = op;
1746
- return Object.assign(Object.assign({}, op), { properties: newProperties, newProperties: properties });
1747
- }
1748
- }
1749
- };
1750
- const PlaitOperation = {
1751
- isSetViewportOperation,
1752
- inverse
1753
- };
1754
-
1755
- const Point = {
1756
- isEquals(point, otherPoint) {
1757
- return point && otherPoint && point[0] === otherPoint[0] && point[1] === otherPoint[1];
1758
- }
1759
- };
1760
-
1761
- const SAVING = new WeakMap();
1762
- const MERGING = new WeakMap();
1763
-
1764
- var PlaitPluginKey;
1765
- (function (PlaitPluginKey) {
1766
- PlaitPluginKey["withSelection"] = "withSelection";
1767
- })(PlaitPluginKey || (PlaitPluginKey = {}));
1768
-
1769
- const IS_FROM_SCROLLING = new WeakMap();
1770
- const IS_FROM_VIEWPORT_CHANGE = new WeakMap();
1771
- function getViewportContainerRect(board) {
1772
- const { hideScrollbar } = board.options;
1773
- const scrollBarWidth = hideScrollbar ? SCROLL_BAR_WIDTH : 0;
1774
- const viewportRect = PlaitBoard.getBoardContainer(board).getBoundingClientRect();
1775
- return {
1776
- width: viewportRect.width + scrollBarWidth,
1777
- height: viewportRect.height + scrollBarWidth
1778
- };
1779
- }
1780
- function getElementHostBBox(board, zoom) {
1781
- const childrenRect = getRectangleByElements(board, board.children, true);
1782
- const viewportContainerRect = PlaitBoard.getBoardContainer(board).getBoundingClientRect();
1783
- const containerWidth = viewportContainerRect.width / zoom;
1784
- const containerHeight = viewportContainerRect.height / zoom;
1785
- let left;
1786
- let right;
1787
- let top;
1788
- let bottom;
1789
- if (childrenRect.width < containerWidth) {
1790
- const centerX = childrenRect.x + childrenRect.width / 2;
1791
- const halfContainerWidth = containerWidth / 2;
1792
- left = centerX - halfContainerWidth;
1793
- right = centerX + halfContainerWidth;
1794
- }
1795
- else {
1796
- left = childrenRect.x;
1797
- right = childrenRect.x + childrenRect.width;
1798
- }
1799
- if (childrenRect.height < containerHeight) {
1800
- const centerY = childrenRect.y + childrenRect.height / 2;
1801
- const halfContainerHeight = containerHeight / 2;
1802
- top = centerY - halfContainerHeight;
1803
- bottom = centerY + halfContainerHeight;
1804
- }
1805
- else {
1806
- top = childrenRect.y;
1807
- bottom = childrenRect.y + childrenRect.height;
1808
- }
1809
- return {
1810
- left,
1811
- right,
1812
- top,
1813
- bottom
1814
- };
1815
- }
1816
- /**
1817
- * 验证缩放比是否符合限制,如果超出限制,则返回合适的缩放比
1818
- * @param zoom 缩放比
1819
- * @param minZoom 最小缩放比
1820
- * @param maxZoom 最大缩放比
1821
- * @returns 正确的缩放比
1822
- */
1823
- function clampZoomLevel(zoom, minZoom = 0.2, maxZoom = 4) {
1824
- return zoom < minZoom ? minZoom : zoom > maxZoom ? maxZoom : zoom;
1825
- }
1826
- function getViewBox(board, zoom) {
1827
- const boardContainerRectangle = PlaitBoard.getBoardContainer(board).getBoundingClientRect();
1828
- const elementHostBBox = getElementHostBBox(board, zoom);
1829
- const horizontalPadding = boardContainerRectangle.width / 2;
1830
- const verticalPadding = boardContainerRectangle.height / 2;
1831
- const viewBox = [
1832
- elementHostBBox.left - horizontalPadding / zoom,
1833
- elementHostBBox.top - verticalPadding / zoom,
1834
- elementHostBBox.right - elementHostBBox.left + (horizontalPadding * 2) / zoom,
1835
- elementHostBBox.bottom - elementHostBBox.top + (verticalPadding * 2) / zoom
1836
- ];
1837
- return viewBox;
1838
- }
1839
- function getViewBoxCenterPoint(board) {
1840
- const childrenRectangle = getRectangleByElements(board, board.children, true);
1841
- return [childrenRectangle.x + childrenRectangle.width / 2, childrenRectangle.y + childrenRectangle.height / 2];
1842
- }
1843
- function setSVGViewBox(board, viewBox) {
1844
- const zoom = board.viewport.zoom;
1845
- const hostElement = PlaitBoard.getHost(board);
1846
- hostElement.style.display = 'block';
1847
- hostElement.style.width = `${viewBox[2] * zoom}px`;
1848
- hostElement.style.height = `${viewBox[3] * zoom}px`;
1849
- if (viewBox && viewBox[2] > 0 && viewBox[3] > 0) {
1850
- hostElement.setAttribute('viewBox', viewBox.join(' '));
1851
- }
1852
- }
1853
- function updateViewportOffset(board) {
1854
- const origination = getViewportOrigination(board);
1855
- if (!origination)
1856
- return;
1857
- const { zoom } = board.viewport;
1858
- const viewBox = getViewBox(board, zoom);
1859
- const scrollLeft = (origination[0] - viewBox[0]) * zoom;
1860
- const scrollTop = (origination[1] - viewBox[1]) * zoom;
1861
- updateViewportContainerScroll(board, scrollLeft, scrollTop);
1862
- }
1863
- function updateViewportContainerScroll(board, left, top, isFromViewportChange = true) {
1864
- const viewportContainer = PlaitBoard.getViewportContainer(board);
1865
- if (viewportContainer.scrollLeft !== left || viewportContainer.scrollTop !== top) {
1866
- viewportContainer.scrollLeft = left;
1867
- viewportContainer.scrollTop = top;
1868
- isFromViewportChange && setIsFromViewportChange(board, true);
1869
- }
1870
- }
1871
- function initializeViewportContainer(board) {
1872
- const { width, height } = getViewportContainerRect(board);
1873
- const viewportContainer = PlaitBoard.getViewportContainer(board);
1874
- viewportContainer.style.width = `${width}px`;
1875
- viewportContainer.style.height = `${height}px`;
1876
- }
1877
- function initializeViewBox(board) {
1878
- const zoom = board.viewport.zoom;
1879
- const viewBox = getViewBox(board, zoom);
1880
- setSVGViewBox(board, viewBox);
1881
- }
1882
- function initializeViewportOffset(board) {
1883
- var _a;
1884
- if (!((_a = board.viewport) === null || _a === void 0 ? void 0 : _a.origination)) {
1885
- const zoom = board.viewport.zoom;
1886
- const viewportContainerRect = PlaitBoard.getBoardContainer(board).getBoundingClientRect();
1887
- const viewBox = getViewBox(board, zoom);
1888
- const centerX = viewBox[0] + viewBox[2] / 2;
1889
- const centerY = viewBox[1] + viewBox[3] / 2;
1890
- const origination = [centerX - viewportContainerRect.width / 2 / zoom, centerY - viewportContainerRect.height / 2 / zoom];
1891
- updateViewportOrigination(board, origination);
1892
- updateViewportOffset(board);
1893
- return;
1894
- }
1895
- updateViewportOffset(board);
1896
- }
1897
- const updateViewportOrigination = (board, origination) => {
1898
- BOARD_TO_VIEWPORT_ORIGINATION.set(board, origination);
1899
- };
1900
- const clearViewportOrigination = (board) => {
1901
- BOARD_TO_VIEWPORT_ORIGINATION.delete(board);
1902
- };
1903
- const getViewportOrigination = (board) => {
1904
- const origination = BOARD_TO_VIEWPORT_ORIGINATION.get(board);
1905
- if (origination) {
1906
- return origination;
1907
- }
1908
- else {
1909
- return board.viewport.origination;
1910
- }
1911
- };
1912
- const isFromScrolling = (board) => {
1913
- return !!IS_FROM_SCROLLING.get(board);
1914
- };
1915
- const setIsFromScrolling = (board, state) => {
1916
- IS_FROM_SCROLLING.set(board, state);
1917
- };
1918
- const isFromViewportChange = (board) => {
1919
- return !!IS_FROM_VIEWPORT_CHANGE.get(board);
1920
- };
1921
- const setIsFromViewportChange = (board, state) => {
1922
- IS_FROM_VIEWPORT_CHANGE.set(board, state);
1923
- };
1924
- function scrollToRectangle(board, client) { }
1925
-
1926
- function setTheme(board, themeColorMode) {
1927
- const operation = { type: 'set_theme', properties: board.theme, newProperties: themeColorMode };
1928
- board.apply(operation);
1929
- }
1930
- const ViewportTransforms = {
1931
- setTheme
1932
- };
1933
-
1934
- function updateViewport(board, origination, zoom) {
1935
- zoom = zoom !== null && zoom !== void 0 ? zoom : board.viewport.zoom;
1936
- setViewport(board, Object.assign(Object.assign({}, board.viewport), { zoom,
1937
- origination }));
1938
- clearViewportOrigination(board);
1939
- }
1940
- const updatePointerType = (board, pointer) => {
1941
- board.pointer = pointer;
1942
- const boardComponent = BOARD_TO_COMPONENT.get(board);
1943
- boardComponent === null || boardComponent === void 0 ? void 0 : boardComponent.markForCheck();
1944
- };
1945
- function updateZoom(board, newZoom, isCenter = true) {
1946
- newZoom = clampZoomLevel(newZoom);
1947
- const mousePoint = PlaitBoard.getMovingPointInBoard(board);
1948
- const nativeElement = PlaitBoard.getBoardContainer(board);
1949
- const nativeElementRect = nativeElement.getBoundingClientRect();
1950
- const boardContainerRect = PlaitBoard.getBoardContainer(board).getBoundingClientRect();
1951
- let focusPoint = [boardContainerRect.width / 2, boardContainerRect.height / 2];
1952
- if (!isCenter && mousePoint && distanceBetweenPointAndRectangle(mousePoint[0], mousePoint[1], nativeElementRect) === 0) {
1953
- focusPoint = toPoint(mousePoint[0], mousePoint[1], nativeElement);
1954
- }
1955
- const zoom = board.viewport.zoom;
1956
- const origination = getViewportOrigination(board);
1957
- const centerX = origination[0] + focusPoint[0] / zoom;
1958
- const centerY = origination[1] + focusPoint[1] / zoom;
1959
- const newOrigination = [centerX - focusPoint[0] / newZoom, centerY - focusPoint[1] / newZoom];
1960
- updateViewport(board, newOrigination, newZoom);
1961
- }
1962
- function fitViewport(board) {
1963
- let scrollBarWidth = getRealScrollBarWidth(board);
1964
- const boardContainerRect = PlaitBoard.getBoardContainer(board).getBoundingClientRect();
1965
- const elementHostBox = getRectangleByElements(board, board.children, true);
1966
- const zoom = board.viewport.zoom;
1967
- const autoFitPadding = 16;
1968
- const viewportWidth = boardContainerRect.width - 2 * autoFitPadding;
1969
- const viewportHeight = boardContainerRect.height - 2 * autoFitPadding;
1970
- let newZoom = zoom;
1971
- if (viewportWidth < elementHostBox.width || viewportHeight < elementHostBox.height) {
1972
- newZoom = Math.min(viewportWidth / elementHostBox.width, viewportHeight / elementHostBox.height);
1973
- }
1974
- else {
1975
- newZoom = 1;
1976
- }
1977
- const centerPoint = getViewBoxCenterPoint(board);
1978
- const newOrigination = [
1979
- centerPoint[0] - boardContainerRect.width / 2 / newZoom + scrollBarWidth / 2 / zoom,
1980
- centerPoint[1] - boardContainerRect.height / 2 / newZoom + scrollBarWidth / 2 / zoom
1981
- ];
1982
- updateViewport(board, newOrigination, newZoom);
1983
- }
1984
- function fitViewportWidth(board, options) {
1985
- let scrollBarWidth = getRealScrollBarWidth(board);
1986
- const boardContainer = PlaitBoard.getBoardContainer(board);
1987
- const boardContainerRectangle = boardContainer.getBoundingClientRect();
1988
- let finalWidth = 0;
1989
- if (options.maxWidth) {
1990
- finalWidth = options.maxWidth;
1991
- }
1992
- else {
1993
- finalWidth = boardContainerRectangle.width;
1994
- }
1995
- const elementHostBox = getRectangleByElements(board, board.children, true);
1996
- const contentWidth = finalWidth - 2 * options.autoFitPadding;
1997
- let newZoom = 0;
1998
- if (contentWidth < elementHostBox.width) {
1999
- newZoom = Math.min(contentWidth / elementHostBox.width);
2000
- }
2001
- else {
2002
- newZoom = 1;
2003
- }
2004
- let finalHeight = elementHostBox.height * newZoom + 2 * options.autoFitPadding;
2005
- if (finalHeight > options.limitHeight) {
2006
- const containerEl = boardContainer.closest(`.${options.containerClass}`);
2007
- containerEl.style.height = `${finalHeight}px`;
2008
- initializeViewportContainer(board);
2009
- }
2010
- else {
2011
- finalHeight = options.limitHeight;
2012
- }
2013
- const centerX = elementHostBox.x + elementHostBox.width / 2;
2014
- const centerY = elementHostBox.y + elementHostBox.height / 2;
2015
- const newOrigination = [
2016
- centerX - finalWidth / 2 / newZoom + scrollBarWidth / 2 / newZoom,
2017
- centerY - finalHeight / 2 / newZoom + scrollBarWidth / 2 / newZoom
2018
- ];
2019
- updateViewport(board, newOrigination, newZoom);
2020
- }
2021
- /**
2022
- * apply theme to every element (remove element custom properties)
2023
- * invoke applyThemeColor
2024
- */
2025
- function updateThemeColor(board, mode) {
2026
- mode = mode !== null && mode !== void 0 ? mode : board.theme.themeColorMode;
2027
- setTheme(board, { themeColorMode: mode });
2028
- depthFirstRecursion(board, element => {
2029
- board.applyTheme(element);
2030
- });
2031
- }
2032
- const BoardTransforms = {
2033
- updatePointerType,
2034
- updateViewport,
2035
- fitViewport,
2036
- updateZoom,
2037
- updateThemeColor,
2038
- fitViewportWidth
2039
- };
2040
-
2041
- const Transforms = Object.assign(Object.assign(Object.assign(Object.assign({}, GeneralTransforms), ViewportTransforms$1), SelectionTransforms), NodeTransforms);
2042
-
2043
- const PathRef = {
2044
- transform(ref, op) {
2045
- const { current } = ref;
2046
- if (current == null) {
2047
- return;
2048
- }
2049
- const path = Path.transform(current, op);
2050
- ref.current = path;
2051
- if (path == null) {
2052
- ref.unref();
2053
- }
2054
- }
2055
- };
2056
-
2057
- function createBoard(children, options) {
2058
- const board = {
2059
- viewport: {
2060
- zoom: 1
2061
- },
2062
- children,
2063
- theme: { themeColorMode: ThemeColorMode.default },
2064
- operations: [],
2065
- history: {
2066
- redos: [],
2067
- undos: []
2068
- },
2069
- selection: null,
2070
- options: options || {
2071
- readonly: false,
2072
- hideScrollbar: false,
2073
- disabledScrollOnNonFocus: false
2074
- },
2075
- pointer: (options === null || options === void 0 ? void 0 : options.readonly) ? PlaitPointerType.hand : PlaitPointerType.selection,
2076
- undo: () => { },
2077
- redo: () => { },
2078
- apply: (operation) => {
2079
- for (const ref of board.pathRefs()) {
2080
- PathRef.transform(ref, operation);
2081
- }
2082
- board.operations.push(operation);
2083
- Transforms.transform(board, operation);
2084
- if (!FLUSHING.get(board)) {
2085
- FLUSHING.set(board, true);
2086
- Promise.resolve().then(() => {
2087
- FLUSHING.set(board, false);
2088
- board.onChange();
2089
- board.operations = [];
2090
- });
2091
- }
2092
- },
2093
- pathRef: (path, options) => {
2094
- const affinity = (options === null || options === void 0 ? void 0 : options.affinity) || 'forward';
2095
- const ref = {
2096
- current: path,
2097
- affinity,
2098
- unref() {
2099
- const { current } = ref;
2100
- const pathRefs = board.pathRefs();
2101
- pathRefs.delete(ref);
2102
- ref.current = null;
2103
- return current;
2104
- }
2105
- };
2106
- const refs = board.pathRefs();
2107
- refs.add(ref);
2108
- return ref;
2109
- },
2110
- pathRefs: () => {
2111
- let refs = PATH_REFS.get(board);
2112
- if (!refs) {
2113
- refs = new Set();
2114
- PATH_REFS.set(board, refs);
2115
- }
2116
- return refs;
2117
- },
2118
- onChange: () => { },
2119
- mousedown: (event) => { },
2120
- mousemove: (event) => { },
2121
- mouseleave: (event) => { },
2122
- globalMousemove: (event) => { },
2123
- mouseup: (event) => { },
2124
- globalMouseup: (event) => { },
2125
- keydown: (event) => { },
2126
- globalKeydown: (event) => { },
2127
- keyup: (event) => { },
2128
- dblclick: (event) => { },
2129
- setFragment: (data) => { },
2130
- insertFragment: (data) => { },
2131
- deleteFragment: (data) => { },
2132
- drawElement: (context) => [],
2133
- redrawElement: (context, previousContext) => { },
2134
- destroyElement: (context) => { },
2135
- isWithinSelection: element => false,
2136
- isHitSelection: element => false,
2137
- isRecursion: element => true,
2138
- isMovable: element => false,
2139
- getRectangle: element => null,
2140
- applyTheme: (element) => { },
2141
- pointerDown: (pointer) => { },
2142
- pointerMove: (pointer) => { },
2143
- pointerUp: (pointer) => { },
2144
- pointerCancel: (pointer) => { },
2145
- pointerOut: (pointer) => { },
2146
- pointerLeave: (pointer) => { },
2147
- globalPointerMove: (pointer) => { },
2148
- globalPointerUp: (pointer) => { },
2149
- };
2150
- return board;
2151
- }
2152
-
2153
- function withBoard(board) {
2154
- const { onChange } = board;
2155
- board.onChange = () => {
2156
- const onContextChange = BOARD_TO_ON_CHANGE.get(board);
2157
- if (onContextChange) {
2158
- onContextChange();
2159
- }
2160
- onChange();
2161
- };
2162
- return board;
2163
- }
2164
-
2165
- function withHistory(board) {
2166
- const { apply, keydown } = board;
2167
- board.history = { undos: [], redos: [] };
2168
- board.redo = () => {
2169
- const { history } = board;
2170
- const { redos } = history;
2171
- if (redos.length > 0) {
2172
- const batch = redos[redos.length - 1];
2173
- PlaitHistoryBoard.withoutSaving(board, () => {
2174
- for (const op of batch) {
2175
- board.apply(op);
2176
- }
2177
- });
2178
- history.redos.pop();
2179
- history.undos.push(batch);
2180
- }
2181
- };
2182
- board.undo = () => {
2183
- const { history } = board;
2184
- const { undos } = history;
2185
- if (undos.length > 0) {
2186
- const batch = undos[undos.length - 1];
2187
- PlaitHistoryBoard.withoutSaving(board, () => {
2188
- const inverseOps = batch.map(PlaitOperation.inverse).reverse();
2189
- for (const op of inverseOps) {
2190
- board.apply(op);
2191
- }
2192
- });
2193
- history.redos.push(batch);
2194
- history.undos.pop();
2195
- }
2196
- };
2197
- board.apply = (op) => {
2198
- const { operations, history } = board;
2199
- const { undos } = history;
2200
- const lastBatch = undos[undos.length - 1];
2201
- const lastOp = lastBatch && lastBatch[lastBatch.length - 1];
2202
- let save = PlaitHistoryBoard.isSaving(board);
2203
- let merge = PlaitHistoryBoard.isMerging(board);
2204
- if (save == null) {
2205
- save = shouldSave(op, lastOp);
2206
- }
2207
- if (save) {
2208
- if (!merge) {
2209
- if (lastBatch == null) {
2210
- merge = false;
2211
- }
2212
- else if (operations.length !== 0) {
2213
- merge = true;
2214
- }
2215
- else {
2216
- merge = shouldMerge(op, lastOp);
2217
- }
2218
- }
2219
- if (lastBatch && merge) {
2220
- lastBatch.push(op);
2221
- }
2222
- else {
2223
- const batch = [op];
2224
- undos.push(batch);
2225
- }
2226
- while (undos.length > 100) {
2227
- undos.shift();
2228
- }
2229
- if (shouldClear(op)) {
2230
- history.redos = [];
2231
- }
2232
- }
2233
- apply(op);
2234
- };
2235
- board.keydown = (event) => {
2236
- if (isHotkey('mod+z', event)) {
2237
- board.undo();
2238
- return;
2239
- }
2240
- if (isHotkey('mod+shift+z', event)) {
2241
- board.redo();
2242
- return;
2243
- }
2244
- keydown(event);
2245
- };
2246
- return board;
2247
- }
2248
-
2249
- function withHandPointer(board) {
2250
- const { mousedown, mousemove, globalMouseup, keydown, keyup } = board;
2251
- let isMoving = false;
2252
- const plaitBoardMove = {
2253
- x: 0,
2254
- y: 0
2255
- };
2256
- board.mousedown = (event) => {
2257
- if (PlaitBoard.isPointer(board, PlaitPointerType.hand) && isMainPointer(event)) {
2258
- isMoving = true;
2259
- PlaitBoard.getBoardContainer(board).classList.add('viewport-moving');
2260
- plaitBoardMove.x = event.x;
2261
- plaitBoardMove.y = event.y;
2262
- }
2263
- mousedown(event);
2264
- };
2265
- board.mousemove = (event) => {
2266
- if (PlaitBoard.isPointer(board, PlaitPointerType.hand) && board.selection && isMoving) {
2267
- const viewportContainer = PlaitBoard.getViewportContainer(board);
2268
- const left = viewportContainer.scrollLeft - (event.x - plaitBoardMove.x);
2269
- const top = viewportContainer.scrollTop - (event.y - plaitBoardMove.y);
2270
- updateViewportContainerScroll(board, left, top, false);
2271
- plaitBoardMove.x = event.x;
2272
- plaitBoardMove.y = event.y;
2273
- }
2274
- mousemove(event);
2275
- };
2276
- board.globalMouseup = (event) => {
2277
- if (board.selection) {
2278
- isMoving = false;
2279
- PlaitBoard.getBoardContainer(board).classList.remove('viewport-moving');
2280
- plaitBoardMove.x = 0;
2281
- plaitBoardMove.y = 0;
2282
- }
2283
- globalMouseup(event);
2284
- };
2285
- board.keydown = (event) => {
2286
- if (event.code === 'Space') {
2287
- if (!PlaitBoard.isPointer(board, PlaitPointerType.hand)) {
2288
- BoardTransforms.updatePointerType(board, PlaitPointerType.hand);
2289
- }
2290
- event.preventDefault();
2291
- }
2292
- keydown(event);
2293
- };
2294
- board.keyup = (event) => {
2295
- if (!board.options.readonly && event.code === 'Space') {
2296
- BoardTransforms.updatePointerType(board, PlaitPointerType.selection);
2297
- }
2298
- keyup(event);
2299
- };
2300
- return board;
2301
- }
2302
-
2303
- function withSelection(board) {
2304
- const { pointerDown, globalPointerMove, globalPointerUp, onChange } = board;
2305
- let start = null;
2306
- let end = null;
2307
- let selectionMovingG;
2308
- let selectionOuterG;
2309
- let previousSelectedElements;
2310
- // prevent text from being selected when user pressed main pointer and is moving
2311
- let needPreventNativeSelectionWhenMoving = false;
2312
- board.pointerDown = (event) => {
2313
- if (event.target instanceof Element && !event.target.closest('.plait-richtext-container')) {
2314
- needPreventNativeSelectionWhenMoving = true;
2315
- }
2316
- if (!isMainPointer(event)) {
2317
- pointerDown(event);
2318
- return;
2319
- }
2320
- const options = board.getPluginOptions(PlaitPluginKey.withSelection);
2321
- const point = transformPoint(board, toPoint(event.x, event.y, PlaitBoard.getHost(board)));
2322
- const range = { anchor: point, focus: point };
2323
- const hitElements = getHitElements(board, { ranges: [range] });
2324
- const selectedElements = getSelectedElements(board);
2325
- if (hitElements.length === 1 && selectedElements.includes(hitElements[0]) && !options.isDisabledSelect) {
2326
- pointerDown(event);
2327
- return;
2328
- }
2329
- if (PlaitBoard.isPointer(board, PlaitPointerType.selection) &&
2330
- hitElements.length === 0 &&
2331
- options.isMultiple &&
2332
- !options.isDisabledSelect) {
2333
- start = point;
2334
- preventTouchMove(board, true);
2335
- }
2336
- Transforms.setSelection(board, { ranges: [range] });
2337
- pointerDown(event);
2338
- };
2339
- board.globalPointerMove = (event) => {
2340
- if (needPreventNativeSelectionWhenMoving) {
2341
- // prevent text from being selected
2342
- event.preventDefault();
2343
- }
2344
- if (start) {
2345
- const movedTarget = transformPoint(board, toPoint(event.x, event.y, PlaitBoard.getHost(board)));
2346
- const { x, y, width, height } = RectangleClient.toRectangleClient([start, movedTarget]);
2347
- selectionMovingG === null || selectionMovingG === void 0 ? void 0 : selectionMovingG.remove();
2348
- if (Math.hypot(width, height) > 5) {
2349
- end = movedTarget;
2350
- throttleRAF(() => {
2351
- if (start && end) {
2352
- Transforms.setSelection(board, { ranges: [{ anchor: start, focus: end }] });
2353
- }
2354
- });
2355
- setSelectionMoving(board);
2356
- const rough = PlaitBoard.getRoughSVG(board);
2357
- selectionMovingG = rough.rectangle(x, y, width, height, {
2358
- stroke: SELECTION_BORDER_COLOR,
2359
- strokeWidth: 1,
2360
- fill: SELECTION_FILL_COLOR,
2361
- fillStyle: 'solid'
2362
- });
2363
- PlaitBoard.getHost(board).append(selectionMovingG);
2364
- }
2365
- }
2366
- globalPointerMove(event);
2367
- };
2368
- board.globalPointerUp = (event) => {
2369
- if (start && end) {
2370
- selectionMovingG === null || selectionMovingG === void 0 ? void 0 : selectionMovingG.remove();
2371
- clearSelectionMoving(board);
2372
- Transforms.setSelection(board, { ranges: [{ anchor: start, focus: end }] });
2373
- }
2374
- if (PlaitBoard.isFocus(board)) {
2375
- const isInBoard = event.target instanceof Node && PlaitBoard.getBoardContainer(board).contains(event.target);
2376
- const isInDocument = event.target instanceof Node && document.contains(event.target);
2377
- const isAttachedElement = event.target instanceof Element && event.target.closest(`.${ATTACHED_ELEMENT_CLASS_NAME}`);
2378
- // Clear selection when mouse board outside area
2379
- // The framework needs to determine whether the board is focused through selection
2380
- if (!isInBoard && !start && !isAttachedElement && isInDocument) {
2381
- Transforms.setSelection(board, null);
2382
- }
2383
- }
2384
- start = null;
2385
- end = null;
2386
- needPreventNativeSelectionWhenMoving = false;
2387
- preventTouchMove(board, false);
2388
- globalPointerUp(event);
2389
- };
2390
- board.onChange = () => {
2391
- const options = board.getPluginOptions(PlaitPluginKey.withSelection);
2392
- if (options.isDisabledSelect) {
2393
- selectionOuterG === null || selectionOuterG === void 0 ? void 0 : selectionOuterG.remove();
2394
- clearSelectedElement(board);
2395
- }
2396
- // calc selected elements entry
2397
- if (board.pointer !== PlaitPointerType.hand && !options.isDisabledSelect) {
2398
- try {
2399
- if (board.operations.find(value => value.type === 'set_selection')) {
2400
- selectionOuterG === null || selectionOuterG === void 0 ? void 0 : selectionOuterG.remove();
2401
- const temporaryElements = getTemporaryElements(board);
2402
- let elements = temporaryElements ? temporaryElements : getHitElements(board);
2403
- if (!options.isMultiple && elements.length > 1) {
2404
- elements = [elements[0]];
2405
- }
2406
- cacheSelectedElements(board, elements);
2407
- previousSelectedElements = elements;
2408
- const { width, height } = getRectangleByElements(board, elements, false);
2409
- if (width > 0 && height > 0 && elements.length > 1) {
2410
- selectionOuterG = createSelectionOuterG(board, elements);
2411
- selectionOuterG.classList.add('selection-outer');
2412
- PlaitBoard.getHost(board).append(selectionOuterG);
2413
- }
2414
- deleteTemporaryElements(board);
2415
- }
2416
- else {
2417
- // wait node destroy and remove selected element state
2418
- setTimeout(() => {
2419
- const currentSelectedElements = getSelectedElements(board);
2420
- if (currentSelectedElements.length && currentSelectedElements.length > 1) {
2421
- const selectedElementChange = currentSelectedElements.some(item => !previousSelectedElements.includes(item));
2422
- if (selectedElementChange) {
2423
- selectionOuterG === null || selectionOuterG === void 0 ? void 0 : selectionOuterG.remove();
2424
- selectionOuterG = createSelectionOuterG(board, currentSelectedElements);
2425
- selectionOuterG.classList.add('selection-outer');
2426
- PlaitBoard.getHost(board).append(selectionOuterG);
2427
- }
2428
- }
2429
- else {
2430
- selectionOuterG === null || selectionOuterG === void 0 ? void 0 : selectionOuterG.remove();
2431
- }
2432
- });
2433
- }
2434
- }
2435
- catch (error) {
2436
- console.error(error);
2437
- }
2438
- }
2439
- onChange();
2440
- };
2441
- board.setPluginOptions(PlaitPluginKey.withSelection, {
2442
- isMultiple: true,
2443
- isDisabledSelect: false
2444
- });
2445
- return board;
2446
- }
2447
- function getTemporaryElements(board) {
2448
- return BOARD_TO_TEMPORARY_ELEMENTS.get(board);
2449
- }
2450
- function deleteTemporaryElements(board) {
2451
- BOARD_TO_TEMPORARY_ELEMENTS.delete(board);
2452
- }
2453
- function isSelectionMoving(board) {
2454
- return !!BOARD_TO_IS_SELECTION_MOVING.get(board);
2455
- }
2456
- function setSelectionMoving(board) {
2457
- PlaitBoard.getBoardContainer(board).classList.add('selection-moving');
2458
- BOARD_TO_IS_SELECTION_MOVING.set(board, true);
2459
- }
2460
- function clearSelectionMoving(board) {
2461
- PlaitBoard.getBoardContainer(board).classList.remove('selection-moving');
2462
- BOARD_TO_IS_SELECTION_MOVING.delete(board);
2463
- }
2464
- function createSelectionOuterG(board, selectElements) {
2465
- const { x, y, width, height } = getRectangleByElements(board, selectElements, false);
2466
- const rough = PlaitBoard.getRoughSVG(board);
2467
- return rough.rectangle(x - 2.5, y - 2.5, width + 5, height + 5, {
2468
- stroke: SELECTION_BORDER_COLOR,
2469
- strokeWidth: 1,
2470
- fillStyle: 'solid'
2471
- });
2472
- }
2473
-
2474
- function withViewport(board) {
2475
- const { onChange } = board;
2476
- const throttleUpdate = debounce(() => {
2477
- initializeViewBox(board);
2478
- updateViewportOffset(board);
2479
- }, 500, { leading: true });
2480
- board.onChange = () => {
2481
- const isSetViewport = board.operations.some(op => op.type === 'set_viewport');
2482
- const isOnlySetSelection = board.operations.some(op => op.type === 'set_selection');
2483
- if (isOnlySetSelection) {
2484
- return onChange();
2485
- }
2486
- if (isSetViewport && isFromScrolling(board)) {
2487
- setIsFromScrolling(board, false);
2488
- return onChange();
2489
- }
2490
- if (isSetViewport) {
2491
- initializeViewBox(board);
2492
- updateViewportOffset(board);
2493
- }
2494
- else {
2495
- throttleUpdate();
2496
- }
2497
- onChange();
2498
- };
2499
- return board;
2500
- }
2501
-
2502
- function withMoving(board) {
2503
- const { mousedown, mousemove, globalMouseup, globalMousemove } = board;
2504
- let offsetX = 0;
2505
- let offsetY = 0;
2506
- let isPreventDefault = false;
2507
- let startPoint;
2508
- let activeElements = [];
2509
- board.mousedown = event => {
2510
- const host = BOARD_TO_HOST.get(board);
2511
- const point = transformPoint(board, toPoint(event.x, event.y, host));
2512
- const range = { anchor: point, focus: point };
2513
- let movableElements = board.children.filter(item => board.isMovable(item));
2514
- if (movableElements.length) {
2515
- startPoint = point;
2516
- const selectedRootElements = getSelectedElements(board).filter(item => movableElements.includes(item));
2517
- const hitElement = getHitElementOfRoot(board, movableElements, range);
2518
- if (hitElement && selectedRootElements.includes(hitElement)) {
2519
- activeElements = selectedRootElements;
2520
- }
2521
- else if (hitElement) {
2522
- activeElements = [hitElement];
2523
- }
2524
- }
2525
- mousedown(event);
2526
- };
2527
- board.mousemove = event => {
2528
- if (startPoint && activeElements.length && !PlaitBoard.hasBeenTextEditing(board)) {
2529
- if (!isPreventDefault) {
2530
- isPreventDefault = true;
2531
- }
2532
- const host = BOARD_TO_HOST.get(board);
2533
- const endPoint = transformPoint(board, toPoint(event.x, event.y, host));
2534
- offsetX = endPoint[0] - startPoint[0];
2535
- offsetY = endPoint[1] - startPoint[1];
2536
- const offsetBuffer = 5;
2537
- if (Math.abs(offsetX) > offsetBuffer || Math.abs(offsetY) > offsetBuffer) {
2538
- throttleRAF(() => {
2539
- const currentElements = activeElements.map(activeElement => {
2540
- const points = activeElement.points || [];
2541
- const [x, y] = activeElement.points[0];
2542
- const newPoints = points.map(p => [p[0] + offsetX, p[1] + offsetY]);
2543
- const index = board.children.findIndex(item => item.id === activeElement.id);
2544
- Transforms.setNode(board, {
2545
- points: newPoints
2546
- }, [index]);
2547
- MERGING.set(board, true);
2548
- return PlaitNode.get(board, [index]);
2549
- });
2550
- PlaitBoard.getBoardContainer(board).classList.add('element-moving');
2551
- addMovingElements(board, currentElements);
2552
- });
2553
- }
2554
- }
2555
- if (isPreventDefault) {
2556
- // 阻止 move 过程中触发画布滚动行为
2557
- event.preventDefault();
2558
- }
2559
- mousemove(event);
2560
- };
2561
- board.globalMousemove = event => {
2562
- if (startPoint) {
2563
- const inPlaitBoardElement = isInPlaitBoard(board, event.x, event.y);
2564
- if (!inPlaitBoardElement) {
2565
- cancelMove(board);
2566
- }
2567
- }
2568
- globalMousemove(event);
2569
- };
2570
- board.globalMouseup = event => {
2571
- isPreventDefault = false;
2572
- if (startPoint) {
2573
- cancelMove(board);
2574
- }
2575
- globalMouseup(event);
2576
- };
2577
- function cancelMove(board) {
2578
- startPoint = null;
2579
- offsetX = 0;
2580
- offsetY = 0;
2581
- activeElements = [];
2582
- removeMovingElements(board);
2583
- MERGING.set(board, false);
2584
- PlaitBoard.getBoardContainer(board).classList.remove('element-moving');
2585
- }
2586
- return board;
2587
- }
2588
-
2589
- const withOptions = (board) => {
2590
- const pluginOptions = new Map();
2591
- const newBoard = board;
2592
- newBoard.getPluginOptions = key => {
2593
- return pluginOptions.get(key);
2594
- };
2595
- newBoard.setPluginOptions = (key, options) => {
2596
- const oldOptions = newBoard.getPluginOptions(key) || {};
2597
- pluginOptions.set(key, Object.assign(Object.assign({}, oldOptions), options));
2598
- };
2599
- return newBoard;
2600
- };
2601
-
2602
- class PlaitIslandBaseComponent {
2603
- constructor(cdr) {
2604
- this.cdr = cdr;
2605
- }
2606
- initialize(board) {
2607
- this.board = board;
2608
- this.markForCheck();
2609
- }
2610
- markForCheck() {
2611
- this.cdr.markForCheck();
2612
- }
2613
- }
2614
- PlaitIslandBaseComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitIslandBaseComponent, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive });
2615
- PlaitIslandBaseComponent.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.2.5", type: PlaitIslandBaseComponent, host: { classAttribute: "plait-island-container" }, ngImport: i0 });
2616
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitIslandBaseComponent, decorators: [{
2617
- type: Directive,
2618
- args: [{
2619
- host: {
2620
- class: 'plait-island-container'
2621
- }
2622
- }]
2623
- }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }]; } });
2624
- class PlaitIslandPopoverBaseComponent {
2625
- initialize(board) {
2626
- this.board = board;
2627
- const onChange = board.onChange;
2628
- board.onChange = () => {
2629
- onChange();
2630
- if (hasOnBoardChange(this)) {
2631
- this.onBoardChange();
2632
- }
2633
- };
2634
- this.onChange = onChange;
2635
- }
2636
- ngOnInit() {
2637
- if (!this.board) {
2638
- throw new Error('can not find board instance');
2639
- }
2640
- this.initialize(this.board);
2641
- this.islandOnInit();
2642
- }
2643
- ngOnDestroy() {
2644
- this.board.onChange = this.onChange;
2645
- this.islandOnDestroy();
2646
- }
2647
- }
2648
- PlaitIslandPopoverBaseComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitIslandPopoverBaseComponent, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2649
- PlaitIslandPopoverBaseComponent.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.2.5", type: PlaitIslandPopoverBaseComponent, inputs: { board: "board" }, host: { classAttribute: "plait-island-popover-container" }, ngImport: i0 });
2650
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitIslandPopoverBaseComponent, decorators: [{
2651
- type: Directive,
2652
- args: [{
2653
- host: {
2654
- class: 'plait-island-popover-container'
2655
- }
2656
- }]
2657
- }], propDecorators: { board: [{
2658
- type: Input
2659
- }] } });
2660
- const hasOnBoardChange = (value) => {
2661
- if (value.onBoardChange) {
2662
- return true;
2663
- }
2664
- else {
2665
- return false;
2666
- }
2667
- };
2668
-
2669
- const withHotkey = (board) => {
2670
- const { keydown, globalKeydown } = board;
2671
- board.keydown = (event) => {
2672
- const options = board.getPluginOptions(PlaitPluginKey.withSelection);
2673
- if (!PlaitBoard.isReadonly(board) && options.isMultiple && isHotkey('mod+a', event)) {
2674
- event.preventDefault();
2675
- let elements = [];
2676
- depthFirstRecursion(board, node => {
2677
- if (PlaitBoard.isBoard(node)) {
2678
- return;
2679
- }
2680
- elements.push(node);
2681
- }, node => {
2682
- if (PlaitBoard.isBoard(node) || board.isRecursion(node)) {
2683
- return true;
2684
- }
2685
- else {
2686
- return false;
2687
- }
2688
- }, true);
2689
- Transforms.setSelectionWithTemporaryElements(board, elements);
2690
- return;
2691
- }
2692
- keydown(event);
2693
- };
2694
- board.globalKeydown = (event) => {
2695
- if (PlaitBoard.getMovingPointInBoard(board) || PlaitBoard.isMovingPointInBoard(board)) {
2696
- if (isHotkey(['mod+=', 'mod++'], { byKey: true })(event)) {
2697
- event.preventDefault();
2698
- BoardTransforms.updateZoom(board, board.viewport.zoom + 0.1, false);
2699
- return;
2700
- }
2701
- if (isHotkey(['mod+shift+=', 'mod+shift++'], { byKey: true })(event)) {
2702
- event.preventDefault();
2703
- BoardTransforms.fitViewport(board);
2704
- return;
2705
- }
2706
- if (isHotkey(['mod+-', 'mod+shift+-'])(event)) {
2707
- event.preventDefault();
2708
- BoardTransforms.updateZoom(board, board.viewport.zoom - 0.1);
2709
- return;
2710
- }
2711
- if (isHotkey(['mod+0', 'mod+shift+0'], { byKey: true })(event)) {
2712
- event.preventDefault();
2713
- BoardTransforms.updateZoom(board, 1);
2714
- return;
2715
- }
2716
- }
2717
- globalKeydown(event);
2718
- };
2719
- return board;
2720
- };
2721
-
2722
- class PlaitContextService {
2723
- constructor() {
2724
- this.uploadingFiles = [];
2725
- }
2726
- getUploadingFile(url) {
2727
- return this.uploadingFiles.find(file => file.url === url);
2728
- }
2729
- setUploadingFile(file) {
2730
- return this.uploadingFiles.push(file);
2731
- }
2732
- removeUploadingFile(fileEntry) {
2733
- this.uploadingFiles = this.uploadingFiles.filter(file => file.url !== fileEntry.url);
2734
- }
2735
- }
2736
- PlaitContextService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitContextService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
2737
- PlaitContextService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitContextService });
2738
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitContextService, decorators: [{
2739
- type: Injectable
2740
- }] });
2741
-
2742
- class PlaitElementComponent {
2743
- constructor(renderer2, viewContainerRef) {
2744
- this.renderer2 = renderer2;
2745
- this.viewContainerRef = viewContainerRef;
2746
- this.initialized = false;
2747
- }
2748
- ngOnInit() {
2749
- this.initialize();
2750
- this.drawElement();
2751
- }
2752
- initialize() {
2753
- NODE_TO_INDEX.set(this.element, this.index);
2754
- NODE_TO_PARENT.set(this.element, this.parent);
2755
- this.initialized = true;
2756
- }
2757
- drawElement() {
2758
- const context = this.getContext();
2759
- const result = this.board.drawElement(context);
2760
- if (Array.isArray(result)) {
2761
- }
2762
- else {
2763
- const componentRef = this.viewContainerRef.createComponent(result);
2764
- const instance = componentRef.instance;
2765
- instance.context = context;
2766
- this.insertG(instance.rootG ? instance.rootG : instance.g);
2767
- this.instance = instance;
2768
- }
2769
- }
2770
- insertG(g) {
2771
- if (PlaitBoard.isBoard(this.parent)) {
2772
- this.parentG.append(g);
2773
- }
2774
- else {
2775
- let siblingG = PlaitElement.getComponent(this.parent).g;
2776
- if (this.index > 0) {
2777
- const brotherElement = this.parent.children[this.index - 1];
2778
- const lastElement = PlaitNode.last(this.board, PlaitBoard.findPath(this.board, brotherElement));
2779
- let component = PlaitElement.getComponent(lastElement) || PlaitElement.getComponent(brotherElement);
2780
- siblingG = component.g;
2781
- }
2782
- this.parentG.insertBefore(g, siblingG);
2783
- }
2784
- }
2785
- ngOnChanges(simpleChanges) {
2786
- if (this.initialized) {
2787
- NODE_TO_INDEX.set(this.element, this.index);
2788
- NODE_TO_PARENT.set(this.element, this.parent);
2789
- const elementChanged = simpleChanges['element'];
2790
- const context = this.getContext();
2791
- if (elementChanged && isSelectedElement(this.board, elementChanged.previousValue)) {
2792
- context.selected = true;
2793
- removeSelectedElement(this.board, elementChanged.previousValue);
2794
- addSelectedElement(this.board, this.element);
2795
- }
2796
- if (this.instance) {
2797
- this.instance.context = context;
2798
- }
2799
- }
2800
- }
2801
- getContext() {
2802
- const isSelected = isSelectedElement(this.board, this.element);
2803
- const context = {
2804
- element: this.element,
2805
- parent: this.parent,
2806
- board: this.board,
2807
- selected: isSelected,
2808
- effect: this.effect
2809
- };
2810
- return context;
2811
- }
2812
- ngOnDestroy() {
2813
- this.board.destroyElement(this.getContext());
2814
- }
2815
- }
2816
- PlaitElementComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitElementComponent, deps: [{ token: i0.Renderer2 }, { token: i0.ViewContainerRef }], target: i0.ɵɵFactoryTarget.Component });
2817
- PlaitElementComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.5", type: PlaitElementComponent, selector: "plait-element", inputs: { index: "index", element: "element", parent: "parent", board: "board", effect: "effect", parentG: "parentG" }, usesOnChanges: true, ngImport: i0, template: '', isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush });
2818
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitElementComponent, decorators: [{
2819
- type: Component,
2820
- args: [{
2821
- selector: 'plait-element',
2822
- template: '',
2823
- changeDetection: ChangeDetectionStrategy.OnPush
2824
- }]
2825
- }], ctorParameters: function () { return [{ type: i0.Renderer2 }, { type: i0.ViewContainerRef }]; }, propDecorators: { index: [{
2826
- type: Input
2827
- }], element: [{
2828
- type: Input
2829
- }], parent: [{
2830
- type: Input
2831
- }], board: [{
2832
- type: Input
2833
- }], effect: [{
2834
- type: Input
2835
- }], parentG: [{
2836
- type: Input
2837
- }] } });
2838
-
2839
- class PlaitChildrenElement {
2840
- constructor() {
2841
- this.trackBy = (index, element) => {
2842
- return element.id;
2843
- };
2844
- }
2845
- ngOnInit() {
2846
- if (!this.parent) {
2847
- this.parent = this.board;
2848
- }
2849
- if (!this.parentG) {
2850
- this.parentG = PlaitBoard.getElementHost(this.board);
2851
- }
2852
- }
2853
- }
2854
- PlaitChildrenElement.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitChildrenElement, deps: [], target: i0.ɵɵFactoryTarget.Component });
2855
- PlaitChildrenElement.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.5", type: PlaitChildrenElement, selector: "plait-children", inputs: { board: "board", parent: "parent", effect: "effect", parentG: "parentG" }, ngImport: i0, template: `
2856
- <plait-element
2857
- *ngFor="let item of parent.children; let index = index; trackBy: trackBy"
2858
- [index]="index"
2859
- [element]="item"
2860
- [parent]="parent"
2861
- [board]="board"
2862
- [effect]="effect"
2863
- [parentG]="parentG"
2864
- ></plait-element>
2865
- `, isInline: true, dependencies: [{ kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "component", type: PlaitElementComponent, selector: "plait-element", inputs: ["index", "element", "parent", "board", "effect", "parentG"] }] });
2866
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitChildrenElement, decorators: [{
2867
- type: Component,
2868
- args: [{
2869
- selector: 'plait-children',
2870
- template: `
2871
- <plait-element
2872
- *ngFor="let item of parent.children; let index = index; trackBy: trackBy"
2873
- [index]="index"
2874
- [element]="item"
2875
- [parent]="parent"
2876
- [board]="board"
2877
- [effect]="effect"
2878
- [parentG]="parentG"
2879
- ></plait-element>
2880
- `
2881
- }]
2882
- }], ctorParameters: function () { return []; }, propDecorators: { board: [{
2883
- type: Input
2884
- }], parent: [{
2885
- type: Input
2886
- }], effect: [{
2887
- type: Input
2888
- }], parentG: [{
2889
- type: Input
2890
- }] } });
2891
-
2892
- const ElementHostClass = 'element-host';
2893
- const ElementUpperHostClass = 'element-upper-host';
2894
- const ElementActiveHostClass = 'element-active-host';
2895
- class PlaitBoardComponent {
2896
- get host() {
2897
- return this.svg.nativeElement;
2898
- }
2899
- get hostClass() {
2900
- return `${HOST_CLASS_NAME} pointer-${this.board.pointer} theme-${this.board.theme.themeColorMode} ${this.getBrowserClassName()}`;
2901
- }
2902
- getBrowserClassName() {
2903
- if (IS_SAFARI) {
2904
- return 'safari';
2905
- }
2906
- if (IS_CHROME) {
2907
- return 'chrome';
2908
- }
2909
- if (IS_FIREFOX) {
2910
- return 'firefox';
2911
- }
2912
- return '';
2913
- }
2914
- get readonly() {
2915
- return this.board.options.readonly;
2916
- }
2917
- get isFocused() {
2918
- return PlaitBoard.isFocus(this.board);
2919
- }
2920
- get disabledScrollOnNonFocus() {
2921
- return this.board.options.disabledScrollOnNonFocus && !PlaitBoard.isFocus(this.board);
2922
- }
2923
- get nativeElement() {
2924
- return this.elementRef.nativeElement;
2925
- }
2926
- constructor(cdr, viewContainerRef, elementRef, ngZone) {
2927
- this.cdr = cdr;
2928
- this.viewContainerRef = viewContainerRef;
2929
- this.elementRef = elementRef;
2930
- this.ngZone = ngZone;
2931
- this.hasInitialized = false;
2932
- this.effect = {};
2933
- this.destroy$ = new Subject();
2934
- this.plaitValue = [];
2935
- this.plaitPlugins = [];
2936
- this.plaitChange = new EventEmitter();
2937
- this.plaitBoardInitialized = new EventEmitter();
2938
- this.trackBy = (index, element) => {
2939
- return element.id;
2940
- };
2941
- }
2942
- ngOnInit() {
2943
- const elementHost = this.host.querySelector(`.${ElementHostClass}`);
2944
- const elementUpperHost = this.host.querySelector(`.${ElementUpperHostClass}`);
2945
- const elementActiveHost = this.host.querySelector(`.${ElementActiveHostClass}`);
2946
- const roughSVG = rough.svg(this.host, {
2947
- options: { roughness: 0, strokeWidth: 1 }
2948
- });
2949
- this.roughSVG = roughSVG;
2950
- this.initializePlugins();
2951
- this.ngZone.runOutsideAngular(() => {
2952
- this.initializeHookListener();
2953
- this.viewportScrollListener();
2954
- this.elementResizeListener();
2955
- fromEvent(document, 'mouseleave')
2956
- .pipe(takeUntil(this.destroy$))
2957
- .subscribe((event) => {
2958
- BOARD_TO_MOVING_POINT.delete(this.board);
2959
- });
2960
- });
2961
- BOARD_TO_COMPONENT.set(this.board, this);
2962
- BOARD_TO_ROUGH_SVG.set(this.board, roughSVG);
2963
- BOARD_TO_HOST.set(this.board, this.host);
2964
- BOARD_TO_ELEMENT_HOST.set(this.board, {
2965
- host: elementHost,
2966
- upperHost: elementUpperHost,
2967
- activeHost: elementActiveHost
2968
- });
2969
- BOARD_TO_ON_CHANGE.set(this.board, () => {
2970
- this.ngZone.run(() => {
2971
- this.detect();
2972
- const changeEvent = {
2973
- children: this.board.children,
2974
- operations: this.board.operations,
2975
- viewport: this.board.viewport,
2976
- selection: this.board.selection,
2977
- theme: this.board.theme
2978
- };
2979
- this.updateIslands();
2980
- this.plaitChange.emit(changeEvent);
2981
- });
2982
- });
2983
- this.hasInitialized = true;
2984
- }
2985
- ngAfterContentInit() {
2986
- this.initializeIslands();
2987
- }
2988
- detect() {
2989
- this.effect = {};
2990
- this.cdr.detectChanges();
2991
- }
2992
- ngOnChanges(changes) {
2993
- if (this.hasInitialized) {
2994
- const valueChange = changes['plaitValue'];
2995
- const options = changes['plaitOptions'];
2996
- if (valueChange)
2997
- this.board.children = valueChange.currentValue;
2998
- if (options)
2999
- this.board.options = options.currentValue;
3000
- this.cdr.markForCheck();
3001
- }
3002
- }
3003
- ngAfterViewInit() {
3004
- this.plaitBoardInitialized.emit(this.board);
3005
- initializeViewportContainer(this.board);
3006
- initializeViewBox(this.board);
3007
- initializeViewportOffset(this.board);
3008
- }
3009
- initializePlugins() {
3010
- let board = withHotkey(withHandPointer(withHistory(withSelection(withMoving(withBoard(withViewport(withOptions(createBoard(this.plaitValue, this.plaitOptions)))))))));
3011
- this.plaitPlugins.forEach(plugin => {
3012
- board = plugin(board);
3013
- });
3014
- this.board = board;
3015
- if (this.plaitViewport) {
3016
- this.board.viewport = this.plaitViewport;
3017
- }
3018
- if (this.plaitTheme) {
3019
- this.board.theme = this.plaitTheme;
3020
- }
3021
- }
3022
- initializeHookListener() {
3023
- fromEvent(this.host, 'mousedown')
3024
- .pipe(takeUntil(this.destroy$))
3025
- .subscribe((event) => {
3026
- this.board.mousedown(event);
3027
- });
3028
- fromEvent(this.host, 'pointerdown')
3029
- .pipe(takeUntil(this.destroy$))
3030
- .subscribe((event) => {
3031
- this.board.pointerDown(event);
3032
- });
3033
- fromEvent(this.host, 'mousemove')
3034
- .pipe(takeUntil(this.destroy$))
3035
- .subscribe((event) => {
3036
- BOARD_TO_MOVING_POINT_IN_BOARD.set(this.board, [event.x, event.y]);
3037
- this.board.mousemove(event);
3038
- });
3039
- fromEvent(this.host, 'pointermove')
3040
- .pipe(takeUntil(this.destroy$))
3041
- .subscribe((event) => {
3042
- BOARD_TO_MOVING_POINT_IN_BOARD.set(this.board, [event.x, event.y]);
3043
- this.board.pointerMove(event);
3044
- });
3045
- fromEvent(this.host, 'mouseleave')
3046
- .pipe(takeUntil(this.destroy$))
3047
- .subscribe((event) => {
3048
- BOARD_TO_MOVING_POINT_IN_BOARD.delete(this.board);
3049
- this.board.mouseleave(event);
3050
- });
3051
- fromEvent(this.host, 'pointerleave')
3052
- .pipe(takeUntil(this.destroy$))
3053
- .subscribe((event) => {
3054
- BOARD_TO_MOVING_POINT_IN_BOARD.delete(this.board);
3055
- this.board.pointerLeave(event);
3056
- });
3057
- fromEvent(document, 'mousemove')
3058
- .pipe(takeUntil(this.destroy$))
3059
- .subscribe((event) => {
3060
- BOARD_TO_MOVING_POINT.set(this.board, [event.x, event.y]);
3061
- this.board.globalMousemove(event);
3062
- });
3063
- fromEvent(document, 'pointermove')
3064
- .pipe(takeUntil(this.destroy$))
3065
- .subscribe((event) => {
3066
- BOARD_TO_MOVING_POINT.set(this.board, [event.x, event.y]);
3067
- this.board.globalPointerMove(event);
3068
- });
3069
- fromEvent(this.host, 'mouseup')
3070
- .pipe(takeUntil(this.destroy$))
3071
- .subscribe((event) => {
3072
- this.board.mouseup(event);
3073
- });
3074
- fromEvent(this.host, 'pointerup')
3075
- .pipe(takeUntil(this.destroy$))
3076
- .subscribe((event) => {
3077
- this.board.pointerUp(event);
3078
- });
3079
- fromEvent(document, 'mouseup')
3080
- .pipe(takeUntil(this.destroy$))
3081
- .subscribe((event) => {
3082
- this.board.globalMouseup(event);
3083
- });
3084
- fromEvent(document, 'pointerup')
3085
- .pipe(takeUntil(this.destroy$))
3086
- .subscribe((event) => {
3087
- this.board.globalPointerUp(event);
3088
- });
3089
- fromEvent(this.host, 'dblclick')
3090
- .pipe(takeUntil(this.destroy$), filter(() => this.isFocused && !PlaitBoard.hasBeenTextEditing(this.board)))
3091
- .subscribe((event) => {
3092
- this.board.dblclick(event);
3093
- });
3094
- fromEvent(document, 'keydown')
3095
- .pipe(takeUntil(this.destroy$), tap(event => {
3096
- this.board.globalKeydown(event);
3097
- }), filter(event => this.isFocused && !PlaitBoard.hasBeenTextEditing(this.board) && !hasInputOrTextareaTarget(event.target)))
3098
- .subscribe((event) => {
3099
- const selectedElements = getSelectedElements(this.board);
3100
- if (selectedElements.length > 0 && (hotkeys.isDeleteBackward(event) || hotkeys.isDeleteForward(event))) {
3101
- this.board.deleteFragment(null);
3102
- }
3103
- this.board.keydown(event);
3104
- });
3105
- fromEvent(document, 'keyup')
3106
- .pipe(takeUntil(this.destroy$), filter(() => this.isFocused && !PlaitBoard.hasBeenTextEditing(this.board)))
3107
- .subscribe((event) => {
3108
- var _a;
3109
- (_a = this.board) === null || _a === void 0 ? void 0 : _a.keyup(event);
3110
- });
3111
- fromEvent(document, 'copy')
3112
- .pipe(takeUntil(this.destroy$), filter(() => this.isFocused && !PlaitBoard.hasBeenTextEditing(this.board)))
3113
- .subscribe((event) => {
3114
- const selectedElements = getSelectedElements(this.board);
3115
- event.preventDefault();
3116
- const rectangle = getRectangleByElements(this.board, selectedElements, false);
3117
- this.board.setFragment(event.clipboardData, rectangle);
3118
- });
3119
- fromEvent(document, 'paste')
3120
- .pipe(takeUntil(this.destroy$), filter(() => this.isFocused && !PlaitBoard.isReadonly(this.board) && !PlaitBoard.hasBeenTextEditing(this.board)))
3121
- .subscribe((clipboardEvent) => {
3122
- const mousePoint = PlaitBoard.getMovingPointInBoard(this.board);
3123
- if (mousePoint) {
3124
- const targetPoint = transformPoint(this.board, toPoint(mousePoint[0], mousePoint[1], this.host));
3125
- this.board.insertFragment(clipboardEvent.clipboardData, targetPoint);
3126
- }
3127
- });
3128
- fromEvent(document, 'cut')
3129
- .pipe(takeUntil(this.destroy$), filter(() => this.isFocused && !PlaitBoard.isReadonly(this.board) && !PlaitBoard.hasBeenTextEditing(this.board)))
3130
- .subscribe((event) => {
3131
- const selectedElements = getSelectedElements(this.board);
3132
- event.preventDefault();
3133
- const rectangle = getRectangleByElements(this.board, selectedElements, false);
3134
- this.board.setFragment(event.clipboardData, rectangle);
3135
- this.board.deleteFragment(event.clipboardData);
3136
- });
3137
- }
3138
- viewportScrollListener() {
3139
- this.ngZone.runOutsideAngular(() => {
3140
- fromEvent(this.viewportContainer.nativeElement, 'scroll')
3141
- .pipe(takeUntil(this.destroy$), filter(() => {
3142
- if (isFromViewportChange(this.board)) {
3143
- setIsFromViewportChange(this.board, false);
3144
- return false;
3145
- }
3146
- return true;
3147
- }))
3148
- .subscribe((event) => {
3149
- const { scrollLeft, scrollTop } = event.target;
3150
- const zoom = this.board.viewport.zoom;
3151
- const viewBox = getViewBox(this.board, zoom);
3152
- const origination = [scrollLeft / zoom + viewBox[0], scrollTop / zoom + viewBox[1]];
3153
- if (Point.isEquals(origination, this.board.viewport.origination)) {
3154
- return;
3155
- }
3156
- BoardTransforms.updateViewport(this.board, origination);
3157
- setIsFromScrolling(this.board, true);
3158
- });
3159
- });
3160
- this.ngZone.runOutsideAngular(() => {
3161
- fromEvent(this.viewportContainer.nativeElement, 'touchmove', { passive: false }).subscribe((event) => {
3162
- if (isPreventTouchMove(this.board)) {
3163
- event.preventDefault();
3164
- }
3165
- });
3166
- });
3167
- }
3168
- elementResizeListener() {
3169
- this.resizeObserver = new ResizeObserver(() => {
3170
- initializeViewportContainer(this.board);
3171
- initializeViewBox(this.board);
3172
- updateViewportOffset(this.board);
3173
- });
3174
- this.resizeObserver.observe(this.nativeElement);
3175
- }
3176
- initializeIslands() {
3177
- var _a;
3178
- (_a = this.islands) === null || _a === void 0 ? void 0 : _a.forEach(island => {
3179
- island.initialize(this.board);
3180
- });
3181
- }
3182
- updateIslands() {
3183
- var _a;
3184
- (_a = this.islands) === null || _a === void 0 ? void 0 : _a.forEach(island => {
3185
- if (hasOnBoardChange(island)) {
3186
- island.onBoardChange();
3187
- }
3188
- island.markForCheck();
3189
- });
3190
- }
3191
- ngOnDestroy() {
3192
- var _a;
3193
- this.destroy$.next();
3194
- this.destroy$.complete();
3195
- this.resizeObserver && ((_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect());
3196
- BOARD_TO_ROUGH_SVG.delete(this.board);
3197
- BOARD_TO_COMPONENT.delete(this.board);
3198
- BOARD_TO_ROUGH_SVG.delete(this.board);
3199
- BOARD_TO_HOST.delete(this.board);
3200
- BOARD_TO_ELEMENT_HOST.delete(this.board);
3201
- BOARD_TO_ON_CHANGE.delete(this.board);
3202
- }
3203
- markForCheck() {
3204
- this.cdr.markForCheck();
3205
- this.ngZone.run(() => {
3206
- this.updateIslands();
3207
- });
3208
- }
3209
- }
3210
- PlaitBoardComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitBoardComponent, deps: [{ token: i0.ChangeDetectorRef }, { token: i0.ViewContainerRef }, { token: i0.ElementRef }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Component });
3211
- PlaitBoardComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.5", type: PlaitBoardComponent, selector: "plait-board", inputs: { plaitValue: "plaitValue", plaitViewport: "plaitViewport", plaitPlugins: "plaitPlugins", plaitOptions: "plaitOptions", plaitTheme: "plaitTheme" }, outputs: { plaitChange: "plaitChange", plaitBoardInitialized: "plaitBoardInitialized" }, host: { properties: { "class": "this.hostClass", "class.readonly": "this.readonly", "class.focused": "this.isFocused", "class.disabled-scroll": "this.disabledScrollOnNonFocus" } }, providers: [PlaitContextService], queries: [{ propertyName: "islands", predicate: PlaitIslandBaseComponent, descendants: true }], viewQueries: [{ propertyName: "svg", first: true, predicate: ["svg"], descendants: true, static: true }, { propertyName: "viewportContainer", first: true, predicate: ["viewportContainer"], descendants: true, read: ElementRef, static: true }], usesOnChanges: true, ngImport: i0, template: `
3212
- <div class="viewport-container" #viewportContainer>
3213
- <svg #svg width="100%" height="100%" style="position: relative;" class="board-host-svg">
3214
- <g class="element-host"></g>
3215
- <g class="element-upper-host"></g>
3216
- <g class="element-active-host"></g>
3217
- </svg>
3218
- <plait-children [board]="board" [effect]="effect"></plait-children>
3219
- </div>
3220
- <ng-content></ng-content>
3221
- `, isInline: true, dependencies: [{ kind: "component", type: PlaitChildrenElement, selector: "plait-children", inputs: ["board", "parent", "effect", "parentG"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
3222
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitBoardComponent, decorators: [{
3223
- type: Component,
3224
- args: [{
3225
- selector: 'plait-board',
3226
- template: `
3227
- <div class="viewport-container" #viewportContainer>
3228
- <svg #svg width="100%" height="100%" style="position: relative;" class="board-host-svg">
3229
- <g class="element-host"></g>
3230
- <g class="element-upper-host"></g>
3231
- <g class="element-active-host"></g>
3232
- </svg>
3233
- <plait-children [board]="board" [effect]="effect"></plait-children>
3234
- </div>
3235
- <ng-content></ng-content>
3236
- `,
3237
- changeDetection: ChangeDetectionStrategy.OnPush,
3238
- providers: [PlaitContextService]
3239
- }]
3240
- }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i0.ViewContainerRef }, { type: i0.ElementRef }, { type: i0.NgZone }]; }, propDecorators: { plaitValue: [{
3241
- type: Input
3242
- }], plaitViewport: [{
3243
- type: Input
3244
- }], plaitPlugins: [{
3245
- type: Input
3246
- }], plaitOptions: [{
3247
- type: Input
3248
- }], plaitTheme: [{
3249
- type: Input
3250
- }], plaitChange: [{
3251
- type: Output
3252
- }], plaitBoardInitialized: [{
3253
- type: Output
3254
- }], hostClass: [{
3255
- type: HostBinding,
3256
- args: ['class']
3257
- }], readonly: [{
3258
- type: HostBinding,
3259
- args: ['class.readonly']
3260
- }], isFocused: [{
3261
- type: HostBinding,
3262
- args: ['class.focused']
3263
- }], disabledScrollOnNonFocus: [{
3264
- type: HostBinding,
3265
- args: ['class.disabled-scroll']
3266
- }], svg: [{
3267
- type: ViewChild,
3268
- args: ['svg', { static: true }]
3269
- }], viewportContainer: [{
3270
- type: ViewChild,
3271
- args: ['viewportContainer', { read: ElementRef, static: true }]
3272
- }], islands: [{
3273
- type: ContentChildren,
3274
- args: [PlaitIslandBaseComponent, { descendants: true }]
3275
- }] } });
3276
-
3277
- const COMPONENTS = [PlaitBoardComponent, PlaitChildrenElement, PlaitElementComponent];
3278
- class PlaitModule {
3279
- }
3280
- PlaitModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
3281
- PlaitModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.5", ngImport: i0, type: PlaitModule, declarations: [PlaitBoardComponent, PlaitChildrenElement, PlaitElementComponent], imports: [CommonModule], exports: [PlaitBoardComponent, PlaitChildrenElement, PlaitElementComponent] });
3282
- PlaitModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitModule, imports: [CommonModule] });
3283
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: PlaitModule, decorators: [{
3284
- type: NgModule,
3285
- args: [{
3286
- declarations: [...COMPONENTS],
3287
- imports: [CommonModule],
3288
- exports: [...COMPONENTS]
3289
- }]
3290
- }] });
3291
-
3292
- /**
3293
- * 1.create board instance
3294
- * 2.build fake node weak map
3295
- */
3296
- const createTestingBoard = (plugins, children, options = { readonly: false, hideScrollbar: true, disabledScrollOnNonFocus: false }) => {
3297
- let board = createBoard(children, options);
3298
- plugins.forEach(plugin => {
3299
- board = plugin(board);
3300
- });
3301
- return board;
3302
- };
3303
-
3304
- const fakeNodeWeakMap = (object) => {
3305
- const children = object.children || [];
3306
- children.forEach((value, index) => {
3307
- NODE_TO_PARENT.set(value, object);
3308
- NODE_TO_INDEX.set(value, index);
3309
- fakeNodeWeakMap(value);
3310
- });
3311
- };
3312
- const clearNodeWeakMap = (object) => {
3313
- const children = object.children || [];
3314
- children.forEach(value => {
3315
- NODE_TO_PARENT.delete(value);
3316
- NODE_TO_INDEX.delete(value);
3317
- clearNodeWeakMap(value);
3318
- });
3319
- };
3320
-
3321
- /**
3322
- * @license
3323
- * Copyright Google LLC All Rights Reserved.
3324
- *
3325
- * Use of this source code is governed by an MIT-style license that can be
3326
- * found in the LICENSE file at https://angular.io/license
3327
- */
3328
- /** Used to generate unique IDs for events. */
3329
- let uniqueIds = 0;
3330
- /**
3331
- * Creates a browser MouseEvent with the specified options.
3332
- * @docs-private
3333
- */
3334
- function createMouseEvent(type, clientX = 0, clientY = 0, offsetX = 1, offsetY = 1, button = 0, modifiers = {}) {
3335
- // Note: We cannot determine the position of the mouse event based on the screen
3336
- // because the dimensions and position of the browser window are not available
3337
- // To provide reasonable `screenX` and `screenY` coordinates, we simply use the
3338
- // client coordinates as if the browser is opened in fullscreen.
3339
- const screenX = clientX;
3340
- const screenY = clientY;
3341
- const event = new MouseEvent(type, {
3342
- bubbles: true,
3343
- cancelable: true,
3344
- composed: true,
3345
- view: window,
3346
- detail: 0,
3347
- relatedTarget: null,
3348
- screenX,
3349
- screenY,
3350
- clientX,
3351
- clientY,
3352
- ctrlKey: modifiers.control,
3353
- altKey: modifiers.alt,
3354
- shiftKey: modifiers.shift,
3355
- metaKey: modifiers.meta,
3356
- button: button,
3357
- buttons: 1
3358
- });
3359
- // The `MouseEvent` constructor doesn't allow us to pass these properties into the constructor.
3360
- // Override them to `1`, because they're used for fake screen reader event detection.
3361
- if (offsetX != null) {
3362
- defineReadonlyEventProperty(event, 'offsetX', offsetX);
3363
- }
3364
- if (offsetY != null) {
3365
- defineReadonlyEventProperty(event, 'offsetY', offsetY);
3366
- }
3367
- return event;
3368
- }
3369
- /**
3370
- * Creates a browser `PointerEvent` with the specified options. Pointer events
3371
- * by default will appear as if they are the primary pointer of their type.
3372
- * https://www.w3.org/TR/pointerevents2/#dom-pointerevent-isprimary.
3373
- *
3374
- * For example, if pointer events for a multi-touch interaction are created, the non-primary
3375
- * pointer touches would need to be represented by non-primary pointer events.
3376
- *
3377
- * @docs-private
3378
- */
3379
- function createPointerEvent(type, clientX = 0, clientY = 0, offsetX, offsetY, options = { isPrimary: true }) {
3380
- const event = new PointerEvent(type, Object.assign({ bubbles: true, cancelable: true, composed: true, view: window, clientX,
3381
- clientY }, options));
3382
- if (offsetX != null) {
3383
- defineReadonlyEventProperty(event, 'offsetX', offsetX);
3384
- }
3385
- if (offsetY != null) {
3386
- defineReadonlyEventProperty(event, 'offsetY', offsetY);
3387
- }
3388
- return event;
3389
- }
3390
- /**
3391
- * Creates a browser TouchEvent with the specified pointer coordinates.
3392
- * @docs-private
3393
- */
3394
- function createTouchEvent(type, pageX = 0, pageY = 0, clientX = 0, clientY = 0) {
3395
- // We cannot use the `TouchEvent` or `Touch` because Firefox and Safari lack support.
3396
- // TODO: Switch to the constructor API when it is available for Firefox and Safari.
3397
- const event = document.createEvent('UIEvent');
3398
- const touchDetails = { pageX, pageY, clientX, clientY, identifier: uniqueIds++ };
3399
- // TS3.6 removes the initUIEvent method and suggests porting to "new UIEvent()".
3400
- event.initUIEvent(type, true, true, window, 0);
3401
- // Most of the browsers don't have a "initTouchEvent" method that can be used to define
3402
- // the touch details.
3403
- defineReadonlyEventProperty(event, 'touches', [touchDetails]);
3404
- defineReadonlyEventProperty(event, 'targetTouches', [touchDetails]);
3405
- defineReadonlyEventProperty(event, 'changedTouches', [touchDetails]);
3406
- return event;
3407
- }
3408
- /**
3409
- * Creates a keyboard event with the specified key and modifiers.
3410
- * @docs-private
3411
- */
3412
- function createKeyboardEvent(type, keyCode = 0, key = '', modifiers = {}) {
3413
- return new KeyboardEvent(type, {
3414
- bubbles: true,
3415
- cancelable: true,
3416
- composed: true,
3417
- view: window,
3418
- keyCode: keyCode,
3419
- key: key,
3420
- shiftKey: modifiers.shift,
3421
- metaKey: modifiers.meta,
3422
- altKey: modifiers.alt,
3423
- ctrlKey: modifiers.control
3424
- });
3425
- }
3426
- /**
3427
- * Creates a fake event object with any desired event type.
3428
- * @docs-private
3429
- */
3430
- function createFakeEvent(type, bubbles = false, cancelable = true, composed = true) {
3431
- return new Event(type, { bubbles, cancelable, composed });
3432
- }
3433
- /**
3434
- * Defines a readonly property on the given event object. Readonly properties on an event object
3435
- * are always set as configurable as that matches default readonly properties for DOM event objects.
3436
- */
3437
- function defineReadonlyEventProperty(event, propertyName, value) {
3438
- Object.defineProperty(event, propertyName, { get: () => value, configurable: true });
3439
- }
3440
- function createModModifierKeys() {
3441
- const modifiers = IS_MAC ? { meta: true } : { control: true };
3442
- return modifiers;
3443
- }
3444
-
3445
- /*
3446
- * Public API Surface of plait
3447
- */
3448
-
3449
- /**
3450
- * Generated bundle index. Do not edit.
3451
- */
3452
-
3453
- export { A, ALT, APOSTROPHE, ATTACHED_ELEMENT_CLASS_NAME, AT_SIGN, B, BACKSLASH, BACKSPACE, BOARD_TO_COMPONENT, BOARD_TO_ELEMENT_HOST, BOARD_TO_HOST, BOARD_TO_IS_SELECTION_MOVING, BOARD_TO_MOVING_ELEMENT, BOARD_TO_MOVING_POINT, BOARD_TO_MOVING_POINT_IN_BOARD, BOARD_TO_ON_CHANGE, BOARD_TO_ROUGH_SVG, BOARD_TO_SELECTED_ELEMENT, BOARD_TO_TEMPORARY_ELEMENTS, BOARD_TO_VIEWPORT_ORIGINATION, BoardTransforms, C, CAPS_LOCK, CLIP_BOARD_FORMAT_KEY, CLOSE_SQUARE_BRACKET, COMMA, CONTEXT_MENU, CONTROL, ColorfulThemeColor, D, DASH, DELETE, DOWN_ARROW, DarkThemeColor, DefaultThemeColor, E, EIGHT, ELEMENT_TO_COMPONENT, END, ENTER, EQUALS, ESCAPE, F, F1, F10, F11, F12, F2, F3, F4, F5, F6, F7, F8, F9, FF_EQUALS, FF_MINUS, FF_MUTE, FF_SEMICOLON, FF_VOLUME_DOWN, FF_VOLUME_UP, FIRST_MEDIA, FIVE, FLUSHING, FOUR, G, H, HOME, HOST_CLASS_NAME, I, INSERT, IS_APPLE, IS_BOARD_CACHE, IS_CHROME, IS_CHROME_LEGACY, IS_EDGE_LEGACY, IS_FIREFOX, IS_IOS, IS_MAC, IS_PREVENT_TOUCH_MOVE, IS_SAFARI, IS_TEXT_EDITABLE, J, K, L, LAST_MEDIA, LEFT_ARROW, M, MAC_ENTER, MAC_META, MAC_WK_CMD_LEFT, MAC_WK_CMD_RIGHT, MAX_RADIUS, MERGING, META, MUTE, N, NINE, NODE_TO_INDEX, NODE_TO_PARENT, NS, NUMPAD_DIVIDE, NUMPAD_EIGHT, NUMPAD_FIVE, NUMPAD_FOUR, NUMPAD_MINUS, NUMPAD_MULTIPLY, NUMPAD_NINE, NUMPAD_ONE, NUMPAD_PERIOD, NUMPAD_PLUS, NUMPAD_SEVEN, NUMPAD_SIX, NUMPAD_THREE, NUMPAD_TWO, NUMPAD_ZERO, NUM_CENTER, NUM_LOCK, O, ONE, OPEN_SQUARE_BRACKET, P, PAGE_DOWN, PAGE_UP, PATH_REFS, PAUSE, PERIOD, PLUS_SIGN, POINTER_BUTTON, PRESS_AND_MOVE_BUFFER, PRINT_SCREEN, Path, PlaitBoard, PlaitBoardComponent, PlaitChildrenElement, PlaitContextService, PlaitElement, PlaitElementComponent, PlaitHistoryBoard, PlaitIslandBaseComponent, PlaitIslandPopoverBaseComponent, PlaitModule, PlaitNode, PlaitOperation, PlaitPluginElementComponent, PlaitPluginKey, PlaitPointerType, Point, Q, QUESTION_MARK, R, RIGHT_ARROW, RectangleClient, ResizeCursorClass, RetroThemeColor, S, SAVING, SCROLL_BAR_WIDTH, SCROLL_LOCK, SELECTION_BORDER_COLOR, SELECTION_FILL_COLOR, SEMICOLON, SEVEN, SHIFT, SINGLE_QUOTE, SIX, SLASH, SPACE, Selection, SoftThemeColor, StarryThemeColor, T, TAB, THREE, TILDE, TWO, ThemeColorMode, ThemeColors, Transforms, U, UP_ARROW, V, VOLUME_DOWN, VOLUME_UP, Viewport, W, X, Y, Z, ZERO, addMovingElements, addSelectedElement, arrowPoints, cacheMovingElements, cacheSelectedElements, clampZoomLevel, clearNodeWeakMap, clearSelectedElement, clearSelectionMoving, clearViewportOrigination, createFakeEvent, createForeignObject, createG, createKeyboardEvent, createModModifierKeys, createMouseEvent, createPath, createPointerEvent, createSVG, createSelectionOuterG, createTestingBoard, createText, createTouchEvent, debounce, deleteTemporaryElements, depthFirstRecursion, distanceBetweenPointAndPoint, distanceBetweenPointAndRectangle, distanceBetweenPointAndSegment, downloadImage, drawArrow, drawBezierPath, drawCircle, drawLine, drawLinearPath, drawRoundRectangle, fakeNodeWeakMap, getBoardRectangle, getClipboardByKey, getClipboardDataByMedia, getDataFromClipboard, getElementHostBBox, getHitElementOfRoot, getHitElements, getIsRecursionFunc, getMovingElements, getRealScrollBarWidth, getRectangleByElements, getSelectedElements, getTemporaryElements, getTextFromClipboard, getViewBox, getViewBoxCenterPoint, getViewportContainerRect, getViewportOrigination, hasBeforeContextChange, hasInputOrTextareaTarget, hasOnBoardChange, hasOnContextChanged, hotkeys, idCreator, initializeViewBox, initializeViewportContainer, initializeViewportOffset, inverse, isDOMElement, isDOMNode, isFromScrolling, isFromViewportChange, isHitElements, isInPlaitBoard, isMainPointer, isNullOrUndefined, isPreventTouchMove, isSecondaryPointer, isSelectedElement, isSelectionMoving, isSetViewportOperation, normalizePoint, preventTouchMove, removeMovingElements, removeSelectedElement, rotate, scrollToRectangle, setClipboardData, setClipboardDataByMedia, setClipboardDataByText, setIsFromScrolling, setIsFromViewportChange, setSVGViewBox, setSelectionMoving, shouldClear, shouldMerge, shouldSave, throttleRAF, toImage, toPoint, transformPoint, transformPoints, updateForeignObject, updateViewportContainerScroll, updateViewportOffset, updateViewportOrigination, withMoving, withOptions, withSelection };
3454
- //# sourceMappingURL=plait-core.mjs.map