js-draw 0.18.2 → 0.20.0

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