js-draw 1.16.1 → 1.18.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (132) hide show
  1. package/README.md +70 -10
  2. package/dist/bundle.js +2 -2
  3. package/dist/bundledStyles.js +1 -1
  4. package/dist/cjs/Editor.d.ts +75 -7
  5. package/dist/cjs/Editor.js +93 -90
  6. package/dist/cjs/Pointer.d.ts +2 -1
  7. package/dist/cjs/Pointer.js +9 -2
  8. package/dist/cjs/commands/localization.d.ts +1 -0
  9. package/dist/cjs/commands/localization.js +1 -0
  10. package/dist/cjs/commands/uniteCommands.d.ts +5 -1
  11. package/dist/cjs/commands/uniteCommands.js +33 -7
  12. package/dist/cjs/components/AbstractComponent.d.ts +17 -5
  13. package/dist/cjs/components/AbstractComponent.js +15 -15
  14. package/dist/cjs/components/Stroke.d.ts +4 -1
  15. package/dist/cjs/components/Stroke.js +158 -2
  16. package/dist/cjs/components/TextComponent.d.ts +36 -1
  17. package/dist/cjs/components/TextComponent.js +39 -1
  18. package/dist/cjs/components/builders/ArrowBuilder.js +1 -1
  19. package/dist/cjs/components/builders/PolylineBuilder.d.ts +35 -0
  20. package/dist/cjs/components/builders/PolylineBuilder.js +122 -0
  21. package/dist/cjs/components/builders/PressureSensitiveFreehandLineBuilder.d.ts +1 -1
  22. package/dist/cjs/components/builders/PressureSensitiveFreehandLineBuilder.js +44 -51
  23. package/dist/cjs/components/builders/autocorrect/makeShapeFitAutocorrect.js +1 -1
  24. package/dist/cjs/components/lib.d.ts +1 -0
  25. package/dist/cjs/components/lib.js +3 -1
  26. package/dist/cjs/components/util/StrokeSmoother.js +4 -4
  27. package/dist/cjs/image/EditorImage.d.ts +4 -1
  28. package/dist/cjs/image/EditorImage.js +5 -2
  29. package/dist/cjs/inputEvents.d.ts +11 -1
  30. package/dist/cjs/localizations/comments.d.ts +3 -0
  31. package/dist/cjs/localizations/comments.js +3 -0
  32. package/dist/cjs/localizations/de.js +1 -3
  33. package/dist/cjs/localizations/es.js +3 -3
  34. package/dist/cjs/rendering/renderers/CanvasRenderer.d.ts +7 -0
  35. package/dist/cjs/rendering/renderers/CanvasRenderer.js +16 -0
  36. package/dist/cjs/rendering/renderers/SVGRenderer.js +1 -1
  37. package/dist/cjs/testing/createEditor.d.ts +2 -2
  38. package/dist/cjs/testing/createEditor.js +2 -2
  39. package/dist/cjs/toolbar/IconProvider.d.ts +9 -4
  40. package/dist/cjs/toolbar/IconProvider.js +21 -7
  41. package/dist/cjs/toolbar/localization.d.ts +6 -1
  42. package/dist/cjs/toolbar/localization.js +7 -2
  43. package/dist/cjs/toolbar/widgets/DocumentPropertiesWidget.js +24 -1
  44. package/dist/cjs/toolbar/widgets/EraserToolWidget.d.ts +6 -1
  45. package/dist/cjs/toolbar/widgets/EraserToolWidget.js +45 -5
  46. package/dist/cjs/toolbar/widgets/PenToolWidget.d.ts +1 -1
  47. package/dist/cjs/toolbar/widgets/PenToolWidget.js +17 -4
  48. package/dist/cjs/toolbar/widgets/PenToolWidget.test.d.ts +1 -0
  49. package/dist/cjs/toolbar/widgets/keybindings.js +1 -1
  50. package/dist/cjs/tools/Eraser.d.ts +24 -4
  51. package/dist/cjs/tools/Eraser.js +108 -21
  52. package/dist/cjs/tools/InputFilter/InputStabilizer.js +3 -3
  53. package/dist/cjs/tools/PasteHandler.js +35 -10
  54. package/dist/cjs/tools/Pen.js +2 -2
  55. package/dist/cjs/tools/SelectionTool/SelectionTool.js +23 -4
  56. package/dist/cjs/tools/SelectionTool/ToPointerAutoscroller.js +1 -1
  57. package/dist/cjs/tools/ToolController.d.ts +17 -1
  58. package/dist/cjs/tools/ToolController.js +21 -8
  59. package/dist/cjs/tools/lib.d.ts +1 -4
  60. package/dist/cjs/tools/lib.js +2 -4
  61. package/dist/cjs/tools/localization.d.ts +2 -2
  62. package/dist/cjs/tools/localization.js +2 -2
  63. package/dist/cjs/util/ClipboardHandler.d.ts +27 -0
  64. package/dist/cjs/util/ClipboardHandler.js +205 -0
  65. package/dist/cjs/util/ClipboardHandler.test.d.ts +1 -0
  66. package/dist/cjs/version.d.ts +5 -0
  67. package/dist/cjs/version.js +6 -1
  68. package/dist/mjs/Editor.d.ts +75 -7
  69. package/dist/mjs/Editor.mjs +93 -90
  70. package/dist/mjs/Pointer.d.ts +2 -1
  71. package/dist/mjs/Pointer.mjs +9 -2
  72. package/dist/mjs/commands/localization.d.ts +1 -0
  73. package/dist/mjs/commands/localization.mjs +1 -0
  74. package/dist/mjs/commands/uniteCommands.d.ts +5 -1
  75. package/dist/mjs/commands/uniteCommands.mjs +33 -7
  76. package/dist/mjs/components/AbstractComponent.d.ts +17 -5
  77. package/dist/mjs/components/AbstractComponent.mjs +15 -15
  78. package/dist/mjs/components/Stroke.d.ts +4 -1
  79. package/dist/mjs/components/Stroke.mjs +159 -3
  80. package/dist/mjs/components/TextComponent.d.ts +36 -1
  81. package/dist/mjs/components/TextComponent.mjs +40 -2
  82. package/dist/mjs/components/builders/ArrowBuilder.mjs +1 -1
  83. package/dist/mjs/components/builders/PolylineBuilder.d.ts +35 -0
  84. package/dist/mjs/components/builders/PolylineBuilder.mjs +115 -0
  85. package/dist/mjs/components/builders/PressureSensitiveFreehandLineBuilder.d.ts +1 -1
  86. package/dist/mjs/components/builders/PressureSensitiveFreehandLineBuilder.mjs +45 -52
  87. package/dist/mjs/components/builders/autocorrect/makeShapeFitAutocorrect.mjs +1 -1
  88. package/dist/mjs/components/lib.d.ts +1 -0
  89. package/dist/mjs/components/lib.mjs +1 -0
  90. package/dist/mjs/components/util/StrokeSmoother.mjs +4 -4
  91. package/dist/mjs/image/EditorImage.d.ts +4 -1
  92. package/dist/mjs/image/EditorImage.mjs +5 -2
  93. package/dist/mjs/inputEvents.d.ts +11 -1
  94. package/dist/mjs/localizations/comments.d.ts +3 -0
  95. package/dist/mjs/localizations/comments.mjs +3 -0
  96. package/dist/mjs/localizations/de.mjs +1 -3
  97. package/dist/mjs/localizations/es.mjs +3 -3
  98. package/dist/mjs/rendering/renderers/CanvasRenderer.d.ts +7 -0
  99. package/dist/mjs/rendering/renderers/CanvasRenderer.mjs +16 -0
  100. package/dist/mjs/rendering/renderers/SVGRenderer.mjs +1 -1
  101. package/dist/mjs/testing/createEditor.d.ts +2 -2
  102. package/dist/mjs/testing/createEditor.mjs +2 -2
  103. package/dist/mjs/toolbar/IconProvider.d.ts +9 -4
  104. package/dist/mjs/toolbar/IconProvider.mjs +21 -7
  105. package/dist/mjs/toolbar/localization.d.ts +6 -1
  106. package/dist/mjs/toolbar/localization.mjs +7 -2
  107. package/dist/mjs/toolbar/widgets/DocumentPropertiesWidget.mjs +24 -1
  108. package/dist/mjs/toolbar/widgets/EraserToolWidget.d.ts +6 -1
  109. package/dist/mjs/toolbar/widgets/EraserToolWidget.mjs +47 -6
  110. package/dist/mjs/toolbar/widgets/PenToolWidget.d.ts +1 -1
  111. package/dist/mjs/toolbar/widgets/PenToolWidget.mjs +17 -4
  112. package/dist/mjs/toolbar/widgets/PenToolWidget.test.d.ts +1 -0
  113. package/dist/mjs/toolbar/widgets/keybindings.mjs +1 -1
  114. package/dist/mjs/tools/Eraser.d.ts +24 -4
  115. package/dist/mjs/tools/Eraser.mjs +108 -22
  116. package/dist/mjs/tools/InputFilter/InputStabilizer.mjs +3 -3
  117. package/dist/mjs/tools/PasteHandler.mjs +35 -10
  118. package/dist/mjs/tools/Pen.mjs +2 -2
  119. package/dist/mjs/tools/SelectionTool/SelectionTool.mjs +23 -4
  120. package/dist/mjs/tools/SelectionTool/ToPointerAutoscroller.mjs +1 -1
  121. package/dist/mjs/tools/ToolController.d.ts +17 -1
  122. package/dist/mjs/tools/ToolController.mjs +21 -8
  123. package/dist/mjs/tools/lib.d.ts +1 -4
  124. package/dist/mjs/tools/lib.mjs +1 -4
  125. package/dist/mjs/tools/localization.d.ts +2 -2
  126. package/dist/mjs/tools/localization.mjs +2 -2
  127. package/dist/mjs/util/ClipboardHandler.d.ts +27 -0
  128. package/dist/mjs/util/ClipboardHandler.mjs +200 -0
  129. package/dist/mjs/util/ClipboardHandler.test.d.ts +1 -0
  130. package/dist/mjs/version.d.ts +5 -0
  131. package/dist/mjs/version.mjs +6 -1
  132. package/package.json +6 -6
