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,383 +0,0 @@
1
- import SerializableCommand from '../commands/SerializableCommand';
2
- import Editor from '../Editor';
3
- import EditorImage from '../EditorImage';
4
- import { LineSegment2, Mat33, Mat33Array, Rect2 } from '@js-draw/math';
5
- import { EditorLocalization } from '../localization';
6
- import AbstractRenderer from '../rendering/renderers/AbstractRenderer';
7
- import { ImageComponentLocalization } from './localization';
8
- import UnresolvedSerializableCommand from '../commands/UnresolvedCommand';
9
-
10
- export type LoadSaveData = (string[]|Record<symbol, string|number>);
11
- export type LoadSaveDataTable = Record<string, Array<LoadSaveData>>;
12
- export type DeserializeCallback = (data: string)=>AbstractComponent;
13
- type ComponentId = string;
14
-
15
- /**
16
- * A base class for everything that can be added to an {@link EditorImage}.
17
- */
18
- export default abstract class AbstractComponent {
19
- // The timestamp (milliseconds) at which the component was
20
- // last changed (i.e. created/translated).
21
- // @deprecated
22
- protected lastChangedTime: number;
23
-
24
- // The bounding box of this component.
25
- // {@link getBBox}, by default, returns `contentBBox`.
26
- // This must be set by components.
27
- protected abstract contentBBox: Rect2;
28
-
29
- private zIndex: number;
30
- private id: string;
31
-
32
- // Topmost z-index
33
- private static zIndexCounter: number = 0;
34
-
35
- protected constructor(
36
- // A unique identifier for the type of component
37
- private readonly componentKind: string,
38
- initialZIndex?: number,
39
- ) {
40
- this.lastChangedTime = (new Date()).getTime();
41
-
42
- if (initialZIndex !== undefined) {
43
- this.zIndex = initialZIndex;
44
- } else {
45
- this.zIndex = AbstractComponent.zIndexCounter++;
46
- }
47
-
48
- // Create a unique ID.
49
- this.id = `${new Date().getTime()}-${Math.random()}`;
50
-
51
- if (AbstractComponent.deserializationCallbacks[componentKind] === undefined) {
52
- throw new Error(`Component ${componentKind} has not been registered using AbstractComponent.registerComponent`);
53
- }
54
- }
55
-
56
- // Returns a unique ID for this element.
57
- // @see { @link EditorImage.lookupElement }
58
- public getId() {
59
- return this.id;
60
- }
61
-
62
- private static deserializationCallbacks: Record<ComponentId, DeserializeCallback|null> = {};
63
-
64
- // Store the deserialization callback (or lack of it) for [componentKind].
65
- // If components are registered multiple times (as may be done in automated tests),
66
- // the most recent deserialization callback is used.
67
- public static registerComponent(
68
- componentKind: string,
69
- deserialize: DeserializeCallback|null,
70
- ) {
71
- this.deserializationCallbacks[componentKind] = deserialize ?? null;
72
- }
73
-
74
- // Stores data attached by a loader.
75
- private loadSaveData: LoadSaveDataTable = {};
76
-
77
- /**
78
- * Attach data that can be used while exporting the component (e.g. to SVG).
79
- *
80
- * This is intended for use by an {@link ImageLoader}.
81
- */
82
- public attachLoadSaveData(key: string, data: LoadSaveData) {
83
- if (!this.loadSaveData[key]) {
84
- this.loadSaveData[key] = [];
85
- }
86
- this.loadSaveData[key].push(data);
87
- }
88
-
89
- /** See {@link attachLoadSaveData} */
90
- public getLoadSaveData(): LoadSaveDataTable {
91
- return this.loadSaveData;
92
- }
93
-
94
- public getZIndex(): number {
95
- return this.zIndex;
96
- }
97
-
98
- /**
99
- * @returns the bounding box of this. This can be a slight overestimate if doing so
100
- * significantly improves performance.
101
- */
102
- public getBBox(): Rect2 {
103
- return this.contentBBox;
104
- }
105
-
106
- /**
107
- * @returns the bounding box of this. Unlike `getBBox`, this should **not** be a rough estimate.
108
- */
109
- public getExactBBox() {
110
- return this.getBBox();
111
- }
112
-
113
- /** Called when this component is added to the given image. */
114
- public onAddToImage(_image: EditorImage): void { }
115
- public onRemoveFromImage(): void { }
116
-
117
- /**
118
- * Renders this component onto the given `canvas`.
119
- *
120
- * If `visibleRect` is given, it should be the region of `canvas` that is visible --
121
- * rendering anything outside of `visibleRect` should have no visible effect on the
122
- * resultant image.
123
- *
124
- * For optimal performance, implementers should call `canvas.startObject` and `canvas.endObject`
125
- * before and after rendering.
126
- */
127
- public abstract render(canvas: AbstractRenderer, visibleRect?: Rect2): void;
128
-
129
- /** @return true if `lineSegment` intersects this component. */
130
- public abstract intersects(lineSegment: LineSegment2): boolean;
131
-
132
- /**
133
- * @returns true if this component intersects `rect` -- it is entirely contained
134
- * within the rectangle or one of the rectangle's edges intersects this component.
135
- *
136
- * The default implementation assumes that `this.getExactBBox()` returns a tight bounding box
137
- * -- that any horiziontal/vertical line that intersects this' boounding box also
138
- * intersects a point in this component. If this is not the case, components must override
139
- * this function.
140
- */
141
- public intersectsRect(rect: Rect2): boolean {
142
- // If this component intersects the given rectangle,
143
- // it is either contained entirely within rect or intersects one of rect's edges.
144
-
145
- // If contained within,
146
- if (rect.containsRect(this.getExactBBox())) {
147
- return true;
148
- }
149
-
150
- // Otherwise check if it intersects one of the rectangle's edges.
151
- const testLines = rect.getEdges();
152
- return testLines.some(edge => this.intersects(edge));
153
- }
154
-
155
- // Return null iff this object cannot be safely serialized/deserialized.
156
- protected abstract serializeToJSON(): any[]|Record<string, any>|number|string|null;
157
-
158
- // Private helper for transformBy: Apply the given transformation to all points of this.
159
- protected abstract applyTransformation(affineTransfm: Mat33): void;
160
-
161
- // Returns a command that, when applied, transforms this by [affineTransfm] and
162
- // updates the editor.
163
- // This also increases the element's z-index so that it is on top.
164
- public transformBy(affineTransfm: Mat33): SerializableCommand {
165
- return new AbstractComponent.TransformElementCommand(affineTransfm, this.getId(), this);
166
- }
167
-
168
- // Returns a command that updates this component's z-index.
169
- public setZIndex(newZIndex: number): SerializableCommand {
170
- return new AbstractComponent.TransformElementCommand(Mat33.identity, this.getId(), this, newZIndex, this.getZIndex());
171
- }
172
-
173
- // @returns true iff this component can be selected (e.g. by the selection tool.)
174
- public isSelectable(): boolean {
175
- return true;
176
- }
177
-
178
- // @returns true iff this component should be added to the background, rather than the
179
- // foreground of the image.
180
- public isBackground(): boolean {
181
- return false;
182
- }
183
-
184
- // @returns an approximation of the proportional time it takes to render this component.
185
- // This is intended to be a rough estimate, but, for example, a stroke with two points sould have
186
- // a renderingWeight approximately twice that of a stroke with one point.
187
- public getProportionalRenderingTime(): number {
188
- return 1;
189
- }
190
-
191
- private static transformElementCommandId = 'transform-element';
192
-
193
- private static TransformElementCommand = class extends UnresolvedSerializableCommand {
194
- private targetZIndex: number;
195
-
196
- // Construct a new TransformElementCommand. `component`, while optional, should
197
- // be provided if available. If not provided, it will be fetched from the editor's
198
- // document when the command is applied.
199
- public constructor(
200
- private affineTransfm: Mat33,
201
- componentID: string,
202
- component?: AbstractComponent,
203
- targetZIndex?: number,
204
- private origZIndex?: number,
205
- ) {
206
- super(AbstractComponent.transformElementCommandId, componentID, component);
207
- this.targetZIndex = targetZIndex ?? AbstractComponent.zIndexCounter++;
208
-
209
- // Ensure that we keep drawing on top even after changing the z-index.
210
- if (this.targetZIndex >= AbstractComponent.zIndexCounter) {
211
- AbstractComponent.zIndexCounter = this.targetZIndex + 1;
212
- }
213
-
214
- if (component && origZIndex === undefined) {
215
- this.origZIndex = component.getZIndex();
216
- }
217
- }
218
-
219
- protected override resolveComponent(image: EditorImage): void {
220
- if (this.component) {
221
- return;
222
- }
223
-
224
- super.resolveComponent(image);
225
- this.origZIndex ??= this.component!.getZIndex();
226
- }
227
-
228
- private updateTransform(editor: Editor, newTransfm: Mat33) {
229
- if (!this.component) {
230
- throw new Error('this.component is undefined or null!');
231
- }
232
-
233
- // Any parent should have only one direct child.
234
- const parent = editor.image.findParent(this.component);
235
- let hadParent = false;
236
- if (parent) {
237
- parent.remove();
238
- hadParent = true;
239
- }
240
-
241
- this.component.applyTransformation(newTransfm);
242
- this.component.lastChangedTime = (new Date()).getTime();
243
-
244
- // Add the element back to the document.
245
- if (hadParent) {
246
- EditorImage.addElement(this.component).apply(editor);
247
- }
248
- }
249
-
250
- public apply(editor: Editor) {
251
- this.resolveComponent(editor.image);
252
-
253
- this.component!.zIndex = this.targetZIndex;
254
- this.updateTransform(editor, this.affineTransfm);
255
- editor.queueRerender();
256
- }
257
-
258
- public unapply(editor: Editor) {
259
- this.resolveComponent(editor.image);
260
-
261
- this.component!.zIndex = this.origZIndex!;
262
- this.updateTransform(editor, this.affineTransfm.inverse());
263
- editor.queueRerender();
264
- }
265
-
266
- public description(_editor: Editor, localizationTable: EditorLocalization) {
267
- return localizationTable.transformedElements(1);
268
- }
269
-
270
- static {
271
- SerializableCommand.register(AbstractComponent.transformElementCommandId, (json: any, editor: Editor) => {
272
- const elem = editor.image.lookupElement(json.id) ?? undefined;
273
- const transform = new Mat33(...(json.transfm as Mat33Array));
274
- const targetZIndex = json.targetZIndex;
275
- const origZIndex = json.origZIndex ?? undefined;
276
-
277
- return new AbstractComponent.TransformElementCommand(
278
- transform,
279
- json.id,
280
- elem,
281
- targetZIndex,
282
- origZIndex,
283
- );
284
- });
285
- }
286
-
287
- protected serializeToJSON() {
288
- return {
289
- id: this.componentID,
290
- transfm: this.affineTransfm.toArray(),
291
- targetZIndex: this.targetZIndex,
292
- origZIndex: this.origZIndex,
293
- };
294
- }
295
- };
296
-
297
- /**
298
- * @return a description that could be read by a screen reader
299
- * (e.g. when adding/erasing the component)
300
- */
301
- public abstract description(localizationTable: ImageComponentLocalization): string;
302
-
303
- // Component-specific implementation of {@link clone}.
304
- protected abstract createClone(): AbstractComponent;
305
-
306
- // Returns a copy of this component.
307
- public clone() {
308
- const clone = this.createClone();
309
-
310
- for (const attachmentKey in this.loadSaveData) {
311
- for (const val of this.loadSaveData[attachmentKey]) {
312
- clone.attachLoadSaveData(attachmentKey, val);
313
- }
314
- }
315
-
316
- return clone;
317
- }
318
-
319
- // Convert the component to an object that can be passed to
320
- // `JSON.stringify`.
321
- //
322
- // Do not rely on the output of this function to take a particular form —
323
- // this function's output can change form without a major version increase.
324
- public serialize() {
325
- const data = this.serializeToJSON();
326
-
327
- if (data === null) {
328
- throw new Error(`${this} cannot be serialized.`);
329
- }
330
-
331
- return {
332
- name: this.componentKind,
333
- zIndex: this.zIndex,
334
- id: this.id,
335
- loadSaveData: this.loadSaveData,
336
- data,
337
- };
338
- }
339
-
340
- // Returns true if `data` is not deserializable. May return false even if [data]
341
- // is not deserializable.
342
- private static isNotDeserializable(json: any|string) {
343
- if (typeof json === 'string') {
344
- json = JSON.parse(json);
345
- }
346
-
347
- if (typeof json !== 'object') {
348
- return true;
349
- }
350
-
351
- if (!this.deserializationCallbacks[json?.name]) {
352
- return true;
353
- }
354
-
355
- if (!json.data) {
356
- return true;
357
- }
358
-
359
- return false;
360
- }
361
-
362
- // Convert a string or an object produced by `JSON.parse` into an `AbstractComponent`.
363
- public static deserialize(json: string|any): AbstractComponent {
364
- if (typeof json === 'string') {
365
- json = JSON.parse(json);
366
- }
367
-
368
- if (AbstractComponent.isNotDeserializable(json)) {
369
- throw new Error(`Element with data ${json} cannot be deserialized.`);
370
- }
371
-
372
- const instance = this.deserializationCallbacks[json.name]!(json.data);
373
- instance.zIndex = json.zIndex;
374
- instance.id = json.id;
375
-
376
- // TODO: What should we do with json.loadSaveData?
377
- // If we attach it to [instance], we create a potential security risk — loadSaveData
378
- // is often used to store unrecognised attributes so they can be preserved on output.
379
- // ...but what if we're deserializing data sent across the network?
380
-
381
- return instance;
382
- }
383
- }
@@ -1,44 +0,0 @@
1
- import { Path, Rect2, Color4 } from '@js-draw/math';
2
- import createEditor from '../testing/createEditor';
3
- import AbstractComponent from './AbstractComponent';
4
- import BackgroundComponent, { BackgroundType, imageBackgroundCSSClassName } from './BackgroundComponent';
5
-
6
- describe('ImageBackground', () => {
7
- it('should render to fill exported SVG', () => {
8
- const editor = createEditor();
9
- const background = new BackgroundComponent(BackgroundType.SolidColor, Color4.green);
10
- editor.image.addElement(background).apply(editor);
11
-
12
- const expectedImportExportRect = new Rect2(-10, 10, 15, 20);
13
- editor.setImportExportRect(expectedImportExportRect).apply(editor);
14
- expect(editor.getImportExportRect()).objEq(expectedImportExportRect);
15
-
16
- expect(background.getBBox()).objEq(expectedImportExportRect);
17
-
18
- const rendered = editor.toSVG();
19
- const renderedBackground = rendered.querySelector(`.${imageBackgroundCSSClassName}`);
20
-
21
- if (renderedBackground === null) {
22
- throw new Error('ImageBackground did not render in exported SVG');
23
- }
24
-
25
- expect(renderedBackground.tagName.toLowerCase()).toBe('path');
26
-
27
- const pathString = renderedBackground.getAttribute('d')!;
28
- expect(pathString).not.toBeNull();
29
-
30
- const path = Path.fromString(pathString);
31
- expect(path.bbox).objEq(editor.getImportExportRect());
32
- });
33
-
34
- it('should be serializable', () => {
35
- const background = BackgroundComponent.ofGrid(Color4.red, 10, Color4.purple);
36
-
37
- const deserializedBackground = AbstractComponent.deserialize(background.serialize()) as BackgroundComponent;
38
- expect(deserializedBackground.getBackgroundType()).toBe(BackgroundType.Grid);
39
- expect(deserializedBackground.getStyle().color).objEq(Color4.red);
40
- expect(deserializedBackground.getMainColor()).objEq(Color4.red);
41
- expect(deserializedBackground.getGridSize()).toBe(background.getGridSize());
42
- expect(deserializedBackground.getSecondaryColor()).objEq(Color4.purple);
43
- });
44
- });