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,348 @@
1
+ import Editor from '../Editor';
2
+ import EditorImage, { EditorImageEventType } from '../EditorImage';
3
+ import { DispatcherEventListener } from '../EventDispatcher';
4
+ import SerializableCommand from '../commands/SerializableCommand';
5
+ import { LineSegment2, Mat33, Rect2, Color4, toRoundedString, Path, PathCommandType, Vec2, PathCommand } from '@js-draw/math';
6
+ import AbstractRenderer from '../rendering/renderers/AbstractRenderer';
7
+ import AbstractComponent from './AbstractComponent';
8
+ import { ImageComponentLocalization } from './localization';
9
+ import RestyleableComponent, { ComponentStyle, createRestyleComponentCommand } from './RestylableComponent';
10
+ import Viewport from '../Viewport';
11
+ import { pathToRenderable } from '../rendering/RenderablePathSpec';
12
+
13
+ export enum BackgroundType {
14
+ SolidColor,
15
+ Grid,
16
+ None,
17
+ }
18
+
19
+ export const imageBackgroundCSSClassName = 'js-draw-image-background';
20
+
21
+ // Class name prefix indicating the size of the background's grid cells (if present).
22
+ export const imageBackgroundGridSizeCSSPrefix = 'js-draw-image-background-grid-';
23
+
24
+ // Flag included in rendered SVGs (etc) that indicates that the secondary color of the
25
+ // background has been manually set.
26
+ export const imageBackgroundNonAutomaticSecondaryColorCSSClassName = 'js-draw-image-background-non-automatic-secondary-color';
27
+
28
+ export const backgroundTypeToClassNameMap = {
29
+ [BackgroundType.Grid]: 'js-draw-image-background-grid',
30
+ [BackgroundType.SolidColor]: imageBackgroundCSSClassName,
31
+ [BackgroundType.None]: '',
32
+ };
33
+
34
+ // Represents the background of the editor's canvas.
35
+ export default class BackgroundComponent extends AbstractComponent implements RestyleableComponent {
36
+ protected contentBBox: Rect2;
37
+ private viewportSizeChangeListener: DispatcherEventListener|null = null;
38
+
39
+ private gridSize: number = Viewport.getGridSize(2);
40
+ private gridStrokeWidth: number = 0.7;
41
+ private secondaryColor: Color4|null = null;
42
+
43
+ // eslint-disable-next-line @typescript-eslint/prefer-as-const
44
+ readonly isRestylableComponent: true = true;
45
+
46
+ public constructor(
47
+ private backgroundType: BackgroundType, private mainColor: Color4
48
+ ) {
49
+ super('image-background', 0);
50
+ this.contentBBox = Rect2.empty;
51
+ }
52
+
53
+ public static ofGrid(
54
+ backgroundColor: Color4, gridSize?: number, gridColor?: Color4, gridStrokeWidth?: number
55
+ ) {
56
+ const background = new BackgroundComponent(BackgroundType.Grid, backgroundColor);
57
+
58
+ if (gridSize !== undefined) {
59
+ background.gridSize = gridSize;
60
+ }
61
+
62
+ if (gridColor !== undefined) {
63
+ background.secondaryColor = gridColor;
64
+ }
65
+
66
+ if (gridStrokeWidth !== undefined) {
67
+ background.gridStrokeWidth = gridStrokeWidth;
68
+ }
69
+
70
+ return background;
71
+ }
72
+
73
+ public getBackgroundType() {
74
+ return this.backgroundType;
75
+ }
76
+
77
+ // @internal
78
+ public getMainColor() {
79
+ return this.mainColor;
80
+ }
81
+
82
+ // @internal
83
+ public getSecondaryColor() {
84
+ return this.secondaryColor;
85
+ }
86
+
87
+ // @internal
88
+ public getGridSize() {
89
+ return this.gridSize;
90
+ }
91
+
92
+ public getStyle(): ComponentStyle {
93
+ let color: Color4|undefined = this.mainColor;
94
+
95
+ if (this.backgroundType === BackgroundType.None) {
96
+ color = undefined;
97
+ }
98
+
99
+ return {
100
+ color,
101
+ };
102
+ }
103
+
104
+ public updateStyle(style: ComponentStyle): SerializableCommand {
105
+ return createRestyleComponentCommand(this.getStyle(), style, this);
106
+ }
107
+
108
+ // @internal
109
+ public forceStyle(style: ComponentStyle, editor: Editor | null): void {
110
+ const fill = style.color;
111
+
112
+ if (!fill) {
113
+ return;
114
+ }
115
+
116
+ this.mainColor = fill;
117
+
118
+ // A solid background and transparent fill is equivalent to no background.
119
+ if (fill.eq(Color4.transparent) && this.backgroundType === BackgroundType.SolidColor) {
120
+ this.backgroundType = BackgroundType.None;
121
+ } else if (this.backgroundType === BackgroundType.None) {
122
+ this.backgroundType = BackgroundType.SolidColor;
123
+ }
124
+
125
+ if (editor) {
126
+ editor.image.queueRerenderOf(this);
127
+ editor.queueRerender();
128
+ }
129
+ }
130
+
131
+ public override onAddToImage(image: EditorImage) {
132
+ if (this.viewportSizeChangeListener) {
133
+ console.warn('onAddToImage called when background is already in an image');
134
+ this.onRemoveFromImage();
135
+ }
136
+
137
+ this.viewportSizeChangeListener = image.notifier.on(
138
+ EditorImageEventType.ExportViewportChanged, () => {
139
+ this.recomputeBBox(image);
140
+ });
141
+ this.recomputeBBox(image);
142
+ }
143
+
144
+ public override onRemoveFromImage(): void {
145
+ this.viewportSizeChangeListener?.remove();
146
+ this.viewportSizeChangeListener = null;
147
+ }
148
+
149
+ private recomputeBBox(image: EditorImage) {
150
+ const importExportRect = image.getImportExportViewport().visibleRect;
151
+ if (!this.contentBBox.eq(importExportRect)) {
152
+ this.contentBBox = importExportRect;
153
+
154
+ // Re-render this if already added to the EditorImage.
155
+ image.queueRerenderOf(this);
156
+ }
157
+ }
158
+
159
+ private generateGridPath(visibleRect?: Rect2) {
160
+ const targetRect = visibleRect?.grownBy(this.gridStrokeWidth)?.intersection(this.contentBBox) ?? this.contentBBox;
161
+
162
+ const roundDownToGrid = (coord: number) => Math.floor(coord / this.gridSize) * this.gridSize;
163
+ const roundUpToGrid = (coord: number) => Math.ceil(coord / this.gridSize) * this.gridSize;
164
+
165
+ const startY = roundUpToGrid(targetRect.y);
166
+ const endY = roundDownToGrid(targetRect.y + targetRect.h);
167
+ const startX = roundUpToGrid(targetRect.x);
168
+ const endX = roundDownToGrid(targetRect.x + targetRect.w);
169
+
170
+ const result: PathCommand[] = [];
171
+
172
+ // Don't generate grids with a huge number of rows/columns -- such grids
173
+ // take a long time to render and are likely invisible due to the number of
174
+ // cells.
175
+ const rowCount = (endY - startY) / this.gridSize;
176
+ const colCount = (endX - startX) / this.gridSize;
177
+ const maxGridCols = 1000;
178
+ const maxGridRows = 1000;
179
+ if (rowCount > maxGridRows || colCount > maxGridCols) {
180
+ return Path.empty;
181
+ }
182
+
183
+ const startPoint = Vec2.of(targetRect.x, startY);
184
+ for (let y = startY; y <= endY; y += this.gridSize) {
185
+ result.push({
186
+ kind: PathCommandType.MoveTo,
187
+ point: Vec2.of(targetRect.x, y),
188
+ });
189
+ result.push({
190
+ kind: PathCommandType.LineTo,
191
+ point: Vec2.of(targetRect.x + targetRect.w, y),
192
+ });
193
+ }
194
+
195
+ for (let x = startX; x <= endX; x += this.gridSize) {
196
+ result.push({
197
+ kind: PathCommandType.MoveTo,
198
+ point: Vec2.of(x, targetRect.y),
199
+ });
200
+ result.push({
201
+ kind: PathCommandType.LineTo,
202
+ point: Vec2.of(x, targetRect.y + targetRect.h)
203
+ });
204
+ }
205
+
206
+ return new Path(startPoint, result);
207
+ }
208
+
209
+ public render(canvas: AbstractRenderer, visibleRect?: Rect2) {
210
+ if (this.backgroundType === BackgroundType.None) {
211
+ return;
212
+ }
213
+ const clip = this.backgroundType === BackgroundType.Grid;
214
+ canvas.startObject(this.contentBBox, clip);
215
+
216
+ if (this.backgroundType === BackgroundType.SolidColor || this.backgroundType === BackgroundType.Grid) {
217
+ // If the rectangle for this region contains the visible rect,
218
+ // we can fill the entire visible rectangle (which may be more efficient than
219
+ // filling the entire region for this.)
220
+ if (visibleRect) {
221
+ const intersection = visibleRect.intersection(this.contentBBox);
222
+ if (intersection) {
223
+ canvas.fillRect(intersection, this.mainColor);
224
+ }
225
+ } else {
226
+ canvas.fillRect(this.contentBBox, this.mainColor);
227
+ }
228
+ }
229
+
230
+ if (this.backgroundType === BackgroundType.Grid) {
231
+ let gridColor = this.secondaryColor;
232
+ gridColor ??= Color4.ofRGBA(1 - this.mainColor.r, 1 - this.mainColor.g, 1 - this.mainColor.b, 0.2);
233
+
234
+ // If the background fill is completely transparent, ensure visibility on otherwise light
235
+ // and dark backgrounds.
236
+ if (this.mainColor.a === 0) {
237
+ gridColor = Color4.ofRGBA(0.5, 0.5, 0.5, 0.2);
238
+ }
239
+
240
+ const style = {
241
+ fill: Color4.transparent,
242
+ stroke: { width: this.gridStrokeWidth, color: gridColor }
243
+ };
244
+ canvas.drawPath(pathToRenderable(this.generateGridPath(visibleRect), style));
245
+ }
246
+
247
+ const backgroundTypeCSSClass = backgroundTypeToClassNameMap[this.backgroundType];
248
+ const classNames = [ imageBackgroundCSSClassName ];
249
+
250
+ if (backgroundTypeCSSClass !== imageBackgroundCSSClassName) {
251
+ classNames.push(backgroundTypeCSSClass);
252
+
253
+ const gridSizeStr = toRoundedString(this.gridSize).replace(/[.]/g, 'p');
254
+ classNames.push(imageBackgroundGridSizeCSSPrefix + gridSizeStr);
255
+ }
256
+
257
+ if (this.secondaryColor !== null) {
258
+ classNames.push(imageBackgroundNonAutomaticSecondaryColorCSSClassName);
259
+ }
260
+
261
+ canvas.endObject(this.getLoadSaveData(), classNames);
262
+ }
263
+
264
+ public intersects(lineSegment: LineSegment2): boolean {
265
+ return this.contentBBox.getEdges().some(edge => edge.intersects(lineSegment));
266
+ }
267
+
268
+ public override isSelectable(): boolean {
269
+ return false;
270
+ }
271
+
272
+ public override isBackground(): boolean {
273
+ return true;
274
+ }
275
+
276
+ protected serializeToJSON() {
277
+ return {
278
+ mainColor: this.mainColor.toHexString(),
279
+ secondaryColor: this.secondaryColor?.toHexString(),
280
+ backgroundType: this.backgroundType,
281
+ gridSize: this.gridSize,
282
+ gridStrokeWidth: this.gridStrokeWidth,
283
+ };
284
+ }
285
+
286
+ protected applyTransformation(_affineTransfm: Mat33) {
287
+ // Do nothing — it doesn't make sense to transform the background.
288
+ }
289
+
290
+ public description(localizationTable: ImageComponentLocalization) {
291
+ if (this.backgroundType === BackgroundType.SolidColor) {
292
+ return localizationTable.filledBackgroundWithColor(this.mainColor.toString());
293
+ } else if (this.backgroundType === BackgroundType.None) {
294
+ return localizationTable.emptyBackground;
295
+ } else if (this.backgroundType === BackgroundType.Grid) {
296
+ return localizationTable.gridBackground;
297
+ } else {
298
+ const exhaustivenessCheck: never = this.backgroundType;
299
+ return exhaustivenessCheck;
300
+ }
301
+ }
302
+
303
+ protected createClone(): AbstractComponent {
304
+ return new BackgroundComponent(this.backgroundType, this.mainColor);
305
+ }
306
+
307
+ // @internal
308
+ public static deserializeFromJSON(json: any) {
309
+ if (typeof json === 'string') {
310
+ json = JSON.parse(json);
311
+ }
312
+
313
+ if (typeof json.mainColor !== 'string') {
314
+ throw new Error('Error deserializing — mainColor must be of type string.');
315
+ }
316
+
317
+ let backgroundType;
318
+ const jsonBackgroundType = json.backgroundType as BackgroundType;
319
+
320
+ if (
321
+ jsonBackgroundType === BackgroundType.None || jsonBackgroundType === BackgroundType.Grid
322
+ || jsonBackgroundType === BackgroundType.SolidColor
323
+ ) {
324
+ backgroundType = jsonBackgroundType;
325
+ } else {
326
+ const exhaustivenessCheck: never = jsonBackgroundType;
327
+ return exhaustivenessCheck;
328
+ }
329
+
330
+ const mainColor = Color4.fromHex(json.mainColor);
331
+ const secondaryColor = json.secondaryColor ? Color4.fromHex(json.secondaryColor) : null;
332
+ const gridSize: number|undefined = json.gridSize ?? undefined;
333
+ const gridStrokeWidth: number|undefined = json.gridStrokeWidth ?? undefined;
334
+
335
+ const result = new BackgroundComponent(backgroundType, mainColor);
336
+ result.secondaryColor = secondaryColor;
337
+ if (gridSize) {
338
+ result.gridSize = gridSize;
339
+ }
340
+ if (gridStrokeWidth) {
341
+ result.gridStrokeWidth = gridStrokeWidth;
342
+ }
343
+
344
+ return result;
345
+ }
346
+ }
347
+
348
+ AbstractComponent.registerComponent('image-background', BackgroundComponent.deserializeFromJSON);
@@ -0,0 +1,176 @@
1
+ import { Mat33Array, Rect2, Mat33, LineSegment2 } from '@js-draw/math';
2
+ import AbstractRenderer, { RenderableImage } from '../rendering/renderers/AbstractRenderer';
3
+ import { assertIsNumber, assertIsNumberArray } from '../util/assertions';
4
+ import AbstractComponent from './AbstractComponent';
5
+ import { ImageComponentLocalization } from './localization';
6
+
7
+ // Represents a raster image.
8
+ export default class ImageComponent extends AbstractComponent {
9
+ protected contentBBox: Rect2;
10
+ private image: RenderableImage;
11
+
12
+ public constructor(image: RenderableImage) {
13
+ super('image-component');
14
+ this.image = {
15
+ ...image,
16
+ label: image.label ?? image.image.getAttribute('alt') ?? image.image.getAttribute('aria-label') ?? undefined,
17
+ };
18
+
19
+ const isHTMLImageElem = (elem: HTMLCanvasElement|HTMLImageElement): elem is HTMLImageElement => {
20
+ return elem.getAttribute('src') !== undefined;
21
+ };
22
+ if (isHTMLImageElem(image.image) && !image.image.complete) {
23
+ image.image.onload = () => this.recomputeBBox();
24
+ }
25
+
26
+ this.recomputeBBox();
27
+ }
28
+
29
+ private getImageRect() {
30
+ return new Rect2(0, 0, this.image.image.width, this.image.image.height);
31
+ }
32
+
33
+ private recomputeBBox() {
34
+ this.contentBBox = this.getImageRect();
35
+ this.contentBBox = this.contentBBox.transformedBoundingBox(this.image.transform);
36
+ }
37
+
38
+ // Load from an image. Waits for the image to load if incomplete.
39
+ public static async fromImage(elem: HTMLImageElement, transform: Mat33) {
40
+ if (!elem.complete) {
41
+ await new Promise((resolve, reject) => {
42
+ elem.onload = resolve;
43
+ elem.onerror = reject;
44
+ elem.onabort = reject;
45
+ });
46
+ }
47
+
48
+ let width, height;
49
+ if (
50
+ typeof elem.width === 'number' && typeof elem.height === 'number'
51
+ && elem.width !== 0 && elem.height !== 0
52
+ ) {
53
+ width = elem.width as number;
54
+ height = elem.height as number;
55
+ } else {
56
+ width = elem.clientWidth;
57
+ height = elem.clientHeight;
58
+ }
59
+
60
+ let image;
61
+ let url = elem.src ?? '';
62
+ if (!url.startsWith('data:image/')) {
63
+ // Convert to a data URL:
64
+ const canvas = document.createElement('canvas');
65
+ canvas.width = width;
66
+ canvas.height = height;
67
+
68
+ const ctx = canvas.getContext('2d')!;
69
+ ctx.drawImage(elem, 0, 0, canvas.width, canvas.height);
70
+ url = canvas.toDataURL();
71
+ image = canvas;
72
+ } else {
73
+ image = new Image();
74
+ image.src = url;
75
+ image.width = width;
76
+ image.height = height;
77
+ }
78
+
79
+ image.setAttribute('alt', elem.getAttribute('alt') ?? '');
80
+ image.setAttribute('aria-label', elem.getAttribute('aria-label') ?? '');
81
+
82
+ return new ImageComponent({
83
+ image,
84
+ base64Url: url,
85
+ transform: transform,
86
+ });
87
+ }
88
+
89
+ public override render(canvas: AbstractRenderer, _visibleRect?: Rect2): void {
90
+ canvas.startObject(this.contentBBox);
91
+ canvas.drawImage(this.image);
92
+ canvas.endObject(this.getLoadSaveData());
93
+ }
94
+
95
+ public override getProportionalRenderingTime(): number {
96
+ // Estimate: Equivalent to a stroke with 10 segments.
97
+ return 10;
98
+ }
99
+
100
+ public override intersects(lineSegment: LineSegment2): boolean {
101
+ const rect = this.getImageRect();
102
+ const edges = rect.getEdges().map(edge => edge.transformedBy(this.image.transform));
103
+ for (const edge of edges) {
104
+ if (edge.intersects(lineSegment)) {
105
+ return true;
106
+ }
107
+ }
108
+ return false;
109
+ }
110
+
111
+ protected applyTransformation(affineTransfm: Mat33) {
112
+ this.image.transform = affineTransfm.rightMul(this.image.transform);
113
+ this.recomputeBBox();
114
+ }
115
+
116
+ public override description(localizationTable: ImageComponentLocalization): string {
117
+ return this.image.label ? localizationTable.imageNode(this.image.label) : localizationTable.unlabeledImageNode;
118
+ }
119
+
120
+ public getAltText() {
121
+ return this.image.label;
122
+ }
123
+
124
+ public getURL() {
125
+ return this.image.base64Url;
126
+ }
127
+
128
+ public getTransformation(): Mat33 {
129
+ return this.image.transform;
130
+ }
131
+
132
+ protected override createClone(): AbstractComponent {
133
+ return new ImageComponent({
134
+ ...this.image,
135
+ });
136
+ }
137
+
138
+ protected override serializeToJSON() {
139
+ return {
140
+ src: this.image.base64Url,
141
+ label: this.image.label,
142
+
143
+ // Store the width and height for bounding box computations while the image is loading.
144
+ width: this.image.image.width,
145
+ height: this.image.image.height,
146
+
147
+ transform: this.image.transform.toArray(),
148
+ };
149
+ }
150
+
151
+ public static deserializeFromJSON(data: any): ImageComponent {
152
+ if (!(typeof data.src === 'string')) {
153
+ throw new Error(`${data} has invalid format! Expected src property.`);
154
+ }
155
+
156
+ assertIsNumberArray(data.transform);
157
+ assertIsNumber(data.width);
158
+ assertIsNumber(data.height);
159
+
160
+ const image = new Image();
161
+ image.src = data.src;
162
+ image.width = data.width;
163
+ image.height = data.height;
164
+
165
+ const transform = new Mat33(...(data.transform as Mat33Array));
166
+
167
+ return new ImageComponent({
168
+ image: image,
169
+ base64Url: data.src,
170
+ label: data.label,
171
+ transform,
172
+ });
173
+ }
174
+ }
175
+
176
+ AbstractComponent.registerComponent('image-component', ImageComponent.deserializeFromJSON);
@@ -0,0 +1,161 @@
1
+ import { Color4 } from '@js-draw/math';
2
+ import SerializableCommand from '../commands/SerializableCommand';
3
+ import UnresolvedSerializableCommand from '../commands/UnresolvedCommand';
4
+ import Editor from '../Editor';
5
+ import { EditorLocalization } from '../localization';
6
+ import TextRenderingStyle, { textStyleFromJSON, textStyleToJSON } from '../rendering/TextRenderingStyle';
7
+ import AbstractComponent from './AbstractComponent';
8
+
9
+ export interface ComponentStyle {
10
+ color?: Color4;
11
+ textStyle?: TextRenderingStyle;
12
+ }
13
+
14
+ const serializeComponentStyle = (style: ComponentStyle) => {
15
+ const result: Record<string, any> = { };
16
+
17
+ if (style.color) {
18
+ result.color = style.color.toHexString();
19
+ }
20
+
21
+ if (style.textStyle) {
22
+ result.textStyle = textStyleToJSON(style.textStyle);
23
+ }
24
+
25
+ return result;
26
+ };
27
+
28
+ const deserializeComponentStyle = (json: Record<string, any>|any): ComponentStyle => {
29
+ const color = json.color ? Color4.fromHex(json.color) : undefined;
30
+ const textStyle = json.textStyle ? textStyleFromJSON(json.textStyle) : undefined;
31
+
32
+ return {
33
+ color,
34
+ textStyle,
35
+ };
36
+ };
37
+
38
+ // For internal use by Components implementing `updateStyle`:
39
+ export const createRestyleComponentCommand = (
40
+ initialStyle: ComponentStyle,
41
+ newStyle: ComponentStyle,
42
+ component: RestyleableComponent,
43
+ ): SerializableCommand => {
44
+ return new DefaultRestyleComponentCommand(
45
+ initialStyle, newStyle, component.getId(), component
46
+ );
47
+ };
48
+
49
+
50
+ // Returns true if `component` is a `RestylableComponent`.
51
+ export const isRestylableComponent = (component: AbstractComponent): component is RestyleableComponent => {
52
+ const hasMethods = 'getStyle' in component && 'updateStyle' in component && 'forceStyle' in component;
53
+ if (!hasMethods) {
54
+ return false;
55
+ }
56
+
57
+ if (!('isRestylableComponent' in component) || !(component as any)['isRestylableComponent']) {
58
+ return false;
59
+ }
60
+
61
+ return true;
62
+ };
63
+
64
+ /**
65
+ * An interface to be implemented by components with a changable color or {@link TextRenderingStyle}.
66
+ *
67
+ * All such classes must have a member variable, `isRestylableComponent` that is set to `true`
68
+ * to allow testing whether the class is a `RestylableComponent` (see {@link isRestylableComponent}).
69
+ */
70
+ export interface RestyleableComponent extends AbstractComponent {
71
+ /**
72
+ * @returns a partial representation of this component's style.
73
+ */
74
+ getStyle(): ComponentStyle;
75
+
76
+ /**
77
+ * Returns a {@link Command} that updates portions of this component's style
78
+ * to the given `style`.
79
+ *
80
+ * @example
81
+ * For some component and editor,
82
+ * ```ts
83
+ * editor.dispatch(component.updateStyle({ color: Color4.red }));
84
+ * ```
85
+ */
86
+ updateStyle(style: ComponentStyle): SerializableCommand;
87
+
88
+ /**
89
+ * Set the style of this component in a way that can't be undone/redone
90
+ * (does not create a command).
91
+ *
92
+ * Prefer `updateStyle(style).apply(editor)`.
93
+ */
94
+ forceStyle(style: ComponentStyle, editor: Editor|null): void;
95
+
96
+ isRestylableComponent: true;
97
+ }
98
+
99
+ export default RestyleableComponent;
100
+
101
+
102
+ const defaultRestyleComponentCommandId = 'default-restyle-element';
103
+
104
+ class DefaultRestyleComponentCommand extends UnresolvedSerializableCommand {
105
+ public constructor(
106
+ private originalStyle: ComponentStyle,
107
+ private newStyle: ComponentStyle,
108
+ componentID: string,
109
+ component?: RestyleableComponent,
110
+ ) {
111
+ super(defaultRestyleComponentCommandId, componentID, component);
112
+ }
113
+
114
+ private getComponent(editor: Editor): RestyleableComponent {
115
+ this.resolveComponent(editor.image);
116
+
117
+ const component = this.component as any;
118
+ if (!component || !component['forceStyle'] || !component['updateStyle']) {
119
+ throw new Error('this.component is missing forceStyle and/or updateStyle methods!');
120
+ }
121
+
122
+ return component;
123
+ }
124
+
125
+ public apply(editor: Editor) {
126
+ this.getComponent(editor).forceStyle(this.newStyle, editor);
127
+ }
128
+
129
+ public unapply(editor: Editor) {
130
+ this.getComponent(editor).forceStyle(this.originalStyle, editor);
131
+ }
132
+
133
+ public description(editor: Editor, localizationTable: EditorLocalization): string {
134
+ return localizationTable.restyledElement(this.getComponent(editor).description(localizationTable));
135
+ }
136
+
137
+ protected serializeToJSON() {
138
+ return {
139
+ id: this.componentID,
140
+ originalStyle: serializeComponentStyle(this.originalStyle),
141
+ newStyle: serializeComponentStyle(this.newStyle),
142
+ };
143
+ }
144
+
145
+ static {
146
+ SerializableCommand.register(defaultRestyleComponentCommandId, (json: any, _editor: Editor) => {
147
+ const origStyle = deserializeComponentStyle(json.originalStyle);
148
+ const newStyle = deserializeComponentStyle(json.newStyle);
149
+ const id = json.id;
150
+ if (typeof json.id !== 'string') {
151
+ throw new Error(`json.id is of type ${(typeof json.id)}, not string.`);
152
+ }
153
+
154
+ return new DefaultRestyleComponentCommand(
155
+ origStyle,
156
+ newStyle,
157
+ id,
158
+ );
159
+ });
160
+ }
161
+ }