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