@@ -13,7 +13,6 @@ import getLocalizationTable from './localizations/getLocalizationTable.mjs';
13
13
  import IconProvider from './toolbar/IconProvider.mjs';
14
14
  import CanvasRenderer from './rendering/renderers/CanvasRenderer.mjs';
15
15
  import untilNextAnimationFrame from './util/untilNextAnimationFrame.mjs';
16
- import fileToBase64Url from './util/fileToBase64Url.mjs';
17
16
  import uniteCommands from './commands/uniteCommands.mjs';
18
17
  import SelectionTool from './tools/SelectionTool/SelectionTool.mjs';
19
18
  import Erase from './commands/Erase.mjs';
@@ -29,6 +28,7 @@ import { editorImageToSVGSync, editorImageToSVGAsync } from './image/export/ed
29
28
  import { MutableReactiveValue } from './util/ReactiveValue.mjs';
30
29
  import listenForKeyboardEventsFrom from './util/listenForKeyboardEventsFrom.mjs';
31
30
  import mitLicenseAttribution from './util/mitLicenseAttribution.mjs';
31
+ import ClipboardHandler from './util/ClipboardHandler.mjs';
32
32
  /**
33
33
  * The main entrypoint for the full editor.
34
34
  *
@@ -47,7 +47,7 @@ import mitLicenseAttribution from './util/mitLicenseAttribution.mjs';
47
47
  * ```
48
48
  *
49
49
  * See also
50
- * [`docs/example/example.ts`](https://github.com/personalizedrefrigerator/js-draw/blob/main/docs/demo/example.ts).
50
+ * * [`examples.md`](https://github.com/personalizedrefrigerator/js-draw/blob/main/docs/examples.md).
51
51
  */
