@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":"usePenTool.js","names":["p","PenIcon","freshScratch","resetScratch","anchorCount","s","n","sp","buildPath","all","subpaths","trailing","anchorsToPath","usePenTool","options","scratchRef","useRef","optsRef","useLatest","forceRender","useReducer","x","overlay","useState","createPenPreviewLayer","commitContinuation","useCallback","edit","deps","cont","drawn","added","addedClosed","pathToAnchors","reverseAnchors","set","next","samePath","asNodeId","commit","open","allClosed","path","id","boundsOfPath","joinable","hit","scene","commitJoin","current","other","otherSet","tail","joined","joint","out","sameNode","rest","i","label","ops","keptId","built","createDeleteOp","applyOps","defaultCommitAdapter","pickUpEndpoint","scratch","radius","scale","viewScale","nearestPathAnchor","pathsNear","wx","wy","h","original","picked","reversed","snap","fn","placeAt","y","withinCloseRadius","withinPxRadius","ax","ay","trail","useMemo","view","follower","createPointerFollower","track","at","first","actions","p","params","join","ActionDisabledReason","origin","ctx","pickedUp","joinHit","linked","applyOutHandle","sm","moveCtx","se","reason","endCtx","defineTool","cursorFor","createElement","anchor","to","target","dx","dy","shift","c","constrainTo45","area","e","pxExtent","px","ids","a","b"],"sources":["../../../../src/tools/builtin/pen/usePenTool.ts"],"sourcesContent":["import { useCallback, useMemo, useReducer, useRef, useState, createElement } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { PrefGroup } from '@weasel-js/prefs';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ActionDeps, InvocationCtx } from '@weasel-js/routing';\nimport { asNodeId } from 'core/scene/types';\nimport { pxExtent, withinPxRadius, nearestPathAnchor, reverseAnchors, type PathAnchorHit } from '@weasel-js/geom';\nimport { PenIcon } from '../../../icons';\nimport { boundsOfPath, type PolygonPath, anchorsToPath, pathToAnchors } from '@weasel-js/geom';\nimport { createPenPreviewLayer } from 'features/paths/penPreviewLayer';\nimport type { Op } from 'core/ops/types';\nimport { createDeleteOp } from 'core/ops/delete';\nimport { defaultCommitAdapter } from 'interactions/actions/defaultCommitAdapter';\nimport { constrainTo45 } from '../../../util/constrainTo45';\nimport { cursorFor } from '@weasel-js/cursor';\nimport { createPointerFollower } from '../shared/pointerFollower';\n\n/**\n * In-progress pen anchor. A click places a corner, with no handles. A drag\n * sets `outHandle` to the drag point and `inHandle` to its mirror through\n * the anchor, which shapes the segment coming into it.\n */\nexport interface PenAnchor {\n x: number;\n y: number;\n outHandle?: { x: number; y: number };\n inHandle?: { x: number; y: number };\n /** True once Alt is held during the placement drag: from then on the\n * in-handle stays where it is, and an anchor dragged with Alt down from\n * the start gets none. */\n altBroken?: boolean;\n}\n\n/** One in-progress subpath of the pen tool: its anchors so far, and whether\n * the user has closed it. */\nexport interface PenSubpath {\n anchors: PenAnchor[]; // LOCAL PenAnchor — in-progress\n closed: boolean;\n}\n\n/**\n * Mutable state shared across pen-tool gestures. The hook keeps a single\n * instance for its life and changes it in place, so click-by-click state\n * survives gesture boundaries and the tool's preview overlay reads the same\n * object.\n *\n * The pen draws new nodes, and extends an existing node's open subpath from\n * one of its ends (see `continuing`). Reshaping an existing path is anchor\n * editing: double-click a path to enter edit mode.\n */\nexport interface PenScratch {\n finishedSubpaths: PenSubpath[];\n current: PenSubpath | null;\n cursor: { x: number; y: number } | null;\n draggingHandleAt: number | null;\n closeHintActive: boolean;\n /** Set while the pen is extending an existing node's open subpath rather\n * than drawing a new node. `current` then starts as that subpath (turned\n * around when it was picked up by its first anchor), and the commit\n * writes back into the node. */\n continuing: PenContinuation | null;\n}\n\n/** Which existing subpath the pen picked up, and the node's path as it was. */\nexport interface PenContinuation {\n id: string;\n /** Index of the picked-up subpath within `original`. */\n sub: number;\n /** True when it was picked up by its first anchor, so `current` runs\n * backwards and is turned around again on commit. */\n reversed: boolean;\n /** The node's path in world coords at pick-up. */\n original: PolygonPath;\n}\n\n/** Options for `usePenTool`: when a closed subpath commits, and how anchors\n * snap. A finished path is inserted through the `insert` dep as kind\n * `'path'`, the route every shape tool takes, so a consumer shapes the node\n * by overriding that dep. */\nexport interface UsePenToolOptions {\n /** Auto-select the new object after commit. Default `true`. */\n autoSelect?: boolean;\n /** When true (default), clicking the first anchor to close a subpath\n * commits immediately — the closed region renders with its fill right\n * away. When false, the closed subpath stays in scratch so the user can\n * start another subpath; commit then fires on Enter / ⌘-click /\n * double-click, producing a compound path. Switching tools first discards\n * it, as Escape does. */\n autoCommitOnClose?: boolean;\n /** Screen-px hit radius for \"click first anchor to close\". Default `8`.\n * Measured as a screen-space circle, so it stays round under non-uniform\n * zoom; aligns with `useSelectTool.handleHitRadius`. */\n closeHitRadius?: number;\n /** Screen-px radius within which a placed anchor lands exactly on an\n * existing path's anchor. Default `8`; `0` turns it off. Takes precedence\n * over `snapPoint`, which applies only when no anchor is in range. */\n anchorSnapRadius?: number;\n /** Optional point snapper applied to every world-space coordinate the\n * pen records or previews — anchor positions (corner clicks, smooth-\n * drag base point), the rubber-band cursor, and the outgoing-handle\n * target. Receives raw world coords; returns snapped world coords.\n * Pen state (anchor handles, etc.) is computed AFTER snapping so the\n * visible geometry stays grid-aligned. */\n snapPoint?: (p: { x: number; y: number }) => { x: number; y: number };\n}\n\nfunction freshScratch(): PenScratch {\n return {\n finishedSubpaths: [],\n current: null,\n cursor: null,\n draggingHandleAt: null,\n closeHintActive: false,\n continuing: null,\n };\n}\n\nfunction resetScratch(s: PenScratch): void {\n s.finishedSubpaths = [];\n s.current = null;\n s.cursor = null;\n s.draggingHandleAt = null;\n s.closeHintActive = false;\n s.continuing = null;\n}\n\n/** Total anchors across finished subpaths plus the in-progress one. */\nfunction anchorCount(s: PenScratch): number {\n return (s.current ? s.current.anchors.length : 0)\n + s.finishedSubpaths.reduce((n, sp) => n + sp.anchors.length, 0);\n}\n\n/** Build a PolygonPath from the pen's accumulated subpaths, by the same\n * rule as any anchor set: segment A→B is a cubic through A's out-handle and\n * B's in-handle when either exists, else a line. */\nfunction buildPath(\n subpaths: PenSubpath[],\n trailing: PenSubpath | null,\n): PolygonPath {\n const all = [...subpaths];\n if (trailing && trailing.anchors.length > 0) all.push(trailing);\n return anchorsToPath(all.map((sp) => sp.anchors), all.map((sp) => sp.closed));\n}\n\n/**\n * Active-slot Tool: click + drag to build a `PolygonPath` Illustrator-style.\n *\n * Click places a corner anchor; click-drag places an anchor with an\n * outgoing bezier handle; click-the-first-anchor closes the subpath; Enter\n * open-finishes; Esc discards, and so does a tool switch. Shift constrains the placement-drag handle to 0/45/90/135°;\n * Alt during drag breaks the handle mirror for the next segment.\n *\n * Reshaping an existing path is not this tool's job — see {@link PenScratch}.\n */\nexport function usePenTool(\n options: UsePenToolOptions = {},\n): Tool {\n const { autoSelect = true, autoCommitOnClose = true, closeHitRadius = 8, anchorSnapRadius = 8, snapPoint } = options;\n\n const scratchRef = useRef<PenScratch | null>(null);\n if (scratchRef.current === null) scratchRef.current = freshScratch();\n\n // Latest options stashed so handlers see fresh values without rebuilding\n // the Tool record.\n const optsRef = useLatest({ autoSelect, autoCommitOnClose, closeHitRadius, anchorSnapRadius, snapPoint });\n\n // Scratch mutations alone don't trigger React re-renders, so the preview\n // layer would not repaint. Force a render after every scratch mutation.\n const [, forceRender] = useReducer((x: number) => x + 1, 0);\n const [overlay] = useState(() => createPenPreviewLayer({ state: scratchRef.current! }));\n\n /** Write the pen's subpaths back into the node it picked up: the first\n * replaces the subpath it continued, any later ones are appended. Skips\n * the write when nothing changed, so an empty pick-up leaves no undo\n * entry. */\n const commitContinuation = useCallback(\n (s: PenScratch, trailing: PenSubpath | null, deps: ActionDeps): void => {\n const edit = deps.editAnchors;\n const cont = s.continuing!;\n const drawn = [...s.finishedSubpaths, ...(trailing ? [trailing] : [])];\n if (!edit || drawn.length === 0) return;\n const { anchors: added, closed: addedClosed } = pathToAnchors(buildPath(drawn, null));\n if (cont.reversed) added[0] = reverseAnchors(added[0]);\n const set = pathToAnchors(cont.original);\n set.anchors.splice(cont.sub, 1, added[0]);\n set.closed.splice(cont.sub, 1, addedClosed[0]);\n set.anchors.push(...added.slice(1));\n set.closed.push(...addedClosed.slice(1));\n const next = anchorsToPath(set.anchors, set.closed, cont.original);\n if (samePath(next, cont.original)) return;\n edit.applyEdit(cont.id, next, 'Continue path');\n if (optsRef.current.autoSelect) deps.selection?.set([asNodeId(cont.id)]);\n },\n [optsRef],\n );\n\n const commit = useCallback((s: PenScratch, deps: ActionDeps): void => {\n const trailing = s.current && s.current.anchors.length > 0 ? s.current : null;\n if (s.continuing) {\n commitContinuation(s, trailing, deps);\n resetScratch(s);\n return;\n }\n // One anchor draws nothing; committing it would leave an invisible node.\n const open = trailing && trailing.anchors.length >= 2 ? trailing : null;\n if (s.finishedSubpaths.length === 0 && !open) {\n resetScratch(s);\n return;\n }\n const allClosed =\n s.finishedSubpaths.every((sp) => sp.closed) &&\n (open === null || open.closed);\n const path = buildPath(s.finishedSubpaths, open);\n const id = deps.insert?.commit(boundsOfPath(path), { kind: 'path', path, closed: allClosed }) ?? null;\n if (id !== null && optsRef.current.autoSelect) deps.selection?.set([id]);\n resetScratch(s);\n }, [commitContinuation, optsRef]);\n\n /** Whether an anchor about to land on `hit` finishes the path by joining\n * onto another open subpath. Its own continued subpath never counts —\n * reaching that one's far end is a close. Declines when the deps can't\n * commit the join as one op batch. */\n const joinable = useCallback((s: PenScratch, deps: ActionDeps, hit: PathAnchorHit | null): hit is PathAnchorHit => {\n if (!hit || hit.end === null || !s.current || s.current.anchors.length === 0) return false;\n const cont = s.continuing;\n if (cont && hit.id === cont.id && hit.sub === cont.sub) return false;\n const scene = deps.scene;\n if (!scene && !deps.applyOps) return false;\n if (!(cont ? deps.editAnchors?.editOps : deps.insert?.build)) return false;\n return cont?.id === hit.id || scene?.get(hit.id as never) !== undefined;\n }, []);\n\n /** Finish the path onto `hit`, the endpoint its last anchor was just placed\n * on: the other subpath's anchors follow on from it, turned around when\n * `hit` is its last anchor, and its node is deleted. The path being drawn\n * keeps its identity — a continued node keeps its id and style, and a new\n * path is minted the way any pen path is. One op batch, so one undo. */\n const commitJoin = useCallback((s: PenScratch, deps: ActionDeps, hit: PathAnchorHit): void => {\n const edit = deps.editAnchors!;\n const scene = deps.scene;\n const current = s.current!;\n const { anchors: added, closed: addedClosed } = pathToAnchors(buildPath([...s.finishedSubpaths, current], null));\n\n const other = edit.getEditablePath(hit.id) as PolygonPath;\n const otherSet = pathToAnchors(other);\n const tail = hit.end === 'last' ? reverseAnchors(otherSet.anchors[hit.sub]) : otherSet.anchors[hit.sub];\n const joined = added[added.length - 1];\n const joint = joined[joined.length - 1];\n const out = current.anchors[current.anchors.length - 1].outHandle ?? tail[0].outHandle;\n if (out) joint.outHandle = { ...out };\n joined.push(...tail.slice(1));\n\n const cont = s.continuing;\n const sameNode = cont?.id === hit.id;\n const rest = sameNode ? { anchors: [], closed: [] } : {\n anchors: otherSet.anchors.filter((_, i) => i !== hit.sub),\n closed: otherSet.closed.filter((_, i) => i !== hit.sub),\n };\n const label = 'Join paths';\n const ops: Op[] = [];\n let keptId: string;\n if (cont) {\n if (cont.reversed) added[0] = reverseAnchors(added[0]);\n const set = pathToAnchors(cont.original);\n set.anchors.splice(cont.sub, 1, added[0]);\n set.closed.splice(cont.sub, 1, addedClosed[0]);\n set.anchors.push(...added.slice(1), ...rest.anchors);\n set.closed.push(...addedClosed.slice(1), ...rest.closed);\n if (sameNode) {\n set.anchors.splice(hit.sub, 1);\n set.closed.splice(hit.sub, 1);\n }\n const next = anchorsToPath(set.anchors, set.closed, cont.original);\n ops.push(...edit.editOps!(cont.id, next, label));\n keptId = cont.id;\n } else {\n const path = anchorsToPath([...added, ...rest.anchors], [...addedClosed, ...rest.closed]);\n const built = deps.insert!.build!(boundsOfPath(path), { kind: 'path', path, closed: false });\n if (built === null) return;\n ops.push(...built.ops);\n keptId = built.id;\n }\n if (!sameNode) ops.push(createDeleteOp({ node: scene!.get(hit.id as never) as { id: string } }));\n\n const applyOps = deps.applyOps;\n if (applyOps) applyOps(ops, label);\n else scene!.applyBatch(ops, label, defaultCommitAdapter(scene!));\n if (optsRef.current.autoSelect) deps.selection?.set([asNodeId(keptId)]);\n resetScratch(s);\n }, [optsRef]);\n\n /** From idle, a press on an open subpath's end anchor picks that subpath\n * up: it becomes `current`, turned so the pressed end is last. Returns\n * whether it did. */\n const pickUpEndpoint = useCallback((deps: ActionDeps, wx: number, wy: number): boolean => {\n const scratch = scratchRef.current!;\n if (scratch.current || scratch.finishedSubpaths.length > 0) return false;\n const radius = optsRef.current.closeHitRadius;\n const scale = viewScale(deps);\n const hit = nearestPathAnchor(pathsNear(deps, wx, wy, radius), { x: wx, y: wy }, radius, scale, (h) => h.end !== null);\n if (!hit) return false;\n const original = deps.editAnchors!.getEditablePath(hit.id) as PolygonPath;\n const picked = pathToAnchors(original).anchors[hit.sub];\n const reversed = hit.end === 'first' && picked.length > 1;\n scratch.current = { anchors: reversed ? reverseAnchors(picked) : picked, closed: false };\n scratch.continuing = { id: hit.id, sub: hit.sub, reversed, original };\n return true;\n }, [optsRef]);\n\n const snap = useCallback((x: number, y: number): { x: number; y: number } => {\n const fn = optsRef.current.snapPoint;\n return fn ? fn({ x, y }) : { x, y };\n }, [optsRef]);\n\n /** Where an anchor pressed at `(x, y)` lands: on an existing path's anchor\n * when one is within `anchorSnapRadius`, else wherever `snapPoint` puts it.\n * `hit` names the anchor it snapped to. */\n const placeAt = useCallback((deps: ActionDeps, x: number, y: number): { x: number; y: number; hit: PathAnchorHit | null } => {\n const radius = optsRef.current.anchorSnapRadius;\n if (radius > 0) {\n const hit = nearestPathAnchor(pathsNear(deps, x, y, radius), { x, y }, radius, viewScale(deps));\n if (hit) return { x: hit.x, y: hit.y, hit };\n }\n return { ...snap(x, y), hit: null };\n }, [snap, optsRef]);\n\n /** Is a world point within the close-hit radius of `(ax, ay)`? Measured as a\n * screen-space circle, so the zone stays round under non-uniform zoom. */\n const withinCloseRadius = useCallback(\n (deps: ActionDeps, ax: number, ay: number, wx: number, wy: number): boolean => {\n return withinPxRadius(ax - wx, ay - wy, optsRef.current.closeHitRadius, viewScale(deps));\n },\n [optsRef],\n );\n\n // The rubber band and the close hint trail the `pointer` dep while a path is\n // in progress. `view` is the camera of the deps last followed through.\n const trail = useMemo(() => {\n let view: ActionDeps['view'];\n const follower = createPointerFollower(() => track());\n const track = (): void => {\n const s = scratchRef.current!;\n if (!s.current && s.finishedSubpaths.length === 0) follower.unfollow();\n const at = s.current ? follower.pointer()?.get() ?? null : null;\n s.cursor = at ? snap(at.worldX, at.worldY) : null;\n const first = s.current && s.current.anchors.length >= 3 ? s.current.anchors[0] : null;\n s.closeHintActive = first !== null && s.cursor !== null && withinPxRadius(\n first.x - s.cursor.x, first.y - s.cursor.y,\n optsRef.current.closeHitRadius, view?.get().scale ?? { x: 1, y: 1 },\n );\n forceRender();\n };\n return {\n /** Repaint after a scratch change. */\n refresh: track,\n /** The same, following `deps`' pointer from here on. */\n update(deps: ActionDeps): void {\n view = deps.view;\n follower.follow(deps.pointer);\n track();\n },\n stop(): void {\n follower.unfollow();\n forceRender();\n },\n };\n }, [snap, optsRef]);\n\n /**\n * Actions the pen owns, registered by `useToolActions` from inside the\n * ActionsProvider — see `ToolDef.actions`. They close over `scratchRef`,\n * so the state never leaves the hook.\n */\n const actions = useMemo<Action[]>(() => {\n const s = () => scratchRef.current!;\n\n return [\n {\n id: 'pen.placeAnchor',\n label: 'Pen — place anchor',\n eligible: { capability: 'creates-paths' },\n requires: ['view', 'pointer', 'areaSelect', 'editAnchors', 'scene', 'applyOps', 'insert', 'selection'],\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const p = params as { pressX?: number; pressY?: number } | undefined;\n if (p?.pressX === undefined || p.pressY === undefined) return;\n // The press point, not the release: a click may drift up to the\n // drag threshold.\n if (pickUpEndpoint(deps, p.pressX, p.pressY)) {\n trail.update(deps);\n return;\n }\n const { x: wx, y: wy, hit } = placeAt(deps, p.pressX, p.pressY);\n const scratch = s();\n\n // Close-on-first-anchor (>= 3 anchors). With `autoCommitOnClose`\n // off the closed subpath stays in scratch for compound-path builds.\n if (scratch.current && scratch.current.anchors.length >= 3) {\n const first = scratch.current.anchors[0];\n if (withinCloseRadius(deps, first.x, first.y, wx, wy)) {\n scratch.current.closed = true;\n scratch.finishedSubpaths.push(scratch.current);\n scratch.current = null;\n scratch.closeHintActive = false;\n if (optsRef.current.autoCommitOnClose) commit(scratch, deps);\n trail.update(deps);\n return;\n }\n }\n\n const join = joinable(scratch, deps, hit);\n // Otherwise: append a corner anchor, starting a subpath if needed.\n if (!scratch.current) scratch.current = { anchors: [], closed: false };\n scratch.current.anchors.push({ x: wx, y: wy });\n if (join) commitJoin(scratch, deps, hit);\n trail.update(deps);\n },\n },\n },\n\n {\n id: 'pen.finishOpen',\n label: 'Pen — finish open path',\n eligible: { capability: 'creates-paths' },\n requires: ['editAnchors', 'insert', 'selection'],\n // Needs an actual path to commit. Declining also lets the gesture\n // fall through: a ⌘-click with fewer than two anchors reaches the\n // plain-click binding and places an anchor instead.\n enabled: () => (anchorCount(s()) >= 2 ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const scratch = s();\n const p = params as { viaDoubleClick?: boolean } | undefined;\n\n // A double click arrives AFTER both of its clicks, so the second\n // one has already appended an anchor. Undo exactly that before\n // committing: pop it, and drop the subpath entirely if it was the\n // only anchor in it (which happens when the FIRST click closed a\n // subpath and the second started a fresh one).\n if (p?.viaDoubleClick && scratch.current) {\n scratch.current.anchors.pop();\n if (scratch.current.anchors.length === 0) scratch.current = null;\n }\n\n commit(scratch, deps);\n trail.refresh();\n },\n },\n },\n\n {\n id: 'pen.dragHandle',\n label: 'Pen — drag out a bezier handle',\n eligible: { capability: 'creates-paths' },\n requires: ['view', 'pointer', 'areaSelect', 'editAnchors', 'scene', 'applyOps', 'insert', 'selection'],\n invoker: {\n timing: 'ongoing' as const,\n start: (ctx: InvocationCtx) => {\n const scratch = s();\n // `drag.start` is the pointerdown position, so the anchor lands\n // where the user pressed rather than where the drag threshold\n // happened to be crossed.\n const origin = ctx.drag?.start ?? ctx.world;\n // Dragging from an open path's end picks the path up and pulls\n // that end's own handle rather than placing a new anchor on it.\n const pickedUp = pickUpEndpoint(ctx.deps, origin.x, origin.y);\n // Dragging on another open path's endpoint joins onto it once\n // the handle is set.\n let joinHit: PathAnchorHit | null = null;\n if (!pickedUp) {\n const { x: ax, y: ay, hit } = placeAt(ctx.deps, origin.x, origin.y);\n if (joinable(scratch, ctx.deps, hit)) joinHit = hit;\n if (!scratch.current) scratch.current = { anchors: [], closed: false };\n scratch.current.anchors.push({ x: ax, y: ay });\n }\n scratch.draggingHandleAt = scratch.current!.anchors.length - 1;\n if (ctx.modifiers.alt) {\n scratch.current!.anchors[scratch.draggingHandleAt].altBroken = true;\n }\n // A picked-up endpoint's in-handle belongs to the existing\n // segment into it, which the pen does not reshape.\n const linked = !pickedUp;\n applyOutHandle(scratch, ctx.world, ctx.modifiers.shift, linked, optsRef.current.snapPoint);\n trail.update(ctx.deps);\n\n return {\n onMove: (moveCtx: InvocationCtx) => {\n const sm = s();\n if (sm.draggingHandleAt === null) return;\n if (moveCtx.modifiers.alt && sm.current) {\n sm.current.anchors[sm.draggingHandleAt].altBroken = true;\n }\n applyOutHandle(sm, moveCtx.world, moveCtx.modifiers.shift, linked, optsRef.current.snapPoint);\n forceRender();\n },\n onEnd: (endCtx: InvocationCtx, reason: 'commit' | 'cancel') => {\n const se = s();\n if (reason === 'cancel') {\n // `start` appended the anchor (or picked a path up); a\n // cancel has to take it back out.\n if (pickedUp) {\n resetScratch(se);\n } else if (se.current && se.draggingHandleAt === se.current.anchors.length - 1) {\n se.current.anchors.pop();\n if (se.current.anchors.length === 0) se.current = null;\n }\n se.draggingHandleAt = null;\n trail.refresh();\n return;\n }\n if (se.draggingHandleAt !== null) {\n if (endCtx.modifiers.alt && se.current) {\n se.current.anchors[se.draggingHandleAt].altBroken = true;\n }\n applyOutHandle(se, endCtx.world, endCtx.modifiers.shift, linked, optsRef.current.snapPoint);\n se.draggingHandleAt = null;\n }\n if (joinHit && se.current) commitJoin(se, ctx.deps, joinHit);\n trail.refresh();\n },\n };\n },\n },\n },\n\n {\n id: 'pen.finish',\n label: 'Pen — finish path',\n eligible: { capability: 'creates-paths' },\n requires: ['editAnchors', 'insert', 'selection'],\n enabled: () => (anchorCount(s()) > 0 ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate' as const,\n run: (deps) => {\n commit(s(), deps);\n trail.refresh();\n },\n },\n },\n\n {\n id: 'pen.cancel',\n label: 'Pen — discard path',\n eligible: { capability: 'creates-paths' },\n // Declining with nothing drawn is what keeps Escape's first-match\n // ladder intact: an empty pen passes the key to `escape`, which goes\n // on to clear the selection / return to the default tool.\n enabled: () => {\n const scratch = s();\n return scratch.current !== null || scratch.finishedSubpaths.length > 0\n ? true\n : ActionDisabledReason.NotApplicable;\n },\n invoker: {\n timing: 'immediate' as const,\n run: () => {\n resetScratch(s());\n trail.refresh();\n },\n },\n },\n ];\n }, [commit, placeAt, withinCloseRadius, pickUpEndpoint, joinable, commitJoin, optsRef, trail, forceRender]);\n\n return useMemo(() => {\n return defineTool({\n id: 'pen',\n keybinding: { key: 'P' },\n capabilities: ['creates-paths'],\n hookName: 'usePenTool',\n cursor: () =>\n scratchRef.current?.closeHintActive\n ? 'pointer'\n : cursorFor('pen', { fallback: 'crosshair' }),\n presentation: {\n label: 'Pen',\n icon: createElement(PenIcon),\n group: 'draw',\n },\n actions,\n overlay,\n overlayPosition: 'before-selection',\n\n onDeactivate: () => {\n // Anything still in scratch is incomplete. Switching tools mid-path\n // discards it, as Escape does, rather than committing a stub polyline.\n resetScratch(scratchRef.current!);\n trail.stop();\n },\n\n bindings: [\n // Plain click places an anchor; ⌘/Ctrl-click open-finishes. Strict\n // modifier matching keeps the two apart.\n { spec: { kind: 'click' as const, mods: { shift: 'optional' as const, alt: 'optional' as const } }, actionId: 'pen.placeAnchor' },\n { spec: { kind: 'click' as const, mods: { mod: true, shift: 'optional' as const, alt: 'optional' as const } }, actionId: 'pen.finishOpen' },\n // Double-click on the last anchor also open-finishes.\n {\n spec: { kind: 'doubleClick' as const, mods: { shift: 'optional' as const, alt: 'optional' as const } },\n actionId: 'pen.finishOpen',\n opts: { params: { viaDoubleClick: true } },\n },\n { spec: { kind: 'drag' as const, mods: { shift: 'optional' as const, alt: 'optional' as const } }, actionId: 'pen.dragHandle' },\n { spec: { kind: 'key' as const, key: 'Enter' }, actionId: 'pen.finish' },\n { spec: { kind: 'key' as const, key: 'Escape' }, actionId: 'pen.cancel' },\n ],\n });\n }, [actions, trail, overlay]);\n}\n\nusePenTool.prefs = {\n name: 'Pen',\n description: 'Pen-tool behavior.',\n children: {\n autoCommitOnClose: {\n kind: 'boolean',\n name: 'Auto-commit pen on close',\n description: \"When you click the pen tool's first anchor to close a region, commit immediately so it renders with its fill. Off: keep the path in preview until you press Enter (lets you build a compound path from multiple closed subpaths).\",\n default: true,\n },\n },\n} satisfies PrefGroup;\n\n/** Point the anchor's outgoing handle at `target`, optionally snapped and\n * optionally constrained to 45° steps. When `linked` and not Alt-broken,\n * the in-handle follows as its mirror through the anchor. */\nfunction applyOutHandle<S extends PenScratch>(\n s: S,\n target: { x: number; y: number },\n shift: boolean,\n linked: boolean,\n snap?: (p: { x: number; y: number }) => { x: number; y: number },\n): void {\n if (s.current === null || s.draggingHandleAt === null) return;\n const anchor = s.current.anchors[s.draggingHandleAt];\n const to = snap ? snap(target) : target;\n let dx = to.x - anchor.x;\n let dy = to.y - anchor.y;\n if (shift) {\n const c = constrainTo45(dx, dy);\n dx = c.dx;\n dy = c.dy;\n }\n anchor.outHandle = { x: anchor.x + dx, y: anchor.y + dy };\n if (linked && !anchor.altBroken) anchor.inHandle = { x: anchor.x - dx, y: anchor.y - dy };\n}\n\nfunction viewScale(deps: ActionDeps): { x: number; y: number } {\n return deps.view?.get().scale ?? { x: 1, y: 1 };\n}\n\n/** Existing editable paths, world coords, with ink within `px` screen\n * pixels of `(wx, wy)` — front-to-back, as the area query returns them.\n * Empty when the host publishes no `areaSelect` or `editAnchors` dep. */\nfunction pathsNear(\n deps: ActionDeps,\n wx: number,\n wy: number,\n px: number,\n): Array<{ id: string; path: PolygonPath }> {\n const area = deps.areaSelect;\n const edit = deps.editAnchors;\n if (!area || !edit) return [];\n const view = deps.view;\n const e = pxExtent(px, viewScale(deps));\n const ids = area.hitTestArea({ x: wx - e.x, y: wy - e.y, width: 2 * e.x, height: 2 * e.y }, view);\n const out: Array<{ id: string; path: PolygonPath }> = [];\n for (const id of ids) {\n const path = edit.getEditablePath(id) as PolygonPath | null;\n if (path?.kind === 'polygon') out.push({ id, path });\n }\n return out;\n}\n\nfunction samePath(a: PolygonPath, b: PolygonPath): boolean {\n if (a.commands.length !== b.commands.length || a.coords.length !== b.coords.length) return false;\n for (let i = 0; i < a.commands.length; i++) if (a.commands[i] !== b.commands[i]) return false;\n for (let i = 0; i < a.coords.length; i++) if (a.coords[i] !== b.coords[i]) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;AA6GA,SAASE,IAA2B;CAClC,OAAO;EACL,kBAAkB,CAAC;EACnB,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,iBAAiB;EACjB,YAAY;CACd;AACF;AAEA,SAASC,EAAa,GAAqB;CAMzC,AALA,EAAE,mBAAmB,CAAC,GACtB,EAAE,UAAU,MACZ,EAAE,SAAS,MACX,EAAE,mBAAmB,MACrB,EAAE,kBAAkB,IACpB,EAAE,aAAa;AACjB;AAGA,SAASC,EAAY,GAAuB;CAC1C,QAAQC,EAAE,UAAUA,EAAE,QAAQ,QAAQ,SAAS,KAC3CA,EAAE,iBAAiB,QAAQ,GAAG,MAAOC,IAAIC,EAAG,QAAQ,QAAQ,CAAC;AACnE;AAKA,SAASC,EACP,GACA,GACa;CACb,IAAMC,IAAM,CAAC,GAAGC,CAAQ;CAExB,OADIC,KAAYA,EAAS,QAAQ,SAAS,KAAGF,EAAI,KAAKE,CAAQ,GACvDC,EAAcH,EAAI,KAAK,MAAOF,EAAG,OAAO,GAAGE,EAAI,KAAK,MAAOF,EAAG,MAAM,CAAC;AAC9E;AAYA,SAAgBM,EACd,IAA6B,CAAC,GACxB;CACN,IAAM,EAAE,gBAAa,IAAM,uBAAoB,IAAM,oBAAiB,GAAG,sBAAmB,GAAG,iBAAcC,GAEvGC,IAAaC,EAA0B,IAAI;CACjD,AAAID,EAAW,YAAY,SAAM,EAAW,UAAUb,EAAa;CAInE,IAAMe,IAAUC,EAAU;EAAE;EAAY;EAAmB;EAAgB;EAAkB;CAAU,CAAC,GAIlG,GAAGC,KAAeC,GAAY,MAAcC,IAAI,GAAG,CAAC,GACpD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lB,EAAS,GAAgB,GAAyB;CACzD,IAAI0F,EAAE,SAAS,WAAWC,EAAE,SAAS,UAAUD,EAAE,OAAO,WAAWC,EAAE,OAAO,QAAQ,OAAO;CAC3F,KAAK,IAAItE,IAAI,GAAGA,IAAIqE,EAAE,SAAS,QAAQ,KAAK,IAAIA,EAAE,SAASrE,OAAOsE,EAAE,SAAStE,IAAI,OAAO;CACxF,KAAK,IAAIA,IAAI,GAAGA,IAAIqE,EAAE,OAAO,QAAQ,KAAK,IAAIA,EAAE,OAAOrE,OAAOsE,EAAE,OAAOtE,IAAI,OAAO;CAClF,OAAO;AACT"}
1
+ {"version":3,"file":"usePenTool.js","names":["p","PenIcon","freshScratch","resetScratch","anchorCount","s","n","sp","buildPath","all","subpaths","trailing","anchorsToPath","usePenTool","options","scratchRef","useRef","optsRef","useLatest","forceRender","useReducer","x","overlay","useState","createPenPreviewLayer","commitContinuation","useCallback","edit","deps","cont","drawn","added","addedClosed","pathToAnchors","reverseAnchors","next","editAnchorSetTracked","set","samePath","asNodeId","commit","open","allClosed","path","id","boundsOfPath","joinable","hit","scene","commitJoin","current","other","otherSet","tail","joined","joint","out","sameNode","rest","i","label","ops","keptId","built","createDeleteOp","applyOps","defaultCommitAdapter","pickUpEndpoint","scratch","radius","scale","viewScale","nearestPathAnchor","pathsNear","wx","wy","h","original","picked","reversed","snap","fn","placeAt","y","withinCloseRadius","withinPxRadius","ax","ay","trail","useMemo","view","follower","createPointerFollower","track","at","first","actions","p","params","join","ActionDisabledReason","origin","ctx","pickedUp","joinHit","linked","applyOutHandle","sm","moveCtx","se","reason","endCtx","defineTool","cursorFor","createElement","anchor","to","target","dx","dy","shift","c","constrainTo45","area","e","pxExtent","px","ids","a","b"],"sources":["../../../../src/tools/builtin/pen/usePenTool.ts"],"sourcesContent":["import { useCallback, useMemo, useReducer, useRef, useState, createElement } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { PrefGroup } from '@weasel-js/prefs';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ActionDeps, InvocationCtx } from '@weasel-js/routing';\nimport { asNodeId } from 'core/scene/types';\nimport { pxExtent, withinPxRadius, nearestPathAnchor, reverseAnchors, type PathAnchorHit } from '@weasel-js/geom';\nimport { PenIcon } from '../../../icons';\nimport { boundsOfPath, type PolygonPath, anchorsToPath, editAnchorSetTracked, pathToAnchors } from '@weasel-js/geom';\nimport { createPenPreviewLayer } from 'features/paths/penPreviewLayer';\nimport type { Op } from 'core/ops/types';\nimport { createDeleteOp } from 'core/ops/delete';\nimport { defaultCommitAdapter } from 'interactions/actions/defaultCommitAdapter';\nimport { constrainTo45 } from '../../../util/constrainTo45';\nimport { cursorFor } from '@weasel-js/cursor';\nimport { createPointerFollower } from '../shared/pointerFollower';\n\n/**\n * In-progress pen anchor. A click places a corner, with no handles. A drag\n * sets `outHandle` to the drag point and `inHandle` to its mirror through\n * the anchor, which shapes the segment coming into it.\n */\nexport interface PenAnchor {\n x: number;\n y: number;\n outHandle?: { x: number; y: number };\n inHandle?: { x: number; y: number };\n /** True once Alt is held during the placement drag: from then on the\n * in-handle stays where it is, and an anchor dragged with Alt down from\n * the start gets none. */\n altBroken?: boolean;\n}\n\n/** One in-progress subpath of the pen tool: its anchors so far, and whether\n * the user has closed it. */\nexport interface PenSubpath {\n anchors: PenAnchor[]; // LOCAL PenAnchor — in-progress\n closed: boolean;\n}\n\n/**\n * Mutable state shared across pen-tool gestures. The hook keeps a single\n * instance for its life and changes it in place, so click-by-click state\n * survives gesture boundaries and the tool's preview overlay reads the same\n * object.\n *\n * The pen draws new nodes, and extends an existing node's open subpath from\n * one of its ends (see `continuing`). Reshaping an existing path is anchor\n * editing: double-click a path to enter edit mode.\n */\nexport interface PenScratch {\n finishedSubpaths: PenSubpath[];\n current: PenSubpath | null;\n cursor: { x: number; y: number } | null;\n draggingHandleAt: number | null;\n closeHintActive: boolean;\n /** Set while the pen is extending an existing node's open subpath rather\n * than drawing a new node. `current` then starts as that subpath (turned\n * around when it was picked up by its first anchor), and the commit\n * writes back into the node. */\n continuing: PenContinuation | null;\n}\n\n/** Which existing subpath the pen picked up, and the node's path as it was. */\nexport interface PenContinuation {\n id: string;\n /** Index of the picked-up subpath within `original`. */\n sub: number;\n /** True when it was picked up by its first anchor, so `current` runs\n * backwards and is turned around again on commit. */\n reversed: boolean;\n /** The node's path in world coords at pick-up. */\n original: PolygonPath;\n}\n\n/** Options for `usePenTool`: when a closed subpath commits, and how anchors\n * snap. A finished path is inserted through the `insert` dep as kind\n * `'path'`, the route every shape tool takes, so a consumer shapes the node\n * by overriding that dep. */\nexport interface UsePenToolOptions {\n /** Auto-select the new object after commit. Default `true`. */\n autoSelect?: boolean;\n /** When true (default), clicking the first anchor to close a subpath\n * commits immediately — the closed region renders with its fill right\n * away. When false, the closed subpath stays in scratch so the user can\n * start another subpath; commit then fires on Enter / ⌘-click /\n * double-click, producing a compound path. Switching tools first discards\n * it, as Escape does. */\n autoCommitOnClose?: boolean;\n /** Screen-px hit radius for \"click first anchor to close\". Default `8`.\n * Measured as a screen-space circle, so it stays round under non-uniform\n * zoom; aligns with `useSelectTool.handleHitRadius`. */\n closeHitRadius?: number;\n /** Screen-px radius within which a placed anchor lands exactly on an\n * existing path's anchor. Default `8`; `0` turns it off. Takes precedence\n * over `snapPoint`, which applies only when no anchor is in range. */\n anchorSnapRadius?: number;\n /** Optional point snapper applied to every world-space coordinate the\n * pen records or previews — anchor positions (corner clicks, smooth-\n * drag base point), the rubber-band cursor, and the outgoing-handle\n * target. Receives raw world coords; returns snapped world coords.\n * Pen state (anchor handles, etc.) is computed AFTER snapping so the\n * visible geometry stays grid-aligned. */\n snapPoint?: (p: { x: number; y: number }) => { x: number; y: number };\n}\n\nfunction freshScratch(): PenScratch {\n return {\n finishedSubpaths: [],\n current: null,\n cursor: null,\n draggingHandleAt: null,\n closeHintActive: false,\n continuing: null,\n };\n}\n\nfunction resetScratch(s: PenScratch): void {\n s.finishedSubpaths = [];\n s.current = null;\n s.cursor = null;\n s.draggingHandleAt = null;\n s.closeHintActive = false;\n s.continuing = null;\n}\n\n/** Total anchors across finished subpaths plus the in-progress one. */\nfunction anchorCount(s: PenScratch): number {\n return (s.current ? s.current.anchors.length : 0)\n + s.finishedSubpaths.reduce((n, sp) => n + sp.anchors.length, 0);\n}\n\n/** Build a PolygonPath from the pen's accumulated subpaths, by the same\n * rule as any anchor set: segment A→B is a cubic through A's out-handle and\n * B's in-handle when either exists, else a line. */\nfunction buildPath(\n subpaths: PenSubpath[],\n trailing: PenSubpath | null,\n): PolygonPath {\n const all = [...subpaths];\n if (trailing && trailing.anchors.length > 0) all.push(trailing);\n return anchorsToPath(all.map((sp) => sp.anchors), all.map((sp) => sp.closed));\n}\n\n/**\n * Active-slot Tool: click + drag to build a `PolygonPath` Illustrator-style.\n *\n * Click places a corner anchor; click-drag places an anchor with an\n * outgoing bezier handle; click-the-first-anchor closes the subpath; Enter\n * open-finishes; Esc discards, and so does a tool switch. Shift constrains the placement-drag handle to 0/45/90/135°;\n * Alt during drag breaks the handle mirror for the next segment.\n *\n * Reshaping an existing path is not this tool's job — see {@link PenScratch}.\n */\nexport function usePenTool(\n options: UsePenToolOptions = {},\n): Tool {\n const { autoSelect = true, autoCommitOnClose = true, closeHitRadius = 8, anchorSnapRadius = 8, snapPoint } = options;\n\n const scratchRef = useRef<PenScratch | null>(null);\n if (scratchRef.current === null) scratchRef.current = freshScratch();\n\n // Latest options stashed so handlers see fresh values without rebuilding\n // the Tool record.\n const optsRef = useLatest({ autoSelect, autoCommitOnClose, closeHitRadius, anchorSnapRadius, snapPoint });\n\n // Scratch mutations alone don't trigger React re-renders, so the preview\n // layer would not repaint. Force a render after every scratch mutation.\n const [, forceRender] = useReducer((x: number) => x + 1, 0);\n const [overlay] = useState(() => createPenPreviewLayer({ state: scratchRef.current! }));\n\n /** Write the pen's subpaths back into the node it picked up: the first\n * replaces the subpath it continued, any later ones are appended. Skips\n * the write when nothing changed, so an empty pick-up leaves no undo\n * entry. */\n const commitContinuation = useCallback(\n (s: PenScratch, trailing: PenSubpath | null, deps: ActionDeps): void => {\n const edit = deps.editAnchors;\n const cont = s.continuing!;\n const drawn = [...s.finishedSubpaths, ...(trailing ? [trailing] : [])];\n if (!edit || drawn.length === 0) return;\n const { anchors: added, closed: addedClosed } = pathToAnchors(buildPath(drawn, null));\n if (cont.reversed) added[0] = reverseAnchors(added[0]);\n const next = editAnchorSetTracked(cont.original, (set) => {\n set.anchors.splice(cont.sub, 1, added[0]);\n set.closed.splice(cont.sub, 1, addedClosed[0]);\n set.anchors.push(...added.slice(1));\n set.closed.push(...addedClosed.slice(1));\n })!;\n if (samePath(next.path, cont.original)) return;\n edit.applyEdit(cont.id, next.path, 'Continue path', next.origins);\n if (optsRef.current.autoSelect) deps.selection?.set([asNodeId(cont.id)]);\n },\n [optsRef],\n );\n\n const commit = useCallback((s: PenScratch, deps: ActionDeps): void => {\n const trailing = s.current && s.current.anchors.length > 0 ? s.current : null;\n if (s.continuing) {\n commitContinuation(s, trailing, deps);\n resetScratch(s);\n return;\n }\n // One anchor draws nothing; committing it would leave an invisible node.\n const open = trailing && trailing.anchors.length >= 2 ? trailing : null;\n if (s.finishedSubpaths.length === 0 && !open) {\n resetScratch(s);\n return;\n }\n const allClosed =\n s.finishedSubpaths.every((sp) => sp.closed) &&\n (open === null || open.closed);\n const path = buildPath(s.finishedSubpaths, open);\n const id = deps.insert?.commit(boundsOfPath(path), { kind: 'path', path, closed: allClosed }) ?? null;\n if (id !== null && optsRef.current.autoSelect) deps.selection?.set([id]);\n resetScratch(s);\n }, [commitContinuation, optsRef]);\n\n /** Whether an anchor about to land on `hit` finishes the path by joining\n * onto another open subpath. Its own continued subpath never counts —\n * reaching that one's far end is a close. Declines when the deps can't\n * commit the join as one op batch. */\n const joinable = useCallback((s: PenScratch, deps: ActionDeps, hit: PathAnchorHit | null): hit is PathAnchorHit => {\n if (!hit || hit.end === null || !s.current || s.current.anchors.length === 0) return false;\n const cont = s.continuing;\n if (cont && hit.id === cont.id && hit.sub === cont.sub) return false;\n const scene = deps.scene;\n if (!scene && !deps.applyOps) return false;\n if (!(cont ? deps.editAnchors?.editOps : deps.insert?.build)) return false;\n return cont?.id === hit.id || scene?.get(hit.id as never) !== undefined;\n }, []);\n\n /** Finish the path onto `hit`, the endpoint its last anchor was just placed\n * on: the other subpath's anchors follow on from it, turned around when\n * `hit` is its last anchor, and its node is deleted. The path being drawn\n * keeps its identity — a continued node keeps its id and style, and a new\n * path is minted the way any pen path is. One op batch, so one undo. */\n const commitJoin = useCallback((s: PenScratch, deps: ActionDeps, hit: PathAnchorHit): void => {\n const edit = deps.editAnchors!;\n const scene = deps.scene;\n const current = s.current!;\n const { anchors: added, closed: addedClosed } = pathToAnchors(buildPath([...s.finishedSubpaths, current], null));\n\n const other = edit.getEditablePath(hit.id) as PolygonPath;\n const otherSet = pathToAnchors(other);\n const tail = hit.end === 'last' ? reverseAnchors(otherSet.anchors[hit.sub]) : otherSet.anchors[hit.sub];\n const joined = added[added.length - 1];\n const joint = joined[joined.length - 1];\n const out = current.anchors[current.anchors.length - 1].outHandle ?? tail[0].outHandle;\n if (out) joint.outHandle = { ...out };\n joined.push(...tail.slice(1));\n\n const cont = s.continuing;\n const sameNode = cont?.id === hit.id;\n const rest = sameNode ? { anchors: [], closed: [] } : {\n anchors: otherSet.anchors.filter((_, i) => i !== hit.sub),\n closed: otherSet.closed.filter((_, i) => i !== hit.sub),\n };\n const label = 'Join paths';\n const ops: Op[] = [];\n let keptId: string;\n if (cont) {\n if (cont.reversed) added[0] = reverseAnchors(added[0]);\n const next = editAnchorSetTracked(cont.original, (set) => {\n set.anchors.splice(cont.sub, 1, added[0]);\n set.closed.splice(cont.sub, 1, addedClosed[0]);\n set.anchors.push(...added.slice(1), ...rest.anchors);\n set.closed.push(...addedClosed.slice(1), ...rest.closed);\n if (!sameNode) return;\n set.anchors.splice(hit.sub, 1);\n set.closed.splice(hit.sub, 1);\n })!;\n ops.push(...edit.editOps!(cont.id, next.path, label, next.origins));\n keptId = cont.id;\n } else {\n const path = anchorsToPath([...added, ...rest.anchors], [...addedClosed, ...rest.closed]);\n const built = deps.insert!.build!(boundsOfPath(path), { kind: 'path', path, closed: false });\n if (built === null) return;\n ops.push(...built.ops);\n keptId = built.id;\n }\n if (!sameNode) ops.push(createDeleteOp({ node: scene!.get(hit.id as never) as { id: string } }));\n\n const applyOps = deps.applyOps;\n if (applyOps) applyOps(ops, label);\n else scene!.applyBatch(ops, label, defaultCommitAdapter(scene!));\n if (optsRef.current.autoSelect) deps.selection?.set([asNodeId(keptId)]);\n resetScratch(s);\n }, [optsRef]);\n\n /** From idle, a press on an open subpath's end anchor picks that subpath\n * up: it becomes `current`, turned so the pressed end is last. Returns\n * whether it did. */\n const pickUpEndpoint = useCallback((deps: ActionDeps, wx: number, wy: number): boolean => {\n const scratch = scratchRef.current!;\n if (scratch.current || scratch.finishedSubpaths.length > 0) return false;\n const radius = optsRef.current.closeHitRadius;\n const scale = viewScale(deps);\n const hit = nearestPathAnchor(pathsNear(deps, wx, wy, radius), { x: wx, y: wy }, radius, scale, (h) => h.end !== null);\n if (!hit) return false;\n const original = deps.editAnchors!.getEditablePath(hit.id) as PolygonPath;\n const picked = pathToAnchors(original).anchors[hit.sub];\n const reversed = hit.end === 'first' && picked.length > 1;\n scratch.current = { anchors: reversed ? reverseAnchors(picked) : picked, closed: false };\n scratch.continuing = { id: hit.id, sub: hit.sub, reversed, original };\n return true;\n }, [optsRef]);\n\n const snap = useCallback((x: number, y: number): { x: number; y: number } => {\n const fn = optsRef.current.snapPoint;\n return fn ? fn({ x, y }) : { x, y };\n }, [optsRef]);\n\n /** Where an anchor pressed at `(x, y)` lands: on an existing path's anchor\n * when one is within `anchorSnapRadius`, else wherever `snapPoint` puts it.\n * `hit` names the anchor it snapped to. */\n const placeAt = useCallback((deps: ActionDeps, x: number, y: number): { x: number; y: number; hit: PathAnchorHit | null } => {\n const radius = optsRef.current.anchorSnapRadius;\n if (radius > 0) {\n const hit = nearestPathAnchor(pathsNear(deps, x, y, radius), { x, y }, radius, viewScale(deps));\n if (hit) return { x: hit.x, y: hit.y, hit };\n }\n return { ...snap(x, y), hit: null };\n }, [snap, optsRef]);\n\n /** Is a world point within the close-hit radius of `(ax, ay)`? Measured as a\n * screen-space circle, so the zone stays round under non-uniform zoom. */\n const withinCloseRadius = useCallback(\n (deps: ActionDeps, ax: number, ay: number, wx: number, wy: number): boolean => {\n return withinPxRadius(ax - wx, ay - wy, optsRef.current.closeHitRadius, viewScale(deps));\n },\n [optsRef],\n );\n\n // The rubber band and the close hint trail the `pointer` dep while a path is\n // in progress. `view` is the camera of the deps last followed through.\n const trail = useMemo(() => {\n let view: ActionDeps['view'];\n const follower = createPointerFollower(() => track());\n const track = (): void => {\n const s = scratchRef.current!;\n if (!s.current && s.finishedSubpaths.length === 0) follower.unfollow();\n const at = s.current ? follower.pointer()?.get() ?? null : null;\n s.cursor = at ? snap(at.worldX, at.worldY) : null;\n const first = s.current && s.current.anchors.length >= 3 ? s.current.anchors[0] : null;\n s.closeHintActive = first !== null && s.cursor !== null && withinPxRadius(\n first.x - s.cursor.x, first.y - s.cursor.y,\n optsRef.current.closeHitRadius, view?.get().scale ?? { x: 1, y: 1 },\n );\n forceRender();\n };\n return {\n /** Repaint after a scratch change. */\n refresh: track,\n /** The same, following `deps`' pointer from here on. */\n update(deps: ActionDeps): void {\n view = deps.view; // eslint-disable-line react-hooks/immutability -- the trail's own camera, read by `track`\n follower.follow(deps.pointer);\n track();\n },\n stop(): void {\n follower.unfollow();\n forceRender();\n },\n };\n }, [snap, optsRef]);\n\n /**\n * Actions the pen owns, registered by `useToolActions` from inside the\n * ActionsProvider — see `ToolDef.actions`. They close over `scratchRef`,\n * so the state never leaves the hook.\n */\n const actions = useMemo<Action[]>(() => {\n const s = () => scratchRef.current!;\n\n return [\n {\n id: 'pen.placeAnchor',\n label: 'Pen — place anchor',\n eligible: { capability: 'creates-paths' },\n requires: ['view', 'pointer', 'areaSelect', 'editAnchors', 'scene', 'applyOps', 'insert', 'selection'],\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const p = params as { pressX?: number; pressY?: number } | undefined;\n if (p?.pressX === undefined || p.pressY === undefined) return;\n // The press point, not the release: a click may drift up to the\n // drag threshold.\n if (pickUpEndpoint(deps, p.pressX, p.pressY)) {\n trail.update(deps);\n return;\n }\n const { x: wx, y: wy, hit } = placeAt(deps, p.pressX, p.pressY);\n const scratch = s();\n\n // Close-on-first-anchor (>= 3 anchors). With `autoCommitOnClose`\n // off the closed subpath stays in scratch for compound-path builds.\n if (scratch.current && scratch.current.anchors.length >= 3) {\n const first = scratch.current.anchors[0];\n if (withinCloseRadius(deps, first.x, first.y, wx, wy)) {\n scratch.current.closed = true;\n scratch.finishedSubpaths.push(scratch.current);\n scratch.current = null;\n scratch.closeHintActive = false;\n if (optsRef.current.autoCommitOnClose) commit(scratch, deps);\n trail.update(deps);\n return;\n }\n }\n\n const join = joinable(scratch, deps, hit);\n // Otherwise: append a corner anchor, starting a subpath if needed.\n if (!scratch.current) scratch.current = { anchors: [], closed: false };\n scratch.current.anchors.push({ x: wx, y: wy });\n if (join) commitJoin(scratch, deps, hit);\n trail.update(deps);\n },\n },\n },\n\n {\n id: 'pen.finishOpen',\n label: 'Pen — finish open path',\n eligible: { capability: 'creates-paths' },\n requires: ['editAnchors', 'insert', 'selection'],\n // Needs an actual path to commit. Declining also lets the gesture\n // fall through: a ⌘-click with fewer than two anchors reaches the\n // plain-click binding and places an anchor instead.\n enabled: () => (anchorCount(s()) >= 2 ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const scratch = s();\n const p = params as { viaDoubleClick?: boolean } | undefined;\n\n // A double click arrives AFTER both of its clicks, so the second\n // one has already appended an anchor. Undo exactly that before\n // committing: pop it, and drop the subpath entirely if it was the\n // only anchor in it (which happens when the FIRST click closed a\n // subpath and the second started a fresh one).\n if (p?.viaDoubleClick && scratch.current) {\n scratch.current.anchors.pop();\n if (scratch.current.anchors.length === 0) scratch.current = null;\n }\n\n commit(scratch, deps);\n trail.refresh();\n },\n },\n },\n\n {\n id: 'pen.dragHandle',\n label: 'Pen — drag out a bezier handle',\n eligible: { capability: 'creates-paths' },\n requires: ['view', 'pointer', 'areaSelect', 'editAnchors', 'scene', 'applyOps', 'insert', 'selection'],\n invoker: {\n timing: 'ongoing' as const,\n start: (ctx: InvocationCtx) => {\n const scratch = s();\n // `drag.start` is the pointerdown position, so the anchor lands\n // where the user pressed rather than where the drag threshold\n // happened to be crossed.\n const origin = ctx.drag?.start ?? ctx.world;\n // Dragging from an open path's end picks the path up and pulls\n // that end's own handle rather than placing a new anchor on it.\n const pickedUp = pickUpEndpoint(ctx.deps, origin.x, origin.y);\n // Dragging on another open path's endpoint joins onto it once\n // the handle is set.\n let joinHit: PathAnchorHit | null = null;\n if (!pickedUp) {\n const { x: ax, y: ay, hit } = placeAt(ctx.deps, origin.x, origin.y);\n if (joinable(scratch, ctx.deps, hit)) joinHit = hit;\n if (!scratch.current) scratch.current = { anchors: [], closed: false };\n scratch.current.anchors.push({ x: ax, y: ay });\n }\n scratch.draggingHandleAt = scratch.current!.anchors.length - 1;\n if (ctx.modifiers.alt) {\n scratch.current!.anchors[scratch.draggingHandleAt].altBroken = true;\n }\n // A picked-up endpoint's in-handle belongs to the existing\n // segment into it, which the pen does not reshape.\n const linked = !pickedUp;\n applyOutHandle(scratch, ctx.world, ctx.modifiers.shift, linked, optsRef.current.snapPoint);\n trail.update(ctx.deps);\n\n return {\n onMove: (moveCtx: InvocationCtx) => {\n const sm = s();\n if (sm.draggingHandleAt === null) return;\n if (moveCtx.modifiers.alt && sm.current) {\n sm.current.anchors[sm.draggingHandleAt].altBroken = true;\n }\n applyOutHandle(sm, moveCtx.world, moveCtx.modifiers.shift, linked, optsRef.current.snapPoint);\n forceRender();\n },\n onEnd: (endCtx: InvocationCtx, reason: 'commit' | 'cancel') => {\n const se = s();\n if (reason === 'cancel') {\n // `start` appended the anchor (or picked a path up); a\n // cancel has to take it back out.\n if (pickedUp) {\n resetScratch(se);\n } else if (se.current && se.draggingHandleAt === se.current.anchors.length - 1) {\n se.current.anchors.pop();\n if (se.current.anchors.length === 0) se.current = null;\n }\n se.draggingHandleAt = null;\n trail.refresh();\n return;\n }\n if (se.draggingHandleAt !== null) {\n if (endCtx.modifiers.alt && se.current) {\n se.current.anchors[se.draggingHandleAt].altBroken = true;\n }\n applyOutHandle(se, endCtx.world, endCtx.modifiers.shift, linked, optsRef.current.snapPoint);\n se.draggingHandleAt = null;\n }\n if (joinHit && se.current) commitJoin(se, ctx.deps, joinHit);\n trail.refresh();\n },\n };\n },\n },\n },\n\n {\n id: 'pen.finish',\n label: 'Pen — finish path',\n eligible: { capability: 'creates-paths' },\n requires: ['editAnchors', 'insert', 'selection'],\n enabled: () => (anchorCount(s()) > 0 ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate' as const,\n run: (deps) => {\n commit(s(), deps);\n trail.refresh();\n },\n },\n },\n\n {\n id: 'pen.cancel',\n label: 'Pen — discard path',\n eligible: { capability: 'creates-paths' },\n // Declining with nothing drawn is what keeps Escape's first-match\n // ladder intact: an empty pen passes the key to `escape`, which goes\n // on to clear the selection / return to the default tool.\n enabled: () => {\n const scratch = s();\n return scratch.current !== null || scratch.finishedSubpaths.length > 0\n ? true\n : ActionDisabledReason.NotApplicable;\n },\n invoker: {\n timing: 'immediate' as const,\n run: () => {\n resetScratch(s());\n trail.refresh();\n },\n },\n },\n ];\n }, [commit, placeAt, withinCloseRadius, pickUpEndpoint, joinable, commitJoin, optsRef, trail, forceRender]);\n\n return useMemo(() => {\n return defineTool({\n id: 'pen',\n keybinding: { key: 'P' },\n capabilities: ['creates-paths'],\n hookName: 'usePenTool',\n cursor: () =>\n scratchRef.current?.closeHintActive\n ? 'pointer'\n : cursorFor('pen', { fallback: 'crosshair' }),\n presentation: {\n label: 'Pen',\n icon: createElement(PenIcon),\n group: 'draw',\n },\n actions,\n overlay,\n overlayPosition: 'before-selection',\n\n onDeactivate: () => {\n // Anything still in scratch is incomplete. Switching tools mid-path\n // discards it, as Escape does, rather than committing a stub polyline.\n resetScratch(scratchRef.current!);\n trail.stop();\n },\n\n bindings: [\n // Plain click places an anchor; ⌘/Ctrl-click open-finishes. Strict\n // modifier matching keeps the two apart.\n { spec: { kind: 'click' as const, mods: { shift: 'optional' as const, alt: 'optional' as const } }, actionId: 'pen.placeAnchor' },\n { spec: { kind: 'click' as const, mods: { mod: true, shift: 'optional' as const, alt: 'optional' as const } }, actionId: 'pen.finishOpen' },\n // Double-click on the last anchor also open-finishes.\n {\n spec: { kind: 'doubleClick' as const, mods: { shift: 'optional' as const, alt: 'optional' as const } },\n actionId: 'pen.finishOpen',\n opts: { params: { viaDoubleClick: true } },\n },\n { spec: { kind: 'drag' as const, mods: { shift: 'optional' as const, alt: 'optional' as const } }, actionId: 'pen.dragHandle' },\n { spec: { kind: 'key' as const, key: 'Enter' }, actionId: 'pen.finish' },\n { spec: { kind: 'key' as const, key: 'Escape' }, actionId: 'pen.cancel' },\n ],\n });\n }, [actions, trail, overlay]);\n}\n\nusePenTool.prefs = {\n name: 'Pen',\n description: 'Pen-tool behavior.',\n children: {\n autoCommitOnClose: {\n kind: 'boolean',\n name: 'Auto-commit pen on close',\n description: \"When you click the pen tool's first anchor to close a region, commit immediately so it renders with its fill. Off: keep the path in preview until you press Enter (lets you build a compound path from multiple closed subpaths).\",\n default: true,\n },\n },\n} satisfies PrefGroup;\n\n/** Point the anchor's outgoing handle at `target`, optionally snapped and\n * optionally constrained to 45° steps. When `linked` and not Alt-broken,\n * the in-handle follows as its mirror through the anchor. */\nfunction applyOutHandle<S extends PenScratch>(\n s: S,\n target: { x: number; y: number },\n shift: boolean,\n linked: boolean,\n snap?: (p: { x: number; y: number }) => { x: number; y: number },\n): void {\n if (s.current === null || s.draggingHandleAt === null) return;\n const anchor = s.current.anchors[s.draggingHandleAt];\n const to = snap ? snap(target) : target;\n let dx = to.x - anchor.x;\n let dy = to.y - anchor.y;\n if (shift) {\n const c = constrainTo45(dx, dy);\n dx = c.dx;\n dy = c.dy;\n }\n anchor.outHandle = { x: anchor.x + dx, y: anchor.y + dy };\n if (linked && !anchor.altBroken) anchor.inHandle = { x: anchor.x - dx, y: anchor.y - dy };\n}\n\nfunction viewScale(deps: ActionDeps): { x: number; y: number } {\n return deps.view?.get().scale ?? { x: 1, y: 1 };\n}\n\n/** Existing editable paths, world coords, with ink within `px` screen\n * pixels of `(wx, wy)` — front-to-back, as the area query returns them.\n * Empty when the host publishes no `areaSelect` or `editAnchors` dep. */\nfunction pathsNear(\n deps: ActionDeps,\n wx: number,\n wy: number,\n px: number,\n): Array<{ id: string; path: PolygonPath }> {\n const area = deps.areaSelect;\n const edit = deps.editAnchors;\n if (!area || !edit) return [];\n const view = deps.view;\n const e = pxExtent(px, viewScale(deps));\n const ids = area.hitTestArea({ x: wx - e.x, y: wy - e.y, width: 2 * e.x, height: 2 * e.y }, view);\n const out: Array<{ id: string; path: PolygonPath }> = [];\n for (const id of ids) {\n const path = edit.getEditablePath(id) as PolygonPath | null;\n if (path?.kind === 'polygon') out.push({ id, path });\n }\n return out;\n}\n\nfunction samePath(a: PolygonPath, b: PolygonPath): boolean {\n if (a.commands.length !== b.commands.length || a.coords.length !== b.coords.length) return false;\n for (let i = 0; i < a.commands.length; i++) if (a.commands[i] !== b.commands[i]) return false;\n for (let i = 0; i < a.coords.length; i++) if (a.coords[i] !== b.coords[i]) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;AA6GA,SAASE,IAA2B;CAClC,OAAO;EACL,kBAAkB,CAAC;EACnB,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,iBAAiB;EACjB,YAAY;CACd;AACF;AAEA,SAASC,EAAa,GAAqB;CAMzC,AALA,EAAE,mBAAmB,CAAC,GACtB,EAAE,UAAU,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ent;
6
- if (typeof i == "function") {
7
- let t = new Set(e), n = /* @__PURE__ */ new Set();
8
- for (let r of e) {
9
- let e = i(r), a = 0;
10
- for (; e != null && a++ < 1e4;) t.has(e) && n.add(e), e = i(e);
11
- }
12
- if (n.size > 0) {
13
- let t = e.filter((e) => !n.has(e));
14
- if (t.length === 1) return t[0];
15
- t.length > 1 && (r = t);
16
- }
5
+ let r = e, i = new Set(e), a = /* @__PURE__ */ new Set();
6
+ for (let t of e) {
7
+ let e = n.getParent(t), r = 0;
8
+ for (; e != null && r++ < 1e4;) i.has(e) && a.add(e), e = n.getParent(e);
9
+ }
10
+ if (a.size > 0) {
11
+ let t = e.filter((e) => !a.has(e));
12
+ if (t.length === 1) return t[0];
13
+ t.length > 1 && (r = t);
17
14
  }
18
15
  return t(r, n);
19
16
  }
20
17
  function t(e, t) {
21
- let r = t?.compareZ;
18
+ let r = t.compareZ;
22
19
  if (typeof r == "function") {
23
20
  let t = e[0];
24
21
  for (let n = 1; n < e.length; n++) r(e[n], t) >= 0 && (t = e[n]);
25
22
  return t;
26
23
  }
27
- let i = t?.getZIndex;
24
+ let i = t.getZIndex;
28
25
  if (typeof i == "function") {
29
26
  let t = e[0], r = n(i, t);
30
27
  for (let a = 1; a < e.length; a++) {
@@ -1 +1 @@
1
- {"version":3,"file":"pickTopMostHit.js","names":["pickTopMostHit","ids","candidates","getParent","adapter","set","dropped","id","p","depth","filtered","pickHighestZ","compareZ","best","i","getZIndex","bestZ","zOf","z"],"sources":["../../../src/tools/builtin/pickTopMostHit.ts"],"sourcesContent":["/** The signals `pickTopMostHit` ranks a hit list by. All optional. */\nexport interface PickTopMostHitAdapter {\n getParent?: (id: string) => string | null;\n /** Paint depth of `id`; higher draws later, so higher wins a hit. Ids the\n * adapter doesn't know sort below every id it does. */\n getZIndex?: (id: string) => number | null | undefined;\n /** Full ordering, for scenes whose depth isn't a number (a path through a\n * tree, say). Negative when `a` paints below `b`. Takes precedence over\n * `getZIndex` when both are present. */\n compareZ?: (a: string, b: string) => number;\n}\n\n/** Reduce a set of hit ids to the single one a click should act on: drop any\n * id that is an ancestor of another in the set, then take the topmost of what\n * remains. A child beats its own ancestor regardless of what z the two report.\n *\n * With no z signal the LAST id wins: scenes walked forward come back\n * bottom-first by convention. A caller that z-sorts topmost-first and exposes\n * neither z hook should resolve before calling. */\nexport function pickTopMostHit(\n ids: readonly string[],\n adapter: PickTopMostHitAdapter | undefined | null,\n): string | null {\n if (ids.length === 0) return null;\n if (ids.length === 1) return ids[0];\n\n let candidates = ids;\n\n const getParent = adapter?.getParent;\n if (typeof getParent === 'function') {\n const set = new Set(ids);\n const dropped = new Set<string>();\n for (const id of ids) {\n let p: string | null = getParent(id);\n // Cap walk to avoid pathological cycles in malformed adapters.\n let depth = 0;\n while (p != null && depth++ < 10_000) {\n if (set.has(p)) dropped.add(p);\n p = getParent(p);\n }\n }\n if (dropped.size > 0) {\n const filtered = ids.filter((id) => !dropped.has(id));\n // A pathological adapter (cyclic `getParent`) can drop everything;\n // keep the original array rather than answering null.\n if (filtered.length === 1) return filtered[0];\n if (filtered.length > 1) candidates = filtered;\n }\n }\n\n return pickHighestZ(candidates, adapter);\n}\n\n/** Highest-z survivor, or the last one when the adapter exposes no z signal.\n * Scanning forward and taking strictly-greater makes the array's own order\n * the tiebreaker, so equal-z ids resolve the same way as no-z ones. */\nfunction pickHighestZ(\n ids: readonly string[],\n adapter: PickTopMostHitAdapter | undefined | null,\n): string {\n const compareZ = adapter?.compareZ;\n if (typeof compareZ === 'function') {\n let best = ids[0];\n for (let i = 1; i < ids.length; i++) {\n if (compareZ(ids[i], best) >= 0) best = ids[i];\n }\n return best;\n }\n\n const getZIndex = adapter?.getZIndex;\n if (typeof getZIndex === 'function') {\n let best = ids[0];\n let bestZ = zOf(getZIndex, best);\n for (let i = 1; i < ids.length; i++) {\n const z = zOf(getZIndex, ids[i]);\n if (z >= bestZ) { best = ids[i]; bestZ = z; }\n }\n return best;\n }\n\n return ids[ids.length - 1];\n}\n\nfunction zOf(getZIndex: (id: string) => number | null | undefined, id: string): number {\n const z = getZIndex(id);\n return typeof z === 'number' && Number.isFinite(z) ? z : -Infinity;\n}\n"],"mappings":";AAmBA,SAAgBA,EACd,GACA,GACe;CACf,IAAIC,EAAI,WAAW,GAAG,OAAO;CAC7B,IAAIA,EAAI,WAAW,GAAG,OAAOA,EAAI;CAEjC,IAAIC,IAAaD,GAEXE,IAAYC,GAAS;CAC3B,IAAI,OAAOD,KAAc,YAAY;EACnC,IAAME,IAAM,IAAI,IAAIJ,CAAG,GACjBK,oBAAU,IAAI,IAAY;EAChC,KAAK,IAAMC,KAAMN,GAAK;GACpB,IAAIO,IAAmBL,EAAUI,CAAE,GAE/BE,IAAQ;GACZ,OAAOD,KAAK,QAAQ,MAAU,MAE5B,AADIH,EAAI,IAAIG,CAAC,KAAGF,EAAQ,IAAIE,CAAC,GAC7B,IAAIL,EAAUK,CAAC;EAEnB;EACA,IAAIF,EAAQ,OAAO,GAAG;GACpB,IAAMI,IAAWT,EAAI,QAAQ,MAAO,CAACK,EAAQ,IAAIC,CAAE,CAAC;GAGpD,IAAIG,EAAS,WAAW,GAAG,OAAOA,EAAS;GAC3C,AAAIA,EAAS,SAAS,MAAG,IAAaA;EACxC;CACF;CAEA,OAAOC,EAAaT,GAAYE,CAAO;AACzC;AAKA,SAASO,EACP,GACA,GACQ;CACR,IAAMC,IAAWR,GAAS;CAC1B,IAAI,OAAOQ,KAAa,YAAY;EAClC,IAAIC,IAAOZ,EAAI;EACf,KAAK,IAAIa,IAAI,GAAGA,IAAIb,EAAI,QAAQ,KAC9B,AAAIW,EAASX,EAAIa,IAAID,CAAI,KAAK,MAAG,IAAOZ,EAAIa;EAE9C,OAAOD;CACT;CAEA,IAAME,IAAYX,GAAS;CAC3B,IAAI,OAAOW,KAAc,YAAY;EACnC,IAAIF,IAAOZ,EAAI,IACXe,IAAQC,EAAIF,GAAWF,CAAI;EAC/B,KAAK,IAAIC,IAAI,GAAGA,IAAIb,EAAI,QAAQ,KAAK;GACnC,IAAMiB,IAAID,EAAIF,GAAWd,EAAIa,EAAE;GAC/B,AAAII,KAAKF,MAAS,IAAOf,EAAIa,IAAI,IAAQI;EAC3C;EACA,OAAOL;CACT;CAEA,OAAOZ,EAAIA,EAAI,SAAS;AAC1B;AAEA,SAASgB,EAAI,GAAsD,GAAoB;CACrF,IAAMC,IAAIH,EAAUR,CAAE;CACtB,OAAO,OAAOW,KAAM,YAAY,OAAO,SAASA,CAAC,IAAIA,IAAI;AAC3D"}
1
+ {"version":3,"file":"pickTopMostHit.js","names":["pickTopMostHit","ids","candidates","set","dropped","id","p","adapter","depth","filtered","pickHighestZ","compareZ","best","i","getZIndex","bestZ","zOf","z"],"sources":["../../../src/tools/builtin/pickTopMostHit.ts"],"sourcesContent":["/** What `pickTopMostHit` ranks a hit list by: the tree, and a z signal where\n * the adapter has one. */\nexport interface PickTopMostHitAdapter {\n getParent: (id: string) => string | null;\n /** Paint depth of `id`; higher draws later, so higher wins a hit. Ids the\n * adapter doesn't know sort below every id it does. */\n getZIndex?: (id: string) => number | null | undefined;\n /** Full ordering, for scenes whose depth isn't a number (a path through a\n * tree, say). Negative when `a` paints below `b`. Takes precedence over\n * `getZIndex` when both are present. */\n compareZ?: (a: string, b: string) => number;\n}\n\n/** Reduce a set of hit ids to the single one a click should act on: drop any\n * id that is an ancestor of another in the set, then take the topmost of what\n * remains. A child beats its own ancestor regardless of what z the two report.\n *\n * With no z signal the LAST id wins: scenes walked forward come back\n * bottom-first by convention. A caller that z-sorts topmost-first and exposes\n * neither z hook should resolve before calling. */\nexport function pickTopMostHit(\n ids: readonly string[],\n adapter: PickTopMostHitAdapter,\n): string | null {\n if (ids.length === 0) return null;\n if (ids.length === 1) return ids[0];\n\n let candidates = ids;\n\n const set = new Set(ids);\n const dropped = new Set<string>();\n for (const id of ids) {\n let p: string | null = adapter.getParent(id);\n // Cap walk to avoid pathological cycles in malformed adapters.\n let depth = 0;\n while (p != null && depth++ < 10_000) {\n if (set.has(p)) dropped.add(p);\n p = adapter.getParent(p);\n }\n }\n if (dropped.size > 0) {\n const filtered = ids.filter((id) => !dropped.has(id));\n // A pathological adapter (cyclic `getParent`) can drop everything;\n // keep the original array rather than answering null.\n if (filtered.length === 1) return filtered[0];\n if (filtered.length > 1) candidates = filtered;\n }\n\n return pickHighestZ(candidates, adapter);\n}\n\n/** Highest-z survivor, or the last one when the adapter exposes no z signal.\n * Scanning forward and taking strictly-greater makes the array's own order\n * the tiebreaker, so equal-z ids resolve the same way as no-z ones. */\nfunction pickHighestZ(\n ids: readonly string[],\n adapter: PickTopMostHitAdapter,\n): string {\n const compareZ = adapter.compareZ;\n if (typeof compareZ === 'function') {\n let best = ids[0];\n for (let i = 1; i < ids.length; i++) {\n if (compareZ(ids[i], best) >= 0) best = ids[i];\n }\n return best;\n }\n\n const getZIndex = adapter.getZIndex;\n if (typeof getZIndex === 'function') {\n let best = ids[0];\n let bestZ = zOf(getZIndex, best);\n for (let i = 1; i < ids.length; i++) {\n const z = zOf(getZIndex, ids[i]);\n if (z >= bestZ) { best = ids[i]; bestZ = z; }\n }\n return best;\n }\n\n return ids[ids.length - 1];\n}\n\nfunction zOf(getZIndex: (id: string) => number | null | undefined, id: string): number {\n const z = getZIndex(id);\n return typeof z === 'number' && Number.isFinite(z) ? z : -Infinity;\n}\n"],"mappings":";AAoBA,SAAgBA,EACd,GACA,GACe;CACf,IAAIC,EAAI,WAAW,GAAG,OAAO;CAC7B,IAAIA,EAAI,WAAW,GAAG,OAAOA,EAAI;CAEjC,IAAIC,IAAaD,GAEXE,IAAM,IAAI,IAAIF,CAAG,GACjBG,oBAAU,IAAI,IAAY;CAChC,KAAK,IAAMC,KAAMJ,GAAK;EACpB,IAAIK,IAAmBC,EAAQ,UAAUF,CAAE,GAEvCG,IAAQ;EACZ,OAAOF,KAAK,QAAQ,MAAU,MAE5B,AADIH,EAAI,IAAIG,CAAC,KAAGF,EAAQ,IAAIE,CAAC,GAC7B,IAAIC,EAAQ,UAAUD,CAAC;CAE3B;CACA,IAAIF,EAAQ,OAAO,GAAG;EACpB,IAAMK,IAAWR,EAAI,QAAQ,MAAO,CAACG,EAAQ,IAAIC,CAAE,CAAC;EAGpD,IAAII,EAAS,WAAW,GAAG,OAAOA,EAAS;EAC3C,AAAIA,EAAS,SAAS,MAAG,IAAaA;CACxC;CAEA,OAAOC,EAAaR,GAAYK,CAAO;AACzC;AAKA,SAASG,EACP,GACA,GACQ;CACR,IAAMC,IAAWJ,EAAQ;CACzB,IAAI,OAAOI,KAAa,YAAY;EAClC,IAAIC,IAAOX,EAAI;EACf,KAAK,IAAIY,IAAI,GAAGA,IAAIZ,EAAI,QAAQ,KAC9B,AAAIU,EAASV,EAAIY,IAAID,CAAI,KAAK,MAAG,IAAOX,EAAIY;EAE9C,OAAOD;CACT;CAEA,IAAME,IAAYP,EAAQ;CAC1B,IAAI,OAAOO,KAAc,YAAY;EACnC,IAAIF,IAAOX,EAAI,IACXc,IAAQC,EAAIF,GAAWF,CAAI;EAC/B,KAAK,IAAIC,IAAI,GAAGA,IAAIZ,EAAI,QAAQ,KAAK;GACnC,IAAMgB,IAAID,EAAIF,GAAWb,EAAIY,EAAE;GAC/B,AAAII,KAAKF,MAAS,IAAOd,EAAIY,IAAI,IAAQI;EAC3C;EACA,OAAOL;CACT;CAEA,OAAOX,EAAIA,EAAI,SAAS;AAC1B;AAEA,SAASe,EAAI,GAAsD,GAAoB;CACrF,IAAMC,IAAIH,EAAUT,CAAE;CACtB,OAAO,OAAOY,KAAM,YAAY,OAAO,SAASA,CAAC,IAAIA,IAAI;AAC3D"}
@@ -1,34 +1,35 @@
1
- import { defineTool as e } from "../../overlayBinding.js";
2
- import t from "../../../icons/PolygonIcon.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 { jsx as s } from "react/jsx-runtime";
6
- import { cursorFor as c } 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/PolygonIcon.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 { jsx as l } from "react/jsx-runtime";
8
+ import { cursorFor as u } from "@weasel-js/cursor";
7
9
  //#region src/tools/builtin/polygon/usePolygonTool.tsx
8
- var l = 3, u = 32;
9
10
  function d(d = {}) {
10
- let { sides: f = 6, label: p = "Polygon", behaviors: m } = d, h = a(f), [, g] = o(0), _ = r(() => g((e) => e + 1), []), v = i(() => ({
11
+ let { sides: f = 6, label: p = "Polygon", behaviors: m } = d, h = s(f), [, g] = c(0), _ = a(() => g((e) => e + 1), []), v = o(() => ({
11
12
  id: "polygon.adjustSides",
12
13
  label: "Polygon — adjust sides",
13
14
  invoker: {
14
15
  timing: "immediate",
15
- run: (e, t) => {
16
- let n = t, r = n?.delta ?? (n?.deltaY !== void 0 && n.deltaY !== 0 ? n.deltaY > 0 ? 1 : -1 : 0);
17
- r !== 0 && (h.current = r > 0 ? Math.min(u, h.current + 1) : Math.max(l, h.current - 1), _());
16
+ run: (e, n) => {
17
+ let r = n, i = r?.delta ?? (r?.deltaY !== void 0 && r.deltaY !== 0 ? r.deltaY > 0 ? 1 : -1 : 0);
18
+ i !== 0 && (h.current = i > 0 ? Math.min(t.max, h.current + 1) : Math.max(t.min, h.current - 1), _());
18
19
  }
19
20
  }
20
21
  }), [_]);
21
- return i(() => e({
22
+ return o(() => n({
22
23
  id: "polygon",
23
24
  keybinding: { key: "G" },
24
25
  capabilities: ["creates-shapes"],
25
26
  hookName: "usePolygonTool",
26
- cursor: c("crosshairPolygon", { fallback: "crosshair" }),
27
+ cursor: u("crosshairPolygon", { fallback: "crosshair" }),
27
28
  actions: [v],
28
29
  presentation: {
29
30
  label: p,
30
31
  group: "shape",
31
- icon: /* @__PURE__ */ s(t, {})
32
+ icon: /* @__PURE__ */ l(r, {})
32
33
  },
33
34
  bindings: [
34
35
  {
@@ -39,9 +40,10 @@ function d(d = {}) {
39
40
  kind: "polygon",
40
41
  sides: h.current
41
42
  }),
42
- ...n(m)
43
+ ...i(m)
43
44
  }
44
45
  },
46
+ e,
45
47
  {
46
48
  spec: {
47
49
  kind: "wheel",
@@ -1 +1 @@
1
- {"version":3,"file":"usePolygonTool.js","names":["PolygonIcon","MIN_SIDES","MAX_SIDES","usePolygonTool","initialSides","options","sidesRef","useRef","setSidesTick","useState","bumpSides","useCallback","n","adjustSidesAction","useMemo","p","params","step","defineTool","cursorFor","insertBindingBehaviors","behaviors","label"],"sources":["../../../../src/tools/builtin/polygon/usePolygonTool.tsx"],"sourcesContent":["import { useCallback, useMemo, useRef, useState } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { PolygonIcon } from '../../../icons';\nimport type { Tool } from '../../overlayBinding';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport type { Action } from '@weasel-js/routing';\nimport { cursorFor } from '@weasel-js/cursor';\n\n/** A point in world coordinates. */\nexport interface PolygonPoint { x: number; y: number }\n\n/** Options for `usePolygonTool`. */\nexport interface UsePolygonToolOptions extends InsertToolOptions {\n label?: string;\n /** Initial side count. Side count persists across gestures\n * (Illustrator convention) and is adjustable mid-drag via\n * ArrowUp/Down or wheel (range 3–32). */\n sides?: number;\n}\n\nconst MIN_SIDES = 3;\nconst MAX_SIDES = 32;\n\n/**\n * Drag-from-center polygon tool. Pointerdown sets center; drag\n * determines radius + rotation; release commits via `insertAction` (the\n * kit's standard insert dep, sourced by `<SceneCanvas>`). Side count\n * defaults to 6, adjustable mid-gesture via ArrowUp/Down or wheel.\n *\n * The live preview is painted by the dispatcher overlay layer reading\n * `insertAction.overlay()` — the action returns `{ kind:'insertPreview',\n * shape:'polygon', bounds, extras: { sides, ... } }`. Consumers wanting\n * a custom polygon node shape override the `insert` dep.\n */\nexport function usePolygonTool<TNode extends { id: string } = { id: string }>(\n options: UsePolygonToolOptions = {},\n): Tool {\n const { sides: initialSides = 6, label = 'Polygon', behaviors } = options;\n // Side count in a ref so keyDown / wheel mutations are visible\n // synchronously to the insert binding's thunked params (re-resolved\n // every frame for the live preview and at commit time). A useState\n // tick alongside forces a render so the dispatcher overlay layer\n // repaints when the count changes between pointer events.\n const sidesRef = useRef(initialSides);\n const [, setSidesTick] = useState(0);\n const bumpSides = useCallback(() => setSidesTick((n) => n + 1), []);\n\n // Wheel-to-adjust-sides action. Bound to `[engaged] wheel` so it only\n // fires while a polygon insert drag is in flight — outside that window\n // wheel falls through to ambient viewport.pan/zoom. The action's run\n // body reads the dispatcher-injected wheel delta from params.\n const adjustSidesAction = useMemo<Action>(\n () => ({\n id: 'polygon.adjustSides',\n label: 'Polygon — adjust sides',\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 // is the dispatcher-injected wheel delta. Wheel \"up\" (deltaY > 0\n // under Mac natural scrolling / page-scrolls-up gesture) adds a\n // side; wheel \"down\" removes one. Matches the user's mental model:\n // scroll up = more.\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 sidesRef.current = step > 0\n ? Math.min(MAX_SIDES, sidesRef.current + 1)\n : Math.max(MIN_SIDES, sidesRef.current - 1);\n bumpSides();\n },\n },\n }),\n [bumpSides],\n );\n\n // `TNode` is retained for source-compat with callers that previously\n // threaded a node-record type through; the tool no longer mints nodes\n // (insertAction does), so the parameter has no runtime effect.\n void ({} as TNode);\n\n return useMemo(\n () =>\n defineTool({\n id: 'polygon',\n keybinding: { key: 'G' },\n capabilities: ['creates-shapes'],\n hookName: 'usePolygonTool',\n cursor: cursorFor('crosshairPolygon', { fallback: 'crosshair' }),\n // Registered by <ToolActionsMounter>, inside the ActionsProvider —\n // see `ToolDef.actions` for why the hook can't register it itself.\n actions: [adjustSidesAction],\n presentation: {\n label,\n group: 'shape',\n icon: <PolygonIcon />,\n },\n bindings: [\n // Default = drag from corner, consistent with rect/ellipse.\n // The dispatcher overlay paints an anchorPoint dot at the\n // click so the radial shape reads as anchored even though no\n // polygon vertex sits at the AABB corner. Alt held flips to\n // center mode (insertAction reads live modifier state).\n {\n spec: { kind: 'drag' },\n actionId: 'insert',\n // Thunked params re-evaluated at commit time (and on every\n // overlay() call for live preview) so mid-gesture\n // ArrowUp/Down/wheel side-count changes flow through both\n // the ghost and the committed geometry.\n opts: {\n params: () => ({\n kind: 'polygon',\n sides: sidesRef.current,\n }),\n ...insertBindingBehaviors(behaviors),\n },\n },\n // Wheel-during-drag → adjust side count. Phase-gated to\n // `engaged` so wheel while the tool is idle still falls\n // through to ambient viewport.pan / viewport.zoom.\n {\n spec: { kind: 'wheel', phase: 'engaged' },\n actionId: 'polygon.adjustSides',\n },\n // Shift+wheel during engaged drag → rotate the in-flight\n // shape in place. Strict modifier matching means this\n // doesn't conflict with the unmodified wheel binding above.\n {\n spec: { kind: 'wheel', phase: 'engaged', mods: { shift: true } },\n actionId: 'insert.adjustRotation',\n },\n // ArrowUp/Down → adjust side count. These were phase-table\n // `initial.keyDown` routes, which put them on the OTHER dispatch\n // pipeline: the tool route claimed the key but its `claim()` never\n // reached the DOM as preventDefault/stopPropagation, so `nudge.up`\n // matched the same keypress on the interactions dispatcher and\n // moved the selection at the same time (audit §4 — derived there,\n // reproduced and now covered by a smoke test). As active-scope\n // bindings they out-prioritize ambient `nudge.*` and the\n // dispatcher's first-match-wins settles it.\n {\n spec: { kind: 'key', key: 'ArrowUp' },\n actionId: 'polygon.adjustSides',\n opts: { params: { delta: 1 } },\n },\n {\n spec: { kind: 'key', key: 'ArrowDown' },\n actionId: 'polygon.adjustSides',\n opts: { params: { delta: -1 } },\n },\n ],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KAAW,MAAM,EAAE,OAAO,GAAK;IAAE;IAC/D,UAAU;GACZ;GAUA;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;EAAmBQ;EAAWC;CAAK,CACtC;AACF"}
1
+ {"version":3,"file":"usePolygonTool.js","names":["PolygonIcon","usePolygonTool","initialSides","options","sidesRef","useRef","setSidesTick","useState","bumpSides","useCallback","n","adjustSidesAction","useMemo","p","params","step","SHAPE_COUNT_RANGE","defineTool","cursorFor","insertBindingBehaviors","behaviors","INSERT_REPOSITION_BINDING","label"],"sources":["../../../../src/tools/builtin/polygon/usePolygonTool.tsx"],"sourcesContent":["import { useCallback, useMemo, useRef, useState } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { PolygonIcon } 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 { cursorFor } from '@weasel-js/cursor';\n\n/** A point in world coordinates. */\nexport interface PolygonPoint { x: number; y: number }\n\n/** Options for `usePolygonTool`. */\nexport interface UsePolygonToolOptions extends InsertToolOptions {\n label?: string;\n /** Initial side count. Side count persists across gestures\n * (Illustrator convention) and is adjustable mid-drag via\n * ArrowUp/Down or wheel (range 3–32). */\n sides?: number;\n}\n\n/**\n * Drag-from-center polygon tool. Pointerdown sets center; drag\n * determines radius + rotation; release commits via `insertAction` (the\n * kit's standard insert dep, sourced by `<SceneCanvas>`). Side count\n * defaults to 6, adjustable mid-gesture via ArrowUp/Down or wheel.\n *\n * The live preview is painted by the dispatcher overlay layer reading\n * `insertAction.overlay()` — the action returns `{ kind:'insertPreview',\n * shape:'polygon', bounds, extras: { sides, ... } }`. Consumers wanting\n * a custom polygon node shape override the `insert` dep.\n */\nexport function usePolygonTool<TNode extends { id: string } = { id: string }>(\n options: UsePolygonToolOptions = {},\n): Tool {\n const { sides: initialSides = 6, label = 'Polygon', behaviors } = options;\n // Side count in a ref so keyDown / wheel mutations are visible\n // synchronously to the insert binding's thunked params (re-resolved\n // every frame for the live preview and at commit time). A useState\n // tick alongside forces a render so the dispatcher overlay layer\n // repaints when the count changes between pointer events.\n const sidesRef = useRef(initialSides);\n const [, setSidesTick] = useState(0);\n const bumpSides = useCallback(() => setSidesTick((n) => n + 1), []);\n\n // Wheel-to-adjust-sides action. Bound to `[engaged] wheel` so it only\n // fires while a polygon insert drag is in flight — outside that window\n // wheel falls through to ambient viewport.pan/zoom. The action's run\n // body reads the dispatcher-injected wheel delta from params.\n const adjustSidesAction = useMemo<Action>(\n () => ({\n id: 'polygon.adjustSides',\n label: 'Polygon — adjust sides',\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 side.\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 sidesRef.current = step > 0\n ? Math.min(SHAPE_COUNT_RANGE.max, sidesRef.current + 1)\n : Math.max(SHAPE_COUNT_RANGE.min, sidesRef.current - 1);\n bumpSides();\n },\n },\n }),\n [bumpSides],\n );\n\n // `TNode` is retained for source-compat with callers that previously\n // threaded a node-record type through; the tool no longer mints nodes\n // (insertAction does), so the parameter has no runtime effect.\n void ({} as TNode);\n\n return useMemo(\n () =>\n defineTool({\n id: 'polygon',\n keybinding: { key: 'G' },\n capabilities: ['creates-shapes'],\n hookName: 'usePolygonTool',\n cursor: cursorFor('crosshairPolygon', { fallback: 'crosshair' }),\n // Registered by <ToolActionsMounter>, inside the ActionsProvider —\n // see `ToolDef.actions` for why the hook can't register it itself.\n actions: [adjustSidesAction],\n presentation: {\n label,\n group: 'shape',\n icon: <PolygonIcon />,\n },\n bindings: [\n // Default = drag from corner, consistent with rect/ellipse.\n // The dispatcher overlay paints an anchorPoint dot at the\n // click so the radial shape reads as anchored even though no\n // polygon vertex sits at the AABB corner. Alt held flips to\n // center mode (insertAction reads live modifier state).\n {\n spec: { kind: 'drag' },\n actionId: 'insert',\n // Thunked params re-evaluated at commit time (and on every\n // overlay() call for live preview) so mid-gesture\n // ArrowUp/Down/wheel side-count changes flow through both\n // the ghost and the committed geometry.\n opts: {\n params: () => ({\n kind: 'polygon',\n sides: sidesRef.current,\n }),\n ...insertBindingBehaviors(behaviors),\n },\n },\n INSERT_REPOSITION_BINDING,\n // Wheel-during-drag → adjust side count. Phase-gated to\n // `engaged` so wheel while the tool is idle still falls\n // through to ambient viewport.pan / viewport.zoom.\n {\n spec: { kind: 'wheel', phase: 'engaged' },\n actionId: 'polygon.adjustSides',\n },\n // Shift+wheel during engaged drag → rotate the in-flight\n // shape in place. Strict modifier matching means this\n // doesn't conflict with the unmodified wheel binding above.\n {\n spec: { kind: 'wheel', phase: 'engaged', mods: { shift: true } },\n actionId: 'insert.adjustRotation',\n },\n // ArrowUp/Down → adjust side count. These were phase-table\n // `initial.keyDown` routes, which put them on the OTHER dispatch\n // pipeline: the tool route claimed the key but its `claim()` never\n // reached the DOM as preventDefault/stopPropagation, so `nudge.up`\n // matched the same keypress on the interactions dispatcher and\n // moved the selection at the same time (audit §4 — derived there,\n // reproduced and now covered by a smoke test). As active-scope\n // bindings they out-prioritize ambient `nudge.*` and the\n // dispatcher's first-match-wins settles it.\n {\n spec: { kind: 'key', key: 'ArrowUp' },\n actionId: 'polygon.adjustSides',\n opts: { params: { delta: 1 } },\n },\n {\n spec: { kind: 'key', key: 'ArrowDown' },\n actionId: 'polygon.adjustSides',\n opts: { params: { delta: -1 } },\n },\n ],\n }),\n [adjustSidesAction, behaviors, label],\n );\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgBC,EACd,IAAiC,CAAC,GAC5B;CACN,IAAM,EAAE,OAAOC,IAAe,GAAG,WAAQ,WAAW,iBAAcC,GAM5DC,IAAWC,EAAOH,CAAY,GAC9B,GAAGI,KAAgBC,EAAS,CAAC,GAC7BC,IAAYC,QAAkBH,GAAc,MAAMI,IAAI,CAAC,GAAG,CAAC,CAAC,GAM5DC,IAAoBC,SACjB;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,EAAS,UAAUA,IAAO,IACtB,KAAK,IAAIC,EAAkB,KAAKZ,EAAS,UAAU,CAAC,IACpD,KAAK,IAAIY,EAAkB,KAAKZ,EAAS,UAAU,CAAC,GACxDI,EAAU;GACZ;EACF;CACF,IACA,CAACA,CAAS,CACZ;CAOA,OAAOI,QAEHK,EAAW;EACT,IAAI;EACJ,YAAY,EAAE,KAAK,IAAI;EACvB,cAAc,CAAC,gBAAgB;EAC/B,UAAU;EACV,QAAQC,EAAU,oBAAoB,EAAE,UAAU,YAAY,CAAC;EAG/D,SAAS,CAACP,CAAiB;EAC3B,cAAc;GACZ;GACA,OAAO;GACP,MAAM,kBAACX,GAAD,CAAc,CAAA;EACtB;EACA,UAAU;GAMR;IACE,MAAM,EAAE,MAAM,OAAO;IACrB,UAAU;IAKV,MAAM;KACJ,eAAe;MACb,MAAM;MACN,OAAOI,EAAS;KAClB;KACA,GAAGe,EAAuBC,CAAS;IACrC;GACF;GACAC;GAIA;IACE,MAAM;KAAE,MAAM;KAAS,OAAO;IAAU;IACxC,UAAU;GACZ;GAIA;IACE,MAAM;KAAE,MAAM;KAAS,OAAO;KAAW,MAAM,EAAE,OAAO,GAAK;IAAE;IAC/D,UAAU;GACZ;GAUA;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;EAAmBS;EAAWE;CAAK,CACtC;AACF"}
@@ -1,20 +1,21 @@
1
- import { defineTool as e } from "../../overlayBinding.js";
2
- import t from "../../../icons/RectIcon.js";
3
- import { insertBindingBehaviors as n } from "../shared/insertToolOptions.js";
4
- import { createElement as r, useMemo as i } from "react";
5
- import { cursorFor as a } from "@weasel-js/cursor";
1
+ import { INSERT_REPOSITION_BINDING as e } from "../../../interactions/actions/insert/repositionAction.js";
2
+ import { defineTool as t } from "../../overlayBinding.js";
3
+ import n from "../../../icons/RectIcon.js";
4
+ import { insertBindingBehaviors as r } from "../shared/insertToolOptions.js";
5
+ import { createElement as i, useMemo as a } from "react";
6
+ import { cursorFor as o } from "@weasel-js/cursor";
6
7
  //#region src/tools/builtin/rect/useRectTool.ts
7
- function o(o = {}) {
8
- let { behaviors: s } = o;
9
- return i(() => e({
8
+ function s(s = {}) {
9
+ let { behaviors: c } = s;
10
+ return a(() => t({
10
11
  id: "rect",
11
12
  keybinding: { key: "R" },
12
13
  capabilities: ["creates-shapes"],
13
14
  hookName: "useRectTool",
14
- cursor: a("crosshairRect", { fallback: "crosshair" }),
15
+ cursor: o("crosshairRect", { fallback: "crosshair" }),
15
16
  presentation: {
16
17
  label: "Rectangle",
17
- icon: r(t),
18
+ icon: i(n),
18
19
  group: "shape"
19
20
  },
20
21
  bindings: [{
@@ -22,12 +23,12 @@ function o(o = {}) {
22
23
  actionId: "insert",
23
24
  opts: {
24
25
  params: { kind: "rect" },
25
- ...n(s)
26
+ ...r(c)
26
27
  }
27
- }]
28
- }), [s]);
28
+ }, e]
29
+ }), [c]);
29
30
  }
30
31
  //#endregion
31
- export { o as useRectTool };
32
+ export { s as useRectTool };
32
33
 
33
34
  //# sourceMappingURL=useRectTool.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useRectTool.js","names":["RectIcon","useRectTool","options","useMemo","defineTool","cursorFor","createElement","insertBindingBehaviors","behaviors"],"sources":["../../../../src/tools/builtin/rect/useRectTool.ts"],"sourcesContent":["import { useMemo, createElement } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { RectIcon } from '../../../icons';\nimport type { Tool } from '../../overlayBinding';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport { cursorFor } from '@weasel-js/cursor';\n\n/**\n * Drag-to-draw rectangle tool.\n *\n * The `drag` binding routes to `insertAction`, which owns the live preview\n * and commits via the `insert` dep on release. Consumers wanting a custom\n * node factory override the dep (`useDepSource('insert', …)`) rather than\n * the tool. Grid snapping comes from the `snap` dep.\n */\nexport function useRectTool(options: InsertToolOptions = {}): Tool {\n const { behaviors } = options;\n return useMemo(\n () =>\n defineTool({\n id: 'rect',\n keybinding: { key: 'R' },\n capabilities: ['creates-shapes'],\n hookName: 'useRectTool',\n cursor: cursorFor('crosshairRect', { fallback: 'crosshair' }),\n presentation: {\n label: 'Rectangle',\n icon: createElement(RectIcon),\n group: 'shape',\n },\n // Single binding: insertAction toggles corner ⇄ center on live Alt\n // state, so Alt can be engaged mid-drag.\n bindings: [\n {\n spec: { kind: 'drag' },\n actionId: 'insert',\n opts: { params: { kind: 'rect' } , ...insertBindingBehaviors(behaviors) },\n },\n ],\n }),\n [behaviors],\n );\n}\n"],"mappings":";;;;;;AAeA,SAAgBC,EAAY,IAA6B,CAAC,GAAS;CACjE,IAAM,EAAE,iBAAcC;CACtB,OAAOC,QAEHC,EAAW;EACT,IAAI;EACJ,YAAY,EAAE,KAAK,IAAI;EACvB,cAAc,CAAC,gBAAgB;EAC/B,UAAU;EACV,QAAQC,EAAU,iBAAiB,EAAE,UAAU,YAAY,CAAC;EAC5D,cAAc;GACZ,OAAO;GACP,MAAMC,EAAcN,CAAQ;GAC5B,OAAO;EACT;EAGA,UAAU,CACR;GACE,MAAM,EAAE,MAAM,OAAO;GACrB,UAAU;GACV,MAAM;IAAE,QAAQ,EAAE,MAAM,OAAO;IAAI,GAAGO,EAAuBC,CAAS;GAAE;EAC1E,CACF;CACF,CAAC,GACH,CAACA,CAAS,CACZ;AACF"}
1
+ {"version":3,"file":"useRectTool.js","names":["RectIcon","useRectTool","options","useMemo","defineTool","cursorFor","createElement","insertBindingBehaviors","behaviors","INSERT_REPOSITION_BINDING"],"sources":["../../../../src/tools/builtin/rect/useRectTool.ts"],"sourcesContent":["import { useMemo, createElement } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { RectIcon } from '../../../icons';\nimport type { Tool } from '../../overlayBinding';\nimport { INSERT_REPOSITION_BINDING } from 'interactions/actions/insert/repositionAction';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport { cursorFor } from '@weasel-js/cursor';\n\n/**\n * Drag-to-draw rectangle tool.\n *\n * The `drag` binding routes to `insertAction`, which owns the live preview\n * and commits via the `insert` dep on release. Consumers wanting a custom\n * node factory override the dep (`useDepSource('insert', …)`) rather than\n * the tool. Grid snapping comes from the `snap` dep.\n */\nexport function useRectTool(options: InsertToolOptions = {}): Tool {\n const { behaviors } = options;\n return useMemo(\n () =>\n defineTool({\n id: 'rect',\n keybinding: { key: 'R' },\n capabilities: ['creates-shapes'],\n hookName: 'useRectTool',\n cursor: cursorFor('crosshairRect', { fallback: 'crosshair' }),\n presentation: {\n label: 'Rectangle',\n icon: createElement(RectIcon),\n group: 'shape',\n },\n // Single binding: insertAction toggles corner ⇄ center on live Alt\n // state, so Alt can be engaged mid-drag.\n bindings: [\n {\n spec: { kind: 'drag' },\n actionId: 'insert',\n opts: { params: { kind: 'rect' } , ...insertBindingBehaviors(behaviors) },\n },\n INSERT_REPOSITION_BINDING,\n ],\n }),\n [behaviors],\n );\n}\n"],"mappings":";;;;;;;AAgBA,SAAgBC,EAAY,IAA6B,CAAC,GAAS;CACjE,IAAM,EAAE,iBAAcC;CACtB,OAAOC,QAEHC,EAAW;EACT,IAAI;EACJ,YAAY,EAAE,KAAK,IAAI;EACvB,cAAc,CAAC,gBAAgB;EAC/B,UAAU;EACV,QAAQC,EAAU,iBAAiB,EAAE,UAAU,YAAY,CAAC;EAC5D,cAAc;GACZ,OAAO;GACP,MAAMC,EAAcN,CAAQ;GAC5B,OAAO;EACT;EAGA,UAAU,CACR;GACE,MAAM,EAAE,MAAM,OAAO;GACrB,UAAU;GACV,MAAM;IAAE,QAAQ,EAAE,MAAM,OAAO;IAAI,GAAGO,EAAuBC,CAAS;GAAE;EAC1E,GACAC,CACF;CACF,CAAC,GACH,CAACD,CAAS,CACZ;AACF"}
@@ -2,35 +2,39 @@ import { toPlane as e } from "../../../core/viewport/parallax.js";
2
2
  import { poseDescriptorForNode as t } from "../../../core/geometry/poseDescriptor.js";
3
3
  import { shapeCoversPoint as n } from "../../../canvas/NodeShape.js";
4
4
  import { ownClipOf as r } from "../../../canvas/pickWalk.js";
5
- import { boundsOfPath as i, meanScale as a, pathContainsPoint as o } from "@weasel-js/geom";
5
+ import { applyToPoint as i, boundsOfPath as a, meanScale as o, pathContainsPoint as s } from "@weasel-js/geom";
6
6
  //#region src/tools/builtin/select/adapterPointQuery.ts
7
- function s(s, c) {
8
- let l = (u, d, f) => ({
9
- hits: (e, a, l) => {
10
- let p = l ? i(l) : t(s, e).getBounds(a);
7
+ function c(c, l) {
8
+ let u = (d, f, p) => ({
9
+ hits: (e, i, o) => {
10
+ let u = o ? a(o) : t(c, e).getBounds(i);
11
11
  if (e.kind !== "container") {
12
- let t = c || l ? f : 0;
13
- return u >= p.x - t && u <= p.x + p.width + t && d >= p.y - t && d <= p.y + p.height + t ? !c || n(e, a, u, d, {
14
- tolerance: f,
15
- derivedPath: l
12
+ let t = l || o ? p : 0;
13
+ return d >= u.x - t && d <= u.x + u.width + t && f >= u.y - t && f <= u.y + u.height + t ? !l || n(e, i, d, f, {
14
+ tolerance: p,
15
+ derivedPath: o
16
16
  }) : !1;
17
17
  }
18
- if (!(u >= p.x && u <= p.x + p.width && d >= p.y && d <= p.y + p.height)) return !1;
19
- let m = r(e, a, l);
20
- return m === null || o(m, u, d);
18
+ if (!(d >= u.x && d <= u.x + u.width && f >= u.y && f <= u.y + u.height)) return !1;
19
+ let m = r(e, i, o);
20
+ return m === null || s(m, d, f);
21
21
  },
22
- clipAdmits: (e) => o(e, u, d),
22
+ clipAdmits: (e) => s(e, d, f),
23
23
  inPlane: (t) => {
24
24
  let n = e(t, {
25
- x: u,
26
- y: d
25
+ x: d,
26
+ y: f
27
27
  });
28
- return l(n.x, n.y, f * a(t.scale));
28
+ return u(n.x, n.y, p * o(t.scale));
29
+ },
30
+ inCopy: (e) => {
31
+ let [t, n] = i(e, d, f);
32
+ return u(t, n, p * Math.sqrt(Math.abs(e[0] * e[3] - e[1] * e[2])));
29
33
  }
30
34
  });
31
- return l;
35
+ return u;
32
36
  }
33
37
  //#endregion
34
- export { s as adapterPointQuery };
38
+ export { c as adapterPointQuery };
35
39
 
36
40
  //# sourceMappingURL=adapterPointQuery.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"adapterPointQuery.js","names":["adapterPointQuery","pointQuery","b","derived","boundsOfPath","poseDescriptorForNode","d","node","pose","slop","preciseLeaves","t","px","py","shapeCoversPoint","own","ownClipOf","pathContainsPoint","clip","p","toPlane","m","meanScale"],"sources":["../../../../src/tools/builtin/select/adapterPointQuery.ts"],"sourcesContent":["import { boundsOfPath, meanScale, pathContainsPoint } from '@weasel-js/geom';\nimport { shapeCoversPoint } from 'canvas/NodeShape';\nimport { ownClipOf, type PickQuery } from 'canvas/pickWalk';\nimport { poseDescriptorForNode, type PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport type { Node } from 'core/scene/types';\nimport { toPlane } from 'core/viewport/parallax';\n\n/**\n * The point query `useSelectTool`'s default `pickEvery` asks of a bare adapter:\n * a point at (px, py) with `t` world units of slop. AABB first (cheap), then\n * the painter's ink when `preciseLeaves` asks for it and it is available. A\n * painter with no `silhouette` — or one that returns null, as `kit:text` does\n * for an empty node — keeps the AABB answer.\n *\n * The AABB pre-filter is grown by the slop: a shape's outline, and the slop\n * around it, reach outside the shape's own bounds.\n *\n * A node that derives its path is tested against that path's box: its own pose\n * is a placeholder, and the box of a straight route has no area to land in\n * without the slop.\n */\nexport function adapterPointQuery<TPose>(\n d: PoseDescriptor<TPose>,\n preciseLeaves: boolean,\n): (px: number, py: number, t: number) => PickQuery<TPose> {\n const pointQuery = (px: number, py: number, t: number): PickQuery<TPose> => ({\n hits: (node, pose, derived) => {\n const b = derived ? boundsOfPath(derived) : poseDescriptorForNode(d, node).getBounds(pose);\n if (node.kind !== 'container') {\n const slop = preciseLeaves || derived ? t : 0;\n if (!(px >= b.x - slop && px <= b.x + b.width + slop\n && py >= b.y - slop && py <= b.y + b.height + slop)) {\n return false;\n }\n if (!preciseLeaves) return true;\n return shapeCoversPoint(\n node as Node<unknown, string, TPose>, pose, px, py, { tolerance: t, derivedPath: derived },\n );\n }\n // A container's own clip *is* its hit shape — it is picked where it\n // paints, and it paints only inside its clip. Ancestor clips are the\n // walk's business; this one is not.\n const inAabb = px >= b.x && px <= b.x + b.width\n && py >= b.y && py <= b.y + b.height;\n if (!inAabb) return false;\n const own = ownClipOf(node, pose, derived);\n return own === null || pathContainsPoint(own, px, py);\n },\n clipAdmits: (clip) => pathContainsPoint(clip, px, py),\n inPlane: (m) => {\n const p = toPlane(m, { x: px, y: py });\n return pointQuery(p.x, p.y, t * meanScale(m.scale));\n },\n });\n return pointQuery;\n}\n"],"mappings":";;;;;;AAqBA,SAAgBA,EACd,GACA,GACyD;CACzD,IAAMC,KAAc,GAAY,GAAY,OAAiC;EAC3E,OAAO,GAAM,GAAM,MAAY;GAC7B,IAAMC,IAAIC,IAAUC,EAAaD,CAAO,IAAIE,EAAsBC,GAAGC,CAAI,CAAC,CAAC,UAAUC,CAAI;GACzF,IAAID,EAAK,SAAS,aAAa;IAC7B,IAAME,IAAOC,KAAiBP,IAAUQ,IAAI;IAM5C,OALMC,KAAMV,EAAE,IAAIO,KAAQG,KAAMV,EAAE,IAAIA,EAAE,QAAQO,KACvCI,KAAMX,EAAE,IAAIO,KAAQI,KAAMX,EAAE,IAAIA,EAAE,SAASO,IAGpD,CAAKC,KACEI,EACLP,GAAsCC,GAAMI,GAAIC,GAAI;KAAE,WAAWF;KAAG,aAAaR;IAAQ,CAC3F,IALS;GAMX;GAMA,IAAI,EAFWS,KAAMV,EAAE,KAAKU,KAAMV,EAAE,IAAIA,EAAE,SACrCW,KAAMX,EAAE,KAAKW,KAAMX,EAAE,IAAIA,EAAE,SACnB,OAAO;GACpB,IAAMa,IAAMC,EAAUT,GAAMC,GAAML,CAAO;GACzC,OAAOY,MAAQ,QAAQE,EAAkBF,GAAKH,GAAIC,CAAE;EACtD;EACA,aAAa,MAASI,EAAkBC,GAAMN,GAAIC,CAAE;EACpD,UAAU,MAAM;GACd,IAAMM,IAAIC,EAAQC,GAAG;IAAE,GAAGT;IAAI,GAAGC;GAAG,CAAC;GACrC,OAAOZ,EAAWkB,EAAE,GAAGA,EAAE,GAAGR,IAAIW,EAAUD,EAAE,KAAK,CAAC;EACpD;CACF;CACA,OAAOpB;AACT"}
1
+ {"version":3,"file":"adapterPointQuery.js","names":["adapterPointQuery","pointQuery","b","derived","boundsOfPath","poseDescriptorForNode","d","node","pose","slop","preciseLeaves","t","px","py","shapeCoversPoint","own","ownClipOf","pathContainsPoint","clip","p","toPlane","m","meanScale","x","y","applyToPoint"],"sources":["../../../../src/tools/builtin/select/adapterPointQuery.ts"],"sourcesContent":["import { applyToPoint, boundsOfPath, meanScale, pathContainsPoint } from '@weasel-js/geom';\nimport { shapeCoversPoint } from 'canvas/NodeShape';\nimport { ownClipOf, type PickQuery } from 'canvas/pickWalk';\nimport { poseDescriptorForNode, type PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport type { Node } from 'core/scene/types';\nimport { toPlane } from 'core/viewport/parallax';\n\n/**\n * The point query `useSelectTool`'s default `pickEvery` asks of a bare adapter:\n * a point at (px, py) with `t` world units of slop. AABB first (cheap), then\n * the painter's ink when `preciseLeaves` asks for it and it is available. A\n * painter with no `silhouette` — or one that returns null, as `kit:text` does\n * for an empty node — keeps the AABB answer.\n *\n * The AABB pre-filter is grown by the slop: a shape's outline, and the slop\n * around it, reach outside the shape's own bounds.\n *\n * A node that derives its path is tested against that path's box: its own pose\n * is a placeholder, and the box of a straight route has no area to land in\n * without the slop.\n */\nexport function adapterPointQuery<TPose>(\n d: PoseDescriptor<TPose>,\n preciseLeaves: boolean,\n): (px: number, py: number, t: number) => PickQuery<TPose> {\n const pointQuery = (px: number, py: number, t: number): PickQuery<TPose> => ({\n hits: (node, pose, derived) => {\n const b = derived ? boundsOfPath(derived) : poseDescriptorForNode(d, node).getBounds(pose);\n if (node.kind !== 'container') {\n const slop = preciseLeaves || derived ? t : 0;\n if (!(px >= b.x - slop && px <= b.x + b.width + slop\n && py >= b.y - slop && py <= b.y + b.height + slop)) {\n return false;\n }\n if (!preciseLeaves) return true;\n return shapeCoversPoint(\n node as Node<unknown, string, TPose>, pose, px, py, { tolerance: t, derivedPath: derived },\n );\n }\n // A container's own clip *is* its hit shape — it is picked where it\n // paints, and it paints only inside its clip. Ancestor clips are the\n // walk's business; this one is not.\n const inAabb = px >= b.x && px <= b.x + b.width\n && py >= b.y && py <= b.y + b.height;\n if (!inAabb) return false;\n const own = ownClipOf(node, pose, derived);\n return own === null || pathContainsPoint(own, px, py);\n },\n clipAdmits: (clip) => pathContainsPoint(clip, px, py),\n inPlane: (m) => {\n const p = toPlane(m, { x: px, y: py });\n return pointQuery(p.x, p.y, t * meanScale(m.scale));\n },\n inCopy: (m) => {\n const [x, y] = applyToPoint(m, px, py);\n return pointQuery(x, y, t * Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])));\n },\n });\n return pointQuery;\n}\n"],"mappings":";;;;;;AAqBA,SAAgBA,EACd,GACA,GACyD;CACzD,IAAMC,KAAc,GAAY,GAAY,OAAiC;EAC3E,OAAO,GAAM,GAAM,MAAY;GAC7B,IAAMC,IAAIC,IAAUC,EAAaD,CAAO,IAAIE,EAAsBC,GAAGC,CAAI,CAAC,CAAC,UAAUC,CAAI;GACzF,IAAID,EAAK,SAAS,aAAa;IAC7B,IAAME,IAAOC,KAAiBP,IAAUQ,IAAI;IAM5C,OALMC,KAAMV,EAAE,IAAIO,KAAQG,KAAMV,EAAE,IAAIA,EAAE,QAAQO,KACvCI,KAAMX,EAAE,IAAIO,KAAQI,KAAMX,EAAE,IAAIA,EAAE,SAASO,IAGpD,CAAKC,KACEI,EACLP,GAAsCC,GAAMI,GAAIC,GAAI;KAAE,WAAWF;KAAG,aAAaR;IAAQ,CAC3F,IALS;GAMX;GAMA,IAAI,EAFWS,KAAMV,EAAE,KAAKU,KAAMV,EAAE,IAAIA,EAAE,SACrCW,KAAMX,EAAE,KAAKW,KAAMX,EAAE,IAAIA,EAAE,SACnB,OAAO;GACpB,IAAMa,IAAMC,EAAUT,GAAMC,GAAML,CAAO;GACzC,OAAOY,MAAQ,QAAQE,EAAkBF,GAAKH,GAAIC,CAAE;EACtD;EACA,aAAa,MAASI,EAAkBC,GAAMN,GAAIC,CAAE;EACpD,UAAU,MAAM;GACd,IAAMM,IAAIC,EAAQC,GAAG;IAAE,GAAGT;IAAI,GAAGC;GAAG,CAAC;GACrC,OAAOZ,EAAWkB,EAAE,GAAGA,EAAE,GAAGR,IAAIW,EAAUD,EAAE,KAAK,CAAC;EACpD;EACA,SAAS,MAAM;GACb,IAAM,CAACE,GAAGC,KAAKC,EAAaJ,GAAGT,GAAIC,CAAE;GACrC,OAAOZ,EAAWsB,GAAGC,GAAGb,IAAI,KAAK,KAAK,KAAK,IAAIU,EAAE,KAAKA,EAAE,KAAKA,EAAE,KAAKA,EAAE,EAAE,CAAC,CAAC;EAC5E;CACF;CACA,OAAOpB;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { gestureLifecycleParams as e } from "../../../interactions/actions/gestureLifecycle.js";
2
- import { isAnchorOrControl as t, isResizeHandle as n, isRotateHandle as r } from "@weasel-js/routing";
2
+ import { isPathEditPart as t, isResizeHandle as n, isRotateHandle as r } from "@weasel-js/routing";
3
3
  import { hitPredicate as i } from "@weasel-js/gestures";
4
4
  //#region src/tools/builtin/select/selectionContributions.ts
5
5
  var a = "selection.move", o = "selection.transform", s = "selection.resize", c = "selection.rotate";