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
package/src/SVGLoader.ts DELETED
@@ -1,672 +0,0 @@
1
- import { Color4, Mat33, Path, Rect2, Vec2 } from '@js-draw/math';
2
- import AbstractComponent from './components/AbstractComponent';
3
- import BackgroundComponent, { BackgroundType, backgroundTypeToClassNameMap, imageBackgroundCSSClassName, imageBackgroundGridSizeCSSPrefix, imageBackgroundNonAutomaticSecondaryColorCSSClassName } from './components/BackgroundComponent';
4
- import ImageComponent from './components/ImageComponent';
5
- import Stroke from './components/Stroke';
6
- import SVGGlobalAttributesObject from './components/SVGGlobalAttributesObject';
7
- import TextComponent, { TextTransformMode } from './components/TextComponent';
8
- import UnknownSVGObject from './components/UnknownSVGObject';
9
- import RenderingStyle from './rendering/RenderingStyle';
10
- import TextRenderingStyle from './rendering/TextRenderingStyle';
11
- import { ComponentAddedListener, ImageLoader, OnDetermineExportRectListener, OnProgressListener } from './types';
12
- import RenderablePathSpec, { pathToRenderable } from './rendering/RenderablePathSpec';
13
-
14
- type OnFinishListener = ()=> void;
15
-
16
- // Size of a loaded image if no size is specified.
17
- export const defaultSVGViewRect = new Rect2(0, 0, 500, 500);
18
-
19
- // Key to retrieve unrecognised attributes from an AbstractComponent
20
- export const svgAttributesDataKey = 'svgAttrs';
21
-
22
- // Like {@link svgAttributesDataKey}, but for styles
23
- export const svgStyleAttributesDataKey = 'svgStyleAttrs';
24
-
25
- // Key that specifies the ID of an SVG element that contained a given node when the image
26
- // was first loaded.
27
- export const svgLoaderAttributeContainerID = 'svgContainerID';
28
-
29
- // [key, value]
30
- export type SVGLoaderUnknownAttribute = [ string, string ];
31
-
32
- // [key, value, priority]
33
- export type SVGLoaderUnknownStyleAttribute = { key: string, value: string, priority?: string };
34
-
35
-
36
- const supportedStrokeFillStyleAttrs = [ 'stroke', 'fill', 'stroke-width' ];
37
-
38
- // Handles loading images from SVG.
39
- export default class SVGLoader implements ImageLoader {
40
- private onAddComponent: ComponentAddedListener|null = null;
41
- private onProgress: OnProgressListener|null = null;
42
- private onDetermineExportRect: OnDetermineExportRectListener|null = null;
43
-
44
- private processedCount: number = 0;
45
- private totalToProcess: number = 0;
46
- private rootViewBox: Rect2|null;
47
-
48
- private constructor(
49
- private source: SVGSVGElement, private onFinish?: OnFinishListener, private readonly storeUnknown: boolean = true) {
50
- }
51
-
52
- // If [computedStyles] is given, it is preferred to directly accessing node's style object.
53
- private getStyle(node: SVGElement, computedStyles?: CSSStyleDeclaration) {
54
- let fill = Color4.transparent;
55
- let stroke;
56
-
57
- // If possible, use computedStyles (allows property inheritance).
58
- const fillAttribute = node.getAttribute('fill') ?? computedStyles?.fill ?? node.style.fill;
59
- if (fillAttribute) {
60
- try {
61
- fill = Color4.fromString(fillAttribute);
62
- } catch (e) {
63
- console.error('Unknown fill color,', fillAttribute);
64
- }
65
- }
66
-
67
- const strokeAttribute = node.getAttribute('stroke') ?? computedStyles?.stroke ?? node.style.stroke;
68
- const strokeWidthAttr = node.getAttribute('stroke-width') ?? computedStyles?.strokeWidth ?? node.style.strokeWidth;
69
- if (strokeAttribute && strokeWidthAttr) {
70
- try {
71
- let width = parseFloat(strokeWidthAttr ?? '1');
72
- if (!isFinite(width)) {
73
- width = 0;
74
- }
75
-
76
- const strokeColor = Color4.fromString(strokeAttribute);
77
-
78
- if (strokeColor.a > 0) {
79
- stroke = {
80
- width,
81
- color: strokeColor,
82
- };
83
- }
84
- } catch (e) {
85
- console.error('Error parsing stroke data:', e);
86
- }
87
- }
88
-
89
- const style: RenderingStyle = {
90
- fill,
91
- stroke,
92
- };
93
- return style;
94
- }
95
-
96
- private strokeDataFromElem(node: SVGPathElement): RenderablePathSpec[] {
97
- const result: RenderablePathSpec[] = [];
98
- const pathData = node.getAttribute('d') ?? '';
99
- const style = this.getStyle(node);
100
-
101
- // Break the path into chunks at each moveTo ('M') command:
102
- const parts = pathData.split('M');
103
- let isFirst = true;
104
- for (const part of parts) {
105
- // Skip effective no-ops -- moveTos without additional commands.
106
- const isNoOpMoveTo = /^[0-9., \t\n]+$/.exec(part);
107
-
108
- if (part !== '' && !isNoOpMoveTo) {
109
- // We split the path by moveTo commands, so add the 'M' back in
110
- // if it was present.
111
- const current = !isFirst ? `M${part}` : part;
112
-
113
- const path = Path.fromString(current);
114
- const spec = pathToRenderable(path, style);
115
- result.push(spec);
116
- }
117
-
118
- isFirst = false;
119
- }
120
-
121
- return result;
122
- }
123
-
124
- private attachUnrecognisedAttrs(
125
- elem: AbstractComponent,
126
- node: SVGElement,
127
- supportedAttrs: Set<string>,
128
- supportedStyleAttrs?: Set<string>
129
- ) {
130
- if (!this.storeUnknown) {
131
- return;
132
- }
133
-
134
- for (const attr of node.getAttributeNames()) {
135
- if (supportedAttrs.has(attr) || (attr === 'style' && supportedStyleAttrs)) {
136
- continue;
137
- }
138
-
139
- elem.attachLoadSaveData(svgAttributesDataKey,
140
- [ attr, node.getAttribute(attr) ] as SVGLoaderUnknownAttribute,
141
- );
142
- }
143
-
144
- if (supportedStyleAttrs && node.style) {
145
- // Use a for loop instead of an iterator: js-dom seems to not
146
- // support using node.style as an iterator.
147
- for (let i = 0; i < node.style.length; i ++) {
148
- const attr = node.style[i];
149
-
150
- if (attr === '' || !attr) {
151
- continue;
152
- }
153
-
154
- if (supportedStyleAttrs.has(attr)) {
155
- continue;
156
- }
157
-
158
- // TODO: Do we need special logic for !important properties?
159
- elem.attachLoadSaveData(svgStyleAttributesDataKey,
160
- {
161
- key: attr,
162
- value: node.style.getPropertyValue(attr),
163
- priority: node.style.getPropertyPriority(attr)
164
- } as SVGLoaderUnknownStyleAttribute
165
- );
166
- }
167
- }
168
- }
169
-
170
- // Adds a stroke with a single path
171
- private async addPath(node: SVGPathElement) {
172
- let elem: AbstractComponent;
173
- try {
174
- const strokeData = this.strokeDataFromElem(node);
175
-
176
- elem = new Stroke(strokeData);
177
-
178
- this.attachUnrecognisedAttrs(
179
- elem, node,
180
- new Set([ ...supportedStrokeFillStyleAttrs, 'd' ]),
181
- new Set(supportedStrokeFillStyleAttrs)
182
- );
183
- } catch (e) {
184
- console.error(
185
- 'Invalid path in node', node,
186
- '\nError:', e,
187
- '\nAdding as an unknown object.'
188
- );
189
-
190
- if (this.storeUnknown) {
191
- elem = new UnknownSVGObject(node);
192
- } else {
193
- return;
194
- }
195
- }
196
- await this.addComponent(elem);
197
- }
198
-
199
- private async addBackground(node: SVGElement) {
200
- // If a grid background,
201
- if (node.classList.contains(backgroundTypeToClassNameMap[BackgroundType.Grid])) {
202
- let foregroundStr: string|null;
203
- let backgroundStr: string|null;
204
- let gridStrokeWidthStr: string|null;
205
-
206
- // If a group,
207
- if (node.tagName.toLowerCase() === 'g') {
208
- // We expect exactly two children. One of these is the solid
209
- // background of the grid
210
- if (node.children.length !== 2) {
211
- await this.addUnknownNode(node);
212
- return;
213
- }
214
-
215
- const background = node.children[0];
216
- const grid = node.children[1];
217
-
218
- backgroundStr = background.getAttribute('fill');
219
- foregroundStr = grid.getAttribute('stroke');
220
- gridStrokeWidthStr = grid.getAttribute('stroke-width');
221
- } else {
222
- backgroundStr = node.getAttribute('fill');
223
- foregroundStr = node.getAttribute('stroke');
224
- gridStrokeWidthStr = node.getAttribute('stroke-width');
225
- }
226
-
227
- // Default to a transparent background.
228
- backgroundStr ??= Color4.transparent.toHexString();
229
-
230
- // A grid must have a foreground color specified.
231
- if (!foregroundStr) {
232
- await this.addUnknownNode(node);
233
- return;
234
- }
235
-
236
- // Extract the grid size from the class name
237
- let gridSize: number|undefined = undefined;
238
- for (const className of node.classList) {
239
- if (className.startsWith(imageBackgroundGridSizeCSSPrefix)) {
240
- const sizeStr = className.substring(imageBackgroundGridSizeCSSPrefix.length);
241
- gridSize = parseFloat(sizeStr.replace(/p/g, '.'));
242
- }
243
- }
244
-
245
- let gridStrokeWidth: number|undefined = undefined;
246
- if (gridStrokeWidthStr) {
247
- gridStrokeWidth = parseFloat(gridStrokeWidthStr);
248
- }
249
-
250
- const backgroundColor = Color4.fromString(backgroundStr);
251
- let foregroundColor: Color4|undefined = Color4.fromString(foregroundStr);
252
-
253
- // Should the foreground color be determined automatically?
254
- if (!node.classList.contains(imageBackgroundNonAutomaticSecondaryColorCSSClassName)) {
255
- foregroundColor = undefined;
256
- }
257
-
258
- const elem = BackgroundComponent.ofGrid(
259
- backgroundColor, gridSize, foregroundColor, gridStrokeWidth
260
- );
261
- await this.addComponent(elem);
262
- }
263
- // Otherwise, if just a <path/>, it's a solid color background.
264
- else if (node.tagName.toLowerCase() === 'path') {
265
- const fill = Color4.fromString(node.getAttribute('fill') ?? node.style.fill ?? 'black');
266
- const elem = new BackgroundComponent(BackgroundType.SolidColor, fill);
267
- await this.addComponent(elem);
268
- }
269
- else {
270
- await this.addUnknownNode(node);
271
- }
272
- }
273
-
274
- // If given, 'supportedAttrs' will have x, y, etc. attributes that were used in computing the transform added to it,
275
- // to prevent storing duplicate transform information when saving the component.
276
- private getTransform(elem: SVGElement, supportedAttrs?: string[], computedStyles?: CSSStyleDeclaration): Mat33 {
277
- computedStyles ??= window.getComputedStyle(elem);
278
-
279
- let transformProperty = computedStyles.transform;
280
- if (transformProperty === '' || transformProperty === 'none') {
281
- transformProperty = elem.style.transform || 'none';
282
- }
283
-
284
- // Prefer the actual .style.transform
285
- // to the computed stylesheet -- in some browsers, the computedStyles version
286
- // can have lower precision.
287
- let transform;
288
- try {
289
- transform = Mat33.fromCSSMatrix(elem.style.transform);
290
- } catch(_e) {
291
- transform = Mat33.fromCSSMatrix(transformProperty);
292
- }
293
-
294
- const elemX = elem.getAttribute('x');
295
- const elemY = elem.getAttribute('y');
296
- if (elemX || elemY) {
297
- const x = parseFloat(elemX ?? '0');
298
- const y = parseFloat(elemY ?? '0');
299
- if (!isNaN(x) && !isNaN(y)) {
300
- supportedAttrs?.push('x', 'y');
301
- transform = transform.rightMul(Mat33.translation(Vec2.of(x, y)));
302
- }
303
- }
304
-
305
- return transform;
306
- }
307
-
308
- private makeText(elem: SVGTextElement|SVGTSpanElement): TextComponent {
309
- const contentList: Array<TextComponent|string> = [];
310
- for (const child of elem.childNodes) {
311
- if (child.nodeType === Node.TEXT_NODE) {
312
- contentList.push(child.nodeValue ?? '');
313
- } else if (child.nodeType === Node.ELEMENT_NODE) {
314
- const subElem = child as SVGElement;
315
- if (subElem.tagName.toLowerCase() === 'tspan') {
316
- // FIXME: tspan's (x, y) components are absolute, not relative to the parent.
317
- contentList.push(this.makeText(subElem as SVGTSpanElement));
318
- } else {
319
- throw new Error(`Unrecognized text child element: ${subElem}`);
320
- }
321
- } else {
322
- throw new Error(`Unrecognized text child node: ${child}.`);
323
- }
324
- }
325
-
326
- // If no content, the content is an empty string.
327
- if (contentList.length === 0) {
328
- contentList.push('');
329
- }
330
-
331
- // Compute styles.
332
- const computedStyles = window.getComputedStyle(elem);
333
- const fontSizeExp = /^([-0-9.e]+)px/i;
334
-
335
- // In some environments, computedStyles.fontSize can be increased by the system.
336
- // Thus, to prevent text from growing on load/save, prefer .style.fontSize.
337
- let fontSizeMatch = fontSizeExp.exec(elem.style.fontSize);
338
- if (!fontSizeMatch && elem.tagName.toLowerCase() === 'tspan' && elem.parentElement) {
339
- // Try to inherit the font size of the parent text element.
340
- fontSizeMatch = fontSizeExp.exec(elem.parentElement.style.fontSize);
341
- }
342
-
343
- // If we still couldn't find a font size, try to use computedStyles (which can be
344
- // wrong).
345
- if (!fontSizeMatch) {
346
- fontSizeMatch = fontSizeExp.exec(computedStyles.fontSize);
347
- }
348
-
349
- const supportedStyleAttrs = [
350
- 'fontFamily',
351
- 'transform',
352
- ...supportedStrokeFillStyleAttrs,
353
- ];
354
- let fontSize = 12;
355
- if (fontSizeMatch) {
356
- supportedStyleAttrs.push('fontSize');
357
- fontSize = parseFloat(fontSizeMatch[1]);
358
- }
359
- const style: TextRenderingStyle = {
360
- size: fontSize,
361
- fontFamily: computedStyles.fontFamily || elem.style.fontFamily || 'sans-serif',
362
- fontWeight: computedStyles.fontWeight || elem.style.fontWeight || undefined,
363
- fontStyle: computedStyles.fontStyle || elem.style.fontStyle || undefined,
364
- renderingStyle: this.getStyle(elem, computedStyles),
365
- };
366
-
367
- const supportedAttrs: string[] = [];
368
- let transform = this.getTransform(elem, supportedAttrs, computedStyles);
369
- let transformMode = TextTransformMode.ABSOLUTE_XY;
370
-
371
- const elemDX = elem.getAttribute('dx');
372
- if (elemDX) {
373
- transformMode = TextTransformMode.RELATIVE_X_ABSOLUTE_Y;
374
- transform = transform.rightMul(Mat33.translation(Vec2.of(parseFloat(elemDX), 0)));
375
- supportedAttrs.push('dx');
376
- }
377
-
378
- const elemDY = elem.getAttribute('dy');
379
- if (elemDY) {
380
- if (transformMode === TextTransformMode.RELATIVE_X_ABSOLUTE_Y) {
381
- transformMode = TextTransformMode.RELATIVE_XY;
382
- } else {
383
- transformMode = TextTransformMode.RELATIVE_Y_ABSOLUTE_X;
384
- }
385
-
386
- transform = transform.rightMul(Mat33.translation(Vec2.of(0, parseFloat(elemDY))));
387
- supportedAttrs.push('dy');
388
- }
389
-
390
- const result = new TextComponent(contentList, transform, style, transformMode);
391
- this.attachUnrecognisedAttrs(
392
- result,
393
- elem,
394
- new Set(supportedAttrs),
395
- new Set(supportedStyleAttrs)
396
- );
397
-
398
- return result;
399
- }
400
-
401
- private async addText(elem: SVGTextElement|SVGTSpanElement) {
402
- try {
403
- const textElem = this.makeText(elem);
404
- await this.addComponent(textElem);
405
- } catch (e) {
406
- console.error('Invalid text object in node', elem, '. Continuing.... Error:', e);
407
- this.addUnknownNode(elem);
408
- }
409
- }
410
-
411
- private async addImage(elem: SVGImageElement) {
412
- const image = new Image();
413
- image.src = elem.getAttribute('xlink:href') ?? elem.href.baseVal;
414
- image.setAttribute('alt', elem.getAttribute('aria-label') ?? '');
415
-
416
- try {
417
- const supportedAttrs: string[] = [];
418
- const transform = this.getTransform(elem, supportedAttrs);
419
- const imageElem = await ImageComponent.fromImage(image, transform);
420
- this.attachUnrecognisedAttrs(
421
- imageElem,
422
- elem,
423
- new Set(supportedAttrs),
424
- new Set([ 'transform' ])
425
- );
426
-
427
- await this.addComponent(imageElem);
428
- } catch (e) {
429
- console.error('Error loading image:', e, '. Element: ', elem, '. Continuing...');
430
- await this.addUnknownNode(elem);
431
- }
432
- }
433
-
434
- private async addUnknownNode(node: SVGElement) {
435
- if (this.storeUnknown) {
436
- const component = new UnknownSVGObject(node);
437
- await this.addComponent(component);
438
- }
439
- }
440
-
441
- private containerGroupIDs: string[] = [];
442
- private encounteredIDs: string[] = [];
443
- private async startGroup(node: SVGGElement) {
444
- node = node.cloneNode(false) as SVGGElement;
445
-
446
- // Select a unique ID based on the node's ID property (if it exists).
447
- // Use `||` and not `??` so that empty string IDs are also replaced.
448
- let id = node.id || `id-${this.encounteredIDs.length}`;
449
-
450
- // Make id unique.
451
- let idSuffixCounter = 0;
452
- let suffix = '';
453
- while (this.encounteredIDs.includes(id + suffix)) {
454
- idSuffixCounter ++;
455
- suffix = '--' + idSuffixCounter;
456
- }
457
- id += suffix;
458
-
459
- // Remove all children from the node -- children will be handled separately
460
- // (not removing children here could cause duplicates in the result, when rendered).
461
- node.replaceChildren();
462
-
463
- node.id = id;
464
-
465
- const component = new UnknownSVGObject(node);
466
- this.addComponent(component);
467
-
468
- // Add to IDs after -- we don't want the <g> element to be marked
469
- // as its own container.
470
- this.containerGroupIDs.push(node.id);
471
- this.encounteredIDs.push(node.id);
472
- }
473
-
474
- // Ends the most recent group started by .startGroup
475
- private async endGroup() {
476
- this.containerGroupIDs.pop();
477
- }
478
-
479
- private async addComponent(component: AbstractComponent) {
480
- // Attach the stack of container IDs
481
- if (this.containerGroupIDs.length > 0) {
482
- component.attachLoadSaveData(
483
- svgLoaderAttributeContainerID,
484
- [ ...this.containerGroupIDs ]
485
- );
486
- }
487
-
488
- await this.onAddComponent?.(component);
489
- }
490
-
491
- private updateViewBox(node: SVGSVGElement) {
492
- const viewBoxAttr = node.getAttribute('viewBox');
493
- if (this.rootViewBox || !viewBoxAttr) {
494
- return;
495
- }
496
-
497
- const components = viewBoxAttr.split(/[ \t\n,]+/);
498
- const x = parseFloat(components[0]);
499
- const y = parseFloat(components[1]);
500
- const width = parseFloat(components[2]);
501
- const height = parseFloat(components[3]);
502
-
503
- if (isNaN(x) || isNaN(y) || isNaN(width) || isNaN(height)) {
504
- console.warn(`node ${node} has an unparsable viewbox. Viewbox: ${viewBoxAttr}. Match: ${components}.`);
505
- return;
506
- }
507
-
508
- this.rootViewBox = new Rect2(x, y, width, height);
509
- this.onDetermineExportRect?.(this.rootViewBox);
510
- }
511
-
512
- private async updateSVGAttrs(node: SVGSVGElement) {
513
- if (this.storeUnknown) {
514
- await this.onAddComponent?.(new SVGGlobalAttributesObject(this.getSourceAttrs(node)));
515
- }
516
- }
517
-
518
- private async visit(node: Element) {
519
- this.totalToProcess += node.childElementCount;
520
- let visitChildren = true;
521
-
522
- switch (node.tagName.toLowerCase()) {
523
- case 'g':
524
- if (node.classList.contains(imageBackgroundCSSClassName)) {
525
- await this.addBackground(node as SVGElement);
526
- visitChildren = false;
527
- } else {
528
- await this.startGroup(node as SVGGElement);
529
- }
530
- // Otherwise, continue -- visit the node's children.
531
- break;
532
- case 'path':
533
- if (node.classList.contains(imageBackgroundCSSClassName)) {
534
- await this.addBackground(node as SVGElement);
535
- } else {
536
- await this.addPath(node as SVGPathElement);
537
- }
538
- break;
539
- case 'text':
540
- await this.addText(node as SVGTextElement);
541
- visitChildren = false;
542
- break;
543
- case 'image':
544
- await this.addImage(node as SVGImageElement);
545
-
546
- // Images should not have children.
547
- visitChildren = false;
548
- break;
549
- case 'svg':
550
- this.updateViewBox(node as SVGSVGElement);
551
- this.updateSVGAttrs(node as SVGSVGElement);
552
- break;
553
- case 'style':
554
- await this.addUnknownNode(node as SVGStyleElement);
555
- break;
556
- default:
557
- console.warn('Unknown SVG element,', node, node.tagName);
558
- if (!(node instanceof SVGElement)) {
559
- console.warn(
560
- 'Element', node, 'is not an SVGElement!', this.storeUnknown ? 'Continuing anyway.' : 'Skipping.'
561
- );
562
- }
563
-
564
- await this.addUnknownNode(node as SVGElement);
565
- return;
566
- }
567
-
568
- if (visitChildren) {
569
- for (const child of node.children) {
570
- await this.visit(child);
571
- }
572
-
573
- if (node.tagName.toLowerCase() === 'g') {
574
- await this.endGroup();
575
- }
576
- }
577
-
578
- this.processedCount ++;
579
- await this.onProgress?.(this.processedCount, this.totalToProcess);
580
- }
581
-
582
- // Get SVG element attributes (e.g. xlink=...)
583
- private getSourceAttrs(node: SVGSVGElement): Array<[string, string|null]> {
584
- return node.getAttributeNames().map(attr => {
585
- return [ attr, node.getAttribute(attr) ];
586
- });
587
- }
588
-
589
- public async start(
590
- onAddComponent: ComponentAddedListener, onProgress: OnProgressListener,
591
- onDetermineExportRect: OnDetermineExportRectListener|null = null
592
- ): Promise<void> {
593
- this.onAddComponent = onAddComponent;
594
- this.onProgress = onProgress;
595
- this.onDetermineExportRect = onDetermineExportRect;
596
-
597
- // Estimate the number of tags to process.
598
- this.totalToProcess = this.source.childElementCount;
599
- this.processedCount = 0;
600
-
601
- this.rootViewBox = null;
602
- await this.visit(this.source);
603
-
604
- const viewBox = this.rootViewBox;
605
-
606
- if (!viewBox) {
607
- this.onDetermineExportRect?.(defaultSVGViewRect);
608
- }
609
-
610
- this.onFinish?.();
611
- }
612
-
613
- /**
614
- * Create an `SVGLoader` from the content of an SVG image. SVGs are loaded within a sandboxed
615
- * iframe with `sandbox="allow-same-origin"`
616
- * [thereby disabling JavaScript](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox).
617
- *
618
- * @see {@link Editor.loadFrom}
619
- * @param text - Textual representation of the SVG (e.g. `<svg viewbox='...'>...</svg>`).
620
- * @param sanitize - if `true`, don't store unknown attributes.
621
- */
622
- public static fromString(text: string, sanitize: boolean = false): SVGLoader {
623
- const sandbox = document.createElement('iframe');
624
- sandbox.src = 'about:blank';
625
- sandbox.setAttribute('sandbox', 'allow-same-origin');
626
- sandbox.setAttribute('csp', 'default-src \'about:blank\'');
627
- sandbox.style.display = 'none';
628
-
629
- // Required to access the frame's DOM. See https://stackoverflow.com/a/17777943/17055750
630
- document.body.appendChild(sandbox);
631
-
632
- if (!sandbox.hasAttribute('sandbox')) {
633
- sandbox.remove();
634
- throw new Error('SVG loading iframe is not sandboxed.');
635
- }
636
-
637
- const sandboxDoc = sandbox.contentWindow?.document ?? sandbox.contentDocument;
638
- if (sandboxDoc == null) throw new Error('Unable to open a sandboxed iframe!');
639
-
640
- sandboxDoc.open();
641
- sandboxDoc.write(`
642
- <!DOCTYPE html>
643
- <html>
644
- <head>
645
- <title>SVG Loading Sandbox</title>
646
- <meta name='viewport' conent='width=device-width,initial-scale=1.0'/>
647
- <meta charset='utf-8'/>
648
- </head>
649
- <body style='font-size: 12px;'>
650
- <script>
651
- console.error('JavaScript should not be able to run here!');
652
- throw new Error(
653
- 'The SVG sandbox is broken! Please double-check the sandboxing setting.'
654
- );
655
- </script>
656
- </body>
657
- </html>
658
- `);
659
- sandboxDoc.close();
660
-
661
- const svgElem = sandboxDoc.createElementNS(
662
- 'http://www.w3.org/2000/svg', 'svg'
663
- );
664
- svgElem.innerHTML = text;
665
- sandboxDoc.body.appendChild(svgElem);
666
-
667
- return new SVGLoader(svgElem, () => {
668
- svgElem.remove();
669
- sandbox.remove();
670
- }, !sanitize);
671
- }
672
- }
@@ -1,34 +0,0 @@
1
-
2
- import { Color4, EditorImage, Path, Stroke, Mat33, Vec2 } from './lib';
3
- import { pathToRenderable } from './rendering/RenderablePathSpec';
4
- import createEditor from './testing/createEditor';
5
-
6
- describe('UndoRedoHistory', () => {
7
- it('should keep history size below maximum', () => {
8
- const editor = createEditor();
9
- const stroke = new Stroke([ pathToRenderable(Path.fromString('m0,0 10,10'), { fill: Color4.red }) ]);
10
- editor.dispatch(EditorImage.addElement(stroke));
11
-
12
- for (let i = 0; i < editor.history['maxUndoRedoStackSize'] + 10; i++) {
13
- editor.dispatch(stroke.transformBy(Mat33.translation(Vec2.of(1, 1))));
14
- }
15
-
16
- expect(editor.history.undoStackSize).toBeLessThan(editor.history['maxUndoRedoStackSize']);
17
- expect(editor.history.undoStackSize).toBeGreaterThan(editor.history['maxUndoRedoStackSize'] / 10);
18
- expect(editor.history.redoStackSize).toBe(0);
19
-
20
- const origUndoStackSize = editor.history.undoStackSize;
21
- while (editor.history.undoStackSize > 0) {
22
- editor.history.undo();
23
- }
24
-
25
- // After undoing as much as possible, the stroke should still be present
26
- expect(editor.image.findParent(stroke)).not.toBe(null);
27
-
28
- // Undoing again shouldn't cause issues.
29
- editor.history.undo();
30
- expect(editor.image.findParent(stroke)).not.toBe(null);
31
-
32
- expect(editor.history.redoStackSize).toBe(origUndoStackSize);
33
- });
34
- });