52
52
  export class Editor {
53
53
  /**
@@ -109,6 +109,10 @@ export class Editor {
109
109
  iconProvider: settings.iconProvider ?? new IconProvider(),
110
110
  notices: [],
111
111
  appInfo: settings.appInfo ? { ...settings.appInfo } : null,
112
+ pens: {
113
+ additionalPenTypes: settings.pens?.additionalPenTypes ?? [],
114
+ filterPenTypes: settings.pens?.filterPenTypes ?? (() => true)
115
+ },
112
116
  };
113
117
  // Validate settings
114
118
  if (this.settings.minZoom > this.settings.maxZoom) {
@@ -189,6 +193,16 @@ export class Editor {
189
193
  }
190
194
  });
191
195
  }
196
+ /**
197
+ * @returns a shallow copy of the current settings of the editor.
198
+ *
199
+ * Do not modify.
200
+ */
201
+ getCurrentSettings() {
202
+ return {
203
+ ...this.settings,
204
+ };
205
+ }
192
206
  /**
193
207
  * @returns a reference to the editor's container.
194
208
  *
@@ -275,19 +289,12 @@ export class Editor {
275
289
  this.accessibilityControlArea.addEventListener('input', () => {
276
290
  this.accessibilityControlArea.value = '';
277
291
  });
278
- document.addEventListener('copy', evt => {
292
+ const copyHandler = new ClipboardHandler(this);
293
+ document.addEventListener('copy', async (evt) => {
279
294
  if (!this.isEventSink(document.querySelector(':focus'))) {
280
295
  return;
281
296
  }
282
- const clipboardData = evt.clipboardData;
283
- if (this.toolController.dispatchInputEvent({
284
- kind: InputEvtType.CopyEvent,
285
- setData: (mime, data) => {
286
- clipboardData?.setData(mime, data);
287
- },
288
- })) {
289
- evt.preventDefault();
290
- }
297
+ copyHandler.copy(evt);
291
298
  });
292
299
  document.addEventListener('paste', evt => {
293
300
  this.handlePaste(evt);
@@ -355,11 +362,21 @@ export class Editor {
355
362
  * (e.g. with synthetic events). @internal
356
363
  */
357
364
  setPointerCapture(target, pointerId) {
358
- target.setPointerCapture(pointerId);
365
+ try {
366
+ target.setPointerCapture(pointerId);
367
+ }
368
+ catch (error) {
369
+ console.warn('Failed to setPointerCapture', error);
370
+ }
359
371
  }
360
372
  /** Can be overridden in a testing environment to handle synthetic events. @internal */
361
373
  releasePointerCapture(target, pointerId) {
362
- target.releasePointerCapture(pointerId);
374
+ try {
375
+ target.releasePointerCapture(pointerId);
376
+ }
377
+ catch (error) {
378
+ console.warn('Failed to releasePointerCapture', error);
379
+ }
363
380
  }
364
381
  /**
365
382
  * Dispatches a `PointerEvent` to the editor. The target element for `evt` must have the same top left
@@ -385,7 +402,7 @@ export class Editor {
385
402
  if (pointer.down) {
386
403
  const prevData = this.pointers[pointer.id];
387
404
  if (prevData) {
388
- const distanceMoved = pointer.screenPos.minus(prevData.screenPos).magnitude();
405
+ const distanceMoved = pointer.screenPos.distanceTo(prevData.screenPos);
389
406
  // If the pointer moved less than two pixels, don't send a new event.
390
407
  if (distanceMoved < 2) {
391
408
  return false;
@@ -444,66 +461,7 @@ export class Editor {
444
461
  if (!this.isEventSink(target)) {
445
462
  return;
446
463
  }
447
- const clipboardData = evt.dataTransfer ?? evt.clipboardData;
448
- if (!clipboardData) {
449
- return;
450
- }
451
- // Handle SVG files (prefer to PNG/JPEG)
452
- for (const file of clipboardData.files) {
453
- if (file.type.toLowerCase() === 'image/svg+xml') {
454
- const text = await file.text();
455
- if (this.toolController.dispatchInputEvent({
456
- kind: InputEvtType.PasteEvent,
457
- mime: file.type,
458
- data: text,
459
- })) {
460
- evt.preventDefault();
461
- return;
462
- }
463
- }
464
- }
465
- // Handle image files.
466
- for (const file of clipboardData.files) {
467
- const fileType = file.type.toLowerCase();
468
- if (fileType === 'image/png' || fileType === 'image/jpg') {
469
- this.showLoadingWarning(0);
470
- const onprogress = (evt) => {
471
- this.showLoadingWarning(evt.loaded / evt.total);
472
- };
473
- try {
474
- const data = await fileToBase64Url(file, { onprogress });
475
- if (data && this.toolController.dispatchInputEvent({
476
- kind: InputEvtType.PasteEvent,
477
- mime: fileType,
478
- data: data,
479
- })) {
480
- evt.preventDefault();
481
- this.hideLoadingWarning();
482
- return;
483
- }
484
- }
485
- catch (e) {
486
- console.error('Error reading image:', e);
487
- }
488
- this.hideLoadingWarning();
489
- }
490
- }
491
- // Supported MIMEs for text data, in order of preference
492
- const supportedMIMEs = [
493
- 'image/svg+xml',
494
- 'text/plain',
495
- ];
496
- for (const mime of supportedMIMEs) {
497
- const data = clipboardData.getData(mime);
498
- if (data && this.toolController.dispatchInputEvent({
499
- kind: InputEvtType.PasteEvent,
500
- mime,
501
- data,
502
- })) {
503
- evt.preventDefault();
504
- return;
505
- }
506
- }
464
+ return await new ClipboardHandler(this).paste(evt);
507
465
  }
508
466
  /**
509
467
  * Forward pointer events from `elem` to this editor. Such that right-click/right-click drag
@@ -614,7 +572,7 @@ export class Editor {
614
572
  const eventBuffer = gestureData[pointerId].eventBuffer;
615
573
  // Skip if the pointer hasn't moved enough to not be a "click".
616
574
  const strokeStartThreshold = 10;
617
- const isWithinClickThreshold = gestureStartPos && currentPos.minus(gestureStartPos).magnitude() < strokeStartThreshold;
575
+ const isWithinClickThreshold = gestureStartPos && currentPos.distanceTo(gestureStartPos) < strokeStartThreshold;
618
576
  if (isWithinClickThreshold && !gestureData[pointerId].hasMovedSignificantly) {
619
577
  eventBuffer.push([eventName, event]);
620
578
  sendToEditor = false;
@@ -728,7 +686,8 @@ export class Editor {
728
686
  /** `apply` a command. `command` will be announced for accessibility. */
729
687
  dispatch(command, addToHistory = true) {
730
688
  const dispatchResult = this.dispatchNoAnnounce(command, addToHistory);
731
- this.announceForAccessibility(command.description(this, this.localization));
689
+ const commandDescription = command.description(this, this.localization);
690
+ this.announceForAccessibility(commandDescription);
732
691
  return dispatchResult;
733
692
  }
734
693
  /**
@@ -942,8 +901,11 @@ export class Editor {
942
901
  * This is a convenience method that creates **and applies** a single command.
943
902
  *
944
903
  * If `selectComponents` is true (the default), the components are selected.
904
+ *
905
+ * `actionDescription`, if given, should be a screenreader-friendly description of the
906
+ * reason components were added (e.g. "pasted").
945
907
  */
946
- async addAndCenterComponents(components, selectComponents = true) {
908
+ async addAndCenterComponents(components, selectComponents = true, actionDescription) {
947
909
  let bbox = null;
948
910
  for (const component of components) {
949
911
  if (bbox) {
@@ -974,7 +936,7 @@ export class Editor {
974
936
  commands.push(component.transformBy(transfm));
975
937
  }
976
938
  const applyChunkSize = 100;
977
- await this.dispatch(uniteCommands(commands, applyChunkSize), true);
939
+ await this.dispatch(uniteCommands(commands, { applyChunkSize, description: actionDescription }), true);
978
940
  if (selectComponents) {
979
941
  for (const selectionTool of this.toolController.getMatchingTools(SelectionTool)) {
980
942
  selectionTool.setEnabled(true);
@@ -994,17 +956,7 @@ export class Editor {
994
956
  * [[include:doc-pages/inline-examples/adding-an-image-and-data-urls.md]]
995
957
  */
996
958
  toDataURL(format = 'image/png', outputSize) {
997
- const canvas = document.createElement('canvas');
998
- const importExportViewport = this.image.getImportExportViewport();
999
- const exportRectSize = importExportViewport.getScreenRectSize();
1000
- const resolution = outputSize ?? exportRectSize;
1001
- canvas.width = resolution.x;
1002
- canvas.height = resolution.y;
1003
- const ctx = canvas.getContext('2d');
1004
- // Scale to ensure that the entire output is visible.
1005
- const scaleFactor = Math.min(resolution.x / exportRectSize.x, resolution.y / exportRectSize.y);
1006
- ctx.scale(scaleFactor, scaleFactor);
1007
- const renderer = new CanvasRenderer(ctx, importExportViewport);
959
+ const { element: canvas, renderer } = CanvasRenderer.fromViewport(this.image.getImportExportViewport(), { canvasSize: outputSize });
1008
960
  this.image.renderAll(renderer);
1009
961
  const dataURL = canvas.toDataURL(format);
1010
962
  return dataURL;
@@ -1097,8 +1049,59 @@ export class Editor {
1097
1049
  }
1098
1050
  return background;
1099
1051
  }
1052
+ /**
1053
+ * This is a convenience method for adding or updating the {@link BackgroundComponent}
1054
+ * and {@link EditorImage.setAutoresizeEnabled} for the current image.
1055
+ *
1056
+ * If there are multiple {@link BackgroundComponent}s in the image, this only modifies
1057
+ * the topmost such element.
1058
+ *
1059
+ * **Example**:
1060
+ * ```ts,runnable
1061
+ * import { Editor, Color4, BackgroundComponentBackgroundType } from 'js-draw';
1062
+ * const editor = new Editor(document.body);
1063
+ * editor.dispatch(editor.setBackgroundStyle({
1064
+ * color: Color4.orange,
1065
+ * type: BackgroundComponentBackgroundType.Grid,
1066
+ * autoresize: true,
1067
+ * }));
1068
+ * ```
1069
+ *
1070
+ * To change the background size, see {@link EditorImage.setImportExportRect}.
1071
+ */
1072
+ setBackgroundStyle(style) {
1073
+ const originalBackground = this.getTopmostBackgroundComponent();
1074
+ const commands = [];
1075
+ if (originalBackground) {
1076
+ commands.push(new Erase([originalBackground]));
1077
+ }
1078
+ const originalType = originalBackground?.getBackgroundType?.() ?? BackgroundType.None;
1079
+ const originalColor = originalBackground?.getStyle?.().color ?? Color4.transparent;
1080
+ const originalFillsScreen = this.image.getAutoresizeEnabled();
1081
+ const defaultType = (style.color && originalType === BackgroundType.None ? BackgroundType.SolidColor : originalType);
1082
+ const backgroundType = style.type ?? defaultType;
1083
+ const backgroundColor = style.color ?? originalColor;
1084
+ const fillsScreen = style.autoresize ?? originalFillsScreen;
1085
+ if (backgroundType !== BackgroundType.None) {
1086
+ const newBackground = new BackgroundComponent(backgroundType, backgroundColor);
1087
+ commands.push(EditorImage.addElement(newBackground));
1088
+ }
1089
+ if (fillsScreen !== originalFillsScreen) {
1090
+ commands.push(this.image.setAutoresizeEnabled(fillsScreen));
1091
+ // Avoid 0x0 backgrounds
1092
+ if (!fillsScreen && this.image.getImportExportRect().maxDimension === 0) {
1093
+ commands.push(this.image.setImportExportRect(this.image.getImportExportRect().resizedTo(Vec2.of(500, 500))));
1094
+ }
1095
+ }
1096
+ return uniteCommands(commands);
1097
+ }
1100
1098
  /**
1101
1099
  * Set the background color of the image.
1100
+ *
1101
+ * This is a convenience method for adding or updating the {@link BackgroundComponent}
1102
+ * for the current image.
1103
+ *
1104
+ * @see {@link setBackgroundStyle}
1102
1105
  */
1103
1106
  setBackgroundColor(color) {
1104
1107
  let background = this.getTopmostBackgroundComponent();
@@ -35,5 +35,6 @@ export default class Pointer {
35
35
  */
36
36
  withCanvasPosition(canvasPos: Point2, viewport: Viewport): Pointer;
37
37
  static ofEvent(evt: PointerEvent, isDown: boolean, viewport: Viewport, relativeTo?: HTMLElement): Pointer;
38
- static ofCanvasPoint(canvasPos: Point2, isDown: boolean, viewport: Viewport, id?: number, device?: PointerDevice, isPrimary?: boolean, pressure?: number | null): Pointer;
38
+ static ofCanvasPoint(canvasPos: Point2, isDown: boolean, viewport: Viewport, id?: number, device?: PointerDevice, isPrimary?: boolean, pressure?: number | null, timeStamp?: number | null): Pointer;
39
+ static ofScreenPoint(screenPos: Point2, isDown: boolean, viewport: Viewport, id?: number, device?: PointerDevice, isPrimary?: boolean, pressure?: number | null, timeStamp?: number | null): Pointer;
39
40
  }
@@ -110,9 +110,16 @@ export default class Pointer {
110
110
  }
111
111
  // Create a new Pointer from a point on the canvas.
112
112
  // Intended for unit tests.
113
- static ofCanvasPoint(canvasPos, isDown, viewport, id = 0, device = PointerDevice.Pen, isPrimary = true, pressure = null) {
113
+ static ofCanvasPoint(canvasPos, isDown, viewport, id = 0, device = PointerDevice.Pen, isPrimary = true, pressure = null, timeStamp = null) {
114
114
  const screenPos = viewport.canvasToScreen(canvasPos);
115
- const timeStamp = performance.now();
115
+ timeStamp ??= performance.now();
116
+ return new Pointer(screenPos, canvasPos, pressure, isPrimary, isDown, device, id, timeStamp);
117
+ }
118
+ // Create a new Pointer from a point on the screen.
119
+ // Intended for unit tests.
120
+ static ofScreenPoint(screenPos, isDown, viewport, id = 0, device = PointerDevice.Pen, isPrimary = true, pressure = null, timeStamp = null) {
121
+ const canvasPos = viewport.screenToCanvas(screenPos);
122
+ timeStamp ??= performance.now();
116
123
  return new Pointer(screenPos, canvasPos, pressure, isPrimary, isDown, device, id, timeStamp);
117
124
  }
118
125
  }
@@ -20,6 +20,7 @@ export interface CommandLocalization {
20
20
  duplicateAction: (elemDescription: string, count: number) => string;
21
21
  inverseOf: (actionDescription: string) => string;
22
22
  unionOf: (actionDescription: string, actionCount: number) => string;
23
+ andNMoreCommands: (count: number) => string;
23
24
  selectedElements: (count: number) => string;
24
25
  }
25
26
  export declare const defaultCommandLocalization: CommandLocalization;
@@ -19,5 +19,6 @@ export const defaultCommandLocalization = {
19
19
  movedRight: 'Moved right',
20
20
  zoomedOut: 'Zoomed out',
21
21
  zoomedIn: 'Zoomed in',
22
+ andNMoreCommands: (count) => `And ${count} more commands.`,
22
23
  selectedElements: (count) => `Selected ${count} element${count === 1 ? '' : 's'}`,
23
24
  };
@@ -1,5 +1,9 @@
1
1
  import Command from './Command';
2
2
  import SerializableCommand from './SerializableCommand';
3
+ export interface UniteCommandsOptions {
4
+ applyChunkSize?: number;
5
+ description?: string;
6
+ }
3
7
  /**
4
8
  * Creates a single command from `commands`. This is useful when undoing should undo *all* commands
5
9
  * in `commands` at once, rather than one at a time.
@@ -36,5 +40,5 @@ import SerializableCommand from './SerializableCommand';
36
40
  * // applying them shouldn't be done all at once (which would block the UI).
37
41
  * ```
38
42
  */
39
- declare const uniteCommands: <T extends Command>(commands: T[], applyChunkSize?: number) => T extends SerializableCommand ? SerializableCommand : Command;
43
+ declare const uniteCommands: <T extends Command>(commands: T[], options?: UniteCommandsOptions | number) => T extends SerializableCommand ? SerializableCommand : Command;
40
44
  export default uniteCommands;
@@ -2,10 +2,11 @@ import waitForAll from '../util/waitForAll.mjs';
2
2
  import Command from './Command.mjs';
3
3
  import SerializableCommand from './SerializableCommand.mjs';
4
4
  class NonSerializableUnion extends Command {
5
- constructor(commands, applyChunkSize) {
5
+ constructor(commands, applyChunkSize, descriptionOverride) {
6
6
  super();
7
7
  this.commands = commands;
8
8
  this.applyChunkSize = applyChunkSize;
9
+ this.descriptionOverride = descriptionOverride;
9
10
  }
10
11
  apply(editor) {
11
12
  if (this.applyChunkSize === undefined) {
@@ -31,9 +32,13 @@ class NonSerializableUnion extends Command {
31
32
  this.commands.forEach(command => command.onDrop(editor));
32
33
  }
33
34
  description(editor, localizationTable) {
35
+ if (this.descriptionOverride) {
36
+ return this.descriptionOverride;
37
+ }
34
38
  const descriptions = [];
35
39
  let lastDescription = null;
36
40
  let duplicateDescriptionCount = 0;
41
+ let handledCommandCount = 0;
37
42
  for (const part of this.commands) {
38
43
  const description = part.description(editor, localizationTable);
39
44
  if (description !== lastDescription && lastDescription !== null) {
@@ -42,7 +47,13 @@ class NonSerializableUnion extends Command {
42
47
  duplicateDescriptionCount = 0;
43
48
  }
44
49
  duplicateDescriptionCount++;
50
+ handledCommandCount++;
45
51
  lastDescription ??= description;
52
+ // Long descriptions aren't very useful to the user.
53
+ const maxDescriptionLength = 12;
54
+ if (descriptions.length > maxDescriptionLength) {
55
+ break;
56
+ }
46
57
  }
47
58
  if (duplicateDescriptionCount > 1) {
48
59
  descriptions.push(localizationTable.unionOf(lastDescription, duplicateDescriptionCount));
@@ -50,15 +61,19 @@ class NonSerializableUnion extends Command {
50
61
  else if (duplicateDescriptionCount === 1) {
51
62
  descriptions.push(lastDescription);
52
63
  }
64
+ if (handledCommandCount < this.commands.length) {
65
+ descriptions.push(localizationTable.andNMoreCommands(this.commands.length - handledCommandCount));
66
+ }
53
67
  return descriptions.join(', ');
54
68
  }
55
69
  }
56
70
  class SerializableUnion extends SerializableCommand {
57
- constructor(commands, applyChunkSize) {
71
+ constructor(commands, applyChunkSize, descriptionOverride) {
58
72
  super('union');
59
73
  this.commands = commands;
60
74
  this.applyChunkSize = applyChunkSize;
61
- this.nonserializableCommand = new NonSerializableUnion(commands, applyChunkSize);
75
+ this.descriptionOverride = descriptionOverride;
76
+ this.nonserializableCommand = new NonSerializableUnion(commands, applyChunkSize, descriptionOverride);
62
77
  }
63
78
  serializeToJSON() {
64
79
  if (this.serializedData) {
@@ -67,6 +82,7 @@ class SerializableUnion extends SerializableCommand {
67
82
  return {
68
83
  applyChunkSize: this.applyChunkSize,
69
84
  data: this.commands.map(command => command.serialize()),
85
+ description: this.descriptionOverride,
70
86
  };
71
87
  }
72
88
  apply(editor) {
@@ -120,7 +136,7 @@ class SerializableUnion extends SerializableCommand {
120
136
  * // applying them shouldn't be done all at once (which would block the UI).
121
137
  * ```
122
138
  */
123
- const uniteCommands = (commands, applyChunkSize) => {
139
+ const uniteCommands = (commands, options) => {
124
140
  let allSerializable = true;
125
141
  for (const command of commands) {
126
142
  if (!(command instanceof SerializableCommand)) {
@@ -128,12 +144,21 @@ const uniteCommands = (commands, applyChunkSize) => {
128
144
  break;
129
145
  }
130
146
  }
147
+ let applyChunkSize;
148
+ let description;
149
+ if (typeof options === 'number') {
150
+ applyChunkSize = options;
151
+ }
152
+ else {
153
+ applyChunkSize = options?.applyChunkSize;
154
+ description = options?.description;
155
+ }
131
156
  if (!allSerializable) {
132
- return new NonSerializableUnion(commands, applyChunkSize);
157
+ return new NonSerializableUnion(commands, applyChunkSize, description);
133
158
  }
134
159
  else {
135
160
  const castedCommands = commands;
136
- return new SerializableUnion(castedCommands, applyChunkSize);
161
+ return new SerializableUnion(castedCommands, applyChunkSize, description);
137
162
  }
138
163
  };
139
164
  SerializableCommand.register('union', (data, editor) => {
@@ -144,10 +169,11 @@ SerializableCommand.register('union', (data, editor) => {
144
169
  if (typeof applyChunkSize !== 'number' && applyChunkSize !== undefined) {
145
170
  throw new Error('serialized applyChunkSize is neither undefined nor a number.');
146
171
  }
172
+ const description = typeof data.description === 'string' ? data.description : undefined;
147
173
  const commands = [];
148
174
  for (const part of data.data) {
149
175
  commands.push(SerializableCommand.deserialize(part, editor));
150
176
  }
151
- return uniteCommands(commands, applyChunkSize);
177
+ return uniteCommands(commands, { applyChunkSize, description });
152
178
  });
153
179
  export default uniteCommands;
@@ -1,8 +1,9 @@
1
1
  import SerializableCommand from '../commands/SerializableCommand';
2
2
  import EditorImage from '../image/EditorImage';
3
- import { LineSegment2, Mat33, Rect2 } from '@js-draw/math';
3
+ import { LineSegment2, Mat33, Path, Rect2 } from '@js-draw/math';
4
4
  import AbstractRenderer from '../rendering/renderers/AbstractRenderer';
5
5
  import { ImageComponentLocalization } from './localization';
6
+ import Viewport from '../Viewport';
6
7
  export type LoadSaveData = (string[] | Record<symbol, string | number>);
7
8
  export type LoadSaveDataTable = Record<string, Array<LoadSaveData>>;
8
9
  export type DeserializeCallback = (data: string) => AbstractComponent;
@@ -112,7 +113,9 @@ export default abstract class AbstractComponent {
112
113
  * this function.
113
114
  */
114
115
  intersectsRect(rect: Rect2): boolean;
115
- protected abstract serializeToJSON(): any[] | Record<string, any> | number | string | null;
116
+ isSelectable(): boolean;
117
+ isBackground(): boolean;
118
+ getProportionalRenderingTime(): number;
116
119
  protected abstract applyTransformation(affineTransfm: Mat33): void;
117
120
  /**
118
121
  * Returns a command that, when applied, transforms this by [affineTransfm] and
@@ -131,9 +134,6 @@ export default abstract class AbstractComponent {
131
134
  * this command.
132
135
  */
133
136
  setZIndexAndTransformBy(affineTransfm: Mat33, newZIndex: number, originalZIndex?: number): SerializableCommand;
134
- isSelectable(): boolean;
135
- isBackground(): boolean;
136
- getProportionalRenderingTime(): number;
137
137
  private static transformElementCommandId;
138
138
  private static TransformElementCommand;
139
139
  /**
@@ -143,6 +143,18 @@ export default abstract class AbstractComponent {
143
143
  abstract description(localizationTable: ImageComponentLocalization): string;
144
144
  protected abstract createClone(): AbstractComponent;
145
145
  clone(): AbstractComponent;
146
+ /**
147
+ * **Optional method**: Divides this component into sections roughly along the given path,
148
+ * removing parts that are roughly within `shape`.
149
+ *
150
+ * **Notes**:
151
+ * - A default implementation may be provided for this method in the future. Until then,
152
+ * this method is `undefined` if unsupported.
153
+ *
154
+ * `viewport` should be provided to determine how newly-added points should be rounded.
155
+ */
156
+ withRegionErased?(shape: Path, viewport: Viewport): AbstractComponent[];
157
+ protected abstract serializeToJSON(): any[] | Record<string, any> | number | string | null;
146
158
  serialize(): {
147
159
  name: string;
148
160
  zIndex: number;
@@ -136,6 +136,21 @@ class AbstractComponent {
136
136
  const testLines = rect.getEdges();
137
137
  return testLines.some(edge => this.intersects(edge));
138
138
  }
139
+ // @returns true iff this component can be selected (e.g. by the selection tool.)
140
+ isSelectable() {
141
+ return true;
142
+ }
143
+ // @returns true iff this component should be added to the background, rather than the
144
+ // foreground of the image.
145
+ isBackground() {
146
+ return false;
147
+ }
148
+ // @returns an approximation of the proportional time it takes to render this component.
149
+ // This is intended to be a rough estimate, but, for example, a stroke with two points sould have
150
+ // a renderingWeight approximately twice that of a stroke with one point.
151
+ getProportionalRenderingTime() {
152
+ return 1;
153
+ }
139
154
  /**
140
155
  * Returns a command that, when applied, transforms this by [affineTransfm] and
141
156
  * updates the editor.
@@ -160,21 +175,6 @@ class AbstractComponent {
160
175
  setZIndexAndTransformBy(affineTransfm, newZIndex, originalZIndex) {
161
176
  return new AbstractComponent.TransformElementCommand(affineTransfm, this.getId(), this, newZIndex, originalZIndex);
162
177
  }
163
- // @returns true iff this component can be selected (e.g. by the selection tool.)
164
- isSelectable() {
165
- return true;
166
- }
167
- // @returns true iff this component should be added to the background, rather than the
168
- // foreground of the image.
169
- isBackground() {
170
- return false;
171
- }
172
- // @returns an approximation of the proportional time it takes to render this component.
173
- // This is intended to be a rough estimate, but, for example, a stroke with two points sould have
174
- // a renderingWeight approximately twice that of a stroke with one point.
175
- getProportionalRenderingTime() {
176
- return 1;
177
- }
178
178
  // Returns a copy of this component.
179
179
  clone() {
180
180
  const clone = this.createClone();
@@ -6,6 +6,7 @@ import AbstractComponent from './AbstractComponent';
6
6
  import { ImageComponentLocalization } from './localization';
7
7
  import RestyleableComponent, { ComponentStyle } from './RestylableComponent';
8
8
  import RenderablePathSpec, { RenderablePathSpecWithPath } from '../rendering/RenderablePathSpec';
9
+ import Viewport from '../Viewport';
9
10
  /**
10
11
  * Represents an {@link AbstractComponent} made up of one or more {@link Path}s.
11
12
  *
@@ -46,10 +47,12 @@ export default class Stroke extends AbstractComponent implements RestyleableComp
46
47
  * ]);
47
48
  * ```
48
49
  */
49
- constructor(parts: RenderablePathSpec[]);
50
+ constructor(parts: RenderablePathSpec[], initialZIndex?: number);
50
51
  getStyle(): ComponentStyle;
51
52
  updateStyle(style: ComponentStyle): SerializableCommand;
52
53
  forceStyle(style: ComponentStyle, editor: Editor | null): void;
54
+ /** @beta -- May fail for concave `path`s */
55
+ withRegionErased(eraserPath: Path, viewport: Viewport): Stroke[];
53
56
  intersects(line: LineSegment2): boolean;
54
57
  intersectsRect(rect: Rect2): boolean;
55
58
  private simplifiedPath;