@weasel-js/core 1.10.0 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/README.md +33 -0
  3. package/dist/affordances/composeAffordanceLayer.js +21 -21
  4. package/dist/affordances/composeAffordanceLayer.js.map +1 -1
  5. package/dist/affordances/hitAffordanceRegions.js +48 -32
  6. package/dist/affordances/hitAffordanceRegions.js.map +1 -1
  7. package/dist/affordances/pathAnchors.js +50 -28
  8. package/dist/affordances/pathAnchors.js.map +1 -1
  9. package/dist/affordances/rotateCursor.js +12 -0
  10. package/dist/affordances/rotateCursor.js.map +1 -0
  11. package/dist/affordances/rotationHandle.js +40 -43
  12. package/dist/affordances/rotationHandle.js.map +1 -1
  13. package/dist/animation/rig/rigNode.js +9 -3
  14. package/dist/animation/rig/rigNode.js.map +1 -1
  15. package/dist/animation/rig/rigSeat.js +46 -13
  16. package/dist/animation/rig/rigSeat.js.map +1 -1
  17. package/dist/animation/rig/skinBinding.js +22 -14
  18. package/dist/animation/rig/skinBinding.js.map +1 -1
  19. package/dist/barrel/canvas.js +29 -28
  20. package/dist/barrel/interactions.js +33 -32
  21. package/dist/barrel/paths.js +11 -10
  22. package/dist/barrel/routing.js +49 -48
  23. package/dist/barrel/scene.js +10 -10
  24. package/dist/barrel/viewport.js +24 -21
  25. package/dist/canvas/Canvas.js +6 -17
  26. package/dist/canvas/Canvas.js.map +1 -1
  27. package/dist/canvas/CanvasView.js +34 -37
  28. package/dist/canvas/CanvasView.js.map +1 -1
  29. package/dist/canvas/CursorCoordsHud.js +3 -3
  30. package/dist/canvas/CursorCoordsHud.js.map +1 -1
  31. package/dist/canvas/DrawCanvas.js +3 -3
  32. package/dist/canvas/DrawCanvas.js.map +1 -1
  33. package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js +24 -23
  34. package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js.map +1 -1
  35. package/dist/canvas/SceneCanvas/StandardActionsRegistrar.js +40 -49
  36. package/dist/canvas/SceneCanvas/StandardActionsRegistrar.js.map +1 -1
  37. package/dist/canvas/SceneCanvas/defaultNodeProperties.js +297 -259
  38. package/dist/canvas/SceneCanvas/defaultNodeProperties.js.map +1 -1
  39. package/dist/canvas/SceneCanvas/features.js +3 -24
  40. package/dist/canvas/SceneCanvas/features.js.map +1 -1
  41. package/dist/canvas/SceneCanvas/insertPreviewCommands.js +97 -0
  42. package/dist/canvas/SceneCanvas/insertPreviewCommands.js.map +1 -0
  43. package/dist/canvas/SceneCanvas/poseGeometry.js.map +1 -1
  44. package/dist/canvas/SceneCanvas/props.js.map +1 -1
  45. package/dist/canvas/SceneCanvas/scenePointQuery.js +50 -0
  46. package/dist/canvas/SceneCanvas/scenePointQuery.js.map +1 -0
  47. package/dist/canvas/SceneCanvas/shapeGeneratorProperties.js +52 -0
  48. package/dist/canvas/SceneCanvas/shapeGeneratorProperties.js.map +1 -0
  49. package/dist/canvas/SceneCanvas/useActionTunings.js +17 -0
  50. package/dist/canvas/SceneCanvas/useActionTunings.js.map +1 -0
  51. package/dist/canvas/SceneCanvas/useCanvasCamera.js +37 -29
  52. package/dist/canvas/SceneCanvas/useCanvasCamera.js.map +1 -1
  53. package/dist/canvas/SceneCanvas/useCanvasDispatcher.js +11 -11
  54. package/dist/canvas/SceneCanvas/useCanvasDispatcher.js.map +1 -1
  55. package/dist/canvas/SceneCanvas/useDispatcherOverlayLayer.js +45 -109
  56. package/dist/canvas/SceneCanvas/useDispatcherOverlayLayer.js.map +1 -1
  57. package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js +49 -41
  58. package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js.map +1 -1
  59. package/dist/canvas/SceneCanvas/useSceneSelectTool.js +64 -96
  60. package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -1
  61. package/dist/canvas/SceneCanvas/worldPointAt.js +3 -4
  62. package/dist/canvas/SceneCanvas/worldPointAt.js.map +1 -1
  63. package/dist/canvas/SceneCanvas.js +77 -80
  64. package/dist/canvas/SceneCanvas.js.map +1 -1
  65. package/dist/canvas/SceneViewCanvas.js +3 -3
  66. package/dist/canvas/SceneViewCanvas.js.map +1 -1
  67. package/dist/canvas/SurfaceCanvas.js +40 -0
  68. package/dist/canvas/SurfaceCanvas.js.map +1 -0
  69. package/dist/canvas/adapterDerivedPath.js +13 -13
  70. package/dist/canvas/adapterDerivedPath.js.map +1 -1
  71. package/dist/canvas/adapterPickSource.js +34 -0
  72. package/dist/canvas/adapterPickSource.js.map +1 -0
  73. package/dist/canvas/affordanceAt.js +1 -1
  74. package/dist/canvas/affordanceAt.js.map +1 -1
  75. package/dist/canvas/buildSceneLayer.js.map +1 -1
  76. package/dist/canvas/buildSceneTree.js +56 -34
  77. package/dist/canvas/buildSceneTree.js.map +1 -1
  78. package/dist/canvas/copiesAbove.js +27 -0
  79. package/dist/canvas/copiesAbove.js.map +1 -0
  80. package/dist/canvas/defaultDrawOne.js +24 -23
  81. package/dist/canvas/defaultDrawOne.js.map +1 -1
  82. package/dist/canvas/deps/editAnchors.js +45 -50
  83. package/dist/canvas/deps/editAnchors.js.map +1 -1
  84. package/dist/canvas/deps/hitTestArea.js +30 -15
  85. package/dist/canvas/deps/hitTestArea.js.map +1 -1
  86. package/dist/canvas/deps/insert.js +134 -100
  87. package/dist/canvas/deps/insert.js.map +1 -1
  88. package/dist/canvas/deps/layout.js +9 -15
  89. package/dist/canvas/deps/layout.js.map +1 -1
  90. package/dist/canvas/derivedPath.js +53 -29
  91. package/dist/canvas/derivedPath.js.map +1 -1
  92. package/dist/canvas/insertPreviewExtent.js +33 -31
  93. package/dist/canvas/insertPreviewExtent.js.map +1 -1
  94. package/dist/canvas/overChildren.js +29 -0
  95. package/dist/canvas/overChildren.js.map +1 -0
  96. package/dist/canvas/paintedCursorLayer.js.map +1 -1
  97. package/dist/canvas/pickReach.js +23 -0
  98. package/dist/canvas/pickReach.js.map +1 -0
  99. package/dist/canvas/pickWalk.js +51 -80
  100. package/dist/canvas/pickWalk.js.map +1 -1
  101. package/dist/canvas/sceneAdapter.js +14 -35
  102. package/dist/canvas/sceneAdapter.js.map +1 -1
  103. package/dist/canvas/sceneSlotWiring.js +11 -10
  104. package/dist/canvas/sceneSlotWiring.js.map +1 -1
  105. package/dist/canvas/sceneViewRender.js +38 -44
  106. package/dist/canvas/sceneViewRender.js.map +1 -1
  107. package/dist/canvas/useCanvasView.js +42 -44
  108. package/dist/canvas/useCanvasView.js.map +1 -1
  109. package/dist/canvas/useSceneAdapter.js +22 -0
  110. package/dist/canvas/useSceneAdapter.js.map +1 -0
  111. package/dist/canvas/useSurfaceInput.js +13 -16
  112. package/dist/canvas/useSurfaceInput.js.map +1 -1
  113. package/dist/canvas/viewRegistry.js +31 -23
  114. package/dist/canvas/viewRegistry.js.map +1 -1
  115. package/dist/canvas/wrapNodeOutput.js +7 -2
  116. package/dist/canvas/wrapNodeOutput.js.map +1 -1
  117. package/dist/clipboard.d.ts +1 -1
  118. package/dist/{clone-2a5hVbBd.d.ts → clone-C0eADtS0.d.ts} +13 -13
  119. package/dist/clone.d.ts +2 -2
  120. package/dist/core/geometry/poseDescriptor.js +49 -23
  121. package/dist/core/geometry/poseDescriptor.js.map +1 -1
  122. package/dist/core/geometry/regionHit.js +2 -2
  123. package/dist/core/geometry/regionHit.js.map +1 -1
  124. package/dist/core/geometry/targetFrame.js.map +1 -1
  125. package/dist/core/layers/children.js +1 -3
  126. package/dist/core/layers/children.js.map +1 -1
  127. package/dist/core/ops/create.js +2 -2
  128. package/dist/core/ops/create.js.map +1 -1
  129. package/dist/core/ops/delete.js +19 -23
  130. package/dist/core/ops/delete.js.map +1 -1
  131. package/dist/core/ops/reorder/index.js +3 -7
  132. package/dist/core/ops/reorder/index.js.map +1 -1
  133. package/dist/core/ops/reorder/setChildOrder.js +2 -4
  134. package/dist/core/ops/reorder/setChildOrder.js.map +1 -1
  135. package/dist/core/ops/reparent.js +0 -1
  136. package/dist/core/ops/reparent.js.map +1 -1
  137. package/dist/core/ops/slot.js +3 -6
  138. package/dist/core/ops/slot.js.map +1 -1
  139. package/dist/core/pages/fitViewToPage.js +15 -0
  140. package/dist/core/pages/fitViewToPage.js.map +1 -0
  141. package/dist/core/pages/pages.js +65 -0
  142. package/dist/core/pages/pages.js.map +1 -0
  143. package/dist/core/pages/pagesLayer.js +27 -0
  144. package/dist/core/pages/pagesLayer.js.map +1 -0
  145. package/dist/core/paint/meshKindLazy.js +2 -2
  146. package/dist/core/paint/meshKindLazy.js.map +1 -1
  147. package/dist/core/scene/NodeProperties.js.map +1 -1
  148. package/dist/core/scene/composeFrame.js.map +1 -1
  149. package/dist/core/scene/composePose.js +58 -20
  150. package/dist/core/scene/composePose.js.map +1 -1
  151. package/dist/core/scene/effectivePose.js +5 -1
  152. package/dist/core/scene/effectivePose.js.map +1 -1
  153. package/dist/core/scene/historyFacade.js +19 -13
  154. package/dist/core/scene/historyFacade.js.map +1 -1
  155. package/dist/core/scene/nodeFnFields.js +7 -0
  156. package/dist/core/scene/nodeFnFields.js.map +1 -1
  157. package/dist/core/scene/outerOps.js +2 -1
  158. package/dist/core/scene/outerOps.js.map +1 -1
  159. package/dist/core/scene/reconcileSpecs.js +1 -1
  160. package/dist/core/scene/reconcileSpecs.js.map +1 -1
  161. package/dist/core/scene/sceneRecording.js +2 -1
  162. package/dist/core/scene/sceneRecording.js.map +1 -1
  163. package/dist/core/scene/types.js.map +1 -1
  164. package/dist/core/viewport/screenSlop.js.map +1 -1
  165. package/dist/core/viewport/useDecayLoop.js +28 -30
  166. package/dist/core/viewport/useDecayLoop.js.map +1 -1
  167. package/dist/core/viewport/useNodeOverlayFrame.js.map +1 -1
  168. package/dist/core/viewport/useViewAnimation.js +70 -69
  169. package/dist/core/viewport/useViewAnimation.js.map +1 -1
  170. package/dist/core/viewport/view.js +8 -5
  171. package/dist/core/viewport/view.js.map +1 -1
  172. package/dist/core/viewport/zoomAt.js +11 -2
  173. package/dist/core/viewport/zoomAt.js.map +1 -1
  174. package/dist/{cornerHandles-BEshc4z3.d.ts → cornerHandles-BSKbyuvQ.d.ts} +1 -1
  175. package/dist/features/paths/editablePath.js +24 -8
  176. package/dist/features/paths/editablePath.js.map +1 -1
  177. package/dist/features/paths/index.js +4 -4
  178. package/dist/features/paths/shapeGenerator.js +89 -0
  179. package/dist/features/paths/shapeGenerator.js.map +1 -0
  180. package/dist/features/paths/usePathEdit.js +13 -13
  181. package/dist/features/poseRun/usePoseRun.js +25 -25
  182. package/dist/features/poseRun/usePoseRun.js.map +1 -1
  183. package/dist/features/text/useSceneTextEdit.js +82 -64
  184. package/dist/features/text/useSceneTextEdit.js.map +1 -1
  185. package/dist/features/viewports/viewResolver.js +28 -24
  186. package/dist/features/viewports/viewResolver.js.map +1 -1
  187. package/dist/icons/SliceIcon.js +24 -0
  188. package/dist/icons/SliceIcon.js.map +1 -0
  189. package/dist/index.d.ts +956 -581
  190. package/dist/index.js +260 -251
  191. package/dist/interactions/actions/align/align.js +9 -9
  192. package/dist/interactions/actions/align/align.js.map +1 -1
  193. package/dist/interactions/actions/booleans/booleans.js +18 -18
  194. package/dist/interactions/actions/booleans/booleans.js.map +1 -1
  195. package/dist/interactions/actions/booleans/operands.js.map +1 -1
  196. package/dist/interactions/actions/clone/action.js +35 -30
  197. package/dist/interactions/actions/clone/action.js.map +1 -1
  198. package/dist/interactions/actions/defaults/anchorEditing.js +56 -59
  199. package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -1
  200. package/dist/interactions/actions/defaults/anchorHandles.js +42 -0
  201. package/dist/interactions/actions/defaults/anchorHandles.js.map +1 -0
  202. package/dist/interactions/actions/defaults/anchorJoin.js +92 -0
  203. package/dist/interactions/actions/defaults/anchorJoin.js.map +1 -0
  204. package/dist/interactions/actions/defaults/bendSegment.js +46 -0
  205. package/dist/interactions/actions/defaults/bendSegment.js.map +1 -0
  206. package/dist/interactions/actions/defaults/copySubtree.js +1 -1
  207. package/dist/interactions/actions/defaults/copySubtree.js.map +1 -1
  208. package/dist/interactions/actions/defaults/duplicate.js +32 -17
  209. package/dist/interactions/actions/defaults/duplicate.js.map +1 -1
  210. package/dist/interactions/actions/defaults/enterPathEdit.js +19 -7
  211. package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -1
  212. package/dist/interactions/actions/defaults/icons/anchorIcons.js +75 -0
  213. package/dist/interactions/actions/defaults/icons/anchorIcons.js.map +1 -0
  214. package/dist/interactions/actions/defaults/icons/editIcons.js +35 -8
  215. package/dist/interactions/actions/defaults/icons/editIcons.js.map +1 -1
  216. package/dist/interactions/actions/defaults/insertPathAnchor.js +16 -31
  217. package/dist/interactions/actions/defaults/insertPathAnchor.js.map +1 -1
  218. package/dist/interactions/actions/defaults/nudge.js +28 -23
  219. package/dist/interactions/actions/defaults/nudge.js.map +1 -1
  220. package/dist/interactions/actions/defaults/pinchZoom.js +29 -29
  221. package/dist/interactions/actions/defaults/pinchZoom.js.map +1 -1
  222. package/dist/interactions/actions/defaults/segmentUnder.js +22 -0
  223. package/dist/interactions/actions/defaults/segmentUnder.js.map +1 -0
  224. package/dist/interactions/actions/defaults/viewportZoom.js +82 -79
  225. package/dist/interactions/actions/defaults/viewportZoom.js.map +1 -1
  226. package/dist/interactions/actions/distribute/distribute.js +8 -8
  227. package/dist/interactions/actions/distribute/distribute.js.map +1 -1
  228. package/dist/interactions/actions/edit-anchors/action.js +58 -55
  229. package/dist/interactions/actions/edit-anchors/action.js.map +1 -1
  230. package/dist/interactions/actions/edit-anchors/preview.js +26 -0
  231. package/dist/interactions/actions/edit-anchors/preview.js.map +1 -0
  232. package/dist/interactions/actions/edit-anchors/symmetry.js +11 -0
  233. package/dist/interactions/actions/edit-anchors/symmetry.js.map +1 -0
  234. package/dist/interactions/actions/flip/action.js.map +1 -1
  235. package/dist/interactions/actions/geometryProjection.js.map +1 -1
  236. package/dist/interactions/actions/insert/action.js +37 -30
  237. package/dist/interactions/actions/insert/action.js.map +1 -1
  238. package/dist/interactions/actions/insert/frame.js +9 -2
  239. package/dist/interactions/actions/insert/frame.js.map +1 -1
  240. package/dist/interactions/actions/insert/repositionAction.js +31 -0
  241. package/dist/interactions/actions/insert/repositionAction.js.map +1 -0
  242. package/dist/interactions/actions/lasso-select/action.js +32 -32
  243. package/dist/interactions/actions/move/action.js +29 -25
  244. package/dist/interactions/actions/move/action.js.map +1 -1
  245. package/dist/interactions/actions/move/behaviors/snapToContainer.js +12 -6
  246. package/dist/interactions/actions/move/behaviors/snapToContainer.js.map +1 -1
  247. package/dist/interactions/actions/move/capture.js +32 -23
  248. package/dist/interactions/actions/move/capture.js.map +1 -1
  249. package/dist/interactions/actions/move/frame.js +2 -14
  250. package/dist/interactions/actions/move/frame.js.map +1 -1
  251. package/dist/interactions/actions/move/session.js +1 -1
  252. package/dist/interactions/actions/move/session.js.map +1 -1
  253. package/dist/interactions/actions/move/translate.js.map +1 -1
  254. package/dist/interactions/actions/outlines/createOutlines.js.map +1 -1
  255. package/dist/interactions/actions/outlines/replaceWithPaths.js +13 -13
  256. package/dist/interactions/actions/outlines/replaceWithPaths.js.map +1 -1
  257. package/dist/interactions/actions/outlines/strokeRegion.js.map +1 -1
  258. package/dist/interactions/actions/pathCommands/cutJoin.js +102 -0
  259. package/dist/interactions/actions/pathCommands/cutJoin.js.map +1 -0
  260. package/dist/interactions/actions/pathCommands/livePathEdit.js +64 -0
  261. package/dist/interactions/actions/pathCommands/livePathEdit.js.map +1 -0
  262. package/dist/interactions/actions/pathCommands/pathNodes.js +99 -0
  263. package/dist/interactions/actions/pathCommands/pathNodes.js.map +1 -0
  264. package/dist/interactions/actions/pathCommands/simplifyOffset.js +42 -0
  265. package/dist/interactions/actions/pathCommands/simplifyOffset.js.map +1 -0
  266. package/dist/interactions/actions/resize/action.js +31 -20
  267. package/dist/interactions/actions/resize/action.js.map +1 -1
  268. package/dist/interactions/actions/resize/commit.js.map +1 -1
  269. package/dist/interactions/actions/resize/frame.js +29 -15
  270. package/dist/interactions/actions/resize/frame.js.map +1 -1
  271. package/dist/interactions/actions/resize/replay.js +47 -0
  272. package/dist/interactions/actions/resize/replay.js.map +1 -0
  273. package/dist/interactions/actions/resize/session.js +49 -35
  274. package/dist/interactions/actions/resize/session.js.map +1 -1
  275. package/dist/interactions/actions/resolveOverlays.js +2 -1
  276. package/dist/interactions/actions/resolveOverlays.js.map +1 -1
  277. package/dist/interactions/actions/rotate/action.js +40 -25
  278. package/dist/interactions/actions/rotate/action.js.map +1 -1
  279. package/dist/interactions/actions/rotate/frame.js +1 -1
  280. package/dist/interactions/actions/rotate/frame.js.map +1 -1
  281. package/dist/interactions/actions/rotate/replay.js +22 -0
  282. package/dist/interactions/actions/rotate/replay.js.map +1 -0
  283. package/dist/interactions/actions/rotate/session.js +42 -32
  284. package/dist/interactions/actions/rotate/session.js.map +1 -1
  285. package/dist/interactions/actions/transform-again/action.js +63 -0
  286. package/dist/interactions/actions/transform-again/action.js.map +1 -0
  287. package/dist/interactions/actions/transform-again/memory.js +35 -0
  288. package/dist/interactions/actions/transform-again/memory.js.map +1 -0
  289. package/dist/interactions/actions/useStandardActions.js +101 -83
  290. package/dist/interactions/actions/useStandardActions.js.map +1 -1
  291. package/dist/move.d.ts +4 -4
  292. package/dist/{originProjection-PPT88jZv.d.ts → originProjection-CoNVpITV.d.ts} +1 -1
  293. package/dist/resize.d.ts +3 -3
  294. package/dist/style.css +1 -1
  295. package/dist/tools/builtin/ellipse/useEllipseTool.js +16 -15
  296. package/dist/tools/builtin/ellipse/useEllipseTool.js.map +1 -1
  297. package/dist/tools/builtin/line/useLineTool.js +16 -15
  298. package/dist/tools/builtin/line/useLineTool.js.map +1 -1
  299. package/dist/tools/builtin/pen/usePenTool.js +111 -111
  300. package/dist/tools/builtin/pen/usePenTool.js.map +1 -1
  301. package/dist/tools/builtin/pickTopMostHit.js +11 -14
  302. package/dist/tools/builtin/pickTopMostHit.js.map +1 -1
  303. package/dist/tools/builtin/polygon/usePolygonTool.js +17 -15
  304. package/dist/tools/builtin/polygon/usePolygonTool.js.map +1 -1
  305. package/dist/tools/builtin/rect/useRectTool.js +15 -14
  306. package/dist/tools/builtin/rect/useRectTool.js.map +1 -1
  307. package/dist/tools/builtin/select/adapterPointQuery.js +22 -18
  308. package/dist/tools/builtin/select/adapterPointQuery.js.map +1 -1
  309. package/dist/tools/builtin/select/selectionContributions.js +1 -1
  310. package/dist/tools/builtin/select/selectionContributions.js.map +1 -1
  311. package/dist/tools/builtin/select/useSelectTool.js +2 -1
  312. package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
  313. package/dist/tools/builtin/slice/useSliceTool.js +42 -40
  314. package/dist/tools/builtin/slice/useSliceTool.js.map +1 -1
  315. package/dist/tools/builtin/star/useStarTool.js +18 -16
  316. package/dist/tools/builtin/star/useStarTool.js.map +1 -1
  317. package/dist/tools/builtin/text/useTextTool.js +2 -2
  318. package/dist/tools/builtin/text/useTextTool.js.map +1 -1
  319. package/dist/{types-CIKDwlsP.d.ts → types-DBbbCy0i.d.ts} +22 -15
  320. package/dist/version.js +1 -1
  321. package/package.json +22 -22
  322. package/dist/canvas/surface.module.js +0 -6
  323. package/dist/canvas/surface.module.js.map +0 -1
  324. package/dist/canvas/surfaceBox.js +0 -16
  325. package/dist/canvas/surfaceBox.js.map +0 -1
  326. package/dist/layout/arrivals.js +0 -33
  327. package/dist/layout/arrivals.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"selectionContributions.js","names":["SELECTION_MOVE_ID","SELECTION_TRANSFORM_ID","SELECTION_RESIZE_ID","SELECTION_ROTATE_ID","selectionMoveBindings","moveOpts","move","options","params","gestureLifecycleParams","withParams","behaviors","hitPredicate","body","isAnchorOrControl","afford","selectionResizeBindings","isResizeHandle","selectionRotateBindings","rotate","opts","isRotateHandle","selectionTransformBindings","selectionMoveContribution","selectionTransformContribution","selectionResizeContribution","selectionRotateContribution","AREA_SELECT_ID","onEmptyCanvas","hit","onBody","areaSelectContribution"],"sources":["../../../../src/tools/builtin/select/selectionContributions.ts"],"sourcesContent":["/**\n * The ambient bindings that act on the selection: moving it, cloning it, and\n * resizing or rotating it from its handles. They belong to the selection, not\n * to the select tool, so they run under any tool that does not claim the\n * gesture itself. `<SceneCanvas features>` installs them as the `move`,\n * `resize` and `rotate` presets.\n */\nimport type { BindingOpts, GestureBinding } from '@weasel-js/routing';\nimport { isResizeHandle, isRotateHandle, isAnchorOrControl } from '@weasel-js/routing';\nimport { hitPredicate } from '@weasel-js/gestures';\nimport type { Contribution } from '../../overlayBinding';\nimport type { UseMoveOptions } from '../../../interactions/actions/move/options';\nimport type { UseRotateOptions } from '../../../interactions/actions/rotate/options';\nimport { gestureLifecycleParams } from '../../../interactions/actions/gestureLifecycle';\n\n/** Options for {@link selectionMoveContribution}. */\nexport interface SelectionMoveOptions<TPose = unknown> {\n /** Move-action options: `behaviors` become the move bindings'\n * `opts.behaviors`, everything else their `opts.params`. */\n move?: UseMoveOptions<TPose>;\n /** Reparent-on-drop behavior for drag-to-move. `'off'` (default) keeps\n * translate-only commits. `'top'` lands the moved nodes at the top of the\n * container under the drop point; `'above'` lands them immediately above the\n * hit sibling. Requires the `nodeAtPoint` dep (`<SceneCanvas>` sources it). */\n reparentOnDrop?: 'off' | 'top' | 'above';\n}\n\n/** Id of the entry {@link selectionMoveContribution} builds. */\nexport const SELECTION_MOVE_ID = 'selection.move';\n/** Id of the entry {@link selectionTransformContribution} builds. */\nexport const SELECTION_TRANSFORM_ID = 'selection.transform';\n/** Id of the entry {@link selectionResizeContribution} builds. */\nexport const SELECTION_RESIZE_ID = 'selection.resize';\n/** Id of the entry {@link selectionRotateContribution} builds. */\nexport const SELECTION_ROTATE_ID = 'selection.rotate';\n\n/** Drag a body to move the selection; Alt-drag to clone it. */\nexport function selectionMoveBindings<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): GestureBinding[] {\n // Shared move-binding opts (params + behaviors). Applied to\n // both the selected-body and unselected-body move bindings so a\n // first-touch drag and a re-drag commit identically.\n const moveOpts: { opts?: BindingOpts } = (() => {\n const move = options.move ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...move, label: move.moveLabel });\n if (options.reparentOnDrop && options.reparentOnDrop !== 'off') params.reparentOnDrop = options.reparentOnDrop;\n if (move.dragThresholdPx !== undefined) params.dragThresholdPx = move.dragThresholdPx;\n if (move.expandIds) params.expandIds = move.expandIds;\n const withParams = Object.keys(params).length > 0 ? { params } : undefined;\n const behaviors = options.move?.behaviors?.length\n ? { behaviors: options.move.behaviors as BindingOpts['behaviors'] }\n : undefined;\n return withParams || behaviors\n ? { opts: { ...withParams, ...behaviors } satisfies BindingOpts }\n : {};\n })();\n\n return [\n // Alt-drag on a body → clone (Illustrator convention).\n // Listed BEFORE bare move so the strict-modifier dispatcher\n // picks this when Alt is held; bare move matches no-mod drags.\n // Both selected and unselected bodies are valid clone targets — the\n // select tool's pointerDown classifier calls `selection.applyClick(top, mods)`\n // on an unselected hit before the drag fires, so cloneAction's\n // `start` sees the hit node in `selection.get()` either way.\n { spec: { kind: 'drag' as const, target: 'selected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n { spec: { kind: 'drag' as const, target: 'unselected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n {\n // Body-drag → move, BUT defer when the pointerdown hit a path\n // anchor / control affordance. Anchors lie on the curve so the\n // body classifier still reports 'selected-body'; without this\n // opt-out, move's binding beats editAnchors's on every anchor drag.\n //\n // `isAnchorOrControl` is the SAME predicate `editAnchorsAction`\n // matches on. That is load-bearing: the two must agree on what\n // counts as an anchor hit or move steals the drag — which is\n // exactly the bug this opt-out exists to prevent.\n spec: {\n kind: 'drag' as const,\n target: {\n kindOf: hitPredicate((afford, body) =>\n body === 'selected-body' && !isAnchorOrControl(afford)),\n },\n },\n actionId: 'move',\n ...moveOpts,\n },\n // Body-drag on a NOT-yet-selected node → also move. The select tool's\n // pointerDown classifier selects the hit node before the drag fires (same\n // contract clone relies on), so by the time moveAction.start() runs the\n // node is in `selection.get()`. Without this binding an unselected-body\n // drag falls through to whatever ambient drag binding comes next — once\n // the `rotate` catch-all, which made the first drag rotate and later ones\n // move. Unselected nodes never carry anchor affordances (those gate on\n // selection), so the plain string-form target is sufficient here.\n {\n spec: { kind: 'drag' as const, target: 'unselected-body' as const },\n actionId: 'move',\n ...moveOpts,\n },\n ];\n}\n\n/** Options for {@link selectionRotateContribution}. */\nexport interface SelectionRotateOptions<TPose = unknown> {\n /** Rotate-action options: `behaviors` become the rotate binding's\n * `opts.behaviors`, everything else its `opts.params`. */\n rotate?: UseRotateOptions<TPose>;\n}\n\n/** Options for {@link selectionTransformContribution}. Resize takes its\n * options through the `resizePolicy` dep (`useResizePolicy`), not here. */\nexport type SelectionTransformOptions<TPose = unknown> = SelectionRotateOptions<TPose>;\n\n/** Drag a resize handle to resize the selection. Options come through the\n * `resizePolicy` dep (`useResizePolicy`). */\nexport function selectionResizeBindings(): GestureBinding[] {\n return [{ spec: { kind: 'drag' as const, target: { kindOf: isResizeHandle } }, actionId: 'resize' }];\n}\n\n/** Drag the rotation handle to rotate the selection. */\nexport function selectionRotateBindings<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): GestureBinding[] {\n const rotate = options.rotate ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...rotate, label: rotate.rotateLabel });\n if (rotate.pivot) params.pivot = rotate.pivot;\n const opts: BindingOpts = {\n ...(Object.keys(params).length > 0 ? { params } : {}),\n ...(rotate.behaviors !== undefined ? { behaviors: rotate.behaviors as BindingOpts['behaviors'] } : {}),\n };\n return [{\n spec: { kind: 'drag' as const, target: { kindOf: isRotateHandle } },\n actionId: 'rotate',\n ...(Object.keys(opts).length > 0 ? { opts } : {}),\n }];\n}\n\n/** Drag a resize handle to resize the selection, the rotation handle to rotate it. */\nexport function selectionTransformBindings<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): GestureBinding[] {\n return [...selectionResizeBindings(), ...selectionRotateBindings(options)];\n}\n\n/** An always-live entry carrying {@link selectionMoveBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['move']}>` does. */\nexport function selectionMoveContribution<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_MOVE_ID,\n eligibility: { always: true },\n bindings: selectionMoveBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionTransformBindings}: resize\n * and rotate in one entry, what `<SceneCanvas features={['transform']}>`\n * turns on. */\nexport function selectionTransformContribution<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_TRANSFORM_ID,\n eligibility: { always: true },\n bindings: selectionTransformBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionResizeBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['resize']}>` does. */\nexport function selectionResizeContribution(): Contribution {\n return {\n id: SELECTION_RESIZE_ID,\n eligibility: { always: true },\n bindings: selectionResizeBindings(),\n };\n}\n\n/** An always-live entry carrying {@link selectionRotateBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['rotate']}>` does. */\nexport function selectionRotateContribution<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_ROTATE_ID,\n eligibility: { always: true },\n bindings: selectionRotateBindings(options),\n };\n}\n\n/** Id of the entry {@link areaSelectContribution} builds. */\nexport const AREA_SELECT_ID = 'selection.areaSelect';\n\n/** A press on empty canvas: no hit, and not on chrome over it — the rotation\n * handle and the outer half of a resize handle sit off the body. */\nexport const onEmptyCanvas = hitPredicate((hit, body) => hit == null && body === 'empty');\n\n/** A press on a node, off chrome. With no `classifyTarget` wired there is no\n * body class to read, and every press off chrome passes. */\nexport const onBody = hitPredicate((hit, body) => hit == null && body !== 'empty');\n\n/** An always-live entry that marquee-selects on a drag across empty canvas,\n * under any tool that does not claim the drag itself. No preset installs it:\n * the select tool already marquees, and a canvas that wants it under every\n * tool adds this to its ambient list. */\nexport function areaSelectContribution(): Contribution {\n return {\n id: AREA_SELECT_ID,\n eligibility: { always: true },\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EACd,IAAyC,CAAC,GAC5B;CACd,OAAO;EACL,IAAIvB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUe,EAAwBX,CAAO;CAC3C;AACF;AAGA,IAAaoB,IAAiB,wBAIjBC,IAAgBhB,GAAc,GAAK,MAASiB,KAAO,QAAQhB,MAAS,OAAO,GAI3EiB,IAASlB,GAAc,GAAK,MAASiB,KAAO,QAAQhB,MAAS,OAAO;AAMjF,SAAgBkB,IAAuC;CACrD,OAAO;EACL,IAAIJ;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAU,CAAC;GAAE,MAAM;IAAE,MAAM;IAAQ,QAAQ,EAAE,QAAQC,EAAc;GAAE;GAAG,UAAU;EAAa,CAAC;CAClG;AACF"}
