js-draw 1.21.1 → 1.21.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (187) hide show
  1. package/dist/Editor.css +4 -2
  2. package/dist/bundle.js +2 -2
  3. package/dist/bundledStyles.js +1 -1
  4. package/dist/cjs/toolbar/widgets/InsertImageWidget/ImageWrapper.d.ts +1 -1
  5. package/dist/cjs/tools/BaseTool.d.ts +61 -0
  6. package/dist/cjs/tools/BaseTool.js +179 -0
  7. package/dist/cjs/tools/Eraser.d.ts +60 -0
  8. package/dist/cjs/tools/Eraser.js +299 -0
  9. package/dist/cjs/tools/Eraser.test.d.ts +1 -0
  10. package/dist/cjs/tools/FindTool.d.ts +21 -0
  11. package/dist/cjs/tools/FindTool.js +137 -0
  12. package/dist/cjs/tools/FindTool.test.d.ts +1 -0
  13. package/dist/cjs/tools/InputFilter/ContextMenuRecognizer.d.ts +17 -0
  14. package/dist/cjs/tools/InputFilter/ContextMenuRecognizer.js +105 -0
  15. package/dist/cjs/tools/InputFilter/ContextMenuRecognizer.test.d.ts +1 -0
  16. package/dist/cjs/tools/InputFilter/FunctionMapper.d.ts +12 -0
  17. package/dist/cjs/tools/InputFilter/FunctionMapper.js +21 -0
  18. package/dist/cjs/tools/InputFilter/InputMapper.d.ts +23 -0
  19. package/dist/cjs/tools/InputFilter/InputMapper.js +38 -0
  20. package/dist/cjs/tools/InputFilter/InputPipeline.d.ts +15 -0
  21. package/dist/cjs/tools/InputFilter/InputPipeline.js +54 -0
  22. package/dist/cjs/tools/InputFilter/InputPipeline.test.d.ts +1 -0
  23. package/dist/cjs/tools/InputFilter/InputStabilizer.d.ts +29 -0
  24. package/dist/cjs/tools/InputFilter/InputStabilizer.js +181 -0
  25. package/dist/cjs/tools/InputFilter/StrokeKeyboardControl.d.ts +21 -0
  26. package/dist/cjs/tools/InputFilter/StrokeKeyboardControl.js +84 -0
  27. package/dist/cjs/tools/PanZoom.d.ts +125 -0
  28. package/dist/cjs/tools/PanZoom.js +517 -0
  29. package/dist/cjs/tools/PanZoom.test.d.ts +1 -0
  30. package/dist/cjs/tools/PasteHandler.d.ts +23 -0
  31. package/dist/cjs/tools/PasteHandler.js +109 -0
  32. package/dist/cjs/tools/Pen.d.ts +54 -0
  33. package/dist/cjs/tools/Pen.js +335 -0
  34. package/dist/cjs/tools/Pen.test.d.ts +1 -0
  35. package/dist/cjs/tools/PipetteTool.d.ts +28 -0
  36. package/dist/cjs/tools/PipetteTool.js +69 -0
  37. package/dist/cjs/tools/ScrollbarTool.d.ts +18 -0
  38. package/dist/cjs/tools/ScrollbarTool.js +85 -0
  39. package/dist/cjs/tools/SelectionTool/SelectAllShortcutHandler.d.ts +9 -0
  40. package/dist/cjs/tools/SelectionTool/SelectAllShortcutHandler.js +32 -0
  41. package/dist/cjs/tools/SelectionTool/Selection.d.ts +72 -0
  42. package/dist/cjs/tools/SelectionTool/Selection.js +634 -0
  43. package/dist/cjs/tools/SelectionTool/SelectionHandle.d.ts +62 -0
  44. package/dist/cjs/tools/SelectionTool/SelectionHandle.js +141 -0
  45. package/dist/cjs/tools/SelectionTool/SelectionMenuShortcut.d.ts +32 -0
  46. package/dist/cjs/tools/SelectionTool/SelectionMenuShortcut.js +86 -0
  47. package/dist/cjs/tools/SelectionTool/SelectionTool.d.ts +42 -0
  48. package/dist/cjs/tools/SelectionTool/SelectionTool.js +500 -0
  49. package/dist/cjs/tools/SelectionTool/SelectionTool.selecting.test.d.ts +1 -0
  50. package/dist/cjs/tools/SelectionTool/SelectionTool.test.d.ts +1 -0
  51. package/dist/cjs/tools/SelectionTool/ToPointerAutoscroller.d.ts +23 -0
  52. package/dist/cjs/tools/SelectionTool/ToPointerAutoscroller.js +83 -0
  53. package/dist/cjs/tools/SelectionTool/TransformMode.d.ts +42 -0
  54. package/dist/cjs/tools/SelectionTool/TransformMode.js +155 -0
  55. package/dist/cjs/tools/SelectionTool/keybindings.d.ts +15 -0
  56. package/dist/cjs/tools/SelectionTool/keybindings.js +38 -0
  57. package/dist/cjs/tools/SelectionTool/types.d.ts +35 -0
  58. package/dist/cjs/tools/SelectionTool/types.js +14 -0
  59. package/dist/cjs/tools/SelectionTool/util/makeClipboardErrorHandlers.d.ts +6 -0
  60. package/dist/cjs/tools/SelectionTool/util/makeClipboardErrorHandlers.js +50 -0
  61. package/dist/cjs/tools/SelectionTool/util/showSelectionContextMenu.d.ts +5 -0
  62. package/dist/cjs/tools/SelectionTool/util/showSelectionContextMenu.js +43 -0
  63. package/dist/cjs/tools/SoundUITool.d.ts +26 -0
  64. package/dist/cjs/tools/SoundUITool.js +171 -0
  65. package/dist/cjs/tools/TextTool.d.ts +36 -0
  66. package/dist/cjs/tools/TextTool.js +285 -0
  67. package/dist/cjs/tools/TextTool.test.d.ts +1 -0
  68. package/dist/cjs/tools/ToolController.d.ts +73 -0
  69. package/dist/cjs/tools/ToolController.js +304 -0
  70. package/dist/cjs/tools/ToolController.test.d.ts +1 -0
  71. package/dist/cjs/tools/ToolEnabledGroup.d.ts +6 -0
  72. package/dist/cjs/tools/ToolEnabledGroup.js +13 -0
  73. package/dist/cjs/tools/ToolSwitcherShortcut.d.ts +16 -0
  74. package/dist/cjs/tools/ToolSwitcherShortcut.js +40 -0
  75. package/dist/cjs/tools/ToolbarShortcutHandler.d.ts +12 -0
  76. package/dist/cjs/tools/ToolbarShortcutHandler.js +34 -0
  77. package/dist/cjs/tools/UndoRedoShortcut.d.ts +8 -0
  78. package/dist/cjs/tools/UndoRedoShortcut.js +27 -0
  79. package/dist/cjs/tools/UndoRedoShortcut.test.d.ts +1 -0
  80. package/dist/cjs/tools/keybindings.d.ts +16 -0
  81. package/dist/cjs/tools/keybindings.js +58 -0
  82. package/dist/cjs/tools/lib.d.ts +14 -0
  83. package/dist/cjs/tools/lib.js +36 -0
  84. package/dist/cjs/tools/localization.d.ts +43 -0
  85. package/dist/cjs/tools/localization.js +45 -0
  86. package/dist/cjs/tools/util/StationaryPenDetector.d.ts +25 -0
  87. package/dist/cjs/tools/util/StationaryPenDetector.js +107 -0
  88. package/dist/cjs/tools/util/createMenuOverlay.d.ts +10 -0
  89. package/dist/cjs/tools/util/createMenuOverlay.js +126 -0
  90. package/dist/cjs/tools/util/createMenuOverlay.test.d.ts +1 -0
  91. package/dist/cjs/version.js +1 -1
  92. package/dist/mjs/toolbar/widgets/InsertImageWidget/ImageWrapper.d.ts +1 -1
  93. package/dist/mjs/tools/BaseTool.d.ts +61 -0
  94. package/dist/mjs/tools/BaseTool.mjs +177 -0
  95. package/dist/mjs/tools/Eraser.d.ts +60 -0
  96. package/dist/mjs/tools/Eraser.mjs +292 -0
  97. package/dist/mjs/tools/Eraser.test.d.ts +1 -0
  98. package/dist/mjs/tools/FindTool.d.ts +21 -0
  99. package/dist/mjs/tools/FindTool.mjs +131 -0
  100. package/dist/mjs/tools/FindTool.test.d.ts +1 -0
  101. package/dist/mjs/tools/InputFilter/ContextMenuRecognizer.d.ts +17 -0
  102. package/dist/mjs/tools/InputFilter/ContextMenuRecognizer.mjs +76 -0
  103. package/dist/mjs/tools/InputFilter/ContextMenuRecognizer.test.d.ts +1 -0
  104. package/dist/mjs/tools/InputFilter/FunctionMapper.d.ts +12 -0
  105. package/dist/mjs/tools/InputFilter/FunctionMapper.mjs +15 -0
  106. package/dist/mjs/tools/InputFilter/InputMapper.d.ts +23 -0
  107. package/dist/mjs/tools/InputFilter/InputMapper.mjs +36 -0
  108. package/dist/mjs/tools/InputFilter/InputPipeline.d.ts +15 -0
  109. package/dist/mjs/tools/InputFilter/InputPipeline.mjs +49 -0
  110. package/dist/mjs/tools/InputFilter/InputPipeline.test.d.ts +1 -0
  111. package/dist/mjs/tools/InputFilter/InputStabilizer.d.ts +29 -0
  112. package/dist/mjs/tools/InputFilter/InputStabilizer.mjs +175 -0
  113. package/dist/mjs/tools/InputFilter/StrokeKeyboardControl.d.ts +21 -0
  114. package/dist/mjs/tools/InputFilter/StrokeKeyboardControl.mjs +78 -0
  115. package/dist/mjs/tools/PanZoom.d.ts +125 -0
  116. package/dist/mjs/tools/PanZoom.mjs +510 -0
  117. package/dist/mjs/tools/PanZoom.test.d.ts +1 -0
  118. package/dist/mjs/tools/PasteHandler.d.ts +23 -0
  119. package/dist/mjs/tools/PasteHandler.mjs +103 -0
  120. package/dist/mjs/tools/Pen.d.ts +54 -0
  121. package/dist/mjs/tools/Pen.mjs +306 -0
  122. package/dist/mjs/tools/Pen.test.d.ts +1 -0
  123. package/dist/mjs/tools/PipetteTool.d.ts +28 -0
  124. package/dist/mjs/tools/PipetteTool.mjs +63 -0
  125. package/dist/mjs/tools/ScrollbarTool.d.ts +18 -0
  126. package/dist/mjs/tools/ScrollbarTool.mjs +79 -0
  127. package/dist/mjs/tools/SelectionTool/SelectAllShortcutHandler.d.ts +9 -0
  128. package/dist/mjs/tools/SelectionTool/SelectAllShortcutHandler.mjs +26 -0
  129. package/dist/mjs/tools/SelectionTool/Selection.d.ts +72 -0
  130. package/dist/mjs/tools/SelectionTool/Selection.mjs +606 -0
  131. package/dist/mjs/tools/SelectionTool/SelectionHandle.d.ts +62 -0
  132. package/dist/mjs/tools/SelectionTool/SelectionHandle.mjs +137 -0
  133. package/dist/mjs/tools/SelectionTool/SelectionMenuShortcut.d.ts +32 -0
  134. package/dist/mjs/tools/SelectionTool/SelectionMenuShortcut.mjs +83 -0
  135. package/dist/mjs/tools/SelectionTool/SelectionTool.d.ts +42 -0
  136. package/dist/mjs/tools/SelectionTool/SelectionTool.mjs +493 -0
  137. package/dist/mjs/tools/SelectionTool/SelectionTool.selecting.test.d.ts +1 -0
  138. package/dist/mjs/tools/SelectionTool/SelectionTool.test.d.ts +1 -0
  139. package/dist/mjs/tools/SelectionTool/ToPointerAutoscroller.d.ts +23 -0
  140. package/dist/mjs/tools/SelectionTool/ToPointerAutoscroller.mjs +77 -0
  141. package/dist/mjs/tools/SelectionTool/TransformMode.d.ts +42 -0
  142. package/dist/mjs/tools/SelectionTool/TransformMode.mjs +146 -0
  143. package/dist/mjs/tools/SelectionTool/keybindings.d.ts +15 -0
  144. package/dist/mjs/tools/SelectionTool/keybindings.mjs +32 -0
  145. package/dist/mjs/tools/SelectionTool/types.d.ts +35 -0
  146. package/dist/mjs/tools/SelectionTool/types.mjs +11 -0
  147. package/dist/mjs/tools/SelectionTool/util/makeClipboardErrorHandlers.d.ts +6 -0
  148. package/dist/mjs/tools/SelectionTool/util/makeClipboardErrorHandlers.mjs +45 -0
  149. package/dist/mjs/tools/SelectionTool/util/showSelectionContextMenu.d.ts +5 -0
  150. package/dist/mjs/tools/SelectionTool/util/showSelectionContextMenu.mjs +38 -0
  151. package/dist/mjs/tools/SoundUITool.d.ts +26 -0
  152. package/dist/mjs/tools/SoundUITool.mjs +165 -0
  153. package/dist/mjs/tools/TextTool.d.ts +36 -0
  154. package/dist/mjs/tools/TextTool.mjs +279 -0
  155. package/dist/mjs/tools/TextTool.test.d.ts +1 -0
  156. package/dist/mjs/tools/ToolController.d.ts +73 -0
  157. package/dist/mjs/tools/ToolController.mjs +275 -0
  158. package/dist/mjs/tools/ToolController.test.d.ts +1 -0
  159. package/dist/mjs/tools/ToolEnabledGroup.d.ts +6 -0
  160. package/dist/mjs/tools/ToolEnabledGroup.mjs +10 -0
  161. package/dist/mjs/tools/ToolSwitcherShortcut.d.ts +16 -0
  162. package/dist/mjs/tools/ToolSwitcherShortcut.mjs +34 -0
  163. package/dist/mjs/tools/ToolbarShortcutHandler.d.ts +12 -0
  164. package/dist/mjs/tools/ToolbarShortcutHandler.mjs +28 -0
  165. package/dist/mjs/tools/UndoRedoShortcut.d.ts +8 -0
  166. package/dist/mjs/tools/UndoRedoShortcut.mjs +21 -0
  167. package/dist/mjs/tools/UndoRedoShortcut.test.d.ts +1 -0
  168. package/dist/mjs/tools/keybindings.d.ts +16 -0
  169. package/dist/mjs/tools/keybindings.mjs +38 -0
  170. package/dist/mjs/tools/lib.d.ts +14 -0
  171. package/dist/mjs/tools/lib.mjs +14 -0
  172. package/dist/mjs/tools/localization.d.ts +43 -0
  173. package/dist/mjs/tools/localization.mjs +42 -0
  174. package/dist/mjs/tools/util/StationaryPenDetector.d.ts +25 -0
  175. package/dist/mjs/tools/util/StationaryPenDetector.mjs +103 -0
  176. package/dist/mjs/tools/util/createMenuOverlay.d.ts +10 -0
  177. package/dist/mjs/tools/util/createMenuOverlay.mjs +121 -0
  178. package/dist/mjs/tools/util/createMenuOverlay.test.d.ts +1 -0
  179. package/dist/mjs/version.mjs +1 -1
  180. package/package.json +4 -4
  181. package/src/tools/FindTool.css +7 -0
  182. package/src/tools/ScrollbarTool.scss +57 -0
  183. package/src/tools/SelectionTool/SelectionTool.scss +165 -0
  184. package/src/tools/SelectionTool/util/makeClipboardErrorHandlers.scss +15 -0
  185. package/src/tools/SoundUITool.scss +22 -0
  186. package/src/tools/tools.scss +6 -0
  187. package/src/tools/util/createMenuOverlay.scss +67 -0
