js-draw 1.21.2 → 1.21.3

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