1
+ {"version":3,"file":"selectionContributions.js","names":["SELECTION_MOVE_ID","SELECTION_TRANSFORM_ID","SELECTION_RESIZE_ID","SELECTION_ROTATE_ID","selectionMoveBindings","moveOpts","move","options","params","gestureLifecycleParams","withParams","behaviors","hitPredicate","body","isPathEditPart","afford","selectionResizeBindings","isResizeHandle","selectionRotateBindings","rotate","opts","isRotateHandle","selectionTransformBindings","selectionMoveContribution","selectionTransformContribution","selectionResizeContribution","selectionRotateContribution","AREA_SELECT_ID","onEmptyCanvas","hit","onBody","areaSelectContribution"],"sources":["../../../../src/tools/builtin/select/selectionContributions.ts"],"sourcesContent":["/**\n * The ambient bindings that act on the selection: moving it, cloning it, and\n * resizing or rotating it from its handles. They belong to the selection, not\n * to the select tool, so they run under any tool that does not claim the\n * gesture itself. `<SceneCanvas features>` installs them as the `move`,\n * `resize` and `rotate` presets.\n */\nimport type { BindingOpts, GestureBinding } from '@weasel-js/routing';\nimport { isResizeHandle, isRotateHandle, isPathEditPart } from '@weasel-js/routing';\nimport { hitPredicate } from '@weasel-js/gestures';\nimport type { Contribution } from '../../overlayBinding';\nimport type { UseMoveOptions } from '../../../interactions/actions/move/options';\nimport type { UseRotateOptions } from '../../../interactions/actions/rotate/options';\nimport { gestureLifecycleParams } from '../../../interactions/actions/gestureLifecycle';\n\n/** Options for {@link selectionMoveContribution}. */\nexport interface SelectionMoveOptions<TPose = unknown> {\n /** Move-action options: `behaviors` become the move bindings'\n * `opts.behaviors`, everything else their `opts.params`. */\n move?: UseMoveOptions<TPose>;\n /** Reparent-on-drop behavior for drag-to-move. `'off'` (default) keeps\n * translate-only commits. `'top'` lands the moved nodes at the top of the\n * container under the drop point; `'above'` lands them immediately above the\n * hit sibling. Requires the `nodeAtPoint` dep (`<SceneCanvas>` sources it). */\n reparentOnDrop?: 'off' | 'top' | 'above';\n}\n\n/** Id of the entry {@link selectionMoveContribution} builds. */\nexport const SELECTION_MOVE_ID = 'selection.move';\n/** Id of the entry {@link selectionTransformContribution} builds. */\nexport const SELECTION_TRANSFORM_ID = 'selection.transform';\n/** Id of the entry {@link selectionResizeContribution} builds. */\nexport const SELECTION_RESIZE_ID = 'selection.resize';\n/** Id of the entry {@link selectionRotateContribution} builds. */\nexport const SELECTION_ROTATE_ID = 'selection.rotate';\n\n/** Drag a body to move the selection; Alt-drag to clone it. */\nexport function selectionMoveBindings<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): GestureBinding[] {\n // Shared move-binding opts (params + behaviors). Applied to\n // both the selected-body and unselected-body move bindings so a\n // first-touch drag and a re-drag commit identically.\n const moveOpts: { opts?: BindingOpts } = (() => {\n const move = options.move ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...move, label: move.moveLabel });\n if (options.reparentOnDrop && options.reparentOnDrop !== 'off') params.reparentOnDrop = options.reparentOnDrop;\n if (move.dragThresholdPx !== undefined) params.dragThresholdPx = move.dragThresholdPx;\n if (move.expandIds) params.expandIds = move.expandIds;\n const withParams = Object.keys(params).length > 0 ? { params } : undefined;\n const behaviors = options.move?.behaviors?.length\n ? { behaviors: options.move.behaviors as BindingOpts['behaviors'] }\n : undefined;\n return withParams || behaviors\n ? { opts: { ...withParams, ...behaviors } satisfies BindingOpts }\n : {};\n })();\n\n return [\n // Alt-drag on a body → clone (Illustrator convention).\n // Listed BEFORE bare move so the strict-modifier dispatcher\n // picks this when Alt is held; bare move matches no-mod drags.\n // Both selected and unselected bodies are valid clone targets — the\n // select tool's pointerDown classifier calls `selection.applyClick(top, mods)`\n // on an unselected hit before the drag fires, so cloneAction's\n // `start` sees the hit node in `selection.get()` either way.\n { spec: { kind: 'drag' as const, target: 'selected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n { spec: { kind: 'drag' as const, target: 'unselected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n {\n // Body-drag → move, BUT defer when the pointerdown hit a path\n // anchor, control, or segment affordance. Those lie on the curve so\n // the body classifier still reports 'selected-body'; without this\n // opt-out, move's binding beats editAnchors's on every anchor drag.\n //\n // `isPathEditPart` covers exactly what `editAnchorsAction` and\n // `bendSegmentAction` match on. That is load-bearing: they must agree\n // on what counts as an anchor or segment hit or move steals the\n // drag — which is exactly the bug this opt-out exists to prevent.\n spec: {\n kind: 'drag' as const,\n target: {\n kindOf: hitPredicate((afford, body) =>\n body === 'selected-body' && !isPathEditPart(afford)),\n },\n },\n actionId: 'move',\n ...moveOpts,\n },\n // Body-drag on a NOT-yet-selected node → also move. The select tool's\n // pointerDown classifier selects the hit node before the drag fires (same\n // contract clone relies on), so by the time moveAction.start() runs the\n // node is in `selection.get()`. Without this binding an unselected-body\n // drag falls through to whatever ambient drag binding comes next — once\n // the `rotate` catch-all, which made the first drag rotate and later ones\n // move. Unselected nodes never carry anchor affordances (those gate on\n // selection), so the plain string-form target is sufficient here.\n {\n spec: { kind: 'drag' as const, target: 'unselected-body' as const },\n actionId: 'move',\n ...moveOpts,\n },\n ];\n}\n\n/** Options for {@link selectionRotateContribution}. */\nexport interface SelectionRotateOptions<TPose = unknown> {\n /** Rotate-action options: `behaviors` become the rotate binding's\n * `opts.behaviors`, everything else its `opts.params`. */\n rotate?: UseRotateOptions<TPose>;\n}\n\n/** Options for {@link selectionTransformContribution}. Resize takes its\n * options through the `resizePolicy` dep (`useResizePolicy`), not here. */\nexport type SelectionTransformOptions<TPose = unknown> = SelectionRotateOptions<TPose>;\n\n/** Drag a resize handle to resize the selection. Options come through the\n * `resizePolicy` dep (`useResizePolicy`). */\nexport function selectionResizeBindings(): GestureBinding[] {\n return [{ spec: { kind: 'drag' as const, target: { kindOf: isResizeHandle } }, actionId: 'resize' }];\n}\n\n/** Drag the rotation handle to rotate the selection. */\nexport function selectionRotateBindings<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): GestureBinding[] {\n const rotate = options.rotate ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...rotate, label: rotate.rotateLabel });\n if (rotate.pivot) params.pivot = rotate.pivot;\n const opts: BindingOpts = {\n ...(Object.keys(params).length > 0 ? { params } : {}),\n ...(rotate.behaviors !== undefined ? { behaviors: rotate.behaviors as BindingOpts['behaviors'] } : {}),\n };\n return [{\n spec: { kind: 'drag' as const, target: { kindOf: isRotateHandle } },\n actionId: 'rotate',\n ...(Object.keys(opts).length > 0 ? { opts } : {}),\n }];\n}\n\n/** Drag a resize handle to resize the selection, the rotation handle to rotate it. */\nexport function selectionTransformBindings<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): GestureBinding[] {\n return [...selectionResizeBindings(), ...selectionRotateBindings(options)];\n}\n\n/** An always-live entry carrying {@link selectionMoveBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['move']}>` does. */\nexport function selectionMoveContribution<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_MOVE_ID,\n eligibility: { always: true },\n bindings: selectionMoveBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionTransformBindings}: resize\n * and rotate in one entry, what `<SceneCanvas features={['transform']}>`\n * turns on. */\nexport function selectionTransformContribution<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_TRANSFORM_ID,\n eligibility: { always: true },\n bindings: selectionTransformBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionResizeBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['resize']}>` does. */\nexport function selectionResizeContribution(): Contribution {\n return {\n id: SELECTION_RESIZE_ID,\n eligibility: { always: true },\n bindings: selectionResizeBindings(),\n };\n}\n\n/** An always-live entry carrying {@link selectionRotateBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['rotate']}>` does. */\nexport function selectionRotateContribution<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_ROTATE_ID,\n eligibility: { always: true },\n bindings: selectionRotateBindings(options),\n };\n}\n\n/** Id of the entry {@link areaSelectContribution} builds. */\nexport const AREA_SELECT_ID = 'selection.areaSelect';\n\n/** A press on empty canvas: no hit, and not on chrome over it — the rotation\n * handle and the outer half of a resize handle sit off the body. */\nexport const onEmptyCanvas = hitPredicate((hit, body) => hit == null && body === 'empty');\n\n/** A press on a node, off chrome. With no `classifyTarget` wired there is no\n * body class to read, and every press off chrome passes. */\nexport const onBody = hitPredicate((hit, body) => hit == null && body !== 'empty');\n\n/** An always-live entry that marquee-selects on a drag across empty canvas,\n * under any tool that does not claim the drag itself. No preset installs it:\n * the select tool already marquees, and a canvas that wants it under every\n * tool adds this to its ambient list. */\nexport function areaSelectContribution(): Contribution {\n return {\n id: AREA_SELECT_ID,\n eligibility: { always: true },\n bindings: [{ spec: { kind: 'drag', target: { kindOf: onEmptyCanvas } }, actionId: 'areaSelect' }],\n };\n}\n"],"mappings":";;;;AA4BA,IAAaA,IAAoB,kBAEpBC,IAAyB,uBAEzBC,IAAsB,oBAEtBC,IAAsB;AAGnC,SAAgBC,EACd,IAAuC,CAAC,GACtB;CAIlB,IAAMC,WAA0C;EAC9C,IAAMC,IAAOC,EAAQ,QAAQ,CAAC,GACxBC,IAAkCC,EAAuB;GAAE,GAAGH;GAAM,OAAOA,EAAK;EAAU,CAAC;EAGjG,AAFIC,EAAQ,kBAAkBA,EAAQ,mBAAmB,UAAO,E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,MAAM;IAAQ,QAAQ,EAAE,QAAQC,EAAc;GAAE;GAAG,UAAU;EAAa,CAAC;CAClG;AACF"}
@@ -1,6 +1,7 @@
1
1
  import { AUTO_POSE_DESCRIPTOR as e } from "../../../core/geometry/autoPoseDescriptor.js";
