js-draw 1.0.1 → 1.0.2

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bundle.js +1 -1
  3. package/dist/cjs/version.js +1 -1
  4. package/dist/mjs/version.mjs +1 -1
  5. package/docs/img/readme-images/js-draw.jpg +0 -0
  6. package/docs/img/readme-images/unsupported-elements--in-editor.png +0 -0
  7. package/package.json +5 -4
  8. package/dist-test/test_imports/package-lock.json +0 -13
  9. package/dist-test/test_imports/package.json +0 -12
  10. package/dist-test/test_imports/test-imports.js +0 -11
  11. package/dist-test/test_imports/test-require.cjs +0 -14
  12. package/src/Editor.loadFrom.test.ts +0 -24
  13. package/src/Editor.test.ts +0 -107
  14. package/src/Editor.toSVG.test.ts +0 -294
  15. package/src/Editor.ts +0 -1443
  16. package/src/EditorImage.test.ts +0 -117
  17. package/src/EditorImage.ts +0 -609
  18. package/src/EventDispatcher.test.ts +0 -123
  19. package/src/EventDispatcher.ts +0 -72
  20. package/src/Pointer.ts +0 -183
  21. package/src/SVGLoader.test.ts +0 -114
  22. package/src/SVGLoader.ts +0 -672
  23. package/src/UndoRedoHistory.test.ts +0 -34
  24. package/src/UndoRedoHistory.ts +0 -102
  25. package/src/Viewport.ts +0 -322
  26. package/src/bundle/bundled.ts +0 -7
  27. package/src/commands/Command.ts +0 -45
  28. package/src/commands/Duplicate.ts +0 -75
  29. package/src/commands/Erase.ts +0 -95
  30. package/src/commands/SerializableCommand.ts +0 -49
  31. package/src/commands/UnresolvedCommand.ts +0 -37
  32. package/src/commands/invertCommand.ts +0 -58
  33. package/src/commands/lib.ts +0 -16
  34. package/src/commands/localization.ts +0 -47
  35. package/src/commands/uniteCommands.test.ts +0 -23
  36. package/src/commands/uniteCommands.ts +0 -140
  37. package/src/components/AbstractComponent.transformBy.test.ts +0 -23
  38. package/src/components/AbstractComponent.ts +0 -383
  39. package/src/components/BackgroundComponent.test.ts +0 -44
  40. package/src/components/BackgroundComponent.ts +0 -348
  41. package/src/components/ImageComponent.ts +0 -176
  42. package/src/components/RestylableComponent.ts +0 -161
  43. package/src/components/SVGGlobalAttributesObject.ts +0 -79
  44. package/src/components/Stroke.test.ts +0 -137
  45. package/src/components/Stroke.ts +0 -294
  46. package/src/components/TextComponent.test.ts +0 -202
  47. package/src/components/TextComponent.ts +0 -429
  48. package/src/components/UnknownSVGObject.test.ts +0 -10
  49. package/src/components/UnknownSVGObject.ts +0 -60
  50. package/src/components/builders/ArrowBuilder.ts +0 -106
  51. package/src/components/builders/CircleBuilder.ts +0 -100
  52. package/src/components/builders/FreehandLineBuilder.test.ts +0 -24
  53. package/src/components/builders/FreehandLineBuilder.ts +0 -210
  54. package/src/components/builders/LineBuilder.ts +0 -77
  55. package/src/components/builders/PressureSensitiveFreehandLineBuilder.ts +0 -453
  56. package/src/components/builders/RectangleBuilder.ts +0 -73
  57. package/src/components/builders/types.ts +0 -15
  58. package/src/components/lib.ts +0 -31
  59. package/src/components/localization.ts +0 -24
  60. package/src/components/util/StrokeSmoother.ts +0 -302
  61. package/src/components/util/describeComponentList.ts +0 -18
  62. package/src/dialogs/makeAboutDialog.ts +0 -82
  63. package/src/inputEvents.ts +0 -143
  64. package/src/lib.ts +0 -91
  65. package/src/localization.ts +0 -34
  66. package/src/localizations/de.ts +0 -146
  67. package/src/localizations/en.ts +0 -8
  68. package/src/localizations/es.ts +0 -74
  69. package/src/localizations/getLocalizationTable.test.ts +0 -27
  70. package/src/localizations/getLocalizationTable.ts +0 -74
  71. package/src/rendering/Display.ts +0 -247
  72. package/src/rendering/RenderablePathSpec.ts +0 -88
  73. package/src/rendering/RenderingStyle.test.ts +0 -68
  74. package/src/rendering/RenderingStyle.ts +0 -55
  75. package/src/rendering/TextRenderingStyle.ts +0 -55
  76. package/src/rendering/caching/CacheRecord.test.ts +0 -48
  77. package/src/rendering/caching/CacheRecord.ts +0 -76
  78. package/src/rendering/caching/CacheRecordManager.ts +0 -71
  79. package/src/rendering/caching/RenderingCache.test.ts +0 -43
  80. package/src/rendering/caching/RenderingCache.ts +0 -66
  81. package/src/rendering/caching/RenderingCacheNode.ts +0 -404
  82. package/src/rendering/caching/testUtils.ts +0 -35
  83. package/src/rendering/caching/types.ts +0 -34
  84. package/src/rendering/lib.ts +0 -8
  85. package/src/rendering/localization.ts +0 -20
  86. package/src/rendering/renderers/AbstractRenderer.ts +0 -232
  87. package/src/rendering/renderers/CanvasRenderer.ts +0 -312
  88. package/src/rendering/renderers/DummyRenderer.test.ts +0 -41
  89. package/src/rendering/renderers/DummyRenderer.ts +0 -142
  90. package/src/rendering/renderers/SVGRenderer.ts +0 -434
  91. package/src/rendering/renderers/TextOnlyRenderer.test.ts +0 -34
  92. package/src/rendering/renderers/TextOnlyRenderer.ts +0 -68
  93. package/src/shortcuts/KeyBinding.test.ts +0 -61
  94. package/src/shortcuts/KeyBinding.ts +0 -257
  95. package/src/shortcuts/KeyboardShortcutManager.test.ts +0 -95
  96. package/src/shortcuts/KeyboardShortcutManager.ts +0 -163
  97. package/src/shortcuts/lib.ts +0 -3
  98. package/src/testing/createEditor.ts +0 -11
  99. package/src/testing/getUniquePointerId.ts +0 -18
  100. package/src/testing/lib.ts +0 -3
  101. package/src/testing/sendPenEvent.ts +0 -36
  102. package/src/testing/sendTouchEvent.ts +0 -71
  103. package/src/toolbar/AbstractToolbar.ts +0 -542
  104. package/src/toolbar/DropdownToolbar.ts +0 -220
  105. package/src/toolbar/EdgeToolbar.test.ts +0 -54
  106. package/src/toolbar/EdgeToolbar.ts +0 -543
  107. package/src/toolbar/IconProvider.ts +0 -861
  108. package/src/toolbar/constants.ts +0 -1
  109. package/src/toolbar/lib.ts +0 -6
  110. package/src/toolbar/localization.ts +0 -136
  111. package/src/toolbar/types.ts +0 -13
  112. package/src/toolbar/widgets/ActionButtonWidget.ts +0 -39
  113. package/src/toolbar/widgets/BaseToolWidget.ts +0 -81
  114. package/src/toolbar/widgets/BaseWidget.ts +0 -495
  115. package/src/toolbar/widgets/DocumentPropertiesWidget.ts +0 -250
  116. package/src/toolbar/widgets/EraserToolWidget.ts +0 -84
  117. package/src/toolbar/widgets/HandToolWidget.ts +0 -239
  118. package/src/toolbar/widgets/InsertImageWidget.ts +0 -248
  119. package/src/toolbar/widgets/OverflowWidget.ts +0 -92
  120. package/src/toolbar/widgets/PenToolWidget.ts +0 -369
  121. package/src/toolbar/widgets/SelectionToolWidget.ts +0 -195
  122. package/src/toolbar/widgets/TextToolWidget.ts +0 -149
  123. package/src/toolbar/widgets/components/makeColorInput.ts +0 -184
  124. package/src/toolbar/widgets/components/makeFileInput.ts +0 -128
  125. package/src/toolbar/widgets/components/makeGridSelector.ts +0 -179
  126. package/src/toolbar/widgets/components/makeSeparator.ts +0 -17
  127. package/src/toolbar/widgets/components/makeThicknessSlider.ts +0 -62
  128. package/src/toolbar/widgets/keybindings.ts +0 -19
  129. package/src/toolbar/widgets/layout/DropdownLayoutManager.ts +0 -262
  130. package/src/toolbar/widgets/layout/EdgeToolbarLayoutManager.ts +0 -71
  131. package/src/toolbar/widgets/layout/types.ts +0 -74
  132. package/src/toolbar/widgets/lib.ts +0 -13
  133. package/src/tools/BaseTool.ts +0 -169
  134. package/src/tools/Eraser.test.ts +0 -103
  135. package/src/tools/Eraser.ts +0 -173
  136. package/src/tools/FindTool.test.ts +0 -67
  137. package/src/tools/FindTool.ts +0 -153
  138. package/src/tools/InputFilter/FunctionMapper.ts +0 -17
  139. package/src/tools/InputFilter/InputMapper.ts +0 -41
  140. package/src/tools/InputFilter/InputPipeline.test.ts +0 -41
  141. package/src/tools/InputFilter/InputPipeline.ts +0 -34
  142. package/src/tools/InputFilter/InputStabilizer.ts +0 -254
  143. package/src/tools/InputFilter/StrokeKeyboardControl.ts +0 -104
  144. package/src/tools/PanZoom.test.ts +0 -339
  145. package/src/tools/PanZoom.ts +0 -525
  146. package/src/tools/PasteHandler.ts +0 -94
  147. package/src/tools/Pen.test.ts +0 -260
  148. package/src/tools/Pen.ts +0 -284
  149. package/src/tools/PipetteTool.ts +0 -84
  150. package/src/tools/SelectionTool/SelectAllShortcutHandler.ts +0 -29
  151. package/src/tools/SelectionTool/Selection.ts +0 -647
  152. package/src/tools/SelectionTool/SelectionHandle.ts +0 -142
  153. package/src/tools/SelectionTool/SelectionTool.test.ts +0 -370
  154. package/src/tools/SelectionTool/SelectionTool.ts +0 -510
  155. package/src/tools/SelectionTool/TransformMode.ts +0 -112
  156. package/src/tools/SelectionTool/types.ts +0 -11
  157. package/src/tools/SoundUITool.ts +0 -221
  158. package/src/tools/TextTool.ts +0 -339
  159. package/src/tools/ToolController.ts +0 -224
  160. package/src/tools/ToolEnabledGroup.ts +0 -14
  161. package/src/tools/ToolSwitcherShortcut.ts +0 -39
  162. package/src/tools/ToolbarShortcutHandler.ts +0 -39
  163. package/src/tools/UndoRedoShortcut.test.ts +0 -62
  164. package/src/tools/UndoRedoShortcut.ts +0 -24
  165. package/src/tools/keybindings.ts +0 -85
  166. package/src/tools/lib.ts +0 -22
  167. package/src/tools/localization.ts +0 -76
  168. package/src/types.ts +0 -151
  169. package/src/util/ReactiveValue.test.ts +0 -168
  170. package/src/util/ReactiveValue.ts +0 -241
  171. package/src/util/assertions.ts +0 -55
  172. package/src/util/fileToBase64.ts +0 -18
  173. package/src/util/guessKeyCodeFromKey.ts +0 -36
  174. package/src/util/listPrefixMatch.ts +0 -19
  175. package/src/util/stopPropagationOfScrollingWheelEvents.ts +0 -20
  176. package/src/util/untilNextAnimationFrame.ts +0 -9
  177. package/src/util/waitForAll.ts +0 -18
  178. package/src/util/waitForTimeout.ts +0 -9
  179. package/src/version.test.ts +0 -12
  180. package/src/version.ts +0 -3
  181. package/tools/allLocales.js +0 -4
  182. package/tools/copyREADME.ts +0 -62
