js-draw 1.0.0 → 1.0.1

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 (244) hide show
  1. package/README.md +20 -6
  2. package/dist/bundle.js +1 -1
  3. package/dist/cjs/Editor.js +1 -1
  4. package/dist/cjs/Editor.loadFrom.test.d.ts +1 -0
  5. package/dist/cjs/Editor.test.d.ts +1 -0
  6. package/dist/cjs/Editor.toSVG.test.d.ts +1 -0
  7. package/dist/cjs/EditorImage.test.d.ts +1 -0
  8. package/dist/cjs/EventDispatcher.test.d.ts +1 -0
  9. package/dist/cjs/SVGLoader.test.d.ts +1 -0
  10. package/dist/cjs/UndoRedoHistory.test.d.ts +1 -0
  11. package/dist/cjs/commands/uniteCommands.test.d.ts +1 -0
  12. package/dist/cjs/components/AbstractComponent.transformBy.test.d.ts +1 -0
  13. package/dist/cjs/components/BackgroundComponent.test.d.ts +1 -0
  14. package/dist/cjs/components/Stroke.test.d.ts +1 -0
  15. package/dist/cjs/components/TextComponent.test.d.ts +1 -0
  16. package/dist/cjs/components/UnknownSVGObject.test.d.ts +1 -0
  17. package/dist/cjs/components/builders/FreehandLineBuilder.test.d.ts +1 -0
  18. package/dist/cjs/localizations/getLocalizationTable.test.d.ts +1 -0
  19. package/dist/cjs/rendering/RenderingStyle.test.d.ts +1 -0
  20. package/dist/cjs/rendering/caching/CacheRecord.test.d.ts +1 -0
  21. package/dist/cjs/rendering/caching/RenderingCache.test.d.ts +1 -0
  22. package/dist/cjs/rendering/renderers/DummyRenderer.test.d.ts +1 -0
  23. package/dist/cjs/rendering/renderers/TextOnlyRenderer.test.d.ts +1 -0
  24. package/dist/cjs/shortcuts/KeyBinding.test.d.ts +1 -0
  25. package/dist/cjs/shortcuts/KeyboardShortcutManager.test.d.ts +1 -0
  26. package/dist/cjs/toolbar/EdgeToolbar.test.d.ts +1 -0
  27. package/dist/cjs/tools/Eraser.test.d.ts +1 -0
  28. package/dist/cjs/tools/FindTool.test.d.ts +1 -0
  29. package/dist/cjs/tools/InputFilter/InputPipeline.test.d.ts +1 -0
  30. package/dist/cjs/tools/PanZoom.test.d.ts +1 -0
  31. package/dist/cjs/tools/Pen.test.d.ts +1 -0
  32. package/dist/cjs/tools/SelectionTool/SelectionTool.test.d.ts +1 -0
  33. package/dist/cjs/tools/UndoRedoShortcut.test.d.ts +1 -0
  34. package/dist/cjs/util/ReactiveValue.test.d.ts +1 -0
  35. package/dist/cjs/version.js +1 -1
  36. package/dist/cjs/version.test.d.ts +1 -0
  37. package/dist/mjs/Editor.loadFrom.test.d.ts +1 -0
  38. package/dist/mjs/Editor.mjs +1 -1
  39. package/dist/mjs/Editor.test.d.ts +1 -0
  40. package/dist/mjs/Editor.toSVG.test.d.ts +1 -0
  41. package/dist/mjs/EditorImage.test.d.ts +1 -0
  42. package/dist/mjs/EventDispatcher.test.d.ts +1 -0
  43. package/dist/mjs/SVGLoader.test.d.ts +1 -0
  44. package/dist/mjs/UndoRedoHistory.test.d.ts +1 -0
  45. package/dist/mjs/commands/uniteCommands.test.d.ts +1 -0
  46. package/dist/mjs/components/AbstractComponent.transformBy.test.d.ts +1 -0
  47. package/dist/mjs/components/BackgroundComponent.test.d.ts +1 -0
  48. package/dist/mjs/components/Stroke.test.d.ts +1 -0
  49. package/dist/mjs/components/TextComponent.test.d.ts +1 -0
  50. package/dist/mjs/components/UnknownSVGObject.test.d.ts +1 -0
  51. package/dist/mjs/components/builders/FreehandLineBuilder.test.d.ts +1 -0
  52. package/dist/mjs/localizations/getLocalizationTable.test.d.ts +1 -0
  53. package/dist/mjs/rendering/RenderingStyle.test.d.ts +1 -0
  54. package/dist/mjs/rendering/caching/CacheRecord.test.d.ts +1 -0
  55. package/dist/mjs/rendering/caching/RenderingCache.test.d.ts +1 -0
  56. package/dist/mjs/rendering/renderers/DummyRenderer.test.d.ts +1 -0
  57. package/dist/mjs/rendering/renderers/TextOnlyRenderer.test.d.ts +1 -0
  58. package/dist/mjs/shortcuts/KeyBinding.test.d.ts +1 -0
  59. package/dist/mjs/shortcuts/KeyboardShortcutManager.test.d.ts +1 -0
  60. package/dist/mjs/toolbar/EdgeToolbar.test.d.ts +1 -0
  61. package/dist/mjs/tools/Eraser.test.d.ts +1 -0
  62. package/dist/mjs/tools/FindTool.test.d.ts +1 -0
  63. package/dist/mjs/tools/InputFilter/InputPipeline.test.d.ts +1 -0
  64. package/dist/mjs/tools/PanZoom.test.d.ts +1 -0
  65. package/dist/mjs/tools/Pen.test.d.ts +1 -0
  66. package/dist/mjs/tools/SelectionTool/SelectionTool.test.d.ts +1 -0
  67. package/dist/mjs/tools/UndoRedoShortcut.test.d.ts +1 -0
  68. package/dist/mjs/util/ReactiveValue.test.d.ts +1 -0
  69. package/dist/mjs/version.mjs +1 -1
  70. package/dist/mjs/version.test.d.ts +1 -0
  71. package/dist-test/test_imports/package-lock.json +13 -0
  72. package/dist-test/test_imports/package.json +12 -0
  73. package/dist-test/test_imports/test-imports.js +11 -0
  74. package/dist-test/test_imports/test-require.cjs +14 -0
  75. package/package.json +2 -2
  76. package/src/Editor.loadFrom.test.ts +24 -0
  77. package/src/Editor.test.ts +107 -0
  78. package/src/Editor.toSVG.test.ts +294 -0
  79. package/src/Editor.ts +1443 -0
  80. package/src/EditorImage.test.ts +117 -0
  81. package/src/EditorImage.ts +609 -0
  82. package/src/EventDispatcher.test.ts +123 -0
  83. package/src/EventDispatcher.ts +72 -0
  84. package/src/Pointer.ts +183 -0
  85. package/src/SVGLoader.test.ts +114 -0
  86. package/src/SVGLoader.ts +672 -0
  87. package/src/UndoRedoHistory.test.ts +34 -0
  88. package/src/UndoRedoHistory.ts +102 -0
  89. package/src/Viewport.ts +322 -0
  90. package/src/bundle/bundled.ts +7 -0
  91. package/src/commands/Command.ts +45 -0
  92. package/src/commands/Duplicate.ts +75 -0
  93. package/src/commands/Erase.ts +95 -0
  94. package/src/commands/SerializableCommand.ts +49 -0
  95. package/src/commands/UnresolvedCommand.ts +37 -0
  96. package/src/commands/invertCommand.ts +58 -0
  97. package/src/commands/lib.ts +16 -0
  98. package/src/commands/localization.ts +47 -0
  99. package/src/commands/uniteCommands.test.ts +23 -0
  100. package/src/commands/uniteCommands.ts +140 -0
  101. package/src/components/AbstractComponent.transformBy.test.ts +23 -0
  102. package/src/components/AbstractComponent.ts +383 -0
  103. package/src/components/BackgroundComponent.test.ts +44 -0
  104. package/src/components/BackgroundComponent.ts +348 -0
  105. package/src/components/ImageComponent.ts +176 -0
  106. package/src/components/RestylableComponent.ts +161 -0
  107. package/src/components/SVGGlobalAttributesObject.ts +79 -0
  108. package/src/components/Stroke.test.ts +137 -0
  109. package/src/components/Stroke.ts +294 -0
  110. package/src/components/TextComponent.test.ts +202 -0
  111. package/src/components/TextComponent.ts +429 -0
  112. package/src/components/UnknownSVGObject.test.ts +10 -0
  113. package/src/components/UnknownSVGObject.ts +60 -0
  114. package/src/components/builders/ArrowBuilder.ts +106 -0
  115. package/src/components/builders/CircleBuilder.ts +100 -0
  116. package/src/components/builders/FreehandLineBuilder.test.ts +24 -0
  117. package/src/components/builders/FreehandLineBuilder.ts +210 -0
  118. package/src/components/builders/LineBuilder.ts +77 -0
  119. package/src/components/builders/PressureSensitiveFreehandLineBuilder.ts +453 -0
  120. package/src/components/builders/RectangleBuilder.ts +73 -0
  121. package/src/components/builders/types.ts +15 -0
  122. package/src/components/lib.ts +31 -0
  123. package/src/components/localization.ts +24 -0
  124. package/src/components/util/StrokeSmoother.ts +302 -0
  125. package/src/components/util/describeComponentList.ts +18 -0
  126. package/src/dialogs/makeAboutDialog.ts +82 -0
  127. package/src/inputEvents.ts +143 -0
  128. package/src/lib.ts +91 -0
  129. package/src/localization.ts +34 -0
  130. package/src/localizations/de.ts +146 -0
  131. package/src/localizations/en.ts +8 -0
  132. package/src/localizations/es.ts +74 -0
  133. package/src/localizations/getLocalizationTable.test.ts +27 -0
  134. package/src/localizations/getLocalizationTable.ts +74 -0
  135. package/src/rendering/Display.ts +247 -0
  136. package/src/rendering/RenderablePathSpec.ts +88 -0
  137. package/src/rendering/RenderingStyle.test.ts +68 -0
  138. package/src/rendering/RenderingStyle.ts +55 -0
  139. package/src/rendering/TextRenderingStyle.ts +55 -0
  140. package/src/rendering/caching/CacheRecord.test.ts +48 -0
  141. package/src/rendering/caching/CacheRecord.ts +76 -0
  142. package/src/rendering/caching/CacheRecordManager.ts +71 -0
  143. package/src/rendering/caching/RenderingCache.test.ts +43 -0
  144. package/src/rendering/caching/RenderingCache.ts +66 -0
  145. package/src/rendering/caching/RenderingCacheNode.ts +404 -0
  146. package/src/rendering/caching/testUtils.ts +35 -0
  147. package/src/rendering/caching/types.ts +34 -0
  148. package/src/rendering/lib.ts +8 -0
  149. package/src/rendering/localization.ts +20 -0
  150. package/src/rendering/renderers/AbstractRenderer.ts +232 -0
  151. package/src/rendering/renderers/CanvasRenderer.ts +312 -0
  152. package/src/rendering/renderers/DummyRenderer.test.ts +41 -0
  153. package/src/rendering/renderers/DummyRenderer.ts +142 -0
  154. package/src/rendering/renderers/SVGRenderer.ts +434 -0
  155. package/src/rendering/renderers/TextOnlyRenderer.test.ts +34 -0
  156. package/src/rendering/renderers/TextOnlyRenderer.ts +68 -0
  157. package/src/shortcuts/KeyBinding.test.ts +61 -0
  158. package/src/shortcuts/KeyBinding.ts +257 -0
  159. package/src/shortcuts/KeyboardShortcutManager.test.ts +95 -0
  160. package/src/shortcuts/KeyboardShortcutManager.ts +163 -0
  161. package/src/shortcuts/lib.ts +3 -0
  162. package/src/testing/createEditor.ts +11 -0
  163. package/src/testing/getUniquePointerId.ts +18 -0
  164. package/src/testing/lib.ts +3 -0
  165. package/src/testing/sendPenEvent.ts +36 -0
  166. package/src/testing/sendTouchEvent.ts +71 -0
  167. package/src/toolbar/AbstractToolbar.ts +542 -0
  168. package/src/toolbar/DropdownToolbar.ts +220 -0
  169. package/src/toolbar/EdgeToolbar.test.ts +54 -0
  170. package/src/toolbar/EdgeToolbar.ts +543 -0
  171. package/src/toolbar/IconProvider.ts +861 -0
  172. package/src/toolbar/constants.ts +1 -0
  173. package/src/toolbar/lib.ts +6 -0
  174. package/src/toolbar/localization.ts +136 -0
  175. package/src/toolbar/types.ts +13 -0
  176. package/src/toolbar/widgets/ActionButtonWidget.ts +39 -0
  177. package/src/toolbar/widgets/BaseToolWidget.ts +81 -0
  178. package/src/toolbar/widgets/BaseWidget.ts +495 -0
  179. package/src/toolbar/widgets/DocumentPropertiesWidget.ts +250 -0
  180. package/src/toolbar/widgets/EraserToolWidget.ts +84 -0
  181. package/src/toolbar/widgets/HandToolWidget.ts +239 -0
  182. package/src/toolbar/widgets/InsertImageWidget.ts +248 -0
  183. package/src/toolbar/widgets/OverflowWidget.ts +92 -0
  184. package/src/toolbar/widgets/PenToolWidget.ts +369 -0
  185. package/src/toolbar/widgets/SelectionToolWidget.ts +195 -0
  186. package/src/toolbar/widgets/TextToolWidget.ts +149 -0
  187. package/src/toolbar/widgets/components/makeColorInput.ts +184 -0
  188. package/src/toolbar/widgets/components/makeFileInput.ts +128 -0
  189. package/src/toolbar/widgets/components/makeGridSelector.ts +179 -0
  190. package/src/toolbar/widgets/components/makeSeparator.ts +17 -0
  191. package/src/toolbar/widgets/components/makeThicknessSlider.ts +62 -0
  192. package/src/toolbar/widgets/keybindings.ts +19 -0
  193. package/src/toolbar/widgets/layout/DropdownLayoutManager.ts +262 -0
  194. package/src/toolbar/widgets/layout/EdgeToolbarLayoutManager.ts +71 -0
  195. package/src/toolbar/widgets/layout/types.ts +74 -0
  196. package/src/toolbar/widgets/lib.ts +13 -0
  197. package/src/tools/BaseTool.ts +169 -0
  198. package/src/tools/Eraser.test.ts +103 -0
  199. package/src/tools/Eraser.ts +173 -0
  200. package/src/tools/FindTool.test.ts +67 -0
  201. package/src/tools/FindTool.ts +153 -0
  202. package/src/tools/InputFilter/FunctionMapper.ts +17 -0
  203. package/src/tools/InputFilter/InputMapper.ts +41 -0
  204. package/src/tools/InputFilter/InputPipeline.test.ts +41 -0
  205. package/src/tools/InputFilter/InputPipeline.ts +34 -0
  206. package/src/tools/InputFilter/InputStabilizer.ts +254 -0
  207. package/src/tools/InputFilter/StrokeKeyboardControl.ts +104 -0
  208. package/src/tools/PanZoom.test.ts +339 -0
  209. package/src/tools/PanZoom.ts +525 -0
  210. package/src/tools/PasteHandler.ts +94 -0
  211. package/src/tools/Pen.test.ts +260 -0
  212. package/src/tools/Pen.ts +284 -0
  213. package/src/tools/PipetteTool.ts +84 -0
  214. package/src/tools/SelectionTool/SelectAllShortcutHandler.ts +29 -0
  215. package/src/tools/SelectionTool/Selection.ts +647 -0
  216. package/src/tools/SelectionTool/SelectionHandle.ts +142 -0
  217. package/src/tools/SelectionTool/SelectionTool.test.ts +370 -0
  218. package/src/tools/SelectionTool/SelectionTool.ts +510 -0
  219. package/src/tools/SelectionTool/TransformMode.ts +112 -0
  220. package/src/tools/SelectionTool/types.ts +11 -0
  221. package/src/tools/SoundUITool.ts +221 -0
  222. package/src/tools/TextTool.ts +339 -0
  223. package/src/tools/ToolController.ts +224 -0
  224. package/src/tools/ToolEnabledGroup.ts +14 -0
  225. package/src/tools/ToolSwitcherShortcut.ts +39 -0
  226. package/src/tools/ToolbarShortcutHandler.ts +39 -0
  227. package/src/tools/UndoRedoShortcut.test.ts +62 -0
  228. package/src/tools/UndoRedoShortcut.ts +24 -0
  229. package/src/tools/keybindings.ts +85 -0
  230. package/src/tools/lib.ts +22 -0
  231. package/src/tools/localization.ts +76 -0
  232. package/src/types.ts +151 -0
  233. package/src/util/ReactiveValue.test.ts +168 -0
  234. package/src/util/ReactiveValue.ts +241 -0
  235. package/src/util/assertions.ts +55 -0
  236. package/src/util/fileToBase64.ts +18 -0
  237. package/src/util/guessKeyCodeFromKey.ts +36 -0
  238. package/src/util/listPrefixMatch.ts +19 -0
  239. package/src/util/stopPropagationOfScrollingWheelEvents.ts +20 -0
  240. package/src/util/untilNextAnimationFrame.ts +9 -0
  241. package/src/util/waitForAll.ts +18 -0
  242. package/src/util/waitForTimeout.ts +9 -0
  243. package/src/version.test.ts +12 -0
  244. package/src/version.ts +3 -0
@@ -0,0 +1,383 @@
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
+ }
@@ -0,0 +1,44 @@
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
+ });