2
2
  import "../../../core/selection/selectionTarget.js";
3
- import { adapterPickSource as t, pickWalk as n, scenePlaneOf as r } from "../../../canvas/pickWalk.js";
3
+ import { adapterPickSource as t } from "../../../canvas/adapterPickSource.js";
4
+ import { pickWalk as n, scenePlaneOf as r } from "../../../canvas/pickWalk.js";
4
5
  import { defineTool as i } from "../../overlayBinding.js";
5
6
  import a from "../../../icons/SelectIcon.js";
6
7
  import { pickTopMostHit as o } from "../pickTopMostHit.js";
@@ -1 +1 @@
1
- {"version":3,"file":"useSelectTool.js","names":["SelectIcon","useSelectTool","d","options","AUTO_POSE_DESCRIPTOR","preciseLeaves","tolerance","pickEveryFn","camera","planeOf","scenePlaneOf","adapter","pickWalk","adapterPickSource","adapterPointQuery","worldX","worldY","pickEveryRef","useLatest","pressRef","useRef","optionsRef","adapterRef","pickAction","useMemo","p","params","selection","deps","mods","opts","sel","top","ids","pickTopMostHit","hitAlreadySelected","isExtend","extendLocked","deferClick","collapseDeferredAction","ActionDisabledReason","deferred","defineTool","createElement","onBody","onEmptyCanvas"],"sources":["../../../../src/tools/builtin/select/useSelectTool.ts"],"sourcesContent":["import { useMemo, useRef, createElement } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { SelectIcon } from '../../../icons';\nimport { pickWalk, adapterPickSource, scenePlaneOf } from 'canvas/pickWalk';\nimport type { View } from 'core/viewport/view';\nimport type { LayerEnumerableAdapter } from 'core/adapters/types';\nimport type { MoveAdapter } from 'core/adapters/types';\nimport type { AreaSelectAdapter } from 'core/adapters/types';\nimport type { NodeId } from 'core/scene/types';\nimport { defineTool } from '../../overlayBinding';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { Tool } from '../../overlayBinding';\nimport { pickTopMostHit } from '../pickTopMostHit';\nimport { adapterPointQuery } from './adapterPointQuery';\nimport { onBody, onEmptyCanvas } from './selectionContributions';\nimport type { PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport { MULTI_RESIZE_TARGET_ID, type Bounds } from '../shared/selectionTarget';\nexport type { Bounds };\nexport { MULTI_RESIZE_TARGET_ID };\n\n/** Options for `useSelectTool`: how a point resolves to nodes, how a click\n * chooses among them, and the appearance of the marquee. */\nexport interface UseSelectToolOptions<TPose> {\n /** Return ids of all objects whose painted body covers (worldX, worldY).\n * Order doesn't matter — the tool collapses parent/child overlap via\n * `pickTopMostHit`. When omitted, defaults to an AABB-vs-point scan over\n * `adapter.getNodes()` using the pose descriptor. Override for tighter\n * shapes (path / polygon hit-tests). */\n pickEvery?: (worldX: number, worldY: number) => string[];\n /** Optional alt-aware selection-update hit returning the single id the\n * click should act on. */\n pickBest?: (\n worldX: number,\n worldY: number,\n alt: boolean,\n selection: readonly string[],\n ) => string | null;\n /** How to read poses for the default `pickEvery`. Default\n * `AUTO_POSE_DESCRIPTOR`. */\n poseDescriptor?: PoseDescriptor<TPose>;\n /**\n * How the default `pickEvery` decides a **leaf** node covers the pointer.\n * Ignored when `pickEvery` is supplied.\n *\n * - `'aabb'` (default) — the pose rect: a click anywhere in the bounding\n * box selects the node.\n * - `'silhouette'` — the pose rect as a pre-test, then the ink the painter\n * lays down: `findShapeSilhouette` filled or not per the painter's `ink`,\n * plus its outline widened by the stroke half-width and `pickTolerance`.\n * A click inside the bounding box but outside the drawn shape misses —\n * the concave notch of a star, the corner outside an ellipse, the blank\n * half of a text box — while a click on the thin outline of an unfilled\n * shape hits.\n *\n * Container nodes already consult their silhouette unconditionally (it is\n * how their clip is derived). A painter with no `silhouette` falls back to\n * the AABB.\n */\n leafPicking?: 'aabb' | 'silhouette';\n /**\n * Grab slop around a shape's outline, in **world** units. Default 0.\n *\n * Only consulted under `leafPicking: 'silhouette'`. World units because\n * this hook has no view; `<SceneCanvas>` takes a screen-pixel figure\n * (`geometry.pickTolerancePx`) and divides by scale on its own pick path.\n * Without some slop a hairline outline is an unhittable target.\n */\n pickTolerance?: number;\n /** Painted alpha per node in the view this tool picks for. A node painted\n * at alpha 0 is not under the pointer. Ignored when `pickEvery` is\n * supplied. */\n alphaOf?: (id: string) => number;\n /** Whether a node's `layer` reaches the screen in the view this tool picks\n * for. Ignored when `pickEvery` is supplied. */\n layerIsPainted?: (layer: string) => boolean;\n /** The camera of the view this tool picks for. With it, a node on an\n * adapter layer carrying `parallax` (`getLayers`) is picked where that\n * camera's plane paints it; without it, every layer is taken to move with\n * the camera. Ignored when `pickEvery` is supplied. */\n getView?: () => View | null;\n /**\n * When this returns true, a Shift/Meta extend-click must NOT change the\n * node selection.\n *\n * `<SceneCanvas>` wires it to \"a path is in anchor-edit mode\", where\n * Shift-click means \"add this anchor to the anchor selection\". Without\n * the lock the same click also toggles the edited node out of the node\n * selection, and the `editAnchors` dep treats that as the edit target\n * disappearing.\n *\n * Only extend-clicks are locked. A plain click still re-selects, so\n * clicking a different node exits edit mode as usual.\n */\n extendClickLocked?: () => boolean;\n}\n\n/** Intersection of the move + area-select adapter interfaces.\n * Resize and rotate run through `resizeAction` / `rotateAction`. */\nexport type SelectAdapter<TNode extends { id: string }, TPose> =\n MoveAdapter<TNode, TPose>\n & AreaSelectAdapter\n & LayerEnumerableAdapter;\n\n/**\n * What the press classified, carried from `select.pick` (pointerDown) to\n * `select.collapseDeferred` (click) and to the tool's cursor.\n *\n * This is tool-local bookkeeping between two dispatches of the same gesture,\n * so it lives in a ref the tool owns rather than in dispatcher state.\n *\n * @internal\n */\ninterface PressClassification {\n /**\n * Set when the press hit an already-selected node inside a multi-selection\n * with no extend modifier.\n *\n * The selection is deliberately NOT collapsed on the press: the user may be\n * starting a drag of the whole set. If the gesture turns out to be a click,\n * `select.collapseDeferred` collapses to this id on release.\n */\n deferredClickId: string | null;\n}\n\n\n\n/** Active-slot Tool:\n * - `select.pick` classifies the press (pointerDown) — it runs the tool's own\n * pickBest/pickEvery so click semantics (selection replace, extend,\n * deferred collapse) live in one place.\n * - an empty drag marquees (`areaSelect`) and a click on empty clears the\n * selection (`clearSelection`); the marquee renders via the dispatcher\n * overlay layer, driven by areaSelectAction's `overlay()`.\n * - moving and transforming the selection are not the tool's: they are the\n * ambient bindings in `selectionContributions.ts`.\n */\nexport function useSelectTool<TNode extends { id: string }, TPose>(\n adapter: SelectAdapter<TNode, TPose>,\n options: UseSelectToolOptions<TPose>,\n): Tool {\n\n // pickEvery / boundsOf defaults — for any adapter the kit can derive both\n // from `adapter.getNodes()` + `adapter.getPose(id)` + the descriptor.\n const d = (options.poseDescriptor ?? AUTO_POSE_DESCRIPTOR) as PoseDescriptor<TPose>;\n const preciseLeaves = options.leafPicking === 'silhouette';\n const tolerance = options.pickTolerance ?? 0;\n const pickEveryFn = options.pickEvery ?? ((worldX: number, worldY: number): string[] => {\n const camera = options.getView?.() ?? null;\n const planeOf = camera ? scenePlaneOf(adapter.getLayers?.(), camera) : null;\n return pickWalk<TPose>(adapterPickSource(adapter as never, {\n ...(options.alphaOf ? { alphaOf: options.alphaOf } : {}),\n ...(options.layerIsPainted ? { layerIsPainted: options.layerIsPainted } : {}),\n ...(planeOf ? { planeOf } : {}),\n }), adapterPointQuery(d, preciseLeaves)(worldX, worldY, tolerance));\n });\n\n const pickEveryRef = useLatest(pickEveryFn);\n\n // What the last press classified. Written by `select.pick`, read by\n // `select.collapseDeferred` and the cursor. See `PressClassification`.\n const pressRef = useRef<PressClassification>({ deferredClickId: null });\n\n // Options in a ref so the actions — built once — always see the live\n // callbacks without rebuilding the Tool record.\n const optionsRef = useLatest(options);\n const adapterRef = useLatest(adapter);\n\n /**\n * `select.pick` — classifies the press and updates the node selection.\n *\n * Bound to `pointerDown` rather than `click` on purpose: pressing an\n * unselected node must highlight it while the button is still down, and any\n * drag that follows has to start from the updated selection (both\n * `moveAction` and `cloneAction` read `selection.get()` in their `start`).\n */\n const pickAction = useMemo<Action>(() => ({\n id: 'select.pick',\n label: 'Select — pick under pointer',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const p = params as {\n worldX?: number; worldY?: number;\n affordance?: unknown;\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n const selection = deps.selection;\n if (!selection || p?.worldX === undefined || p.worldY === undefined) return;\n const mods = p.mods ?? { alt: false, ctrl: false, meta: false, shift: false };\n const opts = optionsRef.current;\n\n const sel = selection.get();\n const top = opts.pickBest\n ? opts.pickBest(p.worldX, p.worldY, mods.alt, sel)\n : (() => {\n const ids = pickEveryRef.current(p.worldX, p.worldY);\n if (ids.length === 0) return null;\n return pickTopMostHit(ids, adapterRef.current) ?? ids[0];\n })();\n\n if (top === null) {\n pressRef.current = { deferredClickId: null };\n return;\n }\n\n const hitAlreadySelected = sel.includes(top as NodeId);\n const isExtend = mods.shift || mods.meta;\n // See `extendClickLocked`. An option rather than `Action.enabled`\n // because it only applies to *extend* presses, and `enabled` is\n // evaluated without the event's modifiers.\n const extendLocked = isExtend && opts.extendClickLocked?.() === true;\n const deferClick = hitAlreadySelected && sel.length > 1 && !isExtend;\n if (!deferClick && !extendLocked) {\n selection.applyClick(top as NodeId, mods);\n }\n pressRef.current = { deferredClickId: deferClick ? top : null };\n },\n },\n }), [optionsRef, pickEveryRef, adapterRef]);\n\n /**\n * `select.collapseDeferred` — the release half of the deferred multi-click.\n *\n * Pressing an already-selected node inside a multi-selection leaves the\n * selection alone so the press can start a drag of the whole set. If the\n * gesture ends without a drag, this collapses to the clicked node.\n */\n const collapseDeferredAction = useMemo<Action>(() => ({\n id: 'select.collapseDeferred',\n label: 'Select — collapse deferred click',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n // Declining when there is nothing deferred is what keeps this binding\n // from swallowing every click on a node. It is bound at ACTIVE scope, so\n // without the gate it would outrank ambient click bindings like\n // `selectAnchor` and silently break anchor selection.\n enabled: () =>\n pressRef.current.deferredClickId !== null\n ? true\n : ActionDisabledReason.NotApplicable,\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const deferred = pressRef.current.deferredClickId;\n pressRef.current = { deferredClickId: null };\n if (deferred === null) return;\n const selection = deps.selection;\n if (!selection) return;\n const p = params as {\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n selection.applyClick(\n deferred as NodeId,\n p?.mods ?? { alt: false, ctrl: false, meta: false, shift: false },\n );\n },\n },\n }), []);\n\n return useMemo(\n () => {\n const base = defineTool({\n id: 'select',\n keybinding: { key: 'V' },\n capabilities: ['creates-selection'],\n hookName: 'useSelectTool',\n // The mid-gesture cursors live on the actions that own those gestures\n // (`moveAction.activeCursor`, `areaSelectAction.activeCursor`).\n cursor: 'default',\n presentation: {\n label: 'Select',\n icon: createElement(SelectIcon),\n group: 'select',\n },\n actions: [pickAction, collapseDeferredAction],\n });\n\n return {\n ...base,\n // Declarative bindings for the gesture dispatcher. The select tool\n // only chooses: press → classify + select, release → collapse a\n // deferred multi-click, empty drag → marquee, click on empty → clear.\n // Moving, cloning, resizing and rotating the selection are ambient\n // bindings owned by the selection (`selectionContributions.ts`), so\n // they run under any tool that leaves the gesture unclaimed.\n bindings: [\n // Every press that landed on the scene rather than on chrome. It\n // classifies the press and applies the selection change, and it does\n // not consume the gesture — the same press goes on to open a drag or\n // synthesize a click.\n //\n // The no-affordance target is load-bearing twice over. A press on a\n // resize handle, a rotate ring, a path anchor, or a registered\n // layer's own chrome is not a body pick, and re-picking underneath\n // it would change the selection the user was about to act on. And\n // because it is expressed in the SPEC rather than as an early\n // return in the action, the press falls through to whatever owns\n // that chrome instead of being consumed here — which is how an\n // ambient binding (`@weasel-js/hud`) gets to see it at all.\n //\n // Modifiers are all `'optional'` because they are *data* here\n // (forwarded to `SelectionApi.applyClick`) rather than a route.\n {\n spec: {\n kind: 'pointerDown' as const,\n target: { kindOf: onBody },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.pick',\n },\n // Release half of the deferred multi-click, modifiers as above. On a node\n // only: a drag leaves a deferral unspent, and a click on empty must clear.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: onBody },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.collapseDeferred',\n },\n // Empty drag → marquee. `onEmptyCanvas` rather than a bare `'empty'`\n // target: the ambient bindings that own the handles rank below this\n // active one, so `'empty'` took drags that start on them.\n {\n spec: { kind: 'drag' as const, target: { kindOf: onEmptyCanvas } },\n actionId: 'areaSelect',\n },\n // resize/rotate bind only drag (no click), so a click on either handle\n // (body genuinely empty) would hit target:'empty' and wrongly clear selection.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: onEmptyCanvas },\n mods: {},\n },\n actionId: 'clearSelection',\n },\n ],\n };\n },\n [pickAction, collapseDeferredAction],\n );\n}\n"],"mappings":";;;;;;;;;;;;AA0IA,SAAgBC,EACd,GACA,GACM;CAIN,IAAMC,IAAKC,EAAQ,kBAAkBC,GAC/BC,IAAgBF,EAAQ,gBAAgB,cACxCG,IAAYH,EAAQ,iBAAiB,GACrCI,IAAcJ,EAAQ,eAAe,GAAgB,MAA6B;EACtF,IAAMK,IAASL,EAAQ,UAAU,KAAK,MAChCM,IAAUD,IAASE,EAAaC,EAAQ,YAAY,GAAGH,CAAM,IAAI;EACvE,OAAOI,EAAgBC,EAAkBF,GAAkB;GACzD,GAAIR,EAAQ,UAAU,EAAE,SAASA,EAAQ,QAAQ,IAAI,CAAC;GACtD,GAAIA,EAAQ,iBAAiB,EAAE,gBAAgBA,EAAQ,eAAe,IAAI,CAAC;GAC3E,GAAIM,IAAU,EAAE,WAAQ,IAAI,CAAC;EAC/B,CAAC,GAAGK,EAAkBZ,GA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,EAAE,QAAQA,EAAc;KAChC,MAAM,CAAC;IACT;IACA,UAAU;GACZ;EACF;CACF,IAEF,CAACtB,GAAYgB,CAAsB,CACrC;AACF"}
1
+ {"version":3,"file":"useSelectTool.js","names":["SelectIcon","useSelectTool","d","options","AUTO_POSE_DESCRIPTOR","preciseLeaves","tolerance","pickEveryFn","camera","planeOf","scenePlaneOf","adapter","pickWalk","adapterPickSource","adapterPointQuery","worldX","worldY","pickEveryRef","useLatest","pressRef","useRef","optionsRef","adapterRef","pickAction","useMemo","p","params","selection","deps","mods","opts","sel","top","ids","pickTopMostHit","hitAlreadySelected","isExtend","extendLocked","deferClick","collapseDeferredAction","ActionDisabledReason","deferred","defineTool","createElement","onBody","onEmptyCanvas"],"sources":["../../../../src/tools/builtin/select/useSelectTool.ts"],"sourcesContent":["import { useMemo, useRef, createElement } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { SelectIcon } from '../../../icons';\nimport { pickWalk, adapterPickSource, scenePlaneOf } from 'canvas/pickWalk';\nimport type { View } from 'core/viewport/view';\nimport type { LayerEnumerableAdapter } from 'core/adapters/types';\nimport type { MoveAdapter } from 'core/adapters/types';\nimport type { AreaSelectAdapter } from 'core/adapters/types';\nimport type { NodeId } from 'core/scene/types';\nimport { defineTool } from '../../overlayBinding';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { Tool } from '../../overlayBinding';\nimport { pickTopMostHit } from '../pickTopMostHit';\nimport { adapterPointQuery } from './adapterPointQuery';\nimport { onBody, onEmptyCanvas } from './selectionContributions';\nimport type { PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport { MULTI_RESIZE_TARGET_ID, type Bounds } from '../shared/selectionTarget';\nexport type { Bounds };\nexport { MULTI_RESIZE_TARGET_ID };\n\n/** Options for `useSelectTool`: how a point resolves to nodes, how a click\n * chooses among them, and the appearance of the marquee. */\nexport interface UseSelectToolOptions<TPose> {\n /** Return ids of all objects whose painted body covers (worldX, worldY).\n * Order doesn't matter — the tool collapses parent/child overlap via\n * `pickTopMostHit`. When omitted, defaults to an AABB-vs-point walk of\n * the adapter's tree using the pose descriptor. Override for tighter\n * shapes (path / polygon hit-tests). */\n pickEvery?: (worldX: number, worldY: number) => string[];\n /** Optional alt-aware selection-update hit returning the single id the\n * click should act on. */\n pickBest?: (\n worldX: number,\n worldY: number,\n alt: boolean,\n selection: readonly string[],\n ) => string | null;\n /** How to read poses for the default `pickEvery`. Default\n * `AUTO_POSE_DESCRIPTOR`. */\n poseDescriptor?: PoseDescriptor<TPose>;\n /**\n * How the default `pickEvery` decides a **leaf** node covers the pointer.\n * Ignored when `pickEvery` is supplied.\n *\n * - `'aabb'` (default) — the pose rect: a click anywhere in the bounding\n * box selects the node.\n * - `'silhouette'` — the pose rect as a pre-test, then the ink the painter\n * lays down: `findShapeSilhouette` filled or not per the painter's `ink`,\n * plus its outline widened by the stroke half-width and `pickTolerance`.\n * A click inside the bounding box but outside the drawn shape misses —\n * the concave notch of a star, the corner outside an ellipse, the blank\n * half of a text box — while a click on the thin outline of an unfilled\n * shape hits.\n *\n * Container nodes already consult their silhouette unconditionally (it is\n * how their clip is derived). A painter with no `silhouette` falls back to\n * the AABB.\n */\n leafPicking?: 'aabb' | 'silhouette';\n /**\n * Grab slop around a shape's outline, in **world** units. Default 0.\n *\n * Only consulted under `leafPicking: 'silhouette'`. World units because\n * this hook has no view; `<SceneCanvas>` takes a screen-pixel figure\n * (`geometry.pickTolerancePx`) and divides by scale on its own pick path.\n * Without some slop a hairline outline is an unhittable target.\n */\n pickTolerance?: number;\n /** Painted alpha per node in the view this tool picks for. A node painted\n * at alpha 0 is not under the pointer. Ignored when `pickEvery` is\n * supplied. */\n alphaOf?: (id: string) => number;\n /** Whether a node's `layer` reaches the screen in the view this tool picks\n * for. Ignored when `pickEvery` is supplied. */\n layerIsPainted?: (layer: string) => boolean;\n /** The camera of the view this tool picks for. With it, a node on an\n * adapter layer carrying `parallax` (`getLayers`) is picked where that\n * camera's plane paints it; without it, every layer is taken to move with\n * the camera. Ignored when `pickEvery` is supplied. */\n getView?: () => View | null;\n /**\n * When this returns true, a Shift/Meta extend-click must NOT change the\n * node selection.\n *\n * `<SceneCanvas>` wires it to \"a path is in anchor-edit mode\", where\n * Shift-click means \"add this anchor to the anchor selection\". Without\n * the lock the same click also toggles the edited node out of the node\n * selection, and the `editAnchors` dep treats that as the edit target\n * disappearing.\n *\n * Only extend-clicks are locked. A plain click still re-selects, so\n * clicking a different node exits edit mode as usual.\n */\n extendClickLocked?: () => boolean;\n}\n\n/** Intersection of the move + area-select adapter interfaces.\n * Resize and rotate run through `resizeAction` / `rotateAction`. */\nexport type SelectAdapter<TNode extends { id: string }, TPose> =\n MoveAdapter<TNode, TPose>\n & AreaSelectAdapter\n & LayerEnumerableAdapter;\n\n/**\n * What the press classified, carried from `select.pick` (pointerDown) to\n * `select.collapseDeferred` (click) and to the tool's cursor.\n *\n * This is tool-local bookkeeping between two dispatches of the same gesture,\n * so it lives in a ref the tool owns rather than in dispatcher state.\n *\n * @internal\n */\ninterface PressClassification {\n /**\n * Set when the press hit an already-selected node inside a multi-selection\n * with no extend modifier.\n *\n * The selection is deliberately NOT collapsed on the press: the user may be\n * starting a drag of the whole set. If the gesture turns out to be a click,\n * `select.collapseDeferred` collapses to this id on release.\n */\n deferredClickId: string | null;\n}\n\n\n\n/** Active-slot Tool:\n * - `select.pick` classifies the press (pointerDown) — it runs the tool's own\n * pickBest/pickEvery so click semantics (selection replace, extend,\n * deferred collapse) live in one place.\n * - an empty drag marquees (`areaSelect`) and a click on empty clears the\n * selection (`clearSelection`); the marquee renders via the dispatcher\n * overlay layer, driven by areaSelectAction's `overlay()`.\n * - moving and transforming the selection are not the tool's: they are the\n * ambient bindings in `selectionContributions.ts`.\n */\nexport function useSelectTool<TNode extends { id: string }, TPose>(\n adapter: SelectAdapter<TNode, TPose>,\n options: UseSelectToolOptions<TPose>,\n): Tool {\n\n // pickEvery / boundsOf defaults — for any adapter the kit can derive both\n // from the adapter's tree + `adapter.getPose(id)` + the descriptor.\n const d = (options.poseDescriptor ?? AUTO_POSE_DESCRIPTOR) as PoseDescriptor<TPose>;\n const preciseLeaves = options.leafPicking === 'silhouette';\n const tolerance = options.pickTolerance ?? 0;\n const pickEveryFn = options.pickEvery ?? ((worldX: number, worldY: number): string[] => {\n const camera = options.getView?.() ?? null;\n const planeOf = camera ? scenePlaneOf(adapter.getLayers?.(), camera) : null;\n return pickWalk<TPose>(adapterPickSource(adapter, {\n ...(options.alphaOf ? { alphaOf: options.alphaOf } : {}),\n ...(options.layerIsPainted ? { layerIsPainted: options.layerIsPainted } : {}),\n ...(planeOf ? { planeOf } : {}),\n }), adapterPointQuery(d, preciseLeaves)(worldX, worldY, tolerance));\n });\n\n const pickEveryRef = useLatest(pickEveryFn);\n\n // What the last press classified. Written by `select.pick`, read by\n // `select.collapseDeferred` and the cursor. See `PressClassification`.\n const pressRef = useRef<PressClassification>({ deferredClickId: null });\n\n // Options in a ref so the actions — built once — always see the live\n // callbacks without rebuilding the Tool record.\n const optionsRef = useLatest(options);\n const adapterRef = useLatest(adapter);\n\n /**\n * `select.pick` — classifies the press and updates the node selection.\n *\n * Bound to `pointerDown` rather than `click` on purpose: pressing an\n * unselected node must highlight it while the button is still down, and any\n * drag that follows has to start from the updated selection (both\n * `moveAction` and `cloneAction` read `selection.get()` in their `start`).\n */\n const pickAction = useMemo<Action>(() => ({\n id: 'select.pick',\n label: 'Select — pick under pointer',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const p = params as {\n worldX?: number; worldY?: number;\n affordance?: unknown;\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n const selection = deps.selection;\n if (!selection || p?.worldX === undefined || p.worldY === undefined) return;\n const mods = p.mods ?? { alt: false, ctrl: false, meta: false, shift: false };\n const opts = optionsRef.current;\n\n const sel = selection.get();\n const top = opts.pickBest\n ? opts.pickBest(p.worldX, p.worldY, mods.alt, sel)\n : (() => {\n const ids = pickEveryRef.current(p.worldX, p.worldY);\n if (ids.length === 0) return null;\n return pickTopMostHit(ids, adapterRef.current) ?? ids[0];\n })();\n\n if (top === null) {\n pressRef.current = { deferredClickId: null };\n return;\n }\n\n const hitAlreadySelected = sel.includes(top as NodeId);\n const isExtend = mods.shift || mods.meta;\n // See `extendClickLocked`. An option rather than `Action.enabled`\n // because it only applies to *extend* presses, and `enabled` is\n // evaluated without the event's modifiers.\n const extendLocked = isExtend && opts.extendClickLocked?.() === true;\n const deferClick = hitAlreadySelected && sel.length > 1 && !isExtend;\n if (!deferClick && !extendLocked) {\n selection.applyClick(top as NodeId, mods);\n }\n pressRef.current = { deferredClickId: deferClick ? top : null };\n },\n },\n }), [optionsRef, pickEveryRef, adapterRef]);\n\n /**\n * `select.collapseDeferred` — the release half of the deferred multi-click.\n *\n * Pressing an already-selected node inside a multi-selection leaves the\n * selection alone so the press can start a drag of the whole set. If the\n * gesture ends without a drag, this collapses to the clicked node.\n */\n const collapseDeferredAction = useMemo<Action>(() => ({\n id: 'select.collapseDeferred',\n label: 'Select — collapse deferred click',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n // Declining when there is nothing deferred is what keeps this binding\n // from swallowing every click on a node. It is bound at ACTIVE scope, so\n // without the gate it would outrank ambient click bindings like\n // `selectAnchor` and silently break anchor selection.\n enabled: () =>\n pressRef.current.deferredClickId !== null\n ? true\n : ActionDisabledReason.NotApplicable,\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const deferred = pressRef.current.deferredClickId;\n pressRef.current = { deferredClickId: null };\n if (deferred === null) return;\n const selection = deps.selection;\n if (!selection) return;\n const p = params as {\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n selection.applyClick(\n deferred as NodeId,\n p?.mods ?? { alt: false, ctrl: false, meta: false, shift: false },\n );\n },\n },\n }), []);\n\n return useMemo(\n () => {\n const base = defineTool({\n id: 'select',\n keybinding: { key: 'V' },\n capabilities: ['creates-selection'],\n hookName: 'useSelectTool',\n // The mid-gesture cursors live on the actions that own those gestures\n // (`moveAction.activeCursor`, `areaSelectAction.activeCursor`).\n cursor: 'default',\n presentation: {\n label: 'Select',\n icon: createElement(SelectIcon),\n group: 'select',\n },\n actions: [pickAction, collapseDeferredAction],\n });\n\n return {\n ...base,\n // Declarative bindings for the gesture dispatcher. The select tool\n // only chooses: press → classify + select, release → collapse a\n // deferred multi-click, empty drag → marquee, click on empty → clear.\n // Moving, cloning, resizing and rotating the selection are ambient\n // bindings owned by the selection (`selectionContributions.ts`), so\n // they run under any tool that leaves the gesture unclaimed.\n bindings: [\n // Every press that landed on the scene rather than on chrome. It\n // classifies the press and applies the selection change, and it does\n // not consume the gesture — the same press goes on to open a drag or\n // synthesize a click.\n //\n // The no-affordance target is load-bearing twice over. A press on a\n // resize handle, a rotate ring, a path anchor, or a registered\n // layer's own chrome is not a body pick, and re-picking underneath\n // it would change the selection the user was about to act on. And\n // because it is expressed in the SPEC rather than as an early\n // return in the action, the press falls through to whatever owns\n // that chrome instead of being consumed here — which is how an\n // ambient binding (`@weasel-js/hud`) gets to see it at all.\n //\n // Modifiers are all `'optional'` because they are *data* here\n // (forwarded to `SelectionApi.applyClick`) rather than a route.\n {\n spec: {\n kind: 'pointerDown' as const,\n target: { kindOf: onBody },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.pick',\n },\n // Release half of the deferred multi-click, modifiers as above. On a node\n // only: a drag leaves a deferral unspent, and a click on empty must clear.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: onBody },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.collapseDeferred',\n },\n // Empty drag → marquee. `onEmptyCanvas` rather than a bare `'empty'`\n // target: the ambient bindings that own the handles rank below this\n // active one, so `'empty'` took drags that start on them.\n {\n spec: { kind: 'drag' as const, target: { kindOf: onEmptyCanvas } },\n actionId: 'areaSelect',\n },\n // resize/rotate bind only drag (no click), so a click on either handle\n // (body genuinely empty) would hit target:'empty' and wrongly clear selection.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: onEmptyCanvas },\n mods: {},\n },\n actionId: 'clearSelection',\n },\n ],\n };\n },\n [pickAction, collapseDeferredAction],\n );\n}\n"],"mappings":";;;;;;;;;;;;;AA0IA,SAAgBC,EACd,GACA,GACM;CAIN,IAAMC,IAAKC,EAAQ,kBAAkBC,GAC/BC,IAAgBF,EAAQ,gBAAgB,cACxCG,IAAYH,EAAQ,iBAAiB,GACrCI,IAAcJ,EAAQ,eAAe,GAAgB,MAA6B;EACtF,IAAMK,IAASL,EAAQ,UAAU,KAAK,MAChCM,IAAUD,IAASE,EAAaC,EAAQ,YAAY,GAAGH,CAAM,IAAI;EACvE,OAAOI,EAAgBC,EAAkBF,GAAS;GAChD,GAAIR,EAAQ,UAAU,EAAE,SAASA,EAAQ,QAAQ,IAAI,CAAC;GACtD,GAAIA,EAAQ,iBAAiB,EAAE,gBAAgBA,EAAQ,eAAe,IAAI,CAAC;GAC3E,GAAIM,IAAU,EAAE,WAAQ,IAAI,CAAC;EAC/B,CAAC,GAAGK,EAAkBZ,GAAGG,CAAa,CAAC,CAACU,GAAQC,GAAQV,CAAS,CAAC;CACpE,IAEMW,IAAeC,EAAUX,CAAW,GAIpCY,IAAWC,EAA4B,EAAE,iBAAiB,KAAK,CAAC,GAIhEC,IAAaH,EAAUf,CAAO,GAC9BmB,IAAaJ,EAAUP,CAAO,GAU9BY,IAAaC,SAAuB;EACxC,IAAI;EACJ,OAAO;EACP,UAAU,EAAE,YAAY,oBAAoB;EAC5C,UAAU,CAAC,WAAW;EACtB,SAAS;GACP,QAAQ;GACR,MAAM,GAAM,MAAW;IACrB,IAAMC,IAAIC,GAKJC,I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CAACD,GAAW;IAChB,IAAMF,IAAIC;IAGV,EAAU,WACRe,GACAhB,GAAG,QAAQ;KAAE,KAAK;KAAO,MAAM;KAAO,MAAM;KAAO,OAAO;IAAM,CAClE;GACF;EACF;CACF,IAAI,CAAC,CAAC;CAEN,OAAOD,SAkBI;EACL,GAjBWkB,EAAW;GACtB,IAAI;GACJ,YAAY,EAAE,KAAK,IAAI;GACvB,cAAc,CAAC,mBAAmB;GAClC,UAAU;GAGV,QAAQ;GACR,cAAc;IACZ,OAAO;IACP,MAAMC,EAAc3C,CAAU;IAC9B,OAAO;GACT;GACA,SAAS,CAACuB,GAAYgB,CAAsB;EAC9C,CAGK;EAOH,UAAU;GAiBR;IACE,MAAM;KACJ,MAAM;KACN,QAAQ,EAAE,QAAQK,EAAO;KACzB,MAAM;MAAE,OAAO;MAAqB,KAAK;MAAqB,MAAM;MAAqB,MAAM;KAAoB;IACrH;IACA,UAAU;GACZ;GAGA;IACE,MAAM;KACJ,MAAM;KACN,QAAQ,EAAE,QAAQA,EAAO;KACzB,MAAM;MAAE,OAAO;MAAqB,KAAK;MAAqB,MAAM;MAAqB,MAAM;KAAoB;IACrH;IACA,UAAU;GACZ;GAIA;IACE,MAAM;KAAE,MAAM;KAAiB,QAAQ,EAAE,QAAQC,EAAc;IAAE;IACjE,UAAU;GACZ;GAGA;IACE,MAAM;KACJ,MAAM;KACN,QAAQ,EAAE,QAAQA,EAAc;KAChC,MAAM,CAAC;IACT;IACA,UAAU;GACZ;EACF;CACF,IAEF,CAACtB,GAAYgB,CAAsB,CACrC;AACF"}
@@ -2,26 +2,27 @@ import { viewToTransform as e } from "../../../core/viewport/view.js";
2
2
  import { worldToScreen as t } from "../../../core/viewport/viewTransform.js";
3
3
  import { sliceAction as n } from "../../../interactions/actions/defaults/slice.js";
4
4
  import { defineTool as r } from "../../overlayBinding.js";
5
- import { createPointerFollower as i } from "../shared/pointerFollower.js";
6
- import { OVERLAY_ROLE_STROKES as a } from "../../../canvas/overlayRoleStrokes.js";
7
- import { ellipsePath as o, polylineFromPoints as s, withinPxRadius as c } from "@weasel-js/geom";
8
- import { useMemo as l, useRef as u } from "react";
9
- import { useLatest as d } from "@weasel-js/react";
10
- import { ActionDisabledReason as f } from "@weasel-js/routing";
11
- import { createEmitter as p } from "@weasel-js/registry";
5
+ import i from "../../../icons/SliceIcon.js";
6
+ import { createPointerFollower as a } from "../shared/pointerFollower.js";
7
+ import { OVERLAY_ROLE_STROKES as o } from "../../../canvas/overlayRoleStrokes.js";
8
+ import { ellipsePath as s, polylineFromPoints as c, withinPxRadius as l } from "@weasel-js/geom";
9
+ import { createElement as u, useMemo as d, useRef as f } from "react";
10
+ import { useLatest as p } from "@weasel-js/react";
11
+ import { ActionDisabledReason as m } from "@weasel-js/routing";
12
+ import { createEmitter as h } from "@weasel-js/registry";
12
13
  //#region src/tools/builtin/slice/useSliceTool.ts