@@ -1,609 +0,0 @@
1
- import Editor from './Editor';
2
- import AbstractRenderer from './rendering/renderers/AbstractRenderer';
3
- import Viewport from './Viewport';
4
- import AbstractComponent from './components/AbstractComponent';
5
- import { Rect2, Vec2, Mat33, Mat33Array } from '@js-draw/math';
6
- import { EditorLocalization } from './localization';
7
- import RenderingCache from './rendering/caching/RenderingCache';
8
- import SerializableCommand from './commands/SerializableCommand';
9
- import EventDispatcher from './EventDispatcher';
10
- import { assertIsNumber, assertIsNumberArray } from './util/assertions';
11
-
12
- // @internal Sort by z-index, low to high
13
- export const sortLeavesByZIndex = (leaves: Array<ImageNode>) => {
14
- leaves.sort((a, b) => a.getContent()!.getZIndex() - b.getContent()!.getZIndex());
15
- };
16
-
17
- export enum EditorImageEventType {
18
- ExportViewportChanged
19
- }
20
-
21
- export type EditorImageNotifier = EventDispatcher<EditorImageEventType, { image: EditorImage }>;
22
-
23
- // Handles lookup/storage of elements in the image
24
- export default class EditorImage {
25
- private root: ImageNode;
26
- private background: ImageNode;
27
- private componentsById: Record<string, AbstractComponent>;
28
- private componentCount: number = 0;
29
-
30
- /** Viewport for the exported/imported image. */
31
- private importExportViewport: Viewport;
32
-
33
- // @internal
34
- public readonly notifier: EditorImageNotifier;
35
-
36
- // @internal
37
- public constructor() {
38
- this.root = new ImageNode();
39
- this.background = new ImageNode();
40
- this.componentsById = {};
41
-
42
- this.notifier = new EventDispatcher();
43
- this.importExportViewport = new Viewport(() => {
44
- this.notifier.dispatch(EditorImageEventType.ExportViewportChanged, {
45
- image: this,
46
- });
47
- });
48
-
49
- // Default to a 500x500 image
50
- this.importExportViewport.updateScreenSize(Vec2.of(500, 500));
51
- }
52
-
53
- // Returns all components that make up the background of this image. These
54
- // components are rendered below all other components.
55
- public getBackgroundComponents(): AbstractComponent[] {
56
- const result = [];
57
-
58
- const leaves = this.background.getLeaves();
59
- sortLeavesByZIndex(leaves);
60
-
61
- for (const leaf of leaves) {
62
- const content = leaf.getContent();
63
-
64
- if (content) {
65
- result.push(content);
66
- }
67
- }
68
- return result;
69
- }
70
-
71
- // Returns the parent of the given element, if it exists.
72
- public findParent(elem: AbstractComponent): ImageNode|null {
73
- return this.background.getChildWithContent(elem) ?? this.root.getChildWithContent(elem);
74
- }
75
-
76
- // Forces a re-render of `elem` when the image is next re-rendered as a whole.
77
- // Does nothing if `elem` is not in this.
78
- public queueRerenderOf(elem: AbstractComponent) {
79
- // TODO: Make more efficient (e.g. increase IDs of all parents,
80
- // make cache take into account last modified time instead of IDs, etc.)
81
- const parent = this.findParent(elem);
82
-
83
- if (parent) {
84
- parent.remove();
85
- this.addElementDirectly(elem);
86
- }
87
- }
88
-
89
- /** @internal */
90
- public renderWithCache(screenRenderer: AbstractRenderer, cache: RenderingCache, viewport: Viewport) {
91
- this.background.render(screenRenderer, viewport.visibleRect);
92
- cache.render(screenRenderer, this.root, viewport);
93
- }
94
-
95
- /**
96
- * Renders all nodes visible from `viewport` (or all nodes if `viewport = null`).
97
- *
98
- * `viewport` is used to improve rendering performance. If given, it must match
99
- * the viewport used by the `renderer` (if any).
100
- */
101
- public render(renderer: AbstractRenderer, viewport: Viewport|null) {
102
- this.background.render(renderer, viewport?.visibleRect);
103
- this.root.render(renderer, viewport?.visibleRect);
104
- }
105
-
106
- /** Renders all nodes, even ones not within the viewport. @internal */
107
- public renderAll(renderer: AbstractRenderer) {
108
- this.render(renderer, null);
109
- }
110
-
111
- /** @returns all elements in the image, sorted by z-index. This can be slow for large images. */
112
- public getAllElements() {
113
- const leaves = this.root.getLeaves();
114
- sortLeavesByZIndex(leaves);
115
-
116
- return leaves.map(leaf => leaf.getContent()!);
117
- }
118
-
119
- /** Returns the number of elements added to this image. @internal */
120
- public estimateNumElements() {
121
- return this.componentCount;
122
- }
123
-
124
- /** @returns a list of `AbstractComponent`s intersecting `region`, sorted by z-index. */
125
- public getElementsIntersectingRegion(region: Rect2): AbstractComponent[] {
126
- const leaves = this.root.getLeavesIntersectingRegion(region);
127
- sortLeavesByZIndex(leaves);
128
-
129
- return leaves.map(leaf => leaf.getContent()!);
130
- }
131
-
132
- /** Called whenever an element is completely removed. @internal */
133
- public onDestroyElement(elem: AbstractComponent) {
134
- this.componentCount --;
135
- delete this.componentsById[elem.getId()];
136
- }
137
-
138
- /**
139
- * @returns the AbstractComponent with `id`, if it exists.
140
- *
141
- * @see {@link AbstractComponent.getId}
142
- */
143
- public lookupElement(id: string): AbstractComponent|null {
144
- return this.componentsById[id] ?? null;
145
- }
146
-
147
- private addElementDirectly(elem: AbstractComponent): ImageNode {
148
- elem.onAddToImage(this);
149
-
150
- this.componentCount ++;
151
- this.componentsById[elem.getId()] = elem;
152
-
153
- // If a background component, add to the background. Else,
154
- // add to the normal component tree.
155
- const parentTree = elem.isBackground() ? this.background : this.root;
156
- return parentTree.addLeaf(elem);
157
- }
158
-
159
- private removeElementDirectly(element: AbstractComponent) {
160
- const container = this.findParent(element);
161
- container?.remove();
162
-
163
- if (container) {
164
- this.onDestroyElement(element);
165
- return true;
166
- }
167
-
168
- return false;
169
- }
170
-
171
- /**
172
- * Returns a command that adds the given element to the `EditorImage`.
173
- * If `applyByFlattening` is true, the content of the wet ink renderer is
174
- * rendered onto the main rendering canvas instead of doing a full re-render.
175
- *
176
- * @see {@link Display.flatten}
177
- */
178
- public static addElement(elem: AbstractComponent, applyByFlattening: boolean = false): SerializableCommand {
179
- return new EditorImage.AddElementCommand(elem, applyByFlattening);
180
- }
181
-
182
- /** @see EditorImage.addElement */
183
- public addElement(elem: AbstractComponent, applyByFlattening?: boolean) {
184
- return EditorImage.addElement(elem, applyByFlattening);
185
- }
186
-
187
- // A Command that can access private [EditorImage] functionality
188
- private static AddElementCommand = class extends SerializableCommand {
189
- private serializedElem: any|null = null;
190
-
191
- // If [applyByFlattening], then the rendered content of this element
192
- // is present on the display's wet ink canvas. As such, no re-render is necessary
193
- // the first time this command is applied (the surfaces are joined instead).
194
- public constructor(
195
- private element: AbstractComponent,
196
- private applyByFlattening: boolean = false
197
- ) {
198
- super('add-element');
199
-
200
- // FIXME: The serialized version of this command may be inaccurate if this is
201
- // serialized when this command is not on the top of the undo stack.
202
- //
203
- // Caching the element's serialized data leads to additional memory usage *and*
204
- // sometimes incorrect behavior in collaborative editing.
205
- this.serializedElem = null;
206
-
207
- if (isNaN(element.getBBox().area)) {
208
- throw new Error('Elements in the image cannot have NaN bounding boxes');
209
- }
210
- }
211
-
212
- public apply(editor: Editor) {
213
- editor.image.addElementDirectly(this.element);
214
-
215
- if (!this.applyByFlattening) {
216
- editor.queueRerender();
217
- } else {
218
- this.applyByFlattening = false;
219
- editor.display.flatten();
220
- }
221
- }
222
-
223
- public unapply(editor: Editor) {
224
- editor.image.removeElementDirectly(this.element);
225
- editor.queueRerender();
226
- }
227
-
228
- public description(_editor: Editor, localization: EditorLocalization) {
229
- return localization.addElementAction(this.element.description(localization));
230
- }
231
-
232
- protected serializeToJSON() {
233
- return {
234
- elemData: this.serializedElem ?? this.element.serialize(),
235
- };
236
- }
237
-
238
- static {
239
- SerializableCommand.register('add-element', (json: any, editor: Editor) => {
240
- const id = json.elemData.id;
241
- const foundElem = editor.image.lookupElement(id);
242
- const elem = foundElem ?? AbstractComponent.deserialize(json.elemData);
243
- const result = new EditorImage.AddElementCommand(elem);
244
- result.serializedElem = json.elemData;
245
- return result;
246
- });
247
- }
248
- };
249
-
250
-
251
-
252
- /**
253
- * @returns a `Viewport` for rendering the image when importing/exporting.
254
- */
255
- public getImportExportViewport() {
256
- return this.importExportViewport;
257
- }
258
-
259
- public setImportExportRect(imageRect: Rect2): SerializableCommand {
260
- const importExportViewport = this.getImportExportViewport();
261
- const origSize = importExportViewport.visibleRect.size;
262
- const origTransform = importExportViewport.canvasToScreenTransform;
263
-
264
- return new EditorImage.SetImportExportRectCommand(origSize, origTransform, imageRect);
265
- }
266
-
267
- // Handles resizing the background import/export region of the image.
268
- private static SetImportExportRectCommand = class extends SerializableCommand {
269
- private static commandId = 'set-import-export-rect';
270
-
271
- public constructor(
272
- private originalSize: Vec2,
273
- private originalTransform: Mat33,
274
- private finalRect: Rect2,
275
- ) {
276
- super(EditorImage.SetImportExportRectCommand.commandId);
277
- }
278
-
279
- public apply(editor: Editor) {
280
- const viewport = editor.image.getImportExportViewport();
281
- viewport.updateScreenSize(this.finalRect.size);
282
- viewport.resetTransform(Mat33.translation(this.finalRect.topLeft.times(-1)));
283
- editor.queueRerender();
284
- }
285
-
286
- public unapply(editor: Editor) {
287
- const viewport = editor.image.getImportExportViewport();
288
- viewport.updateScreenSize(this.originalSize);
289
- viewport.resetTransform(this.originalTransform);
290
- editor.queueRerender();
291
- }
292
-
293
- public description(_editor: Editor, localization: EditorLocalization) {
294
- return localization.resizeOutputCommand(this.finalRect);
295
- }
296
-
297
- protected serializeToJSON() {
298
- return {
299
- originalSize: this.originalSize.xy,
300
- originalTransform: this.originalTransform.toArray(),
301
- newRegion: {
302
- x: this.finalRect.x,
303
- y: this.finalRect.y,
304
- w: this.finalRect.w,
305
- h: this.finalRect.h,
306
- },
307
- };
308
- }
309
-
310
- static {
311
- const commandId = this.commandId;
312
- SerializableCommand.register(commandId, (json: any, _editor: Editor) => {
313
- assertIsNumber(json.originalSize.x);
314
- assertIsNumber(json.originalSize.y);
315
- assertIsNumberArray(json.originalTransform);
316
- assertIsNumberArray([
317
- json.newRegion.x,
318
- json.newRegion.y,
319
- json.newRegion.w,
320
- json.newRegion.h,
321
- ]);
322
-
323
- const originalSize = Vec2.ofXY(json.originalSize);
324
- const originalTransform = new Mat33(...(json.originalTransform as Mat33Array));
325
- const finalRect = new Rect2(
326
- json.newRegion.x, json.newRegion.y, json.newRegion.w, json.newRegion.h
327
- );
328
- return new EditorImage.SetImportExportRectCommand(
329
- originalSize, originalTransform, finalRect
330
- );
331
- });
332
- }
333
- };
334
- }
335
-
336
- type TooSmallToRenderCheck = (rect: Rect2)=> boolean;
337
-
338
- /** Part of the Editor's image. @internal */
339
- export class ImageNode {
340
- private content: AbstractComponent|null;
341
- private bbox: Rect2;
342
- private children: ImageNode[];
343
- private targetChildCount: number = 30;
344
-
345
- private id: number;
346
- private static idCounter: number = 0;
347
-
348
- public constructor(
349
- private parent: ImageNode|null = null
350
- ) {
351
- this.children = [];
352
- this.bbox = Rect2.empty;
353
- this.content = null;
354
-
355
- this.id = ImageNode.idCounter++;
356
- }
357
-
358
- public getId() {
359
- return this.id;
360
- }
361
-
362
- public onContentChange() {
363
- this.id = ImageNode.idCounter++;
364
- }
365
-
366
- public getContent(): AbstractComponent|null {
367
- return this.content;
368
- }
369
-
370
- public getParent(): ImageNode|null {
371
- return this.parent;
372
- }
373
-
374
- private getChildrenIntersectingRegion(region: Rect2): ImageNode[] {
375
- return this.children.filter(child => {
376
- return child.getBBox().intersects(region);
377
- });
378
- }
379
-
380
- public getChildrenOrSelfIntersectingRegion(region: Rect2): ImageNode[] {
381
- if (this.content) {
382
- return [this];
383
- }
384
- return this.getChildrenIntersectingRegion(region);
385
- }
386
-
387
- // Returns a list of `ImageNode`s with content (and thus no children).
388
- public getLeavesIntersectingRegion(region: Rect2, isTooSmall?: TooSmallToRenderCheck): ImageNode[] {
389
- const result: ImageNode[] = [];
390
- let current: ImageNode|undefined;
391
- const workList: ImageNode[] = [];
392
-
393
- workList.push(this);
394
- const toNext = () => {
395
- current = undefined;
396
-
397
- const next = workList.pop();
398
- if (next && !isTooSmall?.(next.bbox)) {
399
- current = next;
400
-
401
- if (current.content !== null && current.getBBox().intersection(region)) {
402
- result.push(current);
403
- }
404
-
405
- workList.push(
406
- ...current.getChildrenIntersectingRegion(region)
407
- );
408
- }
409
- };
410
-
411
- while (workList.length > 0) {
412
- toNext();
413
- }
414
-
415
- return result;
416
- }
417
-
418
- // Returns the child of this with the target content or `null` if no
419
- // such child exists.
420
- public getChildWithContent(target: AbstractComponent): ImageNode|null {
421
- const candidates = this.getLeavesIntersectingRegion(target.getBBox());
422
- for (const candidate of candidates) {
423
- if (candidate.getContent() === target) {
424
- return candidate;
425
- }
426
- }
427
-
428
- return null;
429
- }
430
-
431
- // Returns a list of leaves with this as an ancestor.
432
- // Like getLeavesInRegion, but does not check whether ancestors are in a given rectangle
433
- public getLeaves(): ImageNode[] {
434
- if (this.content) {
435
- return [this];
436
- }
437
-
438
- const result: ImageNode[] = [];
439
- for (const child of this.children) {
440
- result.push(...child.getLeaves());
441
- }
442
-
443
- return result;
444
- }
445
-
446
- public addLeaf(leaf: AbstractComponent): ImageNode {
447
- this.onContentChange();
448
-
449
- if (this.content === null && this.children.length === 0) {
450
- this.content = leaf;
451
- this.recomputeBBox(true);
452
-
453
- return this;
454
- }
455
-
456
- if (this.content !== null) {
457
- console.assert(this.children.length === 0);
458
-
459
- const contentNode = new ImageNode(this);
460
- contentNode.content = this.content;
461
- this.content = null;
462
- this.children.push(contentNode);
463
- contentNode.recomputeBBox(false);
464
- }
465
-
466
- // If this node is contained within the leaf, make this and the leaf
467
- // share a parent.
468
- const leafBBox = leaf.getBBox();
469
- if (leafBBox.containsRect(this.getBBox())) {
470
- const nodeForNewLeaf = new ImageNode(this);
471
-
472
- if (this.children.length < this.targetChildCount) {
473
- this.children.push(nodeForNewLeaf);
474
- } else {
475
- const nodeForChildren = new ImageNode(this);
476
-
477
- nodeForChildren.children = this.children;
478
- this.children = [nodeForNewLeaf, nodeForChildren];
479
- nodeForChildren.recomputeBBox(true);
480
- nodeForChildren.updateParents();
481
- }
482
- return nodeForNewLeaf.addLeaf(leaf);
483
- }
484
-
485
- const containingNodes = this.children.filter(
486
- child => child.getBBox().containsRect(leafBBox)
487
- );
488
-
489
- // Does the leaf already fit within one of the children?
490
- if (containingNodes.length > 0 && this.children.length >= this.targetChildCount) {
491
- // Sort the containers in ascending order by area
492
- containingNodes.sort((a, b) => a.getBBox().area - b.getBBox().area);
493
-
494
- // Choose the smallest child that contains the new element.
495
- const result = containingNodes[0].addLeaf(leaf);
496
- result.rebalance();
497
- return result;
498
- }
499
-
500
-
501
- const newNode = new ImageNode(this);
502
- this.children.push(newNode);
503
- newNode.content = leaf;
504
- newNode.recomputeBBox(true);
505
-
506
- return newNode;
507
- }
508
-
509
- public getBBox(): Rect2 {
510
- return this.bbox;
511
- }
512
-
513
- // Recomputes this' bounding box. If [bubbleUp], also recompute
514
- // this' ancestors bounding boxes. This also re-computes this' bounding box
515
- // in the z-direction (z-indicies).
516
- public recomputeBBox(bubbleUp: boolean) {
517
- const oldBBox = this.bbox;
518
- if (this.content !== null) {
519
- this.bbox = this.content.getBBox();
520
- } else {
521
- this.bbox = Rect2.union(...this.children.map(child => child.getBBox()));
522
- }
523
-
524
- if (bubbleUp && !oldBBox.eq(this.bbox)) {
525
- this.parent?.recomputeBBox(true);
526
- }
527
- }
528
-
529
- private updateParents(recursive: boolean = false) {
530
- for (const child of this.children) {
531
- child.parent = this;
532
-
533
- if (recursive) {
534
- child.updateParents(recursive);
535
- }
536
- }
537
- }
538
-
539
- private rebalance() {
540
- // If the current node is its parent's only child,
541
- if (this.parent && this.parent.children.length === 1) {
542
- console.assert(this.parent.content === null);
543
- console.assert(this.parent.children[0] === this);
544
-
545
- // Remove this' parent, if this' parent isn't the root.
546
- const oldParent = this.parent;
547
- if (oldParent.parent !== null) {
548
- oldParent.children = [];
549
- this.parent = oldParent.parent;
550
- this.parent.children.push(this);
551
- oldParent.parent = null;
552
- this.parent.recomputeBBox(false);
553
- } else if (this.content === null) {
554
- // Remove this and transfer this' children to the parent.
555
- this.parent.children = this.children;
556
- this.parent.updateParents();
557
- this.parent = null;
558
- }
559
- }
560
- }
561
-
562
- // Remove this node and all of its children
563
- public remove() {
564
- this.content?.onRemoveFromImage();
565
-
566
- if (!this.parent) {
567
- this.content = null;
568
- this.children = [];
569
-
570
- return;
571
- }
572
-
573
- const oldChildCount = this.parent.children.length;
574
- this.parent.children = this.parent.children.filter(node => {
575
- return node !== this;
576
- });
577
-
578
- console.assert(
579
- this.parent.children.length === oldChildCount - 1,
580
- `${oldChildCount - 1} ≠ ${this.parent.children.length} after removing all nodes equal to ${this}. Nodes should only be removed once.`
581
- );
582
-
583
- this.parent.children.forEach(child => {
584
- child.rebalance();
585
- });
586
-
587
- this.parent.recomputeBBox(true);
588
-
589
- // Invalidate/disconnect this.
590
- this.content = null;
591
- this.parent = null;
592
- this.children = [];
593
- }
594
-
595
- public render(renderer: AbstractRenderer, visibleRect?: Rect2) {
596
- let leaves;
597
- if (visibleRect) {
598
- leaves = this.getLeavesIntersectingRegion(visibleRect, rect => renderer.isTooSmallToRender(rect));
599
- } else {
600
- leaves = this.getLeaves();
601
- }
602
- sortLeavesByZIndex(leaves);
603
-
604
- for (const leaf of leaves) {
605
- // Leaves by definition have content
606
- leaf.getContent()!.render(renderer, visibleRect);
607
- }
608
- }
609
- }