@@ -0,0 +1,606 @@
1
+ /**
2
+ * @internal
3
+ * @packageDocumentation
4
+ */
5
+ var _a;
6
+ import SerializableCommand from '../../commands/SerializableCommand.mjs';
7
+ import { Mat33, Rect2, Vec2 } from '@js-draw/math';
8
+ import SelectionHandle, { HandleAction, handleSize } from './SelectionHandle.mjs';
9
+ import { cssPrefix } from './SelectionTool.mjs';
10
+ import Viewport from '../../Viewport.mjs';
11
+ import Erase from '../../commands/Erase.mjs';
12
+ import Duplicate from '../../commands/Duplicate.mjs';
13
+ import { DragTransformer, ResizeTransformer, RotateTransformer } from './TransformMode.mjs';
14
+ import { ResizeMode } from './types.mjs';
15
+ import EditorImage from '../../image/EditorImage.mjs';
16
+ import uniteCommands from '../../commands/uniteCommands.mjs';
17
+ import SelectionMenuShortcut from './SelectionMenuShortcut.mjs';
18
+ const updateChunkSize = 100;
19
+ const maxPreviewElemCount = 500;
20
+ // @internal
21
+ class Selection {
22
+ constructor(startPoint, editor, showContextMenu) {
23
+ this.editor = editor;
24
+ // The last-computed bounding box of selected content
25
+ // @see getTightBoundingBox
26
+ this.selectionTightBoundingBox = null;
27
+ this.transform = Mat33.identity;
28
+ // invariant: sorted by increasing z-index
29
+ this.selectedElems = [];
30
+ this.hasParent = true;
31
+ // Maps IDs to whether we removed the component from the image
32
+ this.removedFromImage = {};
33
+ this.activeHandle = null;
34
+ this.backgroundDragging = false;
35
+ this.selectionDuplicatedAnimationTimeout = null;
36
+ this.originalRegion = new Rect2(startPoint.x, startPoint.y, 0, 0);
37
+ this.transformers = {
38
+ drag: new DragTransformer(editor, this),
39
+ resize: new ResizeTransformer(editor, this),
40
+ rotate: new RotateTransformer(editor, this),
41
+ };
42
+ // We need two containers for some CSS to apply (the outer container
43
+ // needs zero height, the inner needs to prevent the selection background
44
+ // from being visible outside of the editor).
45
+ this.outerContainer = document.createElement('div');
46
+ this.outerContainer.classList.add(`${cssPrefix}selection-outer-container`);
47
+ this.innerContainer = document.createElement('div');
48
+ this.innerContainer.classList.add(`${cssPrefix}selection-inner-container`);
49
+ this.backgroundElem = document.createElement('div');
50
+ this.backgroundElem.classList.add(`${cssPrefix}selection-background`);
51
+ this.innerContainer.appendChild(this.backgroundElem);
52
+ this.outerContainer.appendChild(this.innerContainer);
53
+ const makeResizeHandle = (mode, side) => {
54
+ const modeToAction = {
55
+ [ResizeMode.Both]: HandleAction.ResizeXY,
56
+ [ResizeMode.HorizontalOnly]: HandleAction.ResizeX,
57
+ [ResizeMode.VerticalOnly]: HandleAction.ResizeY,
58
+ };
59
+ return new SelectionHandle({
60
+ action: modeToAction[mode],
61
+ side,
62
+ }, this, this.editor.viewport, (startPoint) => this.transformers.resize.onDragStart(startPoint, mode), (currentPoint) => this.transformers.resize.onDragUpdate(currentPoint), () => this.transformers.resize.onDragEnd());
63
+ };
64
+ const resizeHorizontalHandles = [
65
+ makeResizeHandle(ResizeMode.HorizontalOnly, Vec2.of(0, 0.5)),
66
+ makeResizeHandle(ResizeMode.HorizontalOnly, Vec2.of(1, 0.5)),
67
+ ];
68
+ const resizeVerticalHandle = makeResizeHandle(ResizeMode.VerticalOnly, Vec2.of(0.5, 1));
69
+ const resizeBothHandle = makeResizeHandle(ResizeMode.Both, Vec2.of(1, 1));
70
+ const rotationHandle = new SelectionHandle({
71
+ action: HandleAction.Rotate,
72
+ side: Vec2.of(0.5, 0),
73
+ icon: this.editor.icons.makeRotateIcon(),
74
+ }, this, this.editor.viewport, (startPoint) => this.transformers.rotate.onDragStart(startPoint), (currentPoint) => this.transformers.rotate.onDragUpdate(currentPoint), () => this.transformers.rotate.onDragEnd());
75
+ const menuToggleButton = new SelectionMenuShortcut(this, this.editor.viewport, showContextMenu, this.editor.localization);
76
+ this.childwidgets = [
77
+ resizeBothHandle,
78
+ ...resizeHorizontalHandles,
79
+ resizeVerticalHandle,
80
+ rotationHandle,
81
+ menuToggleButton,
82
+ ];
83
+ for (const widget of this.childwidgets) {
84
+ widget.addTo(this.backgroundElem);
85
+ }
86
+ this.updateUI();
87
+ }
88
+ // @internal Intended for unit tests
89
+ getBackgroundElem() {
90
+ return this.backgroundElem;
91
+ }
92
+ getTransform() {
93
+ return this.transform;
94
+ }
95
+ get preTransformRegion() {
96
+ return this.originalRegion;
97
+ }
98
+ // The **canvas** region.
99
+ get region() {
100
+ // TODO: This currently assumes that the region rotates about its center.
101
+ // This may not be true.
102
+ const rotationMatrix = Mat33.zRotation(this.regionRotation, this.originalRegion.center);
103
+ const scaleAndTranslateMat = this.transform.rightMul(rotationMatrix.inverse());
104
+ return this.originalRegion.transformedBoundingBox(scaleAndTranslateMat);
105
+ }
106
+ /**
107
+ * Computes and returns the bounding box of the selection without
108
+ * any additional padding. Computes directly from the elements that are selected.
109
+ * @internal
110
+ */
111
+ computeTightBoundingBox() {
112
+ const bbox = this.selectedElems.reduce((accumulator, elem) => {
113
+ return (accumulator ?? elem.getBBox()).union(elem.getBBox());
114
+ }, null);
115
+ return bbox ?? Rect2.empty;
116
+ }
117
+ get regionRotation() {
118
+ return this.transform.transformVec3(Vec2.unitX).angle();
119
+ }
120
+ get preTransformedScreenRegion() {
121
+ const toScreen = (vec) => this.editor.viewport.canvasToScreen(vec);
122
+ return Rect2.fromCorners(toScreen(this.preTransformRegion.topLeft), toScreen(this.preTransformRegion.bottomRight));
123
+ }
124
+ get preTransformedScreenRegionRotation() {
125
+ return this.editor.viewport.getRotationAngle();
126
+ }
127
+ getScreenRegion() {
128
+ const toScreen = this.editor.viewport.canvasToScreenTransform;
129
+ const scaleFactor = this.editor.viewport.getScaleFactor();
130
+ const screenCenter = toScreen.transformVec2(this.region.center);
131
+ return new Rect2(screenCenter.x, screenCenter.y, scaleFactor * this.region.width, scaleFactor * this.region.height).translatedBy(this.region.size.times(-scaleFactor / 2));
132
+ }
133
+ get screenRegionRotation() {
134
+ return this.regionRotation + this.editor.viewport.getRotationAngle();
135
+ }
136
+ // Applies, previews, but doesn't finalize the given transformation.
137
+ setTransform(transform, preview = true) {
138
+ this.transform = transform;
139
+ if (preview && this.hasParent) {
140
+ this.previewTransformCmds();
141
+ }
142
+ }
143
+ getDeltaZIndexToMoveSelectionToTop() {
144
+ if (this.selectedElems.length === 0) {
145
+ return 0;
146
+ }
147
+ const selectedBottommostZIndex = this.selectedElems[0].getZIndex();
148
+ const visibleObjects = this.editor.image.getElementsIntersectingRegion(this.region);
149
+ const topMostVisibleZIndex = visibleObjects[visibleObjects.length - 1]?.getZIndex() ?? selectedBottommostZIndex;
150
+ const deltaZIndex = (topMostVisibleZIndex + 1) - selectedBottommostZIndex;
151
+ return deltaZIndex;
152
+ }
153
+ // Applies the current transformation to the selection
154
+ finalizeTransform() {
155
+ const fullTransform = this.transform;
156
+ const selectedElems = this.selectedElems;
157
+ // Reset for the next drag
158
+ this.originalRegion = this.originalRegion.transformedBoundingBox(this.transform);
159
+ this.transform = Mat33.identity;
160
+ this.scrollTo();
161
+ let transformPromise = undefined;
162
+ // Make the commands undo-able.
163
+ // Don't check for non-empty transforms because this breaks changing the
164
+ // z-index of the just-transformed commands.
165
+ if (this.selectedElems.length > 0) {
166
+ const deltaZIndex = this.getDeltaZIndexToMoveSelectionToTop();
167
+ transformPromise = this.editor.dispatch(new _a.ApplyTransformationCommand(this, selectedElems, fullTransform, deltaZIndex));
168
+ }
169
+ return transformPromise;
170
+ }
171
+ /** Sends all selected elements to the bottom of the visible image. */
172
+ sendToBack() {
173
+ const visibleObjects = this.editor.image.getElementsIntersectingRegion(this.editor.viewport.visibleRect);
174
+ // VisibleObjects and selectedElems should both be sorted by z-index
175
+ const lowestVisibleZIndex = visibleObjects[0]?.getZIndex() ?? 0;
176
+ const highestSelectedZIndex = this.selectedElems[this.selectedElems.length - 1]?.getZIndex() ?? 0;
177
+ const targetHighestZIndex = lowestVisibleZIndex - 1;
178
+ const deltaZIndex = targetHighestZIndex - highestSelectedZIndex;
179
+ if (deltaZIndex !== 0) {
180
+ const commands = this.selectedElems.map(elem => {
181
+ return elem.setZIndex(elem.getZIndex() + deltaZIndex);
182
+ });
183
+ return uniteCommands(commands, updateChunkSize);
184
+ }
185
+ return null;
186
+ }
187
+ // Preview the effects of the current transformation on the selection
188
+ previewTransformCmds() {
189
+ if (this.selectedElems.length === 0) {
190
+ return;
191
+ }
192
+ // Don't render what we're moving if it's likely to be slow.
193
+ if (this.selectedElems.length > maxPreviewElemCount) {
194
+ this.updateUI();
195
+ return;
196
+ }
197
+ const wetInkRenderer = this.editor.display.getWetInkRenderer();
198
+ wetInkRenderer.clear();
199
+ wetInkRenderer.pushTransform(this.transform);
200
+ const viewportVisibleRect = this.editor.viewport.visibleRect.union(this.region);
201
+ const visibleRect = viewportVisibleRect.transformedBoundingBox(this.transform.inverse());
202
+ for (const elem of this.selectedElems) {
203
+ elem.render(wetInkRenderer, visibleRect);
204
+ }
205
+ wetInkRenderer.popTransform();
206
+ this.updateUI();
207
+ }
208
+ // Find the objects corresponding to this in the document,
209
+ // select them.
210
+ // Returns false iff nothing was selected.
211
+ resolveToObjects() {
212
+ let singleItemSelectionMode = false;
213
+ this.transform = Mat33.identity;
214
+ // Grow the rectangle, if necessary
215
+ if (this.region.w === 0 || this.region.h === 0) {
216
+ const padding = this.editor.viewport.visibleRect.maxDimension / 200;
217
+ this.originalRegion = Rect2.bboxOf(this.region.corners, padding);
218
+ // Only select one item if the rectangle was very small.
219
+ singleItemSelectionMode = true;
220
+ }
221
+ this.selectedElems = this.editor.image.getElementsIntersectingRegion(this.region).filter(elem => {
222
+ return elem.intersectsRect(this.region) && elem.isSelectable();
223
+ });
224
+ if (singleItemSelectionMode && this.selectedElems.length > 0) {
225
+ this.selectedElems = [this.selectedElems[this.selectedElems.length - 1]];
226
+ }
227
+ // Find the bounding box of all selected elements.
228
+ if (!this.recomputeRegion()) {
229
+ return false;
230
+ }
231
+ this.updateUI();
232
+ return true;
233
+ }
234
+ // Recompute this' region from the selected elements.
235
+ // Returns false if the selection is empty.
236
+ recomputeRegion() {
237
+ const newRegion = this.computeTightBoundingBox();
238
+ this.selectionTightBoundingBox = newRegion;
239
+ if (!newRegion) {
240
+ this.cancelSelection();
241
+ return false;
242
+ }
243
+ this.originalRegion = newRegion;
244
+ this.padRegion();
245
+ return true;
246
+ }
247
+ // Applies padding to the current region if it is too small.
248
+ // @internal
249
+ padRegion() {
250
+ const sourceRegion = this.selectionTightBoundingBox ?? this.originalRegion;
251
+ const minSize = this.getMinCanvasSize();
252
+ if (sourceRegion.w < minSize || sourceRegion.h < minSize) {
253
+ // Add padding
254
+ const padding = minSize / 2;
255
+ this.originalRegion = Rect2.bboxOf(sourceRegion.corners, padding);
256
+ this.updateUI();
257
+ }
258
+ }
259
+ getMinCanvasSize() {
260
+ const canvasHandleSize = handleSize / this.editor.viewport.getScaleFactor();
261
+ return canvasHandleSize * 2;
262
+ }
263
+ getSelectedItemCount() {
264
+ return this.selectedElems.length;
265
+ }
266
+ // @internal
267
+ updateUI() {
268
+ // Don't update old selections.
269
+ if (!this.hasParent) {
270
+ return;
271
+ }
272
+ const screenRegion = this.getScreenRegion();
273
+ // marginLeft, marginTop: Display relative to the top left of the selection overlay.
274
+ // left, top don't work for this.
275
+ this.backgroundElem.style.marginLeft = `${screenRegion.topLeft.x}px`;
276
+ this.backgroundElem.style.marginTop = `${screenRegion.topLeft.y}px`;
277
+ this.backgroundElem.style.width = `${screenRegion.width}px`;
278
+ this.backgroundElem.style.height = `${screenRegion.height}px`;
279
+ const rotationDeg = this.screenRegionRotation * 180 / Math.PI;
280
+ this.backgroundElem.style.transform = `rotate(${rotationDeg}deg)`;
281
+ this.backgroundElem.style.transformOrigin = 'center';
282
+ // If closer to perpendicular, apply different CSS
283
+ const perpendicularClassName = `${cssPrefix}rotated-near-perpendicular`;
284
+ if (Math.abs(Math.sin(this.screenRegionRotation)) > 0.5) {
285
+ this.innerContainer.classList.add(perpendicularClassName);
286
+ }
287
+ else {
288
+ this.innerContainer.classList.remove(perpendicularClassName);
289
+ }
290
+ // Hide handles when empty
291
+ if (screenRegion.width === 0 && screenRegion.height === 0) {
292
+ this.innerContainer.classList.add('-empty');
293
+ }
294
+ else {
295
+ this.innerContainer.classList.remove('-empty');
296
+ }
297
+ for (const widget of this.childwidgets) {
298
+ widget.updatePosition(this.getScreenRegion());
299
+ }
300
+ }
301
+ // Add/remove the contents of this seleciton from the editor.
302
+ // Used to prevent previewed content from looking like duplicate content
303
+ // while dragging.
304
+ //
305
+ // Does nothing if a large number of elements are selected (and so modifying
306
+ // the editor image is likely to be slow.)
307
+ //
308
+ // If removed from the image, selected elements are drawn as wet ink.
309
+ //
310
+ // [inImage] should be `true` if the selected elements should be added to the
311
+ // main image, `false` if they should be removed.
312
+ addRemoveSelectionFromImage(inImage) {
313
+ // Don't hide elements if doing so will be slow.
314
+ if (!inImage && this.selectedElems.length > maxPreviewElemCount) {
315
+ return;
316
+ }
317
+ for (const elem of this.selectedElems) {
318
+ const parent = this.editor.image.findParent(elem);
319
+ if (!inImage && parent) {
320
+ this.removedFromImage[elem.getId()] = true;
321
+ parent.remove();
322
+ }
323
+ // If we're making things visible and the selected object wasn't previously
324
+ // visible,
325
+ else if (!parent && this.removedFromImage[elem.getId()]) {
326
+ EditorImage.addElement(elem).apply(this.editor);
327
+ this.removedFromImage[elem.getId()] = false;
328
+ delete this.removedFromImage[elem.getId()];
329
+ }
330
+ }
331
+ // Don't await queueRerender. If we're running in a test, the re-render might never
332
+ // happen.
333
+ this.editor.queueRerender().then(() => {
334
+ if (!inImage) {
335
+ this.previewTransformCmds();
336
+ }
337
+ else {
338
+ // Clear renderings of any in-progress transformations
339
+ const wetInkRenderer = this.editor.display.getWetInkRenderer();
340
+ wetInkRenderer.clear();
341
+ }
342
+ });
343
+ }
344
+ removeDeletedElemsFromSelection() {
345
+ // Remove any deleted elements from the selection.
346
+ this.selectedElems = this.selectedElems.filter(elem => {
347
+ const hasParent = !!this.editor.image.findParent(elem);
348
+ // If we removed the element and haven't added it back yet, don't remove it
349
+ // from the selection.
350
+ const weRemoved = this.removedFromImage[elem.getId()];
351
+ return hasParent || weRemoved;
352
+ });
353
+ }
354
+ onDragStart(pointer) {
355
+ // Clear the HTML selection (prevent HTML drag and drop being triggered by this drag)
356
+ document.getSelection()?.removeAllRanges();
357
+ this.activeHandle = null;
358
+ let result = false;
359
+ this.backgroundDragging = false;
360
+ if (this.region.containsPoint(pointer.canvasPos)) {
361
+ this.backgroundDragging = true;
362
+ result = true;
363
+ }
364
+ for (const widget of this.childwidgets) {
365
+ if (widget.containsPoint(pointer.canvasPos)) {
366
+ this.activeHandle = widget;
367
+ this.backgroundDragging = false;
368
+ result = true;
369
+ }
370
+ }
371
+ if (result) {
372
+ this.removeDeletedElemsFromSelection();
373
+ this.addRemoveSelectionFromImage(false);
374
+ }
375
+ if (this.activeHandle) {
376
+ this.activeHandle.handleDragStart(pointer);
377
+ }
378
+ if (this.backgroundDragging) {
379
+ this.transformers.drag.onDragStart(pointer.canvasPos);
380
+ }
381
+ return result;
382
+ }
383
+ onDragUpdate(pointer) {
384
+ if (this.backgroundDragging) {
385
+ this.transformers.drag.onDragUpdate(pointer.canvasPos);
386
+ }
387
+ if (this.activeHandle) {
388
+ this.activeHandle.handleDragUpdate(pointer);
389
+ }
390
+ }
391
+ onDragEnd() {
392
+ if (this.backgroundDragging) {
393
+ this.transformers.drag.onDragEnd();
394
+ }
395
+ else if (this.activeHandle) {
396
+ this.activeHandle.handleDragEnd();
397
+ }
398
+ this.addRemoveSelectionFromImage(true);
399
+ this.backgroundDragging = false;
400
+ this.activeHandle = null;
401
+ this.updateUI();
402
+ }
403
+ onDragCancel() {
404
+ this.backgroundDragging = false;
405
+ this.activeHandle = null;
406
+ this.setTransform(Mat33.identity);
407
+ this.addRemoveSelectionFromImage(true);
408
+ this.updateUI();
409
+ }
410
+ // Scroll the viewport to this. Does not zoom
411
+ scrollTo() {
412
+ if (this.selectedElems.length === 0) {
413
+ return false;
414
+ }
415
+ const screenSize = this.editor.viewport.getScreenRectSize();
416
+ const screenRect = new Rect2(0, 0, screenSize.x, screenSize.y);
417
+ const selectionScreenRegion = this.getScreenRegion();
418
+ if (!screenRect.containsPoint(selectionScreenRegion.center)) {
419
+ const targetPointScreen = selectionScreenRegion.center;
420
+ const closestPointScreen = screenRect.getClosestPointOnBoundaryTo(targetPointScreen);
421
+ const closestPointCanvas = this.editor.viewport.screenToCanvas(closestPointScreen);
422
+ const targetPointCanvas = this.region.center;
423
+ const delta = closestPointCanvas.minus(targetPointCanvas);
424
+ this.editor.dispatchNoAnnounce(Viewport.transformBy(Mat33.translation(delta.times(0.5))), false);
425
+ this.editor.queueRerender().then(() => {
426
+ this.previewTransformCmds();
427
+ });
428
+ return true;
429
+ }
430
+ return false;
431
+ }
432
+ deleteSelectedObjects() {
433
+ if (this.backgroundDragging || this.activeHandle) {
434
+ this.onDragEnd();
435
+ }
436
+ return new Erase(this.selectedElems);
437
+ }
438
+ runSelectionDuplicatedAnimation() {
439
+ if (this.selectionDuplicatedAnimationTimeout) {
440
+ clearTimeout(this.selectionDuplicatedAnimationTimeout);
441
+ }
442
+ const animationDuration = 400; // ms
443
+ this.backgroundElem.style.animation = `${animationDuration}ms ease selection-duplicated-animation`;
444
+ this.selectionDuplicatedAnimationTimeout = setTimeout(() => {
445
+ this.backgroundElem.style.animation = '';
446
+ this.selectionDuplicatedAnimationTimeout = null;
447
+ }, animationDuration);
448
+ }
449
+ async duplicateSelectedObjects() {
450
+ const wasTransforming = this.backgroundDragging || this.activeHandle;
451
+ let tmpApplyCommand = null;
452
+ if (!wasTransforming) {
453
+ this.runSelectionDuplicatedAnimation();
454
+ }
455
+ if (wasTransforming) {
456
+ // Don't update the selection's focus when redoing/undoing
457
+ const selectionToUpdate = null;
458
+ const deltaZIndex = this.getDeltaZIndexToMoveSelectionToTop();
459
+ tmpApplyCommand = new _a.ApplyTransformationCommand(selectionToUpdate, this.selectedElems, this.transform, deltaZIndex);
460
+ // Transform to ensure that the duplicates are in the correct location
461
+ await tmpApplyCommand.apply(this.editor);
462
+ // Show items again
463
+ this.addRemoveSelectionFromImage(true);
464
+ }
465
+ const duplicateCommand = new Duplicate(this.selectedElems);
466
+ if (wasTransforming) {
467
+ // Move the selected objects back to the correct location.
468
+ await tmpApplyCommand?.unapply(this.editor);
469
+ this.addRemoveSelectionFromImage(false);
470
+ this.previewTransformCmds();
471
+ this.updateUI();
472
+ }
473
+ return duplicateCommand;
474
+ }
475
+ setHandlesVisible(showHandles) {
476
+ if (!showHandles) {
477
+ this.innerContainer.classList.add('-hide-handles');
478
+ }
479
+ else {
480
+ this.innerContainer.classList.remove('-hide-handles');
481
+ }
482
+ }
483
+ addTo(elem) {
484
+ if (this.outerContainer.parentElement) {
485
+ this.outerContainer.remove();
486
+ }
487
+ elem.appendChild(this.outerContainer);
488
+ this.hasParent = true;
489
+ }
490
+ setToPoint(point) {
491
+ this.originalRegion = this.originalRegion.grownToPoint(point);
492
+ this.selectionTightBoundingBox = null;
493
+ this.updateUI();
494
+ }
495
+ cancelSelection() {
496
+ if (this.outerContainer.parentElement) {
497
+ this.outerContainer.remove();
498
+ }
499
+ this.originalRegion = Rect2.empty;
500
+ this.selectionTightBoundingBox = null;
501
+ this.hasParent = false;
502
+ }
503
+ setSelectedObjects(objects, bbox) {
504
+ this.addRemoveSelectionFromImage(true);
505
+ this.originalRegion = bbox;
506
+ this.selectionTightBoundingBox = bbox;
507
+ this.selectedElems = objects.filter(object => object.isSelectable());
508
+ // Enforce increasing z-index invariant
509
+ this.selectedElems.sort((a, b) => a.getZIndex() - b.getZIndex());
510
+ this.padRegion();
511
+ this.updateUI();
512
+ }
513
+ getSelectedObjects() {
514
+ return [...this.selectedElems];
515
+ }
516
+ }
517
+ _a = Selection;
518
+ (() => {
519
+ SerializableCommand.register('selection-tool-transform', (json, _editor) => {
520
+ // The selection box is lost when serializing/deserializing. No need to store box rotation
521
+ const fullTransform = new Mat33(...json.transform);
522
+ const elemIds = (json.elems ?? []);
523
+ const deltaZIndex = parseInt(json.deltaZIndex ?? 0);
524
+ return new _a.ApplyTransformationCommand(null, elemIds, fullTransform, deltaZIndex);
525
+ });
526
+ })();
527
+ Selection.ApplyTransformationCommand = class extends SerializableCommand {
528
+ constructor(selection,
529
+ // If a `string[]`, selectedElems is a list of element IDs.
530
+ selectedElems,
531
+ // Full transformation used to transform elements.
532
+ fullTransform, deltaZIndex) {
533
+ super('selection-tool-transform');
534
+ this.selection = selection;
535
+ this.fullTransform = fullTransform;
536
+ this.deltaZIndex = deltaZIndex;
537
+ const isIDList = (arr) => {
538
+ return typeof arr[0] === 'string';
539
+ };
540
+ // If a list of element IDs,
541
+ if (isIDList(selectedElems)) {
542
+ this.selectedElemIds = selectedElems;
543
+ }
544
+ else {
545
+ this.selectedElemIds = selectedElems.map(elem => elem.getId());
546
+ this.transformCommands = selectedElems.map(elem => {
547
+ return elem.setZIndexAndTransformBy(this.fullTransform, elem.getZIndex() + deltaZIndex);
548
+ });
549
+ }
550
+ }
551
+ resolveToElems(editor, isUndoing) {
552
+ if (this.transformCommands) {
553
+ return;
554
+ }
555
+ this.transformCommands = this.selectedElemIds.map(id => {
556
+ const elem = editor.image.lookupElement(id);
557
+ if (!elem) {
558
+ // There may be valid reasons for an element lookup to fail:
559
+ // For example, if the element was deleted remotely and the remote deletion
560
+ // hasn't been undone.
561
+ console.warn(`Unable to find element with ID, ${id}.`);
562
+ return null;
563
+ }
564
+ let originalZIndex = elem.getZIndex();
565
+ let targetZIndex = elem.getZIndex() + this.deltaZIndex;
566
+ // If the command has already been applied, the element should currently
567
+ // have the target z-index.
568
+ if (isUndoing) {
569
+ targetZIndex = elem.getZIndex();
570
+ originalZIndex = elem.getZIndex() - this.deltaZIndex;
571
+ }
572
+ return elem.setZIndexAndTransformBy(this.fullTransform, targetZIndex, originalZIndex);
573
+ }).filter(// Remove all null commands
574
+ // Remove all null commands
575
+ command => command !== null);
576
+ }
577
+ async apply(editor) {
578
+ this.resolveToElems(editor, false);
579
+ this.selection?.setTransform(this.fullTransform, false);
580
+ this.selection?.updateUI();
581
+ await editor.asyncApplyCommands(this.transformCommands, updateChunkSize);
582
+ this.selection?.setTransform(Mat33.identity, false);
583
+ this.selection?.recomputeRegion();
584
+ this.selection?.updateUI();
585
+ }
586
+ async unapply(editor) {
587
+ this.resolveToElems(editor, true);
588
+ this.selection?.setTransform(this.fullTransform.inverse(), false);
589
+ this.selection?.updateUI();
590
+ await editor.asyncUnapplyCommands(this.transformCommands, updateChunkSize, true);
591
+ this.selection?.setTransform(Mat33.identity, false);
592
+ this.selection?.recomputeRegion();
593
+ this.selection?.updateUI();
594
+ }
595
+ serializeToJSON() {
596
+ return {
597
+ elems: this.selectedElemIds,
598
+ transform: this.fullTransform.toArray(),
599
+ deltaZIndex: this.deltaZIndex,
600
+ };
601
+ }
602
+ description(_editor, localizationTable) {
603
+ return localizationTable.transformedElements(this.selectedElemIds.length);
604
+ }
605
+ };
606
+ export default Selection;
@@ -0,0 +1,62 @@
1
+ import { Point2, Vec2 } from '@js-draw/math';
2
+ import Selection from './Selection';
3
+ import Pointer from '../../Pointer';
4
+ import Viewport from '../../Viewport';
5
+ import { SelectionBoxChild } from './types';
6
+ export declare enum HandleAction {
7
+ ResizeXY = "resize-xy",
8
+ Rotate = "rotate",
9
+ ResizeX = "resize-x",
10
+ ResizeY = "resize-y"
11
+ }
12
+ export interface HandlePresentation {
13
+ side: Vec2;
14
+ icon?: Element;
15
+ action: HandleAction;
16
+ }
17
+ export declare const handleSize = 30;
18
+ export type DragStartCallback = (startPoint: Point2) => void;
19
+ export type DragUpdateCallback = (canvasPoint: Point2) => void;
20
+ export type DragEndCallback = () => Promise<void> | void;
21
+ export default class SelectionHandle implements SelectionBoxChild {
22
+ readonly presentation: HandlePresentation;
23
+ private readonly parent;
24
+ private readonly viewport;
25
+ private readonly onDragStart;
26
+ private readonly onDragUpdate;
27
+ private readonly onDragEnd;
28
+ private element;
29
+ private snapToGrid;
30
+ private shape;
31
+ private parentSide;
32
+ constructor(presentation: HandlePresentation, parent: Selection, viewport: Viewport, onDragStart: DragStartCallback, onDragUpdate: DragUpdateCallback, onDragEnd: DragEndCallback);
33
+ /**
34
+ * Adds this to `container`, where `conatiner` should be the background/selection
35
+ * element visible on the screen.
36
+ */
37
+ addTo(container: HTMLElement): void;
38
+ /**
39
+ * Removes this element from its container. Should only be called
40
+ * after {@link addTo}.
41
+ */
42
+ remove(): void;
43
+ /**
44
+ * Returns this handle's bounding box relative to the top left of the
45
+ * selection box.
46
+ */
47
+ private getBBoxParentCoords;
48
+ /** @returns this handle's bounding box relative to the canvas. */
49
+ private getBBoxCanvasCoords;
50
+ /**
51
+ * Moves the HTML representation of this to the location matching its internal representation.
52
+ */
53
+ updatePosition(): void;
54
+ /** @returns true iff `point` (in editor **canvas** coordinates) is in this. */
55
+ containsPoint(point: Point2): boolean;
56
+ private dragLastPos;
57
+ handleDragStart(pointer: Pointer): boolean;
58
+ handleDragUpdate(pointer: Pointer): void;
59
+ handleDragEnd(): void | Promise<void>;
60
+ setSnapToGrid(snap: boolean): void;
61
+ isSnappingToGrid(): boolean;
62
+ }