13
- var m = 3;
14
- function h(h = {}) {
15
- let g = u({ points: [] }), _ = d({ closeHitRadius: h.closeHitRadius ?? 8 }), v = l(() => {
16
- let e = p();
14
+ var g = 3;
15
+ function _(_ = {}) {
16
+ let v = f({ points: [] }), y = p({ closeHitRadius: _.closeHitRadius ?? 8 }), b = d(() => {
17
+ let e = h();
17
18
  return {
18
19
  notify: e.emit,
19
20
  listen: e.subscribe,
20
- ...i(e.emit)
21
+ ...a(e.emit)
21
22
  };
22
- }, []), y = l(() => {
23
- let e = () => g.current.points, t = () => e().length > 0 || f.NotApplicable, r = () => {
24
- g.current.points = [], v.unfollow(), v.notify();
23
+ }, []), x = d(() => {
24
+ let e = () => v.current.points, t = () => e().length > 0 || m.NotApplicable, r = () => {
25
+ v.current.points = [], b.unfollow(), b.notify();
25
26
  }, i = (t) => {
26
27
  let n = e().slice();
27
28
  r(), n.length >= 2 && t.slice?.commit(n);
@@ -30,7 +31,7 @@ function h(h = {}) {
30
31
  x: 1,
31
32
  y: 1
32
33
  };
33
- if (a.length >= 3 && c(n - o.x, r - o.y, _.current.closeHitRadius, s)) {
34
+ if (a.length >= 3 && l(n - o.x, r - o.y, y.current.closeHitRadius, s)) {
34
35
  a.push({
35
36
  x: o.x,
36
37
  y: o.y
@@ -40,7 +41,7 @@ function h(h = {}) {
40
41
  a.push({
41
42
  x: n,
42
43
  y: r
43
- }), v.follow(t.pointer), v.notify();
44
+ }), b.follow(t.pointer), b.notify();
44
45
  }, o = { capability: "edits-page" };
45
46
  return [
46
47
  n,
@@ -53,7 +54,7 @@ function h(h = {}) {
53
54
  "view",
54
55
  "pointer"
55
56
  ],
56
- enabled: (e) => e?.slice ? !0 : f.NotApplicable,
57
+ enabled: (e) => e?.slice ? !0 : m.NotApplicable,
57
58
  invoker: {
58
59
  timing: "immediate",
59
60
  run: (e, t) => {
@@ -105,7 +106,7 @@ function h(h = {}) {
105
106
  invoker: {
106
107
  timing: "immediate",
107
108
  run: () => {
108
- e().pop(), e().length === 0 ? r() : v.notify();
109
+ e().pop(), e().length === 0 ? r() : b.notify();
109
110
  }
110
111
  }
111
112
  },
@@ -120,36 +121,36 @@ function h(h = {}) {
120
121
  }
121
122
  }
122
123
  ];
123
- }, [v, _]), b = l(() => ({
124
+ }, [b, y]), S = d(() => ({
124
125
  id: "slice-pending-cut",
125
126
  label: "Slice — pending cut",
126
127
  space: "screen",
127
- subscribe: v.listen,
128
+ subscribe: b.listen,
128
129
  draw: (n, r) => {
129
- let i = g.current.points;
130
+ let i = v.current.points;
130
131
  if (i.length === 0) return [];
131
- let c = e(r), l = (e) => {
132
- let [n, r] = t(e.x, e.y, c);
132
+ let a = e(r), l = (e) => {
133
+ let [n, r] = t(e.x, e.y, a);
133
134
  return {
134
135
  x: n,
135
136
  y: r
136
137
  };
137
- }, u = i.map(l), d = v.pointer()?.get();
138
+ }, u = i.map(l), d = b.pointer()?.get();
138
139
  d && u.push(l({
139
140
  x: d.worldX,
140
141
  y: d.worldY
141
142
  }));
142
- let f = a.cut, p = [];
143
+ let f = o.cut, p = [];
143
144
  u.length >= 2 && p.push({
144
145
  kind: "path",
145
- path: s(u),
146
+ path: c(u),
146
147
  stroke: f
147
148
  });
148
149
  for (let e of i.map(l)) p.push({
149
150
  kind: "path",
150
- path: o({
151
- x: e.x - m,
152
- y: e.y - m,
151
+ path: s({
152
+ x: e.x - g,
153
+ y: e.y - g,
153
154
  width: 6,
154
155
  height: 6
155
156
  }),
@@ -157,21 +158,22 @@ function h(h = {}) {
157
158
  });
158
159
  return p;
159
160
  }
160
- }), [v]), { keybinding: x } = h;
161
- return l(() => r({
161
+ }), [b]), { keybinding: C } = _;
162
+ return d(() => r({
162
163
  id: "slice",
163
164
  capabilities: ["edits-page"],
164
165
  hookName: "useSliceTool",
165
166
  cursor: "crosshair",
166
167
  presentation: {
167
168
  label: "Slice",
169
+ icon: u(i),
168
170
  group: "shape"
169
171
  },
170
- ...x === null ? {} : { keybinding: x ?? { key: "K" } },
171
- actions: y,
172
- overlay: b,
172
+ ...C === null ? {} : { keybinding: C ?? { key: "K" } },
173
+ actions: x,
174
+ overlay: S,
173
175
  onDeactivate: () => {
174
- g.current.points = [], v.unfollow(), v.notify();
176
+ v.current.points = [], b.unfollow(), b.notify();
175
177
  },
176
178
  bindings: [
177
179
  {
@@ -241,13 +243,13 @@ function h(h = {}) {
241
243
  }
242
244
  ]
243
245
  }), [
244
- y,
245
- b,
246
246
  x,
247
- v
247
+ S,
248
+ C,
249
+ b
248
250
  ]);
249
251
  }
250
252
  //#endregion
251
- export { h as useSliceTool };
253
+ export { _ as useSliceTool };
252
254
 
253
255
  //# sourceMappingURL=useSliceTool.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSliceTool.js","names":["VERTEX_RADIUS_PX","useSliceTool","scratchRef","useRef","optsRef","useLatest","options","live","useMemo","changed","createEmitter","createPointerFollower","actions","points","pending","ActionDisabledReason","reset","commit","cut","deps","place","pts","first","scale","withinPxRadius","x","y","eligible","sliceAction","\"slice\"","p","params","reason","at","endCtx","overlay","t","viewToTransform","view","toScreen","worldToScreen","run","stroke","OVERLAY_ROLE_STROKES","\"cut\"","out","polylineFromPoints","ellipsePath","defineTool","keybinding"],"sources":["../../../../src/tools/builtin/slice/useSliceTool.ts"],"sourcesContent":["import { useMemo, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport type { RenderLayer } from 'core/layers/render';\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { Action, ActionDeps, InvocationCtx, ToolKeybinding } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport { createPointerFollower } from '../shared/pointerFollower';\nimport { sliceAction } from 'interactions/actions/defaults/slice';\nimport { withinPxRadius } from '@weasel-js/geom';\nimport { worldToScreen } from 'core/viewport/viewTransform';\nimport { viewToTransform } from 'core/viewport/view';\nimport { ellipsePath, polylineFromPoints } from '@weasel-js/geom';\nimport { OVERLAY_ROLE_STROKES } from 'canvas/overlayRoleStrokes';\nimport { createEmitter } from '@weasel-js/registry';\n\n/** Options for `useSliceTool`. */\nexport interface UseSliceToolOptions {\n /** Override the default keybinding (`{ key: 'K' }`). Pass `null` to omit. */\n keybinding?: ToolKeybinding | null;\n /** Screen-px radius around the first point within which a click closes the\n * cut into a loop and commits it. Default `8`. */\n closeHitRadius?: number;\n}\n\n/** The click-by-click cut in progress, in world coords. */\nexport interface SliceScratch {\n points: { x: number; y: number }[];\n}\n\nconst VERTEX_RADIUS_PX = 3;\n\n/**\n * Knife tool. A drag cuts along a straight line, and an Alt-drag along its\n * freehand trail, through `sliceAction`. Clicks place a cut one point at a\n * time: Enter or a double-click commits it, Escape discards it, Backspace\n * takes back the last point, and a click on the first point closes it into a\n * loop and commits. While points are placed, a drag places one more where it\n * is released instead of cutting on its own.\n *\n * Every cut goes to the `slice` dep, which decides what it does to the scene.\n * `<SceneCanvas>` publishes one that cuts every path the cut crosses.\n */\nexport function useSliceTool(options: UseSliceToolOptions = {}): Tool {\n const scratchRef = useRef<SliceScratch>({ points: [] });\n const optsRef = useLatest({ closeHitRadius: options.closeHitRadius ?? 8 });\n\n // What the overlay layer's `subscribe` hears: a change to the points, and,\n // while any are placed, every move of the pointer the rubber band follows.\n const live = useMemo(() => {\n const changed = createEmitter();\n return {\n notify: changed.emit,\n listen: changed.subscribe,\n ...createPointerFollower(changed.emit),\n };\n }, []);\n\n const actions = useMemo<Action[]>(() => {\n const points = () => scratchRef.current.points;\n const pending = () => (points().length > 0 ? true : ActionDisabledReason.NotApplicable);\n\n const reset = (): void => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n };\n const commit = (deps: ActionDeps): void => {\n const cut = points().slice();\n reset();\n if (cut.length >= 2) deps.slice?.commit(cut);\n };\n const place = (deps: ActionDeps, x: number, y: number): void => {\n const pts = points();\n const first = pts[0];\n const scale = deps.view?.get().scale ?? { x: 1, y: 1 };\n if (pts.length >= 3 && withinPxRadius(x - first.x, y - first.y, optsRef.current.closeHitRadius, scale)) {\n pts.push({ x: first.x, y: first.y });\n commit(deps);\n return;\n }\n pts.push({ x, y });\n live.follow(deps.pointer);\n live.notify();\n };\n\n const eligible = { capability: 'edits-page' } as const;\n return [\n sliceAction,\n {\n id: 'slice.addPoint',\n label: 'Slice — place point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: (deps) => (deps?.['slice'] ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const p = params as { pressX?: number; pressY?: number } | undefined;\n if (p?.pressX === undefined || p.pressY === undefined) return;\n place(deps, p.pressX, p.pressY);\n },\n },\n },\n {\n id: 'slice.dragPoint',\n label: 'Slice — drag out a point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: pending,\n invoker: {\n timing: 'ongoing',\n // The dispatcher hands `onEnd` a context with empty deps.\n start: ({ deps }: InvocationCtx) => ({\n onMove: () => {},\n onEnd: (endCtx: InvocationCtx, reason: 'commit' | 'cancel') => {\n if (reason === 'cancel' || points().length === 0) return;\n const at = endCtx.drag?.current ?? endCtx.world;\n place(deps, at.x, at.y);\n },\n }),\n },\n },\n {\n id: 'slice.finish',\n label: 'Slice — cut along the points',\n eligible,\n requires: ['slice'],\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n // A double click arrives after both of its clicks, so the second\n // has already placed a point on top of the first.\n if ((params as { viaDoubleClick?: boolean } | undefined)?.viaDoubleClick) points().pop();\n commit(deps);\n },\n },\n },\n {\n id: 'slice.dropPoint',\n label: 'Slice — take back the last point',\n eligible,\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: () => {\n points().pop();\n if (points().length === 0) reset();\n else live.notify();\n },\n },\n },\n {\n id: 'slice.cancel',\n label: 'Slice — discard the points',\n eligible,\n // Declining with nothing placed leaves Escape to the ambient `escape`.\n enabled: pending,\n invoker: { timing: 'immediate', run: () => reset() },\n },\n ];\n }, [live, optsRef]);\n\n const overlay = useMemo<RenderLayer<unknown>>(() => ({\n id: 'slice-pending-cut',\n label: 'Slice — pending cut',\n space: 'screen',\n subscribe: live.listen,\n draw: (_data, view) => {\n const pts = scratchRef.current.points;\n if (pts.length === 0) return [];\n const t = viewToTransform(view);\n const toScreen = (p: { x: number; y: number }) => {\n const [x, y] = worldToScreen(p.x, p.y, t);\n return { x, y };\n };\n const run = pts.map(toScreen);\n const at = live.pointer()?.get();\n if (at) run.push(toScreen({ x: at.worldX, y: at.worldY }));\n const stroke = OVERLAY_ROLE_STROKES['cut'];\n const out: DrawCommand[] = [];\n if (run.length >= 2) out.push({ kind: 'path', path: polylineFromPoints(run), stroke });\n for (const p of pts.map(toScreen)) {\n out.push({\n kind: 'path',\n path: ellipsePath({\n x: p.x - VERTEX_RADIUS_PX,\n y: p.y - VERTEX_RADIUS_PX,\n width: VERTEX_RADIUS_PX * 2,\n height: VERTEX_RADIUS_PX * 2,\n }),\n fill: { paint: stroke.paint },\n });\n }\n return out;\n },\n }), [live]);\n\n const { keybinding } = options;\n return useMemo(() => defineTool({\n id: 'slice',\n capabilities: ['edits-page'],\n hookName: 'useSliceTool',\n cursor: 'crosshair',\n presentation: { label: 'Slice', group: 'shape' },\n ...(keybinding === null ? {} : { keybinding: keybinding ?? { key: 'K' } }),\n actions,\n overlay,\n onDeactivate: () => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n },\n bindings: [\n { spec: { kind: 'click', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.addPoint' },\n {\n spec: { kind: 'doubleClick', mods: { shift: 'optional', alt: 'optional' } },\n actionId: 'slice.finish',\n opts: { params: { viaDoubleClick: true } },\n },\n // Ahead of the cutting drags: it declines unless points are placed.\n { spec: { kind: 'drag', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.dragPoint', opts: { yields: true } },\n { spec: { kind: 'drag' }, actionId: 'slice' },\n { spec: { kind: 'drag', mods: { alt: true } }, actionId: 'slice', opts: { params: { cut: 'freehand' } } },\n { spec: { kind: 'key', key: 'Enter' }, actionId: 'slice.finish' },\n { spec: { kind: 'key', key: 'Escape' }, actionId: 'slice.cancel' },\n { spec: { kind: 'key', key: 'Backspace' }, actionId: 'slice.dropPoint' },\n ],\n }), [actions, overlay, keybinding, live]);\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,IAAMA,IAAmB;AAazB,SAAgBC,EAAa,IAA+B,CAAC,GAAS;CACpE,IAAMC,IAAaC,EAAqB,EAAE,QAAQ,CAAC,EAAE,CAAC,GAChDC,IAAUC,EAAU,EAAE,gBAAgBC,EAAQ,kBAAkB,EAAE,CAAC,GAInEC,IAAOC,QAAc;EACzB,IAAMC,IAAUC,EAAc;EAC9B,OAAO;GACL,QAAQD,EAAQ;GAChB,QAAQA,EAAQ;GAChB,GAAGE,EAAsBF,EAAQ,IAAI;EACvC;CACF,GAAG,CAAC,CAAC,GAECG,IAAUJ,QAAwB;EACtC,IAAMK,UAAeX,EAAW,QAAQ,QAClCY,UAAiBD,EAAO,CAAC,CAAC,SAAS,KAAWE,EAAqB,eAEnEC,UAAoB;GAGxB,AAFA,EAAW,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;IAAE,MAAM;KAAE,MAAM;KAAQ,MAAM,EAAE,KAAK,GAAK;IAAE;IAAG,UAAU;IAAS,MAAM,EAAE,QAAQ,EAAE,KAAK,WAAW,EAAE;GAAE;GACxG;IAAE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAQ;IAAG,UAAU;GAAe;GAChE;IAAE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAS;IAAG,UAAU;GAAe;GACjE;IAAE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAY;IAAG,UAAU;GAAkB;EACzE;CACF,CAAC,GAAG;EAACK;EAASuB;EAASc;EAAY1C;CAAI,CAAC;AAC1C"}
1
+ {"version":3,"file":"useSliceTool.js","names":["SliceIcon","VERTEX_RADIUS_PX","useSliceTool","scratchRef","useRef","optsRef","useLatest","options","live","useMemo","changed","createEmitter","createPointerFollower","actions","points","pending","ActionDisabledReason","reset","commit","cut","deps","place","pts","first","scale","withinPxRadius","x","y","eligible","sliceAction","\"slice\"","p","params","reason","at","endCtx","overlay","t","viewToTransform","view","toScreen","worldToScreen","run","stroke","OVERLAY_ROLE_STROKES","\"cut\"","out","polylineFromPoints","ellipsePath","defineTool","createElement","keybinding"],"sources":["../../../../src/tools/builtin/slice/useSliceTool.ts"],"sourcesContent":["import { createElement, useMemo, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport type { RenderLayer } from 'core/layers/render';\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { Action, ActionDeps, InvocationCtx, ToolKeybinding } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport { createPointerFollower } from '../shared/pointerFollower';\nimport { sliceAction } from 'interactions/actions/defaults/slice';\nimport { withinPxRadius } from '@weasel-js/geom';\nimport { worldToScreen } from 'core/viewport/viewTransform';\nimport { viewToTransform } from 'core/viewport/view';\nimport { ellipsePath, polylineFromPoints } from '@weasel-js/geom';\nimport { OVERLAY_ROLE_STROKES } from 'canvas/overlayRoleStrokes';\nimport { createEmitter } from '@weasel-js/registry';\nimport { SliceIcon } from '../../../icons';\n\n/** Options for `useSliceTool`. */\nexport interface UseSliceToolOptions {\n /** Override the default keybinding (`{ key: 'K' }`). Pass `null` to omit. */\n keybinding?: ToolKeybinding | null;\n /** Screen-px radius around the first point within which a click closes the\n * cut into a loop and commits it. Default `8`. */\n closeHitRadius?: number;\n}\n\n/** The click-by-click cut in progress, in world coords. */\nexport interface SliceScratch {\n points: { x: number; y: number }[];\n}\n\nconst VERTEX_RADIUS_PX = 3;\n\n/**\n * Knife tool. A drag cuts along a straight line, and an Alt-drag along its\n * freehand trail, through `sliceAction`. Clicks place a cut one point at a\n * time: Enter or a double-click commits it, Escape discards it, Backspace\n * takes back the last point, and a click on the first point closes it into a\n * loop and commits. While points are placed, a drag places one more where it\n * is released instead of cutting on its own.\n *\n * Every cut goes to the `slice` dep, which decides what it does to the scene.\n * `<SceneCanvas>` publishes one that cuts every path the cut crosses.\n */\nexport function useSliceTool(options: UseSliceToolOptions = {}): Tool {\n const scratchRef = useRef<SliceScratch>({ points: [] });\n const optsRef = useLatest({ closeHitRadius: options.closeHitRadius ?? 8 });\n\n // What the overlay layer's `subscribe` hears: a change to the points, and,\n // while any are placed, every move of the pointer the rubber band follows.\n const live = useMemo(() => {\n const changed = createEmitter();\n return {\n notify: changed.emit,\n listen: changed.subscribe,\n ...createPointerFollower(changed.emit),\n };\n }, []);\n\n const actions = useMemo<Action[]>(() => {\n const points = () => scratchRef.current.points;\n const pending = () => (points().length > 0 ? true : ActionDisabledReason.NotApplicable);\n\n const reset = (): void => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n };\n const commit = (deps: ActionDeps): void => {\n const cut = points().slice();\n reset();\n if (cut.length >= 2) deps.slice?.commit(cut);\n };\n const place = (deps: ActionDeps, x: number, y: number): void => {\n const pts = points();\n const first = pts[0];\n const scale = deps.view?.get().scale ?? { x: 1, y: 1 };\n if (pts.length >= 3 && withinPxRadius(x - first.x, y - first.y, optsRef.current.closeHitRadius, scale)) {\n pts.push({ x: first.x, y: first.y });\n commit(deps);\n return;\n }\n pts.push({ x, y });\n live.follow(deps.pointer);\n live.notify();\n };\n\n const eligible = { capability: 'edits-page' } as const;\n return [\n sliceAction,\n {\n id: 'slice.addPoint',\n label: 'Slice — place point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: (deps) => (deps?.['slice'] ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const p = params as { pressX?: number; pressY?: number } | undefined;\n if (p?.pressX === undefined || p.pressY === undefined) return;\n place(deps, p.pressX, p.pressY);\n },\n },\n },\n {\n id: 'slice.dragPoint',\n label: 'Slice — drag out a point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: pending,\n invoker: {\n timing: 'ongoing',\n // The dispatcher hands `onEnd` a context with empty deps.\n start: ({ deps }: InvocationCtx) => ({\n onMove: () => {},\n onEnd: (endCtx: InvocationCtx, reason: 'commit' | 'cancel') => {\n if (reason === 'cancel' || points().length === 0) return;\n const at = endCtx.drag?.current ?? endCtx.world;\n place(deps, at.x, at.y);\n },\n }),\n },\n },\n {\n id: 'slice.finish',\n label: 'Slice — cut along the points',\n eligible,\n requires: ['slice'],\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n // A double click arrives after both of its clicks, so the second\n // has already placed a point on top of the first.\n if ((params as { viaDoubleClick?: boolean } | undefined)?.viaDoubleClick) points().pop();\n commit(deps);\n },\n },\n },\n {\n id: 'slice.dropPoint',\n label: 'Slice — take back the last point',\n eligible,\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: () => {\n points().pop();\n if (points().length === 0) reset();\n else live.notify();\n },\n },\n },\n {\n id: 'slice.cancel',\n label: 'Slice — discard the points',\n eligible,\n // Declining with nothing placed leaves Escape to the ambient `escape`.\n enabled: pending,\n invoker: { timing: 'immediate', run: () => reset() },\n },\n ];\n }, [live, optsRef]);\n\n const overlay = useMemo<RenderLayer<unknown>>(() => ({\n id: 'slice-pending-cut',\n label: 'Slice — pending cut',\n space: 'screen',\n subscribe: live.listen,\n draw: (_data, view) => {\n const pts = scratchRef.current.points;\n if (pts.length === 0) return [];\n const t = viewToTransform(view);\n const toScreen = (p: { x: number; y: number }) => {\n const [x, y] = worldToScreen(p.x, p.y, t);\n return { x, y };\n };\n const run = pts.map(toScreen);\n const at = live.pointer()?.get();\n if (at) run.push(toScreen({ x: at.worldX, y: at.worldY }));\n const stroke = OVERLAY_ROLE_STROKES['cut'];\n const out: DrawCommand[] = [];\n if (run.length >= 2) out.push({ kind: 'path', path: polylineFromPoints(run), stroke });\n for (const p of pts.map(toScreen)) {\n out.push({\n kind: 'path',\n path: ellipsePath({\n x: p.x - VERTEX_RADIUS_PX,\n y: p.y - VERTEX_RADIUS_PX,\n width: VERTEX_RADIUS_PX * 2,\n height: VERTEX_RADIUS_PX * 2,\n }),\n fill: { paint: stroke.paint },\n });\n }\n return out;\n },\n }), [live]);\n\n const { keybinding } = options;\n return useMemo(() => defineTool({\n id: 'slice',\n capabilities: ['edits-page'],\n hookName: 'useSliceTool',\n cursor: 'crosshair',\n presentation: { label: 'Slice', icon: createElement(SliceIcon), group: 'shape' },\n ...(keybinding === null ? {} : { keybinding: keybinding ?? { key: 'K' } }),\n actions,\n overlay,\n onDeactivate: () => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n },\n bindings: [\n { spec: { kind: 'click', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.addPoint' },\n {\n spec: { kind: 'doubleClick', mods: { shift: 'optional', alt: 'optional' } },\n actionId: 'slice.finish',\n opts: { params: { viaDoubleClick: true } },\n },\n // Ahead of the cutting drags: it declines unless points are placed.\n { spec: { kind: 'drag', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.dragPoint', opts: { yields: true } },\n { spec: { kind: 'drag' }, actionId: 'slice' },\n { spec: { kind: 'drag', mods: { alt: true } }, actionId: 'slice', opts: { params: { cut: 'freehand' } } },\n { spec: { kind: 'key', key: 'Enter' }, actionId: 'slice.finish' },\n { spec: { kind: 'key', key: 'Escape' }, actionId: 'slice.cancel' },\n { spec: { kind: 'key', key: 'Backspace' }, actionId: 'slice.dropPoint' },\n ],\n }), [actions, overlay, keybinding, live]);\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,IAAMC,IAAmB;AAazB,SAAgBC,EAAa,IAA+B,CAAC,GAAS;CACpE,IAAMC,IAAaC,EAAqB,EAAE,QAAQ,CAAC,EAAE,CAAC,GAChDC,IAAUC,EAAU,EAAE,gBAAgBC,EAAQ,kBAAkB,EAAE,CAAC,GAInEC,IAAOC,QAAc;EACzB,IAAMC,IAAUC,EAAc;EAC9B,OAAO;GACL,QAAQD,EAAQ;GAChB,QAAQA,EAAQ;GAChB,GAAGE,EAAsBF,EAAQ,IAAI;EACvC;CACF,GAAG,CAAC,CAAC,GAECG,IAAUJ,QAAwB;EACtC,IAAMK,UAAeX,EAAW,QAAQ,QAClCY,UAAiBD,EAAO,CAAC,CAAC,SAAS,KAAWE,EAAqB,eAEnEC,UAAoB;GAGxB,AAFA,EAAW,QAAQ,SAAS,CAAC,GAC7BT,EAAK,SAAS,GACdA,EAAK,OAAO;EACd,GACMU,KAAU,MAA2B;GACzC,IAAMC,IAAML,EAAO,CAAC,CAAC,MAAM;GAE3B,AADAG,EAAM,GACFE,EAAI,UAAU,KAAGC,EAAK,OAAO,OAAOD,CAAG;EAC7C,GACME,KAAS,GAAkB,GAAW,MAAoB;GAC9D,IAAMC,IAAMR,EAAO,GACbS,IAAQD,EAAI,IACZE,IAAQJ,EAAK,MAAM,IAAI,CAAC,CAAC,SAAS;IAAE,GAAG;IAAG,GAAG;GAAE;GACrD,IAAIE,EAAI,UAAU,KAAKG,EAAeC,IAAIH,EAAM,GAAGI,IAAIJ,EAAM,GAAGlB,EAAQ,QAAQ,gBAAgBmB,CAAK,GAAG;IAEtG,AADAF,EA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arIcon.js";
3
- import { insertBindingBehaviors as n } from "../shared/insertToolOptions.js";
4
- import { useCallback as r, useMemo as i, useRef as a, useState as o } from "react";
5
- import { useLatest as s } from "@weasel-js/react";
6
- import { jsx as c } from "react/jsx-runtime";
7
- import { cursorFor as l } from "@weasel-js/cursor";
1
+ import { INSERT_REPOSITION_BINDING as e } from "../../../interactions/actions/insert/repositionAction.js";
2
+ import { SHAPE_COUNT_RANGE as t } from "../../../features/paths/shapeGenerator.js";
3
+ import { defineTool as n } from "../../overlayBinding.js";
4
+ import r from "../../../icons/StarIcon.js";
5
+ import { insertBindingBehaviors as i } from "../shared/insertToolOptions.js";
6
+ import { useCallback as a, useMemo as o, useRef as s, useState as c } from "react";
7
+ import { useLatest as l } from "@weasel-js/react";
8
+ import { jsx as u } from "react/jsx-runtime";
9
+ import { cursorFor as d } from "@weasel-js/cursor";
8
10
  //#region src/tools/builtin/star/useStarTool.tsx
9
- var u = 3, d = 32;
10
11
  function f(f = {}) {
11
- let { points: p = 5, innerRatio: m = .5, label: h = "Star", behaviors: g } = f, _ = a(p), v = s(m), [, y] = o(0), b = r(() => y((e) => e + 1), []), x = i(() => ({
12
+ let { points: p = 5, innerRatio: m = .5, label: h = "Star", behaviors: g } = f, _ = s(p), v = l(m), [, y] = c(0), b = a(() => y((e) => e + 1), []), x = o(() => ({
12
13
  id: "star.adjustPoints",
13
14
  label: "Star — adjust points",
14
15
  invoker: {
15
16
  timing: "immediate",
16
- run: (e, t) => {
17
- let n = t, r = n?.delta ?? (n?.deltaY !== void 0 && n.deltaY !== 0 ? n.deltaY > 0 ? 1 : -1 : 0);
18
- r !== 0 && (_.current = r > 0 ? Math.min(d, _.current + 1) : Math.max(u, _.current - 1), b());
17
+ run: (e, n) => {
18
+ let r = n, i = r?.delta ?? (r?.deltaY !== void 0 && r.deltaY !== 0 ? r.deltaY > 0 ? 1 : -1 : 0);
19
+ i !== 0 && (_.current = i > 0 ? Math.min(t.max, _.current + 1) : Math.max(t.min, _.current - 1), b());
19
20
  }
20
21
  }
21
22
  }), [b]);
22
- return i(() => e({
23
+ return o(() => n({
23
24
  id: "star",
24
25
  capabilities: ["creates-shapes"],
25
26
  hookName: "useStarTool",
26
- cursor: l("crosshairStar", { fallback: "crosshair" }),
27
+ cursor: d("crosshairStar", { fallback: "crosshair" }),
27
28
  actions: [x],
28
29
  presentation: {
29
30
  label: h,
30
31
  group: "shape",
31
- icon: /* @__PURE__ */ c(t, {})
32
+ icon: /* @__PURE__ */ u(r, {})
32
33
  },
33
34
  bindings: [
34
35
  {
@@ -40,9 +41,10 @@ function f(f = {}) {
40
41
  points: _.current,
41
42
  innerRadiusRatio: v.current
42
43
  }),
43
- ...n(g)
44
+ ...i(g)
44
45
  }
45
46
  },
47
+ e,
46
48
  {
47
49
  spec: {
48
50
  kind: "wheel",
@@ -1 +1 @@
1
- {"version":3,"file":"useStarTool.js","names":["StarIcon","MIN_POINTS","MAX_POINTS","useStarTool","initialPoints","options","pointsRef","useRef","innerRatioRef","useLatest","innerRatio","setPointsTick","useState","bumpPoints","useCallback","n","adjustPointsAction","useMemo","p","params","step","defineTool","cursorFor","insertBindingBehaviors","behaviors","label"],"sources":["../../../../src/tools/builtin/star/useStarTool.tsx"],"sourcesContent":["import { useCallback, useMemo, useRef, useState } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { StarIcon } from '../../../icons';\nimport type { Tool } from '../../overlayBinding';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport type { Action } from '@weasel-js/routing';\nimport { useLatest } from '@weasel-js/react';\nimport { cursorFor } from '@weasel-js/cursor';\n\n/** A point in world coordinates. */\nexport interface StarPoint { x: number; y: number }\n\n/** Options for `useStarTool`. */\nexport interface UseStarToolOptions extends InsertToolOptions {\n label?: string;\n /** Initial point count. Persists across gestures (Illustrator\n * convention), adjustable mid-drag via ArrowUp/Down or wheel\n * (range 3–32). */\n points?: number;\n /** Inner-radius / outer-radius ratio. Default 0.5. Consumers wanting\n * per-instance ratios should override the `insert` dep. */\n innerRatio?: number;\n}\n\nconst MIN_POINTS = 3;\nconst MAX_POINTS = 32;\n\n/**\n * Drag-from-center star tool. Pointerdown sets center; drag determines\n * outer radius + rotation; release commits via `insertAction`. Inner\n * radius = outer × `innerRatio` (default 0.5). Point count defaults to\n * 5, adjustable mid-gesture via ArrowUp/Down or wheel.\n *\n * Live preview painted by the dispatcher overlay layer reading\n * `insertAction.overlay()`. Consumers wanting custom star geometry\n * override the `insert` dep.\n */\nexport function useStarTool<TNode extends { id: string } = { id: string }>(\n options: UseStarToolOptions = {},\n): Tool {\n const {\n points: initialPoints = 5,\n innerRatio = 0.5,\n label = 'Star',\n behaviors,\n } = options;\n const pointsRef = useRef(initialPoints);\n const innerRatioRef = useLatest(innerRatio);\n const [, setPointsTick] = useState(0);\n const bumpPoints = useCallback(() => setPointsTick((n) => n + 1), []);\n\n // Wheel-to-adjust-points action. Phase-gated to `[engaged]` so it\n // fires only mid-drag.\n const adjustPointsAction = useMemo<Action>(\n () => ({\n id: 'star.adjustPoints',\n label: 'Star — adjust points',\n invoker: {\n timing: 'immediate' as const,\n run: (_deps, params) => {\n const p = params as { deltaY?: number; delta?: number } | undefined;\n // `delta` comes from the ArrowUp/ArrowDown key bindings; `deltaY`\n // from the wheel. Wheel up (deltaY > 0 under natural scrolling)\n // adds a point.\n const step = p?.delta ?? (p?.deltaY !== undefined && p.deltaY !== 0\n ? (p.deltaY > 0 ? 1 : -1)\n : 0);\n if (step === 0) return;\n pointsRef.current = step > 0\n ? Math.min(MAX_POINTS, pointsRef.current + 1)\n : Math.max(MIN_POINTS, pointsRef.current - 1);\n bumpPoints();\n },\n },\n }),\n [bumpPoints],\n );\n\n void ({} as TNode);\n\n return useMemo(\n () =>\n defineTool({\n id: 'star',\n capabilities: ['creates-shapes'],\n hookName: 'useStarTool',\n cursor: cursorFor('crosshairStar', { fallback: 'crosshair' }),\n // Registered by <ToolActionsMounter>, inside the ActionsProvider —\n // see `ToolDef.actions` for why the hook can't register it itself.\n actions: [adjustPointsAction],\n presentation: {\n label,\n group: 'shape',\n icon: <StarIcon />,\n },\n bindings: [\n // Default = drag from corner; anchor dot in the overlay sells\n // the click point. Alt flips to center mode (live toggle).\n {\n spec: { kind: 'drag' },\n actionId: 'insert',\n opts: {\n params: () => ({\n kind: 'star',\n points: pointsRef.current,\n innerRadiusRatio: innerRatioRef.current,\n }),\n ...insertBindingBehaviors(behaviors),\n },\n },\n {\n spec: { kind: 'wheel', phase: 'engaged' },\n actionId: 'star.adjustPoints',\n },\n {\n spec: { kind: 'wheel', phase: 'engaged', mods: { shift: true } },\n actionId: 'insert.adjustRotation',\n },\n // ArrowUp/Down → adjust point count. Ported off the phase table for\n // the same reason as polygon's: as an `initial.keyDown` route the\n // key was claimed on the tool pipeline while `nudge.*` matched the\n // same press on the interactions dispatcher, so both fired.\n {\n spec: { kind: 'key', key: 'ArrowUp' },\n actionId: 'star.adjustPoints',\n opts: { params: { delta: 1 } },\n },\n {\n spec: { kind: 'key', key: 'ArrowDown' },\n actionId: 'star.adjustPoints',\n opts: { params: { delta: -1 } },\n },\n ],\n }),\n [adjustPointsAction, behaviors, label, innerRatioRef],\n );\n}\n"],"mappings":";;;;;;;;AAwBA,IAAMC,IAAa,GACbC,IAAa;AAYnB,SAAgBC,EACd,IAA8B,CAAC,GACzB;CACN,IAAM,EACJ,QAAQC,IAAgB,GACxB,gBAAa,IACb,WAAQ,QACR,iBACEC,GACEC,IAAYC,EAAOH,CAAa,GAChCI,IAAgBC,EAAUC,CAAU,GACpC,GAAGC,KAAiBC,EAAS,CAAC,GAC9BC,IAAaC,QAAkBH,GAAe,MAAMI,IAAI,CAAC,GAAG,CAAC,CAAC,GAI9DC,IAAqBC,SAClB;EACL,IAAI;EACJ,OAAO;EACP,SAAS;GACP,QAAQ;GACR,MAAM,GAAO,MAAW;IACtB,IAAMC,IAAIC,GAIJC,IAAOF,GAAG,UAAUA,GAAG,WAAW,KAAA,KAAaA,EAAE,WAAW,IAC7DA,EAAE,SAAS,IAAI,IAAI,KACpB;IACJ,AAAIE,MAAS,MACb,EAAU,UAAUA,IAAO,IACvB,KAAK,IAAIlB,GAAYI,EAAU,UAAU,CAAC,IAC1C,KAAK,IAAIL,GAAYK,EAAU,UAAU,CAAC,GAC9CO,EAAW;GACb;EACF;CACF,IACA,CAACA,CAAU,CACb;CAIA,OAAOI,QAEHI,EAAW;EACT,IAAI;EACJ,cAAc,CAAC,gBAAgB;EAC/B,UAAU;EACV,QAAQC,EAAU,iBAAiB,EAAE,UAAU,YAAY,CAAC;EAG5D,SAAS,CAACN,CAAkB;EAC5B,cAAc;GACZ;GACA,OAAO;GACP,MAAM,kBAAChB,GAAD,CAAW,CAAA;EACnB;EACA,UAAU;GAGR;IACE,MAAM,EAAE,MAAM,OAAO;IACrB,UAAU;IACV,MAAM;KACJ,eAAe;MACb,MAAM;MACN,QAAQM,EAAU;MAClB,kBAAkBE,EAAc;KAClC;KACA,GAAGe,EAAuBC,CAAS;IACrC;GACF;GACA;IACE,MAAM;KAAE,MAAM;KAAS,OAAO;IAAU;IACxC,UAAU;GACZ;GACA;IACE,MAAM;KAAE,MAAM;KAAS,OAAO;KAAW,MAAM,EAAE,OAAO,GAAK;IAAE;IAC/D,UAAU;GACZ;GAKA;IACE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAU;IACpC,UAAU;IACV,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;GAC/B;GACA;IACE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAY;IACtC,UAAU;IACV,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAG,EAAE;GAChC;EACF;CACF,CAAC,GACH;EAACR;EAAoBQ;EAAWC;EAAOjB;CAAa,CACtD;AACF"}
1
+ {"version":3,"file":"useStarTool.js","names":["StarIcon","useStarTool","initialPoints","options","pointsRef","useRef","innerRatioRef","useLatest","innerRatio","setPointsTick","useState","bumpPoints","useCallback","n","adjustPointsAction","useMemo","p","params","step","SHAPE_COUNT_RANGE","defineTool","cursorFor","insertBindingBehaviors","behaviors","INSERT_REPOSITION_BINDING","label"],"sources":["../../../../src/tools/builtin/star/useStarTool.tsx"],"sourcesContent":["import { useCallback, useMemo, useRef, useState } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { StarIcon } from '../../../icons';\nimport type { Tool } from '../../overlayBinding';\nimport { INSERT_REPOSITION_BINDING } from 'interactions/actions/insert/repositionAction';\nimport { SHAPE_COUNT_RANGE } from 'features/paths/shapeGenerator';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport type { Action } from '@weasel-js/routing';\nimport { useLatest } from '@weasel-js/react';\nimport { cursorFor } from '@weasel-js/cursor';\n\n/** A point in world coordinates. */\nexport interface StarPoint { x: number; y: number }\n\n/** Options for `useStarTool`. */\nexport interface UseStarToolOptions extends InsertToolOptions {\n label?: string;\n /** Initial point count. Persists across gestures (Illustrator\n * convention), adjustable mid-drag via ArrowUp/Down or wheel\n * (range 3–32). */\n points?: number;\n /** Inner-radius / outer-radius ratio. Default 0.5. Consumers wanting\n * per-instance ratios should override the `insert` dep. */\n innerRatio?: number;\n}\n\n/**\n * Drag-from-center star tool. Pointerdown sets center; drag determines\n * outer radius + rotation; release commits via `insertAction`. Inner\n * radius = outer × `innerRatio` (default 0.5). Point count defaults to\n * 5, adjustable mid-gesture via ArrowUp/Down or wheel.\n *\n * Live preview painted by the dispatcher overlay layer reading\n * `insertAction.overlay()`. Consumers wanting custom star geometry\n * override the `insert` dep.\n */\nexport function useStarTool<TNode extends { id: string } = { id: string }>(\n options: UseStarToolOptions = {},\n): Tool {\n const {\n points: initialPoints = 5,\n innerRatio = 0.5,\n label = 'Star',\n behaviors,\n } = options;\n const pointsRef = useRef(initialPoints);\n const innerRatioRef = useLatest(innerRatio);\n const [, setPointsTick] = useState(0);\n const bumpPoints = useCallback(() => setPointsTick((n) => n + 1), []);\n\n // Wheel-to-adjust-points action. Phase-gated to `[engaged]` so it\n // fires only mid-drag.\n const adjustPointsAction = useMemo<Action>(\n () => ({\n id: 'star.adjustPoints',\n label: 'Star — adjust points',\n invoker: {\n timing: 'immediate' as const,\n run: (_deps, params) => {\n const p = params as { deltaY?: number; delta?: number } | undefined;\n // `delta` comes from the ArrowUp/ArrowDown key bindings; `deltaY`\n // from the wheel. Wheel up (deltaY > 0 under natural scrolling)\n // adds a point.\n const step = p?.delta ?? (p?.deltaY !== undefined && p.deltaY !== 0\n ? (p.deltaY > 0 ? 1 : -1)\n : 0);\n if (step === 0) return;\n pointsRef.current = step > 0\n ? Math.min(SHAPE_COUNT_RANGE.max, pointsRef.current + 1)\n : Math.max(SHAPE_COUNT_RANGE.min, pointsRef.current - 1);\n bumpPoints();\n },\n },\n }),\n [bumpPoints],\n );\n\n void ({} as TNode);\n\n return useMemo(\n () =>\n defineTool({\n id: 'star',\n capabilities: ['creates-shapes'],\n hookName: 'useStarTool',\n cursor: cursorFor('crosshairStar', { fallback: 'crosshair' }),\n // Registered by <ToolActionsMounter>, inside the ActionsProvider —\n // see `ToolDef.actions` for why the hook can't register it itself.\n actions: [adjustPointsAction],\n presentation: {\n label,\n group: 'shape',\n icon: <StarIcon />,\n },\n bindings: [\n // Default = drag from corner; anchor dot in the overlay sells\n // the click point. Alt flips to center mode (live toggle).\n {\n spec: { kind: 'drag' },\n actionId: 'insert',\n opts: {\n params: () => ({\n kind: 'star',\n points: pointsRef.current,\n innerRadiusRatio: innerRatioRef.current,\n }),\n ...insertBindingBehaviors(behaviors),\n },\n },\n INSERT_REPOSITION_BINDING,\n {\n spec: { kind: 'wheel', phase: 'engaged' },\n actionId: 'star.adjustPoints',\n },\n {\n spec: { kind: 'wheel', phase: 'engaged', mods: { shift: true } },\n actionId: 'insert.adjustRotation',\n },\n // ArrowUp/Down → adjust point count. Ported off the phase table for\n // the same reason as polygon's: as an `initial.keyDown` route the\n // key was claimed on the tool pipeline while `nudge.*` matched the\n // same press on the interactions dispatcher, so both fired.\n {\n spec: { kind: 'key', key: 'ArrowUp' },\n actionId: 'star.adjustPoints',\n opts: { params: { delta: 1 } },\n },\n {\n spec: { kind: 'key', key: 'ArrowDown' },\n actionId: 'star.adjustPoints',\n opts: { params: { delta: -1 } },\n },\n ],\n }),\n [adjustPointsAction, behaviors, label, innerRatioRef],\n );\n}\n"],"mappings":";;;;;;;;;;AAoCA,SAAgBC,EACd,IAA8B,CAAC,GACzB;CACN,IAAM,EACJ,QAAQC,IAAgB,GACxB,gBAAa,IACb,WAAQ,QACR,iBACEC,GACEC,IAAYC,EAAOH,CAAa,GAChCI,IAAgBC,EAAUC,CAAU,GACpC,GAAGC,KAAiBC,EAAS,CAAC,GAC9BC,IAAaC,QAAkBH,GAAe,MAAMI,IAAI,CAAC,GAAG,CAAC,CAAC,GAI9DC,IAAqBC,SAClB;EACL,IAAI;EACJ,OAAO;EACP,SAAS;GACP,QAAQ;GACR,MAAM,GAAO,MAAW;IACtB,IAAMC,IAAIC,GAIJC,IAAOF,GAAG,UAAUA,GAAG,WAAW,KAAA,KAAaA,EAAE,WAAW,IAC7DA,EAAE,SAAS,IAAI,IAAI,KACpB;IACJ,AAAIE,MAAS,MACb,EAAU,UAAUA,IAAO,IACvB,KAAK,IAAIC,EAAkB,KAAKf,EAAU,UAAU,CAAC,IACrD,KAAK,IAAIe,EAAkB,KAAKf,EAAU,UAAU,CAAC,GACzDO,EAAW;GACb;EACF;CACF,IACA,CAACA,CAAU,CACb;CAIA,OAAOI,QAEHK,EAAW;EACT,IAAI;EACJ,cAAc,CAAC,gBAAgB;EAC/B,UAAU;EACV,QAAQC,EAAU,iBAAiB,EAAE,UAAU,YAAY,CAAC;EAG5D,SAAS,CAACP,CAAkB;EAC5B,cAAc;GACZ;GACA,OAAO;GACP,MAAM,kBAACd,GAAD,CAAW,CAAA;EACnB;EACA,UAAU;GAGR;IACE,MAAM,EAAE,MAAM,OAAO;IACrB,UAAU;IACV,MAAM;KACJ,eAAe;MACb,MAAM;MACN,QAAQI,EAAU;MAClB,kBAAkBE,EAAc;KAClC;KACA,GAAGgB,EAAuBC,CAAS;IACrC;GACF;GACAC;GACA;IACE,MAAM;KAAE,MAAM;KAAS,OAAO;IAAU;IACxC,UAAU;GACZ;GACA;IACE,MAAM;KAAE,MAAM;KAAS,OAAO;KAAW,MAAM,EAAE,OAAO,GAAK;IAAE;IAC/D,UAAU;GACZ;GAKA;IACE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAU;IACpC,UAAU;IACV,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;GAC/B;GACA;IACE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAY;IACtC,UAAU;IACV,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAG,EAAE;GAChC;EACF;CACF,CAAC,GACH;EAACV;EAAoBS;EAAWE;EAAOnB;CAAa,CACtD;AACF"}
@@ -34,8 +34,8 @@ function o(t = {}) {
34
34
  }), [r]);
35
35
  }
36
36
  var s = {
37
- toDisplay: (e) => Math.round(e * 1e3) / 10,
38
- fromDisplay: (e) => Math.round(e * 1e3) / 1e5,
37
+ scale: .01,
38
+ precision: 1,
39
39
  suffix: "%"
40
40
  }, c = (e, t) => ({
41
41
  kind: "boolean",
@@ -1 +1 @@
1
- {"version":3,"file":"useTextTool.js","names":["TextIcon","PRESENTATION","createElement","useTextTool","options","useMemo","defineTool","insertBindingBehaviors","behaviors","PERCENT","v","flag","name"],"sources":["../../../../src/tools/builtin/text/useTextTool.ts"],"sourcesContent":["import { useMemo, createElement } from 'react';\nimport type { PrefGroup } from '@weasel-js/prefs';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport { TextIcon } from '../../../icons';\n\nconst PRESENTATION = {\n label: 'Text',\n icon: createElement(TextIcon),\n group: 'type',\n};\n\n/** Text tool. Drag-rect insertion is owned end-to-end by the dispatcher's\n * `insertAction` (kind: `'text'`); click-on-selected-text-node enters edit\n * mode via the `enterTextEdit` action.\n *\n * Consumers must register both the `insert` dep (e.g. through\n * `SceneCanvas`'s `useInsertDepSource`) and the `textEdit` dep\n * (`enterTextEditAction`'s contract — see\n * `src/interactions/actions/defaults/enterTextEdit.ts`). Custom node\n * factories and hit gating belong on those deps, not on the tool. */\nexport function useTextTool(options: InsertToolOptions = {}): Tool {\n const { behaviors } = options;\n return useMemo<Tool>(\n () =>\n defineTool({\n id: 'text',\n keybinding: { key: 'T' },\n capabilities: ['creates-text'],\n hookName: 'useTextTool',\n cursor: 'text',\n presentation: PRESENTATION,\n bindings: [\n { spec: { kind: 'drag' }, actionId: 'insert', opts: { params: { kind: 'text' }, ...insertBindingBehaviors(behaviors) } },\n { spec: { kind: 'click', target: 'selected-body' }, actionId: 'enterTextEdit' },\n ],\n }),\n [behaviors],\n );\n}\n\n/** Both script primitives are fractions of the inherited size, so both read\n * as percentages. The step is a tenth of a point because the field snaps the\n * *displayed* value to it, and a coarser one would render a superscript's\n * 58.3% as 60% and commit that on the next edit. */\nconst PERCENT = {\n toDisplay: (v: number) => Math.round(v * 1000) / 10,\n // Rounded rather than divided: 33.3 / 100 is 0.33299999999999996, and that\n // dust would be written into the document and shown back on the next read.\n fromDisplay: (v: number) => Math.round(v * 1000) / 100_000,\n suffix: '%',\n};\n\n/** A run flag: on or off per character, drawn as one segment of a bar. */\nconst flag = (name: string, icon: string) =>\n ({\n kind: 'boolean',\n name,\n description: `${name} for the characters in the range.`,\n icon,\n control: 'toggle',\n default: false,\n }) as const;\n\n/**\n * What the tool offers while a caret range is active — the character half of\n * text styling, against the node-level Character group a selection shows.\n *\n * Keyed by {@link StyledRun} field, so a host reads values out of a\n * `RangeStyle` and writes a `RunStylePatch` back with no name mapping of its\n * own. `script` is a preset over `baselineShift` and `fontScale`, so all three\n * are here and naming either primitive overrides that half. `noFill` is the one\n * key that is not a field: on, it is `fill: null`.\n */\nuseTextTool.options = {\n name: 'Text',\n description: 'Character styling for the selected range.',\n children: {\n bold: {\n ...flag('Bold', 'bold'),\n pair: { with: ['italic', 'underline', 'strikethrough', 'overline'], label: 'Character style' },\n },\n italic: flag('Italic', 'italic'),\n underline: flag('Underline', 'underline'),\n strikethrough: flag('Strikethrough', 'strikethrough'),\n overline: flag('Overline', 'overline'),\n // Clearable: the two values are exclusive *and* absent is a third state,\n // so clicking the lit segment turns the script off.\n script: {\n kind: 'enum',\n name: 'Script',\n description: 'Raise or lower the range off the baseline, at a smaller size.',\n control: 'toggle',\n clearable: true,\n default: undefined,\n options: [\n { value: 'super', label: 'Superscript', icon: 'superscript' },\n { value: 'sub', label: 'Subscript', icon: 'subscript' },\n ],\n },\n textTransform: {\n kind: 'enum',\n name: 'Case',\n description: 'Draw the range in capitals, lowercase or title case. The text itself is unchanged.',\n control: 'toggle',\n default: 'none',\n options: [{ value: 'none', label: 'None', short: ['–'] }, { value: 'uppercase', label: 'Uppercase', short: ['AA'] }, { value: 'lowercase', label: 'Lowercase', short: ['aa'] }, { value: 'capitalize', label: 'Capitalize', short: ['Aa'] }],\n },\n fontVariantCaps: {\n kind: 'enum',\n name: 'Small caps',\n description: 'Draw lowercase letters in the range as smaller capitals. The text itself is unchanged.',\n control: 'toggle',\n default: 'normal',\n options: [{ value: 'normal', label: 'Normal', short: ['–'] }, { value: 'small-caps', label: 'Small caps', short: ['Sc'] }],\n },\n fontFamily: {\n kind: 'font-family',\n name: 'Font',\n description: 'Typeface for the range.',\n default: undefined,\n },\n // Listed from the weights the range's family has registered. Bold is a\n // preset over it: toggling Bold clears it, picking one clears Bold.\n fontWeight: {\n kind: 'font-weight',\n name: 'Weight',\n description: 'Weight of the range, from the faces its family has.',\n default: undefined,\n },\n fontSize: { kind: 'number', name: 'Size', description: 'Type size.', min: 1, step: 1, default: 16 },\n letterSpacing: {\n kind: 'number',\n name: 'Tracking',\n // The typographic term, short enough for a strip; `name` stays the\n // accessible one.\n short: ['VA'],\n description: 'Space added between characters.',\n step: 0.1,\n default: 0,\n },\n baselineShift: {\n kind: 'number',\n name: 'Baseline shift',\n short: ['Shift'],\n description: 'Raise or lower the range, in ems of the inherited size.',\n step: 0.001,\n unit: PERCENT,\n default: 0,\n },\n fontScale: {\n kind: 'number',\n name: 'Scale',\n description: 'Size of the range against the inherited size.',\n min: 0.01,\n step: 0.001,\n unit: PERCENT,\n default: 1,\n },\n fill: {\n kind: 'color',\n name: 'Color',\n description: 'Ink for the range.',\n alpha: true,\n default: '#000000',\n },\n noFill: {\n kind: 'boolean',\n name: 'No fill',\n description: 'Draw the range with no fill.',\n icon: 'paintNone',\n control: 'toggle',\n default: false,\n },\n },\n} satisfies PrefGroup;\n"],"mappings":";;;;;AAOA,IAAMC,IAAe;CACnB,OAAO;CACP,MAAMC,EAAcF,CAAQ;CAC5B,OAAO;AACT;AAWA,SAAgBG,EAAY,IAA6B,CAAC,GAAS;CACjE,IAAM,EAAE,iBAAcC;CACtB,OAAOC,QAEHC,EAAW;EACT,IAAI;EACJ,YAAY,EAAE,KAAK,IAAI;EACvB,cAAc,CAAC,cAAc;EAC7B,UAAU;EACV,QAAQ;EACR,cAAcL;EACd,UAAU,CACR;GAAE,MAAM,EAAE,MAAM,OAAO;GAAG,UAAU;GAAU,MAAM;IAAE,QAAQ,EAAE,MAAM,OAAO;IAAG,GAAGM,EAAuBC,CAAS;GAAE;EAAE,GACvH;GAAE,MAAM;IAAE,MAAM;IAAS,QAAQ;GAAgB;GAAG,UAAU;EAAgB,CAChF;CACF,CAAC,GACH,CAACA,CAAS,CACZ;AACF;AAMA,IAAMC,IAAU;CACd,YAAY,MAAc,KAAK,MAAMC,IAAI,GAAI,IAAI;CAGjD,cAAc,MAAc,KAAK,MAAMA,IAAI,GAAI,IAAI;CACnD,QAAQ;AACV,GAGMC,KAAQ,GAAc,OACzB;CACC,MAAM;CACN;CACA,aAAa,GAAGC,EAAK;CACrB;CACA,SAAS;CACT,SAAS;AACX;AAYF,EAAY,UAAU;CACpB,MAAM;CACN,aAAa;CACb,UAAU;EACR,MAAM;GACJ,GAAGD,EAAK,QAAQ,MAAM;G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AI;GACZ,aAAa;GACb,MAAM;GACN,SAAS;EACX;EACA,eAAe;GACb,MAAM;GACN,MAAM;GACN,OAAO,CAAC,OAAO;GACf,aAAa;GACb,MAAM;GACN,MAAMF;GACN,SAAS;EACX;EACA,WAAW;GACT,MAAM;GACN,MAAM;GACN,aAAa;GACb,KAAK;GACL,MAAM;GACN,MAAMA;GACN,SAAS;EACX;EACA,MAAM;GACJ,MAAM;GACN,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,QAAQ;GACN,MAAM;GACN,MAAM;GACN,aAAa;GACb,MAAM;GACN,SAAS;GACT,SAAS;EACX;CACF;AACF"}
1
+ {"version":3,"file":"useTextTool.js","names":["TextIcon","PRESENTATION","createElement","useTextTool","options","useMemo","defineTool","insertBindingBehaviors","behaviors","PERCENT","flag","name"],"sources":["../../../../src/tools/builtin/text/useTextTool.ts"],"sourcesContent":["import { useMemo, createElement } from 'react';\nimport type { PrefGroup } from '@weasel-js/prefs';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport { TextIcon } from '../../../icons';\n\nconst PRESENTATION = {\n label: 'Text',\n icon: createElement(TextIcon),\n group: 'type',\n};\n\n/** Text tool. Drag-rect insertion is owned end-to-end by the dispatcher's\n * `insertAction` (kind: `'text'`); click-on-selected-text-node enters edit\n * mode via the `enterTextEdit` action.\n *\n * Consumers must register both the `insert` dep (e.g. through\n * `SceneCanvas`'s `useInsertDepSource`) and the `textEdit` dep\n * (`enterTextEditAction`'s contract — see\n * `src/interactions/actions/defaults/enterTextEdit.ts`). Custom node\n * factories and hit gating belong on those deps, not on the tool. */\nexport function useTextTool(options: InsertToolOptions = {}): Tool {\n const { behaviors } = options;\n return useMemo<Tool>(\n () =>\n defineTool({\n id: 'text',\n keybinding: { key: 'T' },\n capabilities: ['creates-text'],\n hookName: 'useTextTool',\n cursor: 'text',\n presentation: PRESENTATION,\n bindings: [\n { spec: { kind: 'drag' }, actionId: 'insert', opts: { params: { kind: 'text' }, ...insertBindingBehaviors(behaviors) } },\n { spec: { kind: 'click', target: 'selected-body' }, actionId: 'enterTextEdit' },\n ],\n }),\n [behaviors],\n );\n}\n\n/** Both script primitives are fractions of the inherited size, so both read\n * as percentages. A tenth of a point shows because the field snaps the\n * *displayed* value to its step, and a coarser one would render a\n * superscript's 58.3% as 60% and commit that on the next edit. */\nconst PERCENT = { scale: 0.01, precision: 1, suffix: '%' };\n\n/** A run flag: on or off per character, drawn as one segment of a bar. */\nconst flag = (name: string, icon: string) =>\n ({\n kind: 'boolean',\n name,\n description: `${name} for the characters in the range.`,\n icon,\n control: 'toggle',\n default: false,\n }) as const;\n\n/**\n * What the tool offers while a caret range is active — the character half of\n * text styling, against the node-level Character group a selection shows.\n *\n * Keyed by {@link StyledRun} field, so a host reads values out of a\n * `RangeStyle` and writes a `RunStylePatch` back with no name mapping of its\n * own. `script` is a preset over `baselineShift` and `fontScale`, so all three\n * are here and naming either primitive overrides that half. `noFill` is the one\n * key that is not a field: on, it is `fill: null`.\n */\nuseTextTool.options = {\n name: 'Text',\n description: 'Character styling for the selected range.',\n children: {\n bold: {\n ...flag('Bold', 'bold'),\n pair: { with: ['italic', 'underline', 'strikethrough', 'overline'], label: 'Character style' },\n },\n italic: flag('Italic', 'italic'),\n underline: flag('Underline', 'underline'),\n strikethrough: flag('Strikethrough', 'strikethrough'),\n overline: flag('Overline', 'overline'),\n // Clearable: the two values are exclusive *and* absent is a third state,\n // so clicking the lit segment turns the script off.\n script: {\n kind: 'enum',\n name: 'Script',\n description: 'Raise or lower the range off the baseline, at a smaller size.',\n control: 'toggle',\n clearable: true,\n default: undefined,\n options: [\n { value: 'super', label: 'Superscript', icon: 'superscript' },\n { value: 'sub', label: 'Subscript', icon: 'subscript' },\n ],\n },\n textTransform: {\n kind: 'enum',\n name: 'Case',\n description: 'Draw the range in capitals, lowercase or title case. The text itself is unchanged.',\n control: 'toggle',\n default: 'none',\n options: [{ value: 'none', label: 'None', short: ['–'] }, { value: 'uppercase', label: 'Uppercase', short: ['AA'] }, { value: 'lowercase', label: 'Lowercase', short: ['aa'] }, { value: 'capitalize', label: 'Capitalize', short: ['Aa'] }],\n },\n fontVariantCaps: {\n kind: 'enum',\n name: 'Small caps',\n description: 'Draw lowercase letters in the range as smaller capitals. The text itself is unchanged.',\n control: 'toggle',\n default: 'normal',\n options: [{ value: 'normal', label: 'Normal', short: ['–'] }, { value: 'small-caps', label: 'Small caps', short: ['Sc'] }],\n },\n fontFamily: {\n kind: 'font-family',\n name: 'Font',\n description: 'Typeface for the range.',\n default: undefined,\n },\n // Listed from the weights the range's family has registered. Bold is a\n // preset over it: toggling Bold clears it, picking one clears Bold.\n fontWeight: {\n kind: 'font-weight',\n name: 'Weight',\n description: 'Weight of the range, from the faces its family has.',\n default: undefined,\n },\n fontSize: { kind: 'number', name: 'Size', description: 'Type size.', min: 1, step: 1, default: 16 },\n letterSpacing: {\n kind: 'number',\n name: 'Tracking',\n // The typographic term, short enough for a strip; `name` stays the\n // accessible one.\n short: ['VA'],\n description: 'Space added between characters.',\n step: 0.1,\n default: 0,\n },\n baselineShift: {\n kind: 'number',\n name: 'Baseline shift',\n short: ['Shift'],\n description: 'Raise or lower the range, in ems of the inherited size.',\n step: 0.001,\n unit: PERCENT,\n default: 0,\n },\n fontScale: {\n kind: 'number',\n name: 'Scale',\n description: 'Size of the range against the inherited size.',\n min: 0.01,\n step: 0.001,\n unit: PERCENT,\n default: 1,\n },\n fill: {\n kind: 'color',\n name: 'Color',\n description: 'Ink for the range.',\n alpha: true,\n default: '#000000',\n },\n noFill: {\n kind: 'boolean',\n name: 'No fill',\n description: 'Draw the range with no fill.',\n icon: 'paintNone',\n control: 'toggle',\n default: false,\n },\n },\n} satisfies PrefGroup;\n"],"mappings":";;;;;AAOA,IAAMC,IAAe;CACnB,OAAO;CACP,MAAMC,EAAcF,CAAQ;CAC5B,OAAO;AACT;AAWA,SAAgB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