@weasel-js/core 1.9.2 → 1.9.4

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 (542) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/README.md +2 -2
  3. package/dist/WeaselProvider.js +5 -5
  4. package/dist/affordances/composeAffordanceLayer.js +10 -20
  5. package/dist/affordances/composeAffordanceLayer.js.map +1 -1
  6. package/dist/affordances/cornerResize.js +25 -17
  7. package/dist/affordances/cornerResize.js.map +1 -1
  8. package/dist/affordances/hitAffordanceRegions.js +27 -20
  9. package/dist/affordances/hitAffordanceRegions.js.map +1 -1
  10. package/dist/affordances/rotationHandle.js +18 -18
  11. package/dist/affordances/rotationHandle.js.map +1 -1
  12. package/dist/animation/behaviors/momentum.js +93 -55
  13. package/dist/animation/behaviors/momentum.js.map +1 -1
  14. package/dist/animation/loop.js +10 -12
  15. package/dist/animation/loop.js.map +1 -1
  16. package/dist/animation/reflow.js +8 -8
  17. package/dist/animation/reflow.js.map +1 -1
  18. package/dist/animation/stagger.js +64 -56
  19. package/dist/animation/stagger.js.map +1 -1
  20. package/dist/animation/timeline/booking.js +62 -54
  21. package/dist/animation/timeline/booking.js.map +1 -1
  22. package/dist/animation/timeline/createTimeline.js +85 -76
  23. package/dist/animation/timeline/createTimeline.js.map +1 -1
  24. package/dist/animation/timeline/sampleTrack.js +13 -5
  25. package/dist/animation/timeline/sampleTrack.js.map +1 -1
  26. package/dist/animation/useAnimator.js +45 -35
  27. package/dist/animation/useAnimator.js.map +1 -1
  28. package/dist/animation/wrappers/animateLifecycle.js +31 -24
  29. package/dist/animation/wrappers/animateLifecycle.js.map +1 -1
  30. package/dist/animation/wrappers/animateOnSetPose.js +28 -26
  31. package/dist/animation/wrappers/animateOnSetPose.js.map +1 -1
  32. package/dist/animation/wrappers/instantPose.js +13 -0
  33. package/dist/animation/wrappers/instantPose.js.map +1 -0
  34. package/dist/{poseDescriptor-D-OH-tu5.d.ts → autoPoseDescriptor-Ct7yqivU.d.ts} +28 -3
  35. package/dist/barrel/chrome.js +16 -0
  36. package/dist/barrel/input.js +19 -0
  37. package/dist/barrel/interactions.js +42 -0
  38. package/dist/barrel/paint.js +18 -0
  39. package/dist/barrel/paths.js +19 -0
  40. package/dist/barrel/renderer.js +20 -0
  41. package/dist/barrel/routing.js +51 -0
  42. package/dist/barrel/text.js +18 -0
  43. package/dist/barrel/viewport.js +52 -0
  44. package/dist/builtins-DPcdghtB.d.ts +1223 -0
  45. package/dist/canvas/Canvas.js +363 -448
  46. package/dist/canvas/Canvas.js.map +1 -1
  47. package/dist/canvas/CanvasView.js +164 -165
  48. package/dist/canvas/CanvasView.js.map +1 -1
  49. package/dist/canvas/CursorCoordsHud.js +37 -32
  50. package/dist/canvas/CursorCoordsHud.js.map +1 -1
  51. package/dist/canvas/DrawCanvas.js +49 -43
  52. package/dist/canvas/DrawCanvas.js.map +1 -1
  53. package/dist/canvas/MinimapCanvas.js +26 -25
  54. package/dist/canvas/MinimapCanvas.js.map +1 -1
  55. package/dist/canvas/NodeShape.js +59 -377
  56. package/dist/canvas/NodeShape.js.map +1 -1
  57. package/dist/canvas/PickHud.js +50 -47
  58. package/dist/canvas/PickHud.js.map +1 -1
  59. package/dist/canvas/SceneCanvas/GestureDispatcherMounter.js +167 -0
  60. package/dist/canvas/SceneCanvas/GestureDispatcherMounter.js.map +1 -0
  61. package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js +13 -13
  62. package/dist/canvas/SceneCanvas/StandardActionsRegistrar.js +67 -0
  63. package/dist/canvas/SceneCanvas/StandardActionsRegistrar.js.map +1 -0
  64. package/dist/canvas/SceneCanvas/ToolKeybindingsMounter.js +16 -0
  65. package/dist/canvas/SceneCanvas/ToolKeybindingsMounter.js.map +1 -0
  66. package/dist/canvas/SceneCanvas/coordTrace.js +10 -0
  67. package/dist/canvas/SceneCanvas/coordTrace.js.map +1 -0
  68. package/dist/canvas/SceneCanvas/defaultNodeProperties.js +146 -92
  69. package/dist/canvas/SceneCanvas/defaultNodeProperties.js.map +1 -1
  70. package/dist/canvas/SceneCanvas/defaultNodeRouting.js +9 -8
  71. package/dist/canvas/SceneCanvas/defaultNodeRouting.js.map +1 -1
  72. package/dist/canvas/SceneCanvas/features.js +1 -0
  73. package/dist/canvas/SceneCanvas/features.js.map +1 -1
  74. package/dist/canvas/SceneCanvas/isDev.js +12 -0
  75. package/dist/canvas/SceneCanvas/isDev.js.map +1 -0
  76. package/dist/canvas/SceneCanvas/poseGeometry.js +29 -28
  77. package/dist/canvas/SceneCanvas/poseGeometry.js.map +1 -1
  78. package/dist/canvas/SceneCanvas/poseRegistrars.js +13 -0
  79. package/dist/canvas/SceneCanvas/poseRegistrars.js.map +1 -0
  80. package/dist/canvas/SceneCanvas/props.js +38 -0
  81. package/dist/canvas/SceneCanvas/props.js.map +1 -0
  82. package/dist/canvas/SceneCanvas/useBuiltinShapeTools.js +21 -62
  83. package/dist/canvas/SceneCanvas/useBuiltinShapeTools.js.map +1 -1
  84. package/dist/canvas/SceneCanvas/useDispatcherOverlayLayer.js.map +1 -1
  85. package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js +46 -48
  86. package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js.map +1 -1
  87. package/dist/canvas/SceneCanvas/useSceneSelectTool.js +33 -33
  88. package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -1
  89. package/dist/canvas/SceneCanvas.js +534 -788
  90. package/dist/canvas/SceneCanvas.js.map +1 -1
  91. package/dist/canvas/SceneViewCanvas.js +45 -43
  92. package/dist/canvas/SceneViewCanvas.js.map +1 -1
  93. package/dist/canvas/buildSceneLayer.js +91 -0
  94. package/dist/canvas/buildSceneLayer.js.map +1 -0
  95. package/dist/canvas/buildSceneTree.js +16 -19
  96. package/dist/canvas/buildSceneTree.js.map +1 -1
  97. package/dist/canvas/canvasRenderer.js +68 -52
  98. package/dist/canvas/canvasRenderer.js.map +1 -1
  99. package/dist/canvas/deps/changes.js +13 -0
  100. package/dist/canvas/deps/changes.js.map +1 -0
  101. package/dist/canvas/deps/editAnchors.js +28 -28
  102. package/dist/canvas/deps/insert.js +119 -91
  103. package/dist/canvas/deps/insert.js.map +1 -1
  104. package/dist/canvas/deps/slice.js +46 -45
  105. package/dist/canvas/deps/slice.js.map +1 -1
  106. package/dist/canvas/deps/textEdit.js +10 -9
  107. package/dist/canvas/deps/textEdit.js.map +1 -1
  108. package/dist/canvas/derivedPath.js +46 -23
  109. package/dist/canvas/derivedPath.js.map +1 -1
  110. package/dist/canvas/getNodeAtPoint.js +7 -7
  111. package/dist/canvas/getNodeAtPoint.js.map +1 -1
  112. package/dist/canvas/hud.module.js +1 -1
  113. package/dist/canvas/hud.module.js.map +1 -1
  114. package/dist/canvas/kitRequirements.js +2 -2
  115. package/dist/canvas/kitRequirements.js.map +1 -1
  116. package/dist/canvas/layerOrder.js +13 -6
  117. package/dist/canvas/layerOrder.js.map +1 -1
  118. package/dist/canvas/minimapMath.js +12 -10
  119. package/dist/canvas/minimapMath.js.map +1 -1
  120. package/dist/canvas/nodeShapes/derivedPainter.js +34 -0
  121. package/dist/canvas/nodeShapes/derivedPainter.js.map +1 -0
  122. package/dist/canvas/nodeShapes/imagePainter.js +87 -0
  123. package/dist/canvas/nodeShapes/imagePainter.js.map +1 -0
  124. package/dist/canvas/nodeShapes/memo.js +9 -0
  125. package/dist/canvas/nodeShapes/memo.js.map +1 -0
  126. package/dist/canvas/nodeShapes/nodePaint.js +57 -0
  127. package/dist/canvas/nodeShapes/nodePaint.js.map +1 -0
  128. package/dist/canvas/nodeShapes/pathPainter.js +38 -0
  129. package/dist/canvas/nodeShapes/pathPainter.js.map +1 -0
  130. package/dist/canvas/nodeShapes/poseBox.js +20 -0
  131. package/dist/canvas/nodeShapes/poseBox.js.map +1 -0
  132. package/dist/canvas/nodeShapes/rectFallbackPainter.js +38 -0
  133. package/dist/canvas/nodeShapes/rectFallbackPainter.js.map +1 -0
  134. package/dist/canvas/nodeShapes/shapePainter.js +72 -0
  135. package/dist/canvas/nodeShapes/shapePainter.js.map +1 -0
  136. package/dist/canvas/nodeShapes/textPainter.js +55 -0
  137. package/dist/canvas/nodeShapes/textPainter.js.map +1 -0
  138. package/dist/canvas/overlayRoleStrokes.js.map +1 -1
  139. package/dist/canvas/paintCull.js +10 -11
  140. package/dist/canvas/paintCull.js.map +1 -1
  141. package/dist/canvas/pickWalk.js +52 -63
  142. package/dist/canvas/pickWalk.js.map +1 -1
  143. package/dist/canvas/poseRotation.js +11 -23
  144. package/dist/canvas/poseRotation.js.map +1 -1
  145. package/dist/canvas/renderDebugSnapshot.js +5 -5
  146. package/dist/canvas/renderSceneToPixels.js +3 -1
  147. package/dist/canvas/renderSceneToPixels.js.map +1 -1
  148. package/dist/canvas/sceneAdapter.js +66 -148
  149. package/dist/canvas/sceneAdapter.js.map +1 -1
  150. package/dist/canvas/sceneClipboard.js +112 -0
  151. package/dist/canvas/sceneClipboard.js.map +1 -0
  152. package/dist/canvas/sceneSlotWiring.js +4 -4
  153. package/dist/canvas/sceneSlotWiring.js.map +1 -1
  154. package/dist/canvas/sceneViewRender.js +39 -40
  155. package/dist/canvas/sceneViewRender.js.map +1 -1
  156. package/dist/canvas/useCanvasRenderer.js +14 -6
  157. package/dist/canvas/useCanvasRenderer.js.map +1 -1
  158. package/dist/canvas/useCanvasView.js +58 -0
  159. package/dist/canvas/useCanvasView.js.map +1 -0
  160. package/dist/canvas/useFrameLoop.js +35 -26
  161. package/dist/canvas/useFrameLoop.js.map +1 -1
  162. package/dist/canvas/useSceneLayerList.js +21 -0
  163. package/dist/canvas/useSceneLayerList.js.map +1 -0
  164. package/dist/clipboard.d.ts +10 -6
  165. package/dist/clone.d.ts +4 -3
  166. package/dist/core/adapters/arrayAdapter.js +48 -39
  167. package/dist/core/adapters/arrayAdapter.js.map +1 -1
  168. package/dist/core/device/index.js +5 -4
  169. package/dist/core/device/useDeviceProfile.js +38 -44
  170. package/dist/core/device/useDeviceProfile.js.map +1 -1
  171. package/dist/core/device/watchDevicePixelRatio.js +17 -0
  172. package/dist/core/device/watchDevicePixelRatio.js.map +1 -0
  173. package/dist/core/fillInPoseFrame.js.map +1 -1
  174. package/dist/core/geometry/poseDescriptor.js +21 -19
  175. package/dist/core/geometry/poseDescriptor.js.map +1 -1
  176. package/dist/core/geometry/poseFrame.js +44 -0
  177. package/dist/core/geometry/poseFrame.js.map +1 -0
  178. package/dist/core/geometry/poseRotation.js.map +1 -1
  179. package/dist/core/geometry/regionHit.js +9 -10
  180. package/dist/core/geometry/regionHit.js.map +1 -1
  181. package/dist/core/geometry/unionBounds.js +31 -29
  182. package/dist/core/geometry/unionBounds.js.map +1 -1
  183. package/dist/core/isPlainObject.js +2 -11
  184. package/dist/core/ops/arrange.js +1 -0
  185. package/dist/core/ops/arrange.js.map +1 -1
  186. package/dist/core/ops/create.js +10 -5
  187. package/dist/core/ops/create.js.map +1 -1
  188. package/dist/core/ops/delete.js +12 -24
  189. package/dist/core/ops/delete.js.map +1 -1
  190. package/dist/core/ops/reorder/index.js +43 -40
  191. package/dist/core/ops/reorder/index.js.map +1 -1
  192. package/dist/core/ops/reorder/setChildOrder.js +34 -0
  193. package/dist/core/ops/reorder/setChildOrder.js.map +1 -0
  194. package/dist/core/paintKinds.js +5 -5
  195. package/dist/core/paintKinds.js.map +1 -1
  196. package/dist/core/scene/NodeProperties.js.map +1 -1
  197. package/dist/core/scene/appliedLog.js +37 -0
  198. package/dist/core/scene/appliedLog.js.map +1 -0
  199. package/dist/core/scene/arrivalWindow.js +101 -0
  200. package/dist/core/scene/arrivalWindow.js.map +1 -0
  201. package/dist/core/scene/derivedPath.js.map +1 -1
  202. package/dist/core/scene/historyFacade.js +84 -0
  203. package/dist/core/scene/historyFacade.js.map +1 -0
  204. package/dist/core/scene/kitOps.js +173 -0
  205. package/dist/core/scene/kitOps.js.map +1 -0
  206. package/dist/core/scene/layerStack.js +38 -0
  207. package/dist/core/scene/layerStack.js.map +1 -0
  208. package/dist/core/scene/lockGuard.js +37 -0
  209. package/dist/core/scene/lockGuard.js.map +1 -0
  210. package/dist/core/scene/nodeFnFields.js +5 -6
  211. package/dist/core/scene/nodeFnFields.js.map +1 -1
  212. package/dist/core/scene/nodeMemo.js +45 -19
  213. package/dist/core/scene/nodeMemo.js.map +1 -1
  214. package/dist/core/scene/nodeStore.js +126 -0
  215. package/dist/core/scene/nodeStore.js.map +1 -0
  216. package/dist/core/scene/pickability.js +6 -0
  217. package/dist/core/scene/pickability.js.map +1 -0
  218. package/dist/core/scene/poseFeed.js +38 -38
  219. package/dist/core/scene/poseFeed.js.map +1 -1
  220. package/dist/core/scene/poseOverrides.js +34 -38
  221. package/dist/core/scene/poseOverrides.js.map +1 -1
  222. package/dist/core/scene/renderOrder.js +84 -0
  223. package/dist/core/scene/renderOrder.js.map +1 -0
  224. package/dist/core/scene/scene.js +289 -866
  225. package/dist/core/scene/scene.js.map +1 -1
  226. package/dist/core/scene/serialization.js +68 -0
  227. package/dist/core/scene/serialization.js.map +1 -0
  228. package/dist/core/scene/treeOrder.js +13 -0
  229. package/dist/core/scene/treeOrder.js.map +1 -0
  230. package/dist/core/scene/types.js.map +1 -1
  231. package/dist/core/viewport/meanScale.js +1 -1
  232. package/dist/core/viewport/meanScale.js.map +1 -1
  233. package/dist/core/viewport/view.js +12 -12
  234. package/dist/core/viewport/view.js.map +1 -1
  235. package/dist/core/viewport/zoomBounds.js +10 -8
  236. package/dist/core/viewport/zoomBounds.js.map +1 -1
  237. package/dist/{cornerHandles-BCrDp_mH.d.ts → cornerHandles-CtCb8a3G.d.ts} +1 -1
  238. package/dist/debug/createDebugOverlayLayer.js +14 -14
  239. package/dist/debug/createDebugOverlayLayer.js.map +1 -1
  240. package/dist/debug/flag.js +2 -41
  241. package/dist/features/chrome-caps/useHoverTracking.js +22 -17
  242. package/dist/features/chrome-caps/useHoverTracking.js.map +1 -1
  243. package/dist/features/focus/gateLayer.js +3 -4
  244. package/dist/features/focus/gateLayer.js.map +1 -1
  245. package/dist/features/images/imageCache.js +19 -9
  246. package/dist/features/images/imageCache.js.map +1 -1
  247. package/dist/features/ingestion/contentHandlers.js +14 -11
  248. package/dist/features/ingestion/contentHandlers.js.map +1 -1
  249. package/dist/features/ingestion/index.js +1 -1
  250. package/dist/features/ingestion/registerKitHandlers.js +7 -7
  251. package/dist/features/ingestion/weaselJsonHandler.js +17 -14
  252. package/dist/features/ingestion/weaselJsonHandler.js.map +1 -1
  253. package/dist/features/meshPaint/lazyKind.js +201 -35
  254. package/dist/features/meshPaint/lazyKind.js.map +1 -1
  255. package/dist/features/meshPaint/meshPaint.js +82 -79
  256. package/dist/features/meshPaint/meshPaint.js.map +1 -1
  257. package/dist/features/minimap/createMinimapContribution.js +42 -42
  258. package/dist/features/minimap/layers.js +44 -62
  259. package/dist/features/minimap/layers.js.map +1 -1
  260. package/dist/features/parallax/createParallaxPlane.js +10 -14
  261. package/dist/features/parallax/createParallaxPlane.js.map +1 -1
  262. package/dist/features/paths/anchorEdits.js +19 -8
  263. package/dist/features/paths/anchorEdits.js.map +1 -1
  264. package/dist/features/paths/anchors.js +31 -26
  265. package/dist/features/paths/anchors.js.map +1 -1
  266. package/dist/features/paths/booleans.js +2 -2
  267. package/dist/features/paths/index.js +13 -11
  268. package/dist/features/paths/markerCommands.js +37 -36
  269. package/dist/features/paths/markerCommands.js.map +1 -1
  270. package/dist/features/paths/pathInWorld.js +19 -19
  271. package/dist/features/paths/pathInWorld.js.map +1 -1
  272. package/dist/features/paths/pathLayer.js.map +1 -1
  273. package/dist/features/paths/strokeToPath.js +40 -0
  274. package/dist/features/paths/strokeToPath.js.map +1 -0
  275. package/dist/features/paths/tessellate/stroke.js.map +1 -1
  276. package/dist/features/patterns/commandPaint.js +18 -0
  277. package/dist/features/patterns/commandPaint.js.map +1 -0
  278. package/dist/features/patterns/index.js +5 -17
  279. package/dist/features/patterns/index.js.map +1 -1
  280. package/dist/features/patterns/rasterizeTile.js +17 -0
  281. package/dist/features/patterns/rasterizeTile.js.map +1 -0
  282. package/dist/features/patterns/resolveSpec.js +52 -44
  283. package/dist/features/patterns/resolveSpec.js.map +1 -1
  284. package/dist/features/poseRun/usePoseRun.js +8 -3
  285. package/dist/features/poseRun/usePoseRun.js.map +1 -1
  286. package/dist/features/selection/SelectionContext.js +5 -0
  287. package/dist/features/selection/SelectionContext.js.map +1 -1
  288. package/dist/features/selection/overlay.js +18 -18
  289. package/dist/features/selection/overlay.js.map +1 -1
  290. package/dist/features/text/domOffsets.js +82 -0
  291. package/dist/features/text/domOffsets.js.map +1 -0
  292. package/dist/features/text/domRuns.js +103 -131
  293. package/dist/features/text/domRuns.js.map +1 -1
  294. package/dist/features/text/hitTest.js +5 -2
  295. package/dist/features/text/hitTest.js.map +1 -1
  296. package/dist/features/text/isTextData.js +8 -0
  297. package/dist/features/text/isTextData.js.map +1 -0
  298. package/dist/features/text/overlayDirection.js +15 -0
  299. package/dist/features/text/overlayDirection.js.map +1 -0
  300. package/dist/features/text/runs/rangeStyle.js +32 -34
  301. package/dist/features/text/runs/rangeStyle.js.map +1 -1
  302. package/dist/features/text/textCommand.js +34 -33
  303. package/dist/features/text/textCommand.js.map +1 -1
  304. package/dist/features/text/textToPath.js +40 -40
  305. package/dist/features/text/textToPath.js.map +1 -1
  306. package/dist/features/text/useSceneTextEdit.js +76 -82
  307. package/dist/features/text/useSceneTextEdit.js.map +1 -1
  308. package/dist/features/text/useTextEdit.js +184 -160
  309. package/dist/features/text/useTextEdit.js.map +1 -1
  310. package/dist/features/tiling/createTiledLayer.js +24 -22
  311. package/dist/features/tiling/createTiledLayer.js.map +1 -1
  312. package/dist/index.d.ts +11010 -7700
  313. package/dist/index.js +316 -309
  314. package/dist/input/keyState.js +42 -43
  315. package/dist/input/keyState.js.map +1 -1
  316. package/dist/input/useKeyModifiers.js +11 -0
  317. package/dist/input/useKeyModifiers.js.map +1 -0
  318. package/dist/interactions/actions/align/align.js +8 -8
  319. package/dist/interactions/actions/clipboard/clipboardOps.js +34 -32
  320. package/dist/interactions/actions/clipboard/clipboardOps.js.map +1 -1
  321. package/dist/interactions/actions/clipboard/materializePaste.js +10 -7
  322. package/dist/interactions/actions/clipboard/materializePaste.js.map +1 -1
  323. package/dist/interactions/actions/clipboard/wireFormat.js.map +1 -1
  324. package/dist/interactions/actions/clone/behaviors/cloneByAltDrag.js.map +1 -1
  325. package/dist/interactions/actions/defaultCommitAdapter.js +20 -18
  326. package/dist/interactions/actions/defaultCommitAdapter.js.map +1 -1
  327. package/dist/interactions/actions/defaults/align.js +9 -10
  328. package/dist/interactions/actions/defaults/align.js.map +1 -1
  329. package/dist/interactions/actions/defaults/anchorEditing.js +59 -81
  330. package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -1
  331. package/dist/interactions/actions/defaults/areaSelect.js +35 -38
  332. package/dist/interactions/actions/defaults/areaSelect.js.map +1 -1
  333. package/dist/interactions/actions/defaults/clipboard.js +26 -10
  334. package/dist/interactions/actions/defaults/clipboard.js.map +1 -1
  335. package/dist/interactions/actions/defaults/clone.js +44 -60
  336. package/dist/interactions/actions/defaults/clone.js.map +1 -1
  337. package/dist/interactions/actions/defaults/copySubtree.js +40 -0
  338. package/dist/interactions/actions/defaults/copySubtree.js.map +1 -0
  339. package/dist/interactions/actions/defaults/distribute.js +14 -13
  340. package/dist/interactions/actions/defaults/distribute.js.map +1 -1
  341. package/dist/interactions/actions/defaults/duplicate.js +17 -57
  342. package/dist/interactions/actions/defaults/duplicate.js.map +1 -1
  343. package/dist/interactions/actions/defaults/editAnchors.js +18 -18
  344. package/dist/interactions/actions/defaults/enterTextEdit.js.map +1 -1
  345. package/dist/interactions/actions/defaults/flip.js +52 -46
  346. package/dist/interactions/actions/defaults/flip.js.map +1 -1
  347. package/dist/interactions/actions/defaults/group.js +43 -48
  348. package/dist/interactions/actions/defaults/group.js.map +1 -1
  349. package/dist/interactions/actions/defaults/ingest.js +35 -33
  350. package/dist/interactions/actions/defaults/ingest.js.map +1 -1
  351. package/dist/interactions/actions/defaults/insert.js +50 -51
  352. package/dist/interactions/actions/defaults/insert.js.map +1 -1
  353. package/dist/interactions/actions/defaults/insertPathAnchor.js +7 -7
  354. package/dist/interactions/actions/defaults/lassoSelect.js +67 -70
  355. package/dist/interactions/actions/defaults/lassoSelect.js.map +1 -1
  356. package/dist/interactions/actions/defaults/move.js +267 -249
  357. package/dist/interactions/actions/defaults/move.js.map +1 -1
  358. package/dist/interactions/actions/defaults/nudge.js +40 -68
  359. package/dist/interactions/actions/defaults/nudge.js.map +1 -1
  360. package/dist/interactions/actions/defaults/nudgeSteps.js +37 -0
  361. package/dist/interactions/actions/defaults/nudgeSteps.js.map +1 -0
  362. package/dist/interactions/actions/defaults/reorder.js +2 -0
  363. package/dist/interactions/actions/defaults/reorder.js.map +1 -1
  364. package/dist/interactions/actions/defaults/resize.js +104 -98
  365. package/dist/interactions/actions/defaults/resize.js.map +1 -1
  366. package/dist/interactions/actions/defaults/rotate.js +111 -110
  367. package/dist/interactions/actions/defaults/rotate.js.map +1 -1
  368. package/dist/interactions/actions/defaults/setFill.js +7 -7
  369. package/dist/interactions/actions/defaults/setFillOpacity.js +4 -4
  370. package/dist/interactions/actions/defaults/setStroke.js +12 -12
  371. package/dist/interactions/actions/defaults/setStrokeOpacity.js +6 -6
  372. package/dist/interactions/actions/defaults/sliceOps.js +19 -19
  373. package/dist/interactions/actions/defaults/viewportDragPan.js +37 -26
  374. package/dist/interactions/actions/defaults/viewportDragPan.js.map +1 -1
  375. package/dist/interactions/actions/edit-anchors/geometry.js +28 -23
  376. package/dist/interactions/actions/edit-anchors/geometry.js.map +1 -1
  377. package/dist/interactions/actions/flip/helpers.js +30 -17
  378. package/dist/interactions/actions/flip/helpers.js.map +1 -1
  379. package/dist/interactions/actions/hitSelection.js +8 -0
  380. package/dist/interactions/actions/hitSelection.js.map +1 -0
  381. package/dist/interactions/actions/lasso-select/behaviors/selectFromLasso.js +14 -18
  382. package/dist/interactions/actions/lasso-select/behaviors/selectFromLasso.js.map +1 -1
  383. package/dist/interactions/actions/move/behaviors/snapBackOrDelete.js +5 -5
  384. package/dist/interactions/actions/move/behaviors/snapBackOrDelete.js.map +1 -1
  385. package/dist/interactions/actions/move/behaviors/snapToContainer.js +32 -21
  386. package/dist/interactions/actions/move/behaviors/snapToContainer.js.map +1 -1
  387. package/dist/interactions/actions/move/gestureAdapter.js +32 -15
  388. package/dist/interactions/actions/move/gestureAdapter.js.map +1 -1
  389. package/dist/interactions/actions/move/landedDescendants.js +33 -0
  390. package/dist/interactions/actions/move/landedDescendants.js.map +1 -0
  391. package/dist/interactions/actions/outlines/createOutlines.js +18 -18
  392. package/dist/interactions/actions/poseDescriptorDep.js +16 -4
  393. package/dist/interactions/actions/poseDescriptorDep.js.map +1 -1
  394. package/dist/interactions/actions/poseFrame.js +11 -6
  395. package/dist/interactions/actions/poseFrame.js.map +1 -1
  396. package/dist/interactions/actions/previewOverrides.js +5 -5
  397. package/dist/interactions/actions/previewOverrides.js.map +1 -1
  398. package/dist/interactions/actions/selectionSubtree.js +69 -0
  399. package/dist/interactions/actions/selectionSubtree.js.map +1 -0
  400. package/dist/interactions/actions/useStandardActions.js +66 -62
  401. package/dist/interactions/actions/useStandardActions.js.map +1 -1
  402. package/dist/interactions/gestures/dragGesture/dragGesture.js +4 -7
  403. package/dist/interactions/gestures/dragGesture/dragGesture.js.map +1 -1
  404. package/dist/interactions/gestures/dragGesture/dragPointOf.js +23 -0
  405. package/dist/interactions/gestures/dragGesture/dragPointOf.js.map +1 -0
  406. package/dist/interactions/gestures/handleDrag/handleDrag.js +21 -26
  407. package/dist/interactions/gestures/handleDrag/handleDrag.js.map +1 -1
  408. package/dist/interactions/gestures/pointerDrag/pointerDrag.js +8 -6
  409. package/dist/interactions/gestures/pointerDrag/pointerDrag.js.map +1 -1
  410. package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js +8 -4
  411. package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js.map +1 -1
  412. package/dist/{math-Drrw4ewZ.d.ts → math-J-ACHyEg.d.ts} +1 -2
  413. package/dist/math.d.ts +2 -3
  414. package/dist/move.d.ts +12 -11
  415. package/dist/{originProjection-DEklpDc_.d.ts → originProjection-gHnOup4e.d.ts} +1 -1
  416. package/dist/{registerProgram-BMZRDgrh.d.ts → registerProgram-T9S_PfAX.d.ts} +18 -7
  417. package/dist/renderer/DrawCommand.js.map +1 -1
  418. package/dist/renderer/WeaselRenderer.js +75 -73
  419. package/dist/renderer/WeaselRenderer.js.map +1 -1
  420. package/dist/renderer/cache/GLImageCache.js +15 -5
  421. package/dist/renderer/cache/GLImageCache.js.map +1 -1
  422. package/dist/renderer/cache/GLMeshCache.js +23 -23
  423. package/dist/renderer/cache/GLMeshCache.js.map +1 -1
  424. package/dist/renderer/cache/GLTextureCache.js +18 -1
  425. package/dist/renderer/cache/GLTextureCache.js.map +1 -1
  426. package/dist/renderer/cache/cache.js.map +1 -1
  427. package/dist/renderer/cache/markerCommandCache.js.map +1 -1
  428. package/dist/renderer/cache/strokeMeshCache.js.map +1 -1
  429. package/dist/renderer/cullDrawCommands.js +11 -11
  430. package/dist/renderer/draw/batch.js +133 -0
  431. package/dist/renderer/draw/batch.js.map +1 -0
  432. package/dist/renderer/draw/clip.js +89 -0
  433. package/dist/renderer/draw/clip.js.map +1 -0
  434. package/dist/renderer/draw/customShader.js +230 -0
  435. package/dist/renderer/draw/customShader.js.map +1 -0
  436. package/dist/renderer/draw/drawTriangles.js +8 -0
  437. package/dist/renderer/draw/drawTriangles.js.map +1 -0
  438. package/dist/renderer/draw/effects.js +28 -0
  439. package/dist/renderer/draw/effects.js.map +1 -0
  440. package/dist/renderer/draw/flushBatch.js +35 -0
  441. package/dist/renderer/draw/flushBatch.js.map +1 -0
  442. package/dist/renderer/draw/gradient.js +90 -0
  443. package/dist/renderer/draw/gradient.js.map +1 -0
  444. package/dist/renderer/draw/image.js +38 -0
  445. package/dist/renderer/draw/image.js.map +1 -0
  446. package/dist/renderer/draw/mesh.js +16 -0
  447. package/dist/renderer/draw/mesh.js.map +1 -0
  448. package/dist/renderer/draw/paintBind.js +70 -0
  449. package/dist/renderer/draw/paintBind.js.map +1 -0
  450. package/dist/renderer/draw/pathPaint.js +142 -0
  451. package/dist/renderer/draw/pathPaint.js.map +1 -0
  452. package/dist/renderer/draw/scratchPass.js +83 -0
  453. package/dist/renderer/draw/scratchPass.js.map +1 -0
  454. package/dist/renderer/draw/stencil.js +28 -0
  455. package/dist/renderer/draw/stencil.js.map +1 -0
  456. package/dist/renderer/draw/text.js +167 -0
  457. package/dist/renderer/draw/text.js.map +1 -0
  458. package/dist/renderer/draw/uniforms.js +77 -0
  459. package/dist/renderer/draw/uniforms.js.map +1 -0
  460. package/dist/renderer/draw.js +60 -1116
  461. package/dist/renderer/draw.js.map +1 -1
  462. package/dist/renderer/effects/EffectTargets.js +3 -0
  463. package/dist/renderer/effects/EffectTargets.js.map +1 -1
  464. package/dist/renderer/effects/composite.js +7 -5
  465. package/dist/renderer/effects/composite.js.map +1 -1
  466. package/dist/renderer/index.js +18 -17
  467. package/dist/renderer/math/color.js +63 -83
  468. package/dist/renderer/math/color.js.map +1 -1
  469. package/dist/renderer/math/mat3.js +15 -11
  470. package/dist/renderer/math/mat3.js.map +1 -1
  471. package/dist/renderer/math/viewToMat3.js +1 -1
  472. package/dist/renderer/math/viewToMat3.js.map +1 -1
  473. package/dist/renderer/shaders/ShaderProgram.js +13 -13
  474. package/dist/renderer/shaders/ShaderProgram.js.map +1 -1
  475. package/dist/renderer/shaders/glyphPaint.js +3 -3
  476. package/dist/renderer/shaders/glyphPaint.js.map +1 -1
  477. package/dist/renderer/shaders/gradFill.js +2 -1
  478. package/dist/renderer/shaders/gradFill.js.map +1 -1
  479. package/dist/renderer/shaders/pathFill.js +2 -1
  480. package/dist/renderer/shaders/pathFill.js.map +1 -1
  481. package/dist/renderer/shaders/patternFill.js +2 -1
  482. package/dist/renderer/shaders/patternFill.js.map +1 -1
  483. package/dist/renderer/shaders/registerProgram.js.map +1 -1
  484. package/dist/renderer/strokeLengths.js.map +1 -1
  485. package/dist/renderer/textures/registerTexture.js +25 -5
  486. package/dist/renderer/textures/registerTexture.js.map +1 -1
  487. package/dist/renderer.d.ts +16 -15
  488. package/dist/renderer.js +17 -16
  489. package/dist/resize.d.ts +5 -6
  490. package/dist/resize.js +5 -5
  491. package/dist/style.css +1 -1
  492. package/dist/test-hook/install.js +12 -6
  493. package/dist/test-hook/install.js.map +1 -1
  494. package/dist/{test-seams-CuIxe0xY.d.ts → test-seams-DM2B87-g.d.ts} +4 -4
  495. package/dist/test-seams.d.ts +2 -2
  496. package/dist/tools/builtin/ellipse/useEllipseTool.js +1 -0
  497. package/dist/tools/builtin/ellipse/useEllipseTool.js.map +1 -1
  498. package/dist/tools/builtin/hand/useHandTool.js +1 -0
  499. package/dist/tools/builtin/hand/useHandTool.js.map +1 -1
  500. package/dist/tools/builtin/lasso/useLassoTool.js +11 -11
  501. package/dist/tools/builtin/lasso/useLassoTool.js.map +1 -1
  502. package/dist/tools/builtin/line/useLineTool.js +1 -0
  503. package/dist/tools/builtin/line/useLineTool.js.map +1 -1
  504. package/dist/tools/builtin/pen/usePenTool.js +153 -103
  505. package/dist/tools/builtin/pen/usePenTool.js.map +1 -1
  506. package/dist/tools/builtin/pencil/usePencilTool.js +1 -0
  507. package/dist/tools/builtin/pencil/usePencilTool.js.map +1 -1
  508. package/dist/tools/builtin/polygon/usePolygonTool.js +13 -8
  509. package/dist/tools/builtin/polygon/usePolygonTool.js.map +1 -1
  510. package/dist/tools/builtin/rect/useRectTool.js +1 -0
  511. package/dist/tools/builtin/rect/useRectTool.js.map +1 -1
  512. package/dist/tools/builtin/select/selectionContributions.js +24 -23
  513. package/dist/tools/builtin/select/selectionContributions.js.map +1 -1
  514. package/dist/tools/builtin/select/useSelectTool.js +51 -48
  515. package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
  516. package/dist/tools/builtin/shared/pointerFollower.js +17 -0
  517. package/dist/tools/builtin/shared/pointerFollower.js.map +1 -0
  518. package/dist/tools/builtin/slice/useSliceTool.js +49 -54
  519. package/dist/tools/builtin/slice/useSliceTool.js.map +1 -1
  520. package/dist/tools/builtin/star/useStarTool.js +22 -16
  521. package/dist/tools/builtin/star/useStarTool.js.map +1 -1
  522. package/dist/tools/builtin/text/useTextTool.js +13 -2
  523. package/dist/tools/builtin/text/useTextTool.js.map +1 -1
  524. package/dist/tools/useKeybindings.js +14 -30
  525. package/dist/tools/useKeybindings.js.map +1 -1
  526. package/dist/{types-B_9g6hMM.d.ts → types-B4iJRHC3.d.ts} +5 -1
  527. package/dist/{types-A37hYkeR.d.ts → types-k-5Oqh-U.d.ts} +31 -7
  528. package/dist/util/color.js +3 -3
  529. package/dist/util/color.js.map +1 -1
  530. package/dist/util/paint.js.map +1 -1
  531. package/dist/version.js +1 -1
  532. package/package.json +20 -18
  533. package/dist/autoPoseDescriptor-vCdt55xm.d.ts +0 -27
  534. package/dist/builtins-C-VgUlWI.d.ts +0 -4514
  535. package/dist/core/isPlainObject.js.map +0 -1
  536. package/dist/debug/flag.js.map +0 -1
  537. package/dist/interactions/actions/defaults/freshNodeId.js +0 -10
  538. package/dist/interactions/actions/defaults/freshNodeId.js.map +0 -1
  539. package/dist/renderer/shaders/imageFill.js +0 -14
  540. package/dist/renderer/shaders/imageFill.js.map +0 -1
  541. package/dist/tools/prefs.js +0 -47
  542. package/dist/tools/prefs.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","commitContinuation","useCallback","cont","drawn","edit","added","addedClosed","pathToAnchors","reverseAnchors","set","next","samePath","commit","deps","allClosed","path","pose","id","joinable","hit","scene","commitJoin","current","other","otherSet","tail","joined","joint","out","sameNode","rest","i","label","ops","keptId","node","createInsertOp","createDeleteOp","applyOps","defaultCommitAdapter","pickUpEndpoint","scratch","radius","scale","viewScale","nearestPathAnchor","pathsNear","wx","wy","h","original","picked","reversed","snap","fn","placeAt","y","withinCloseRadius","withinPxRadius","ax","ay","actions","useMemo","p","params","first","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","view","e","pxExtent","px","ids","a","b"],"sources":["../../../../src/tools/builtin/pen/usePenTool.ts"],"sourcesContent":["import { useCallback, useMemo, useReducer, useRef, createElement } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport type { ToolPrefGroup } from '../../prefs';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ActionDeps, InvocationCtx } from '@weasel-js/routing';\nimport type { EditAnchorsDep } from 'interactions/actions/depSchema';\nimport { pxExtent, withinPxRadius } from 'core/viewport/pxExtent';\nimport { PenIcon } from '../../../icons';\nimport type { PolygonPath } from '@weasel-js/geom';\nimport { anchorsToPath, pathToAnchors } from 'features/paths/anchors';\nimport { nearestPathAnchor, reverseAnchors, type PathAnchorHit } from 'features/paths/nearestAnchor';\nimport type { Op } from 'core/ops/types';\nimport { createInsertOp } from 'core/ops/create';\nimport { createDeleteOp } from 'core/ops/delete';\nimport { defaultCommitAdapter } from 'interactions/actions/defaultCommitAdapter';\nimport { constrainTo45 } from '../../../util/constrainTo45';\nimport { cursorFor } from '@weasel-js/cursor';\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 scratch shared across pen-tool gestures. The hook keeps a stable\n * reference to a single instance and `initScratch` returns it on every call,\n * so click-by-click state survives gesture boundaries and the preview layer\n * can read the same object.\n *\n * ## The pen draws paths; it does not reshape them\n *\n * It draws new nodes, and extends an existing node's open subpath from one\n * of its ends (see `continuing`). Reshaping an existing path is anchor\n * editing: double-click a path to\n * enter edit mode, then use the `editAnchors` / `insertPathAnchor` /\n * `nudgeAnchors` / `deleteAnchors` / `marqueeAnchors` / `cutPathAtAnchor`\n * Actions.\n *\n * The pen used to carry a second, private implementation of all of that,\n * with its own scratch mode, hit-test override, overlay, and undo\n * plumbing. It was reachable only through a `getPathObj` option whose\n * contract required `pose.kind` to be `'polygon'` or `'rect'` — which no\n * kit-created node has, including the ones the pen itself creates. So it\n * was dead in every consumer while shadowing the live implementation, and\n * the two had drifted. Its geometry now lives in\n * `features/paths/anchorEdits.ts`, driven by those Actions.\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`: how a finished path becomes a pose, where it is\n * inserted, and when a closed subpath commits. */\nexport interface UsePenToolOptions<TPose> {\n /** Wrap a finished PolygonPath in the consumer's pose type. */\n wrapPath: (path: PolygonPath, opts: { closed: boolean }) => TPose;\n /** Insert + select adapter. */\n adapter: {\n addNode: (pose: TPose) => string;\n setSelection: (ids: string[]) => void;\n /** Build, without inserting, the node `addNode` would insert for `pose`,\n * so the pen can put it in a larger op batch — a new path finished on\n * another open path's endpoint is inserted and the other path deleted\n * in one undo step. Without it, that click only places an anchor. */\n makeNode?: (pose: TPose) => { id: string };\n };\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 / tool-switch /\n * ⌘-click / double-click, producing a compound path. */\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 * Wire to `gridSnapStrategy`-style spacing via the consumer:\n *\n * snapPoint: (p) => ({\n * x: Math.round(p.x / SPACING) * SPACING,\n * y: Math.round(p.y / SPACING) * SPACING,\n * })\n *\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 * State machine: Idle / Drawing / BetweenSubpaths (see design doc).\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; tool-switch commits if ≥2 anchors else\n * discards. 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<TPose>(\n options: UsePenToolOptions<TPose>,\n): Tool<PenScratch> {\n const { wrapPath, adapter, autoSelect = true, autoCommitOnClose = true, closeHitRadius = 8, anchorSnapRadius = 8, snapPoint } = options;\n\n // Persistent scratch: single ref reused across gestures so multi-click\n // state survives the dispatcher's per-gesture initScratch contract.\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 (which would lose scratch identity in the dispatcher).\n const optsRef = useLatest({ wrapPath, adapter, autoSelect, autoCommitOnClose, closeHitRadius, anchorSnapRadius, snapPoint });\n\n // Scratch is a mutable ref (so click-by-click state survives the\n // dispatcher's per-gesture initScratch contract). Mutations alone don't\n // trigger React re-renders, so Canvas never re-paints and the preview\n // layer stays invisible until something else (e.g. commit) bumps host\n // state. Force a render after every scratch mutation so the host's\n // <Canvas layers={{...}}> literal gets a new identity and the paint\n // useEffect fires. Pull the trigger via ref so the memoized Tool record\n // doesn't need to rebuild.\n const [, forceRender] = useReducer((x: number) => x + 1, 0);\n\n // Geometry helpers shared by the actions below. They read `optsRef` so a\n // re-render with new options is visible without rebuilding the actions\n // (which would lose the scratch identity `penPreviewLayer` reads through\n // `Tool.initScratch`).\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, edit: EditAnchorsDep | undefined): void => {\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: PolygonPath = { ...anchorsToPath(set.anchors, set.closed), fillRule: cont.original.fillRule };\n if (samePath(next, cont.original)) return;\n edit.applyEdit(cont.id, next, 'Continue path');\n if (optsRef.current.autoSelect) optsRef.current.adapter.setSelection([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.editAnchors);\n resetScratch(s);\n return;\n }\n if (s.finishedSubpaths.length === 0 && !trailing) return;\n const allClosed =\n s.finishedSubpaths.every((sp) => sp.closed) &&\n (trailing === null || trailing.closed);\n const path = buildPath(s.finishedSubpaths, trailing);\n const pose = optsRef.current.wrapPath(path, { closed: allClosed });\n const id = optsRef.current.adapter.addNode(pose);\n if (optsRef.current.autoSelect) optsRef.current.adapter.setSelection([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 : optsRef.current.adapter.makeNode)) return false;\n return cont?.id === hit.id || scene?.get(hit.id as never) !== undefined;\n }, [optsRef]);\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: PolygonPath = { ...anchorsToPath(set.anchors, set.closed), fillRule: cont.original.fillRule };\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 node = optsRef.current.adapter.makeNode!(optsRef.current.wrapPath(path, { closed: false }));\n ops.push(createInsertOp({ node }));\n keptId = node.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) optsRef.current.adapter.setSelection([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 /**\n * Actions the pen owns, registered by `useToolActions` from inside the\n * ActionsProvider — see `ToolDef.actions`.\n *\n * They close over `scratchRef`, which is why the pen needs no `Selector`\n * exposing tool scratch to the action layer: the state never leaves the\n * hook. `useMemo([])` keeps their identity stable for the same reason\n * `scratchRef` is a ref — the preview layer reads that one object.\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', 'areaSelect', 'editAnchors', 'scene', 'applyOps'],\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, and an anchor should land where you put the\n // pointer down. Snapping happens here rather than at press time\n // so the snapped value is what the geometry records.\n if (pickUpEndpoint(deps, p.pressX, p.pressY)) {\n forceRender();\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 // on (default) this commits right away so the closed region\n // renders with its fill — Illustrator-style. With it off the\n // closed subpath stays in scratch for compound-path builds and\n // commits on Enter / tool switch.\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 forceRender();\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 forceRender();\n },\n },\n },\n\n {\n id: 'pen.finishOpen',\n label: 'Pen — finish open path',\n eligible: { capability: 'creates-paths' },\n requires: ['editAnchors'],\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). The net effect\n // matches the pen's old private 300ms detector — one anchor\n // placed, path finished — while using the dispatcher's single\n // definition of a double click.\n //\n // No position check is needed: the anchor to drop is by\n // construction the one the second click just appended.\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 forceRender();\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', 'areaSelect', 'editAnchors', 'scene', 'applyOps'],\n invoker: {\n timing: 'ongoing' as const,\n start: (ctx: InvocationCtx) => {\n const scratch = s();\n // `drag.start` is the pointerdown position — the dispatcher\n // buffers the press and releases it at the drag threshold, so the\n // anchor lands where the user pressed rather than where the\n // threshold 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 forceRender();\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 (pointercancel is the reachable one — Escape and a\n // tool switch both reset the whole scratch first) has to\n // 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 forceRender();\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 forceRender();\n },\n };\n },\n },\n },\n\n {\n id: 'pen.finish',\n label: 'Pen — finish path',\n eligible: { capability: 'creates-paths' },\n requires: ['editAnchors'],\n enabled: () => (anchorCount(s()) > 0 ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate' as const,\n run: (deps) => {\n commit(s(), deps);\n forceRender();\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 forceRender();\n },\n },\n },\n ];\n }, [commit, placeAt, withinCloseRadius, pickUpEndpoint, joinable, commitJoin, optsRef]);\n\n return useMemo(() => {\n return defineTool<PenScratch>({\n id: 'pen',\n capabilities: ['creates-paths'],\n hookName: 'usePenTool',\n // Reads the tool's own ref rather than a scratch handed in by a\n // dispatcher — the pen owns this state and nothing else needs it.\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 // Persistent-ref scratch. `penPreviewLayer` reads the in-progress path\n // by calling `Tool.initScratch()` and getting this same object back, so\n // the identity is load-bearing.\n initScratch: () => scratchRef.current!,\n actions,\n\n onDeactivate: () => {\n // Anything still in scratch is by definition incomplete — the user\n // hasn't closed it (close-on-first-anchor), open-finished it\n // (cmd-click), or pressed Enter. Switching tools mid-path should\n // discard, not auto-commit a stub polyline that the user didn't\n // ask for. Mirrors Escape's behavior so \"stop drawing\" is\n // consistent across exits.\n resetScratch(scratchRef.current!);\n forceRender();\n },\n\n bindings: [\n // Plain click places an anchor; ⌘/Ctrl-click open-finishes\n // (Illustrator). Strict modifier matching keeps the two apart, and\n // `mod` resolves to meta on mac / ctrl elsewhere — the tool-route\n // grammar's modifier matcher accepted either key on either platform.\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. This used to be\n // a private 300ms/radius check inside the click route — a fourth\n // double-click detector in a codebase that had just collapsed three\n // into one (audit 3.3).\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]);\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 ToolPrefGroup;\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":";;;;;;;;;;;;;;AA4IA,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;AAcA,SAAgBM,EACd,GACkB;CAClB,IAAM,EAAE,aAAU,YAAS,gBAAa,IAAM,uBAAoB,IAAM,oBAAiB,GAAG,sBAAmB,GAAG,iBAAcC,GAI1HC,IAAaC,EAA0B,IAAI;CACjD,AAAID,EAAW,YAAY,SAAM,EAAW,UAAUb,EAAa;CAInE,IAAMe,IAAUC,EAAU;EAAE;EAAU;EAAS;EAAY;EAAmB;EAAgB;EAAkB;CAAU,CAAC,GAUrH,GAAGC,KAAeC,GAAY,MAAcC,IAAI,GAAG,CAAC,GAWpDC,IAAqBC,GACxB,GAAe,GAA6B,MAA2C;EACtF,IAAMC,IAAO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SAAS,UAAUD,EAAE,OAAO,WAAWC,EAAE,OAAO,QAAQ,OAAO;CAC3F,KAAK,IAAIlE,IAAI,GAAGA,IAAIiE,EAAE,SAAS,QAAQ,KAAK,IAAIA,EAAE,SAASjE,OAAOkE,EAAE,SAASlE,IAAI,OAAO;CACxF,KAAK,IAAIA,IAAI,GAAGA,IAAIiE,EAAE,OAAO,QAAQ,KAAK,IAAIA,EAAE,OAAOjE,OAAOkE,EAAE,OAAOlE,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","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, 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 } from 'core/viewport/pxExtent';\nimport { PenIcon } from '../../../icons';\nimport { boundsOfPath, type PolygonPath } from '@weasel-js/geom';\nimport { anchorsToPath, pathToAnchors } from 'features/paths/anchors';\nimport { nearestPathAnchor, reverseAnchors, type PathAnchorHit } from 'features/paths/nearestAnchor';\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 scratch shared across pen-tool gestures. The hook keeps a stable\n * reference to a single instance and `initScratch` returns it on every call,\n * so click-by-click state survives gesture boundaries and the preview layer\n * can read the same object.\n *\n * ## The pen draws paths; it does not reshape them\n *\n * It draws new nodes, and extends an existing node's open subpath from one\n * of its ends (see `continuing`). Reshaping an existing path is anchor\n * editing: double-click a path to\n * enter edit mode, then use the `editAnchors` / `insertPathAnchor` /\n * `nudgeAnchors` / `deleteAnchors` / `marqueeAnchors` / `cutPathAtAnchor`\n * Actions.\n *\n * The pen used to carry a second, private implementation of all of that,\n * with its own scratch mode, hit-test override, overlay, and undo\n * plumbing. It was reachable only through a `getPathObj` option whose\n * contract required `pose.kind` to be `'polygon'` or `'rect'` — which no\n * kit-created node has, including the ones the pen itself creates. So it\n * was dead in every consumer while shadowing the live implementation, and\n * the two had drifted. Its geometry now lives in\n * `features/paths/anchorEdits.ts`, driven by those Actions.\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 * Wire to `gridSnapStrategy`-style spacing via the consumer:\n *\n * snapPoint: (p) => ({\n * x: Math.round(p.x / SPACING) * SPACING,\n * y: Math.round(p.y / SPACING) * SPACING,\n * })\n *\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 * State machine: Idle / Drawing / BetweenSubpaths (see design doc).\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<PenScratch> {\n const { autoSelect = true, autoCommitOnClose = true, closeHitRadius = 8, anchorSnapRadius = 8, snapPoint } = options;\n\n // Persistent scratch: single ref reused across gestures so multi-click\n // state survives the dispatcher's per-gesture initScratch contract.\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 (which would lose scratch identity in the dispatcher).\n const optsRef = useLatest({ autoSelect, autoCommitOnClose, closeHitRadius, anchorSnapRadius, snapPoint });\n\n // Scratch is a mutable ref (so click-by-click state survives the\n // dispatcher's per-gesture initScratch contract). Mutations alone don't\n // trigger React re-renders, so Canvas never re-paints and the preview\n // layer stays invisible until something else (e.g. commit) bumps host\n // state. Force a render after every scratch mutation so the host's\n // <Canvas layers={{...}}> literal gets a new identity and the paint\n // useEffect fires. Pull the trigger via ref so the memoized Tool record\n // doesn't need to rebuild.\n const [, forceRender] = useReducer((x: number) => x + 1, 0);\n\n // Geometry helpers shared by the actions below. They read `optsRef` so a\n // re-render with new options is visible without rebuilding the actions\n // (which would lose the scratch identity `penPreviewLayer` reads through\n // `Tool.initScratch`).\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: PolygonPath = { ...anchorsToPath(set.anchors, set.closed), fillRule: cont.original.fillRule };\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: PolygonPath = { ...anchorsToPath(set.anchors, set.closed), fillRule: cont.original.fillRule };\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`.\n *\n * They close over `scratchRef`, which is why the pen needs no `Selector`\n * exposing tool scratch to the action layer: the state never leaves the\n * hook. `useMemo([])` keeps their identity stable for the same reason\n * `scratchRef` is a ref — the preview layer reads that one object.\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, and an anchor should land where you put the\n // pointer down. Snapping happens here rather than at press time\n // so the snapped value is what the geometry records.\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 // on (default) this commits right away so the closed region\n // renders with its fill — Illustrator-style. With it off the\n // closed subpath stays in scratch for compound-path builds and\n // commits on Enter.\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). The net effect\n // matches the pen's old private 300ms detector — one anchor\n // placed, path finished — while using the dispatcher's single\n // definition of a double click.\n //\n // No position check is needed: the anchor to drop is by\n // construction the one the second click just appended.\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 — the dispatcher\n // buffers the press and releases it at the drag threshold, so the\n // anchor lands where the user pressed rather than where the\n // threshold 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 (pointercancel is the reachable one — Escape and a\n // tool switch both reset the whole scratch first) has to\n // 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]);\n\n return useMemo(() => {\n return defineTool<PenScratch>({\n id: 'pen',\n keybinding: { key: 'P' },\n capabilities: ['creates-paths'],\n hookName: 'usePenTool',\n // Reads the tool's own ref rather than a scratch handed in by a\n // dispatcher — the pen owns this state and nothing else needs it.\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 // Persistent-ref scratch. `penPreviewLayer` reads the in-progress path\n // by calling `Tool.initScratch()` and getting this same object back, so\n // the identity is load-bearing.\n initScratch: () => scratchRef.current!,\n actions,\n\n onDeactivate: () => {\n // Anything still in scratch is by definition incomplete — the user\n // hasn't closed it (close-on-first-anchor), open-finished it\n // (cmd-click), or pressed Enter. Switching tools mid-path should\n // discard, not auto-commit a stub polyline that the user didn't\n // ask for. Mirrors Escape's behavior so \"stop drawing\" is\n // consistent across exits.\n resetScratch(scratchRef.current!);\n trail.stop();\n },\n\n bindings: [\n // Plain click places an anchor; ⌘/Ctrl-click open-finishes\n // (Illustrator). Strict modifier matching keeps the two apart, and\n // `mod` resolves to meta on mac / ctrl elsewhere — the tool-route\n // grammar's modifier matcher accepted either key on either platform.\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. This used to be\n // a private 300ms/radius check inside the click route — a fourth\n // double-click detector in a codebase that had just collapsed three\n // into one (audit 3.3).\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]);\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":";;;;;;;;;;;;;;;;AAmIA,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;AAaA,SAAgBM,EACd,IAA6B,CAAC,GACZ;CAClB,IAAM,EAAE,gBAAa,IAAM,uBAAoB,IAAM,oBAAiB,GAAG,sBAAmB,GAAG,iBAAcC,GAIvGC,IAAaC,EAA0B,IAAI;CACjD,AAAID,EAAW,YAAY,SAAM,EAAW,UAAUb,EAAa;CAInE,IAAMe,IAAUC,EAAU;EAAE;EAAY;EAAmB;EAAgB;EAAkB;CAAU,CAAC,GAUlG,GAAGC,KAAeC,GAAY,MAAcC,IAAI,GAAG,CAAC,GAWpDC,IAAqBC,GACxB,GAAe,GAA6B,MAA2B;EACtE,IAAMC,IAAOC,EAAK,aACZC,IAA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AE,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"}
@@ -9,6 +9,7 @@ function o(o = {}) {
9
9
  let { behaviors: s } = o;
10
10
  return r(() => e({
11
11
  id: "pencil",
12
+ keybinding: { key: "N" },
12
13
  capabilities: ["creates-paths"],
13
14
  hookName: "usePencilTool",
14
15
  cursor: a("pencil", { fallback: "crosshair" }),
@@ -1 +1 @@
1
- {"version":3,"file":"usePencilTool.js","names":["PencilIcon","usePencilTool","options","useMemo","defineTool","cursorFor","insertBindingBehaviors","behaviors"],"sources":["../../../../src/tools/builtin/pencil/usePencilTool.tsx"],"sourcesContent":["import { useMemo } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { PencilIcon } from '../../../icons';\nimport type { Tool } from '../../overlayBinding';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport { cursorFor } from '@weasel-js/cursor';\n\n/** A single pointer sample captured during a freehand pencil stroke.\n *\n * `pressure` / `tiltX` / `tiltY` come straight from the underlying\n * `PointerEvent` and let downstream consumers modulate stroke width or\n * opacity by stylus input. Mouse and ordinary touch report\n * `pressure: 0.5` while a button is held, `0` otherwise (per the Pointer\n * Events spec), so a consumer that wants stylus-only modulation should\n * gate on `pointerType` from the originating event — the kit exposes\n * `usePointerStylus()` for that.\n *\n * The dispatcher accumulates these on the drag trail and hands the whole\n * array to `insertAction`, which forwards it as the `pencil` insert\n * extras' `samples`. A consumer that wants pressure-driven\n * `Stroke.vertexWidths` reads it off the samples in its own `insert` dep\n * (`useDepSource('insert', …)`) — see `apps/site/demos/StrokeAndFillDemo.tsx`.\n */\nexport interface PencilPoint {\n x: number;\n y: number;\n /** 0..1. Absent when the originating event carried no pressure. */\n pressure?: number;\n /** Degrees, ±90. Zero for mouse/touch. */\n tiltX?: number;\n /** Degrees, ±90. Zero for mouse/touch. */\n tiltY?: number;\n}\n\n/**\n * Freehand pencil tool. The `drag` binding routes to `insertAction`,\n * which accumulates the pointer trail and commits it as\n * `{ kind: 'pencil', samples }`. The kit's default `insert` dep runs\n * `schneiderFit` over the samples to produce a cubic-Bezier path.\n */\nexport function usePencilTool(options: InsertToolOptions = {}): Tool<null> {\n const { behaviors } = options;\n return useMemo(\n () =>\n defineTool<null>({\n id: 'pencil',\n capabilities: ['creates-paths'],\n hookName: 'usePencilTool',\n cursor: cursorFor('pencil', { fallback: 'crosshair' }),\n presentation: {\n label: 'Pencil',\n group: 'draw',\n icon: <PencilIcon />,\n },\n bindings: [\n {\n spec: { kind: 'drag', target: 'empty' },\n actionId: 'insert',\n opts: { params: { kind: 'pencil' } , ...insertBindingBehaviors(behaviors) },\n },\n ],\n }),\n [behaviors],\n );\n}\n"],"mappings":";;;;;;;AAwCA,SAAgBC,EAAc,IAA6B,CAAC,GAAe;CACzE,IAAM,EAAE,iBAAcC;CACtB,OAAOC,QAEHC,EAAiB;EACf,IAAI;EACJ,cAAc,CAAC,eAAe;EAC9B,UAAU;EACV,QAAQC,EAAU,UAAU,EAAE,UAAU,YAAY,CAAC;EACrD,cAAc;GACZ,OAAO;GACP,OAAO;GACP,MAAM,kBAACL,GAAD,CAAa,CAAA;EACrB;EACA,UAAU,CACR;GACE,MAAM;IAAE,MAAM;IAAQ,QAAQ;GAAQ;GACtC,UAAU;GACV,MAAM;IAAE,QAAQ,EAAE,MAAM,SAAS;IAAI,GAAGM,EAAuBC,CAAS;GAAE;EAC5E,CACF;CACF,CAAC,GACH,CAACA,CAAS,CACZ;AACF"}
1
+ {"version":3,"file":"usePencilTool.js","names":["PencilIcon","usePencilTool","options","useMemo","defineTool","cursorFor","insertBindingBehaviors","behaviors"],"sources":["../../../../src/tools/builtin/pencil/usePencilTool.tsx"],"sourcesContent":["import { useMemo } from 'react';\nimport { defineTool } from '../../overlayBinding';\nimport { PencilIcon } from '../../../icons';\nimport type { Tool } from '../../overlayBinding';\nimport { insertBindingBehaviors, type InsertToolOptions } from '../shared/insertToolOptions';\nimport { cursorFor } from '@weasel-js/cursor';\n\n/** A single pointer sample captured during a freehand pencil stroke.\n *\n * `pressure` / `tiltX` / `tiltY` come straight from the underlying\n * `PointerEvent` and let downstream consumers modulate stroke width or\n * opacity by stylus input. Mouse and ordinary touch report\n * `pressure: 0.5` while a button is held, `0` otherwise (per the Pointer\n * Events spec), so a consumer that wants stylus-only modulation should\n * gate on `pointerType` from the originating event — the kit exposes\n * `usePointerStylus()` for that.\n *\n * The dispatcher accumulates these on the drag trail and hands the whole\n * array to `insertAction`, which forwards it as the `pencil` insert\n * extras' `samples`. A consumer that wants pressure-driven\n * `Stroke.vertexWidths` reads it off the samples in its own `insert` dep\n * (`useDepSource('insert', …)`) — see `apps/site/demos/StrokeAndFillDemo.tsx`.\n */\nexport interface PencilPoint {\n x: number;\n y: number;\n /** 0..1. Absent when the originating event carried no pressure. */\n pressure?: number;\n /** Degrees, ±90. Zero for mouse/touch. */\n tiltX?: number;\n /** Degrees, ±90. Zero for mouse/touch. */\n tiltY?: number;\n}\n\n/**\n * Freehand pencil tool. The `drag` binding routes to `insertAction`,\n * which accumulates the pointer trail and commits it as\n * `{ kind: 'pencil', samples }`. The kit's default `insert` dep runs\n * `schneiderFit` over the samples to produce a cubic-Bezier path.\n */\nexport function usePencilTool(options: InsertToolOptions = {}): Tool<null> {\n const { behaviors } = options;\n return useMemo(\n () =>\n defineTool<null>({\n id: 'pencil',\n keybinding: { key: 'N' },\n capabilities: ['creates-paths'],\n hookName: 'usePencilTool',\n cursor: cursorFor('pencil', { fallback: 'crosshair' }),\n presentation: {\n label: 'Pencil',\n group: 'draw',\n icon: <PencilIcon />,\n },\n bindings: [\n {\n spec: { kind: 'drag', target: 'empty' },\n actionId: 'insert',\n opts: { params: { kind: 'pencil' } , ...insertBindingBehaviors(behaviors) },\n },\n ],\n }),\n [behaviors],\n );\n}\n"],"mappings":";;;;;;;AAwCA,SAAgBC,EAAc,IAA6B,CAAC,GAAe;CACzE,IAAM,EAAE,iBAAcC;CACtB,OAAOC,QAEHC,EAAiB;EACf,IAAI;EACJ,YAAY,EAAE,KAAK,IAAI;EACvB,cAAc,CAAC,eAAe;EAC9B,UAAU;EACV,QAAQC,EAAU,UAAU,EAAE,UAAU,YAAY,CAAC;EACrD,cAAc;GACZ,OAAO;GACP,OAAO;GACP,MAAM,kBAACL,GAAD,CAAa,CAAA;EACrB;EACA,UAAU,CACR;GACE,MAAM;IAAE,MAAM;IAAQ,QAAQ;GAAQ;GACtC,UAAU;GACV,MAAM;IAAE,QAAQ,EAAE,MAAM,SAAS;IAAI,GAAGM,EAAuBC,CAAS;GAAE;EAC5E,CACF;CACF,CAAC,GACH,CAACA,CAAS,CACZ;AACF"}
@@ -7,25 +7,26 @@ import { cursorFor as c } from "@weasel-js/cursor";
7
7
  //#region src/tools/builtin/polygon/usePolygonTool.tsx
8
8
  var l = 3, u = 32;
9
9
  function d(d = {}) {
10
- let { sides: f = 6, behaviors: p } = d, m = a(f), [, h] = o(0), g = r(() => h((e) => e + 1), []), _ = i(() => ({
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
11
  id: "polygon.adjustSides",
12
12
  label: "Polygon — adjust sides",
13
13
  invoker: {
14
14
  timing: "immediate",
15
15
  run: (e, t) => {
16
16
  let n = t, r = n?.delta ?? (n?.deltaY !== void 0 && n.deltaY !== 0 ? n.deltaY > 0 ? 1 : -1 : 0);
17
- r !== 0 && (m.current = r > 0 ? Math.min(u, m.current + 1) : Math.max(l, m.current - 1), g());
17
+ r !== 0 && (h.current = r > 0 ? Math.min(u, h.current + 1) : Math.max(l, h.current - 1), _());
18
18
  }
19
19
  }
20
- }), [g]);
20
+ }), [_]);
21
21
  return i(() => e({
22
22
  id: "polygon",
23
+ keybinding: { key: "G" },
23
24
  capabilities: ["creates-shapes"],
24
25
  hookName: "usePolygonTool",
25
26
  cursor: c("crosshairPolygon", { fallback: "crosshair" }),
26
- actions: [_],
27
+ actions: [v],
27
28
  presentation: {
28
- label: "Polygon",
29
+ label: p,
29
30
  group: "shape",
30
31
  icon: /* @__PURE__ */ s(t, {})
31
32
  },
@@ -36,9 +37,9 @@ function d(d = {}) {
36
37
  opts: {
37
38
  params: () => ({
38
39
  kind: "polygon",
39
- sides: m.current
40
+ sides: h.current
40
41
  }),
41
- ...n(p)
42
+ ...n(m)
42
43
  }
43
44
  },
44
45
  {
@@ -73,7 +74,11 @@ function d(d = {}) {
73
74
  opts: { params: { delta: -1 } }
74
75
  }
75
76
  ]
76
- }), [_, p]);
77
+ }), [
78
+ v,
79
+ m,
80
+ p
81
+ ]);
77
82
  }
78
83
  //#endregion
79
84
  export { d as usePolygonTool };
@@ -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"],"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<null> {\n const { sides: initialSides = 6, 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<null>({\n id: 'polygon',\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: 'Polygon',\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 ],\n }),\n [adjustSidesAction, behaviors],\n );\n}\n"],"mappings":";;;;;;;AAoBA,IAAMC,IAAY,GACZC,IAAY;AAalB,SAAgBC,EACd,IAAiC,CAAC,GACtB;CACZ,IAAM,EAAE,OAAOC,IAAe,GAAG,iBAAcC,GAMzCC,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,GAMJC,IAAOF,GAAG,UAAUA,GAAG,WAAW,KAAA,KAAaA,EAAE,WAAW,IAC7DA,EAAE,SAAS,IAAI,IAAI,KACpB;IACJ,AAAIE,MAAS,MACb,EAAS,UAAUA,IAAO,IACtB,KAAK,IAAIf,GAAWI,EAAS,UAAU,CAAC,IACxC,KAAK,IAAIL,GAAWK,EAAS,UAAU,CAAC,GAC5CI,EAAU;GACZ;EACF;CACF,IACA,CAACA,CAAS,CACZ;CAOA,OAAOI,QAEHI,EAAiB;EACf,IAAI;EACJ,cAAc,CAAC,gBAAgB;EAC/B,UAAU;EACV,QAAQC,EAAU,oBAAoB,EAAE,UAAU,YAAY,CAAC;EAG/D,SAAS,CAACN,CAAiB;EAC3B,cAAc;GACZ,OAAO;GACP,OAAO;GACP,MAAM,kBAACb,GAAD,CAAc,CAAA;EACtB;EACA,UAAU;GAMR;IACE,MAAM,EAAE,MAAM,OAAO;IACrB,UAAU;IAKV,MAAM;KACJ,eAAe;MACb,MAAM;MACN,OAAOM,EAAS;KAClB;KACA,GAAGc,EAAuBC,CAAS;IACrC;GACF;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,CAACR,GAAmBQ,CAAS,CAC/B;AACF"}
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<null> {\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<null>({\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 ],\n }),\n [adjustSidesAction, behaviors, label],\n );\n}\n"],"mappings":";;;;;;;AAoBA,IAAMC,IAAY,GACZC,IAAY;AAalB,SAAgBC,EACd,IAAiC,CAAC,GACtB;CACZ,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,GAMJC,IAAOF,GAAG,UAAUA,GAAG,WAAW,KAAA,KAAaA,EAAE,WAAW,IAC7DA,EAAE,SAAS,IAAI,IAAI,KACpB;IACJ,AAAIE,MAAS,MACb,EAAS,UAAUA,IAAO,IACtB,KAAK,IAAIf,GAAWI,EAAS,UAAU,CAAC,IACxC,KAAK,IAAIL,GAAWK,EAAS,UAAU,CAAC,GAC5CI,EAAU;GACZ;EACF;CACF,IACA,CAACA,CAAS,CACZ;CAOA,OAAOI,QAEHI,EAAiB;EACf,IAAI;EACJ,YAAY,EAAE,KAAK,IAAI;EACvB,cAAc,CAAC,gBAAgB;EAC/B,UAAU;EACV,QAAQC,EAAU,oBAAoB,EAAE,UAAU,YAAY,CAAC;EAG/D,SAAS,CAACN,CAAiB;EAC3B,cAAc;GACZ;GACA,OAAO;GACP,MAAM,kBAACb,GAAD,CAAc,CAAA;EACtB;EACA,UAAU;GAMR;IACE,MAAM,EAAE,MAAM,OAAO;IACrB,UAAU;IAKV,MAAM;KACJ,eAAe;MACb,MAAM;MACN,OAAOM,EAAS;KAClB;KACA,GAAGc,EAAuBC,CAAS;IACrC;GACF;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;EAACR;EAAmBQ;EAAWC;CAAK,CACtC;AACF"}
@@ -8,6 +8,7 @@ function o(o = {}) {
8
8
  let { behaviors: s } = o;
9
9
  return i(() => e({
10
10
  id: "rect",
11
+ keybinding: { key: "R" },
11
12
  capabilities: ["creates-shapes"],
12
13
  hookName: "useRectTool",
13
14
  cursor: a("crosshairRect", { fallback: "crosshair" }),
@@ -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 gesture is owned end-to-end by the dispatcher: the `drag` binding\n * routes to `insertAction`, which tracks the live bounds, paints the\n * preview through its `overlay()` surface, and commits via the `insert`\n * dep on release. `<SceneCanvas>` sources that dep from\n * `useInsertDepSource`; consumers wanting a custom node factory override\n * the dep (`useDepSource('insert', …)`) rather than the tool.\n *\n * Grid snapping comes from the `snap` dep, also read by `insertAction` —\n * see `SnapDep` in `interactions/actions/depSchema.ts`.\n */\nexport function useRectTool(options: InsertToolOptions = {}): Tool<null> {\n const { behaviors } = options;\n return useMemo(\n () =>\n defineTool<null>({\n id: 'rect',\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 based on\n // live Alt state so users can engage/disengage Alt mid-drag and\n // see the bounds snap between the two modes.\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":";;;;;;AAoBA,SAAgBC,EAAY,IAA6B,CAAC,GAAe;CACvE,IAAM,EAAE,iBAAcC;CACtB,OAAOC,QAEHC,EAAiB;EACf,IAAI;EACJ,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;EAIA,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"],"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 gesture is owned end-to-end by the dispatcher: the `drag` binding\n * routes to `insertAction`, which tracks the live bounds, paints the\n * preview through its `overlay()` surface, and commits via the `insert`\n * dep on release. `<SceneCanvas>` sources that dep from\n * `useInsertDepSource`; consumers wanting a custom node factory override\n * the dep (`useDepSource('insert', …)`) rather than the tool.\n *\n * Grid snapping comes from the `snap` dep, also read by `insertAction` —\n * see `SnapDep` in `interactions/actions/depSchema.ts`.\n */\nexport function useRectTool(options: InsertToolOptions = {}): Tool<null> {\n const { behaviors } = options;\n return useMemo(\n () =>\n defineTool<null>({\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 based on\n // live Alt state so users can engage/disengage Alt mid-drag and\n // see the bounds snap between the two modes.\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":";;;;;;AAoBA,SAAgBC,EAAY,IAA6B,CAAC,GAAe;CACvE,IAAM,EAAE,iBAAcC;CACtB,OAAOC,QAEHC,EAAiB;EACf,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;EAIA,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,8 +1,9 @@
1
1
  import { gestureLifecycleParams as e } from "../../../interactions/actions/gestureLifecycle.js";
2
2
  import { isAnchorOrControl as t, isResizeHandle as n, isRotateHandle as r } from "@weasel-js/routing";
3
+ import { hitPredicate as i } from "@weasel-js/gestures";
3
4
  //#region src/tools/builtin/select/selectionContributions.ts
4
- var i = "selection.move", a = "selection.transform", o = "selection.resize", s = "selection.rotate";
5
- function c(n = {}) {
5
+ var a = "selection.move", o = "selection.transform", s = "selection.resize", c = "selection.rotate";
6
+ function l(n = {}) {
6
7
  let r = (() => {
7
8
  let t = n.move ?? {}, r = e({
8
9
  ...t,
@@ -35,7 +36,7 @@ function c(n = {}) {
35
36
  {
36
37
  spec: {
37
38
  kind: "drag",
38
- target: { kindOf: (e, n) => n === "selected-body" && !t(e) }
39
+ target: { kindOf: i((e, n) => n === "selected-body" && !t(e)) }
39
40
  },
40
41
  actionId: "move",
41
42
  ...r
@@ -50,7 +51,7 @@ function c(n = {}) {
50
51
  }
51
52
  ];
52
53
  }
53
- function l() {
54
+ function u() {
54
55
  return [{
55
56
  spec: {
56
57
  kind: "drag",
@@ -59,7 +60,7 @@ function l() {
59
60
  actionId: "resize"
60
61
  }];
61
62
  }
62
- function u(t = {}) {
63
+ function d(t = {}) {
63
64
  let n = t.rotate ?? {}, i = e({
64
65
  ...n,
65
66
  label: n.rotateLabel
@@ -78,52 +79,52 @@ function u(t = {}) {
78
79
  ...Object.keys(a).length > 0 ? { opts: a } : {}
79
80
  }];
80
81
  }
81
- function d(e = {}) {
82
- return [...l(), ...u(e)];
83
- }
84
82
  function f(e = {}) {
85
- return {
86
- id: i,
87
- eligibility: { always: !0 },
88
- bindings: c(e)
89
- };
83
+ return [...u(), ...d(e)];
90
84
  }
91
85
  function p(e = {}) {
92
86
  return {
93
87
  id: a,
94
88
  eligibility: { always: !0 },
95
- bindings: d(e)
89
+ bindings: l(e)
96
90
  };
97
91
  }
98
- function m() {
92
+ function m(e = {}) {
99
93
  return {
100
94
  id: o,
101
95
  eligibility: { always: !0 },
102
- bindings: l()
96
+ bindings: f(e)
103
97
  };
104
98
  }
105
- function h(e = {}) {
99
+ function h() {
106
100
  return {
107
101
  id: s,
108
102
  eligibility: { always: !0 },
109
- bindings: u(e)
103
+ bindings: u()
104
+ };
105
+ }
106
+ function g(e = {}) {
107
+ return {
108
+ id: c,
109
+ eligibility: { always: !0 },
110
+ bindings: d(e)
110
111
  };
111
112
  }
112
- var g = "selection.areaSelect", _ = (e, t) => e == null && t === "empty";
113
- function v() {
113
+ var _ = "selection.areaSelect", v = i((e, t) => e == null && t === "empty");
114
+ function y() {
114
115
  return {
115
- id: g,
116
+ id: _,
116
117
  eligibility: { always: !0 },
117
118
  bindings: [{
118
119
  spec: {
119
120
  kind: "drag",
120
- target: { kindOf: _ }
121
+ target: { kindOf: v }
121
122
  },
122
123
  actionId: "areaSelect"
123
124
  }]
124
125
  };
125
126
  }
126
127
  //#endregion
127
- export { g as AREA_SELECT_ID, i as SELECTION_MOVE_ID, o as SELECTION_RESIZE_ID, s as SELECTION_ROTATE_ID, a as SELECTION_TRANSFORM_ID, v as areaSelectContribution, _ as onEmptyCanvas, c as selectionMoveBindings, f as selectionMoveContribution, l as selectionResizeBindings, m as selectionResizeContribution, u as selectionRotateBindings, h as selectionRotateContribution, d as selectionTransformBindings, p as selectionTransformContribution };
128
+ export { _ as AREA_SELECT_ID, a as SELECTION_MOVE_ID, s as SELECTION_RESIZE_ID, c as SELECTION_ROTATE_ID, o as SELECTION_TRANSFORM_ID, y as areaSelectContribution, v as onEmptyCanvas, l as selectionMoveBindings, p as selectionMoveContribution, u as selectionResizeBindings, h as selectionResizeContribution, d as selectionRotateBindings, g as selectionRotateContribution, f as selectionTransformBindings, m as selectionTransformContribution };
128
129
 
129
130
  //# sourceMappingURL=selectionContributions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"selectionContributions.js","names":["SELECTION_MOVE_ID","SELECTION_TRANSFORM_ID","SELECTION_RESIZE_ID","SELECTION_ROTATE_ID","selectionMoveBindings","moveOpts","move","options","params","gestureLifecycleParams","withParams","behaviors","body","isAnchorOrControl","afford","selectionResizeBindings","isResizeHandle","selectionRotateBindings","rotate","opts","isRotateHandle","selectionTransformBindings","selectionMoveContribution","selectionTransformContribution","selectionResizeContribution","selectionRotateContribution","AREA_SELECT_ID","onEmptyCanvas","hit","areaSelectContribution"],"sources":["../../../../src/tools/builtin/select/selectionContributions.ts"],"sourcesContent":["/**\n * The ambient bindings that act on the selection: moving it, cloning it, and\n * resizing or rotating it from its handles. They belong to the selection, not\n * to the select tool, so they run under any tool that does not claim the\n * gesture itself. `<SceneCanvas features>` installs them as the `move`,\n * `resize` and `rotate` presets.\n */\nimport type { BindingOpts, GestureBinding } from '@weasel-js/routing';\nimport { isResizeHandle, isRotateHandle, isAnchorOrControl } from '@weasel-js/routing';\nimport type { Contribution } from '../../overlayBinding';\nimport type { UseMoveOptions } from '../../../interactions/actions/move/options';\nimport type { UseRotateOptions } from '../../../interactions/actions/rotate/options';\nimport { gestureLifecycleParams } from '../../../interactions/actions/gestureLifecycle';\n\n/** Options for {@link selectionMoveContribution}. */\nexport interface SelectionMoveOptions<TPose = unknown> {\n /** Move-action options: `behaviors` become the move bindings'\n * `opts.behaviors`, everything else their `opts.params`. */\n move?: UseMoveOptions<TPose>;\n /** Reparent-on-drop behavior for drag-to-move. `'off'` (default) keeps\n * translate-only commits. `'top'` lands the moved nodes at the top of the\n * container under the drop point; `'above'` lands them immediately above the\n * hit sibling. Requires the `nodeAtPoint` dep (`<SceneCanvas>` sources it). */\n reparentOnDrop?: 'off' | 'top' | 'above';\n}\n\n/** Id of the entry {@link selectionMoveContribution} builds. */\nexport const SELECTION_MOVE_ID = 'selection.move';\n/** Id of the entry {@link selectionTransformContribution} builds. */\nexport const SELECTION_TRANSFORM_ID = 'selection.transform';\n/** Id of the entry {@link selectionResizeContribution} builds. */\nexport const SELECTION_RESIZE_ID = 'selection.resize';\n/** Id of the entry {@link selectionRotateContribution} builds. */\nexport const SELECTION_ROTATE_ID = 'selection.rotate';\n\n/** Drag a body to move the selection; Alt-drag to clone it. */\nexport function selectionMoveBindings<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): GestureBinding[] {\n // Shared move-binding opts (params + behaviors). Applied to\n // both the selected-body and unselected-body move bindings so a\n // first-touch drag and a re-drag commit identically.\n const moveOpts: { opts?: BindingOpts } = (() => {\n const move = options.move ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...move, label: move.moveLabel });\n if (options.reparentOnDrop && options.reparentOnDrop !== 'off') params.reparentOnDrop = options.reparentOnDrop;\n if (move.dragThresholdPx !== undefined) params.dragThresholdPx = move.dragThresholdPx;\n if (move.expandIds) params.expandIds = move.expandIds;\n const withParams = Object.keys(params).length > 0 ? { params } : undefined;\n const behaviors = options.move?.behaviors?.length\n ? { behaviors: options.move.behaviors as BindingOpts['behaviors'] }\n : undefined;\n return withParams || behaviors\n ? { opts: { ...withParams, ...behaviors } satisfies BindingOpts }\n : {};\n })();\n\n return [\n // Alt-drag on a body → clone (Illustrator convention).\n // Listed BEFORE bare move so the strict-modifier dispatcher\n // picks this when Alt is held; bare move matches no-mod drags.\n // Both selected and unselected bodies are valid clone targets — the\n // select tool's pointerDown classifier calls `selection.applyClick(top, mods)`\n // on an unselected hit before the drag fires, so cloneAction's\n // `start` sees the hit node in `selection.get()` either way.\n { spec: { kind: 'drag' as const, target: 'selected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n { spec: { kind: 'drag' as const, target: 'unselected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n {\n // Body-drag → move, BUT defer when the pointerdown hit a path\n // anchor / control affordance. Anchors lie on the curve so the\n // body classifier still reports 'selected-body'; without this\n // opt-out, move's binding beats editAnchors's on every anchor drag.\n //\n // `isAnchorOrControl` is the SAME predicate `editAnchorsAction`\n // matches on. That is load-bearing: the two must agree on what\n // counts as an anchor hit or move steals the drag — which is\n // exactly the bug this opt-out exists to prevent.\n spec: {\n kind: 'drag' as const,\n target: {\n kindOf: (afford: unknown, body?: string): boolean =>\n body === 'selected-body' && !isAnchorOrControl(afford),\n },\n },\n actionId: 'move',\n ...moveOpts,\n },\n // Body-drag on a NOT-yet-selected node → also move. The select tool's\n // pointerDown classifier selects the hit node before the drag fires (same\n // contract clone relies on), so by the time moveAction.start() runs the\n // node is in `selection.get()`. Without this binding an unselected-body\n // drag falls through to whatever ambient drag binding comes next — once\n // the `rotate` catch-all, which made the first drag rotate and later ones\n // move. Unselected nodes never carry anchor affordances (those gate on\n // selection), so the plain string-form target is sufficient here.\n {\n spec: { kind: 'drag' as const, target: 'unselected-body' as const },\n actionId: 'move',\n ...moveOpts,\n },\n ];\n}\n\n/** Options for {@link selectionRotateContribution}. */\nexport interface SelectionRotateOptions<TPose = unknown> {\n /** Rotate-action options: `behaviors` become the rotate binding's\n * `opts.behaviors`, everything else its `opts.params`. */\n rotate?: UseRotateOptions<TPose>;\n}\n\n/** Options for {@link selectionTransformContribution}. Resize takes its\n * options through the `resizePolicy` dep (`useResizePolicy`), not here. */\nexport type SelectionTransformOptions<TPose = unknown> = SelectionRotateOptions<TPose>;\n\n/** Drag a resize handle to resize the selection. Options come through the\n * `resizePolicy` dep (`useResizePolicy`). */\nexport function selectionResizeBindings(): GestureBinding[] {\n return [{ spec: { kind: 'drag' as const, target: { kindOf: isResizeHandle } }, actionId: 'resize' }];\n}\n\n/** Drag the rotation handle to rotate the selection. */\nexport function selectionRotateBindings<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): GestureBinding[] {\n const rotate = options.rotate ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...rotate, label: rotate.rotateLabel });\n if (rotate.pivot) params.pivot = rotate.pivot;\n const opts: BindingOpts = {\n ...(Object.keys(params).length > 0 ? { params } : {}),\n ...(rotate.behaviors?.length ? { behaviors: rotate.behaviors as BindingOpts['behaviors'] } : {}),\n };\n return [{\n spec: { kind: 'drag' as const, target: { kindOf: isRotateHandle } },\n actionId: 'rotate',\n ...(Object.keys(opts).length > 0 ? { opts } : {}),\n }];\n}\n\n/** Drag a resize handle to resize the selection, the rotation handle to rotate it. */\nexport function selectionTransformBindings<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): GestureBinding[] {\n return [...selectionResizeBindings(), ...selectionRotateBindings(options)];\n}\n\n/** An always-live entry carrying {@link selectionMoveBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['move']}>` does. */\nexport function selectionMoveContribution<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_MOVE_ID,\n eligibility: { always: true },\n bindings: selectionMoveBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionTransformBindings}: resize\n * and rotate in one entry, what `<SceneCanvas features={['transform']}>`\n * turns on. */\nexport function selectionTransformContribution<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_TRANSFORM_ID,\n eligibility: { always: true },\n bindings: selectionTransformBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionResizeBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['resize']}>` does. */\nexport function selectionResizeContribution(): Contribution {\n return {\n id: SELECTION_RESIZE_ID,\n eligibility: { always: true },\n bindings: selectionResizeBindings(),\n };\n}\n\n/** An always-live entry carrying {@link selectionRotateBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['rotate']}>` does. */\nexport function selectionRotateContribution<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_ROTATE_ID,\n eligibility: { always: true },\n bindings: selectionRotateBindings(options),\n };\n}\n\n/** Id of the entry {@link areaSelectContribution} builds. */\nexport const AREA_SELECT_ID = 'selection.areaSelect';\n\n/** A press on empty canvas: no hit, and not on chrome over it — the rotation\n * handle and the outer half of a resize handle sit off the body. */\nexport const onEmptyCanvas = (hit: unknown, body?: string): boolean => hit == null && body === 'empty';\n\n/** An always-live entry that marquee-selects on a drag across empty canvas,\n * under any tool that does not claim the drag itself. No preset installs it:\n * the select tool already marquees, and a canvas that wants it under every\n * tool adds this to its ambient list. */\nexport function areaSelectContribution(): Contribution {\n return {\n id: AREA_SELECT_ID,\n eligibility: { always: true },\n bindings: [{ spec: { kind: 'drag', target: { kindOf: onEmptyCanvas } }, actionId: 'areaSelect' }],\n };\n}\n"],"mappings":";;;AA2BA,IAAaA,IAAoB,kBAEpBC,IAAyB,uBAEzBC,IAAsB,oBAEtBC,IAAsB;AAGnC,SAAgBC,EACd,IAAuC,CAAC,GACtB;CAIlB,IAAMC,WAA0C;EAC9C,IAAMC,IAAOC,EAAQ,QAAQ,CAAC,GACxBC,IAAkCC,EAAuB;GAAE,GAAGH;GAAM,OAAOA,EAAK;EAAU,CAAC;EAGjG,AAFIC,EAAQ,kBAAkBA,EAAQ,mBAAmB,UAAO,EAAO,iBAAiBA,EAAQ,iBAC5FD,EAAK,oBAAoB,KAAA,MAAW,EAAO,kBAAkBA,EAAK,kBAClEA,EAAK,cAAW,EAAO,YAAYA,EAAK;EAC5C,IAAMI,IAAa,OAAO,KAAKF,CAAM,CAAC,CAAC,SAAS,IAAI,EAAE,UAAO,IAAI,KAAA,GAC3DG,IAAYJ,EAAQ,MAAM,WAAW,SACvC,EAAE,WAAWA,EAAQ,KAAK,UAAsC,IAChE,KAAA;EACJ,OAAOG,KAAcC,IACjB,EAAE,MAAM;GAAE,GAAGD;GAAY,GAAGC;EAAU,EAAwB,IAC9D,CAAC;CACP,EAAA,CAAG;CAEH,OAAO;EAQL;GAAE,M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Be,EACd,IAAuC,CAAC,GAC1B;CACd,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUI,EAAsBG,CAAO;CACzC;AACF;AAKA,SAAgBgB,EACd,IAA4C,CAAC,GAC/B;CACd,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUoB,EAA2Bd,CAAO;CAC9C;AACF;AAIA,SAAgBiB,IAA4C;CAC1D,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUa,EAAwB;CACpC;AACF;AAIA,SAAgBU,EACd,IAAyC,CAAC,GAC5B;CACd,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUc,EAAwBV,CAAO;CAC3C;AACF;AAGA,IAAamB,IAAiB,wBAIjBC,KAAiB,GAAc,MAA2BC,KAAO,QAAQhB,MAAS;AAM/F,SAAgBiB,IAAuC;CACrD,OAAO;EACL,IAAIH;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAU,CAAC;GAAE,MAAM;IAAE,MAAM;IAAQ,QAAQ,EAAE,QAAQC,EAAc;GAAE;GAAG,UAAU;EAAa,CAAC;CAClG;AACF"}
1
+ {"version":3,"file":"selectionContributions.js","names":["SELECTION_MOVE_ID","SELECTION_TRANSFORM_ID","SELECTION_RESIZE_ID","SELECTION_ROTATE_ID","selectionMoveBindings","moveOpts","move","options","params","gestureLifecycleParams","withParams","behaviors","hitPredicate","body","isAnchorOrControl","afford","selectionResizeBindings","isResizeHandle","selectionRotateBindings","rotate","opts","isRotateHandle","selectionTransformBindings","selectionMoveContribution","selectionTransformContribution","selectionResizeContribution","selectionRotateContribution","AREA_SELECT_ID","onEmptyCanvas","hit","areaSelectContribution"],"sources":["../../../../src/tools/builtin/select/selectionContributions.ts"],"sourcesContent":["/**\n * The ambient bindings that act on the selection: moving it, cloning it, and\n * resizing or rotating it from its handles. They belong to the selection, not\n * to the select tool, so they run under any tool that does not claim the\n * gesture itself. `<SceneCanvas features>` installs them as the `move`,\n * `resize` and `rotate` presets.\n */\nimport type { BindingOpts, GestureBinding } from '@weasel-js/routing';\nimport { isResizeHandle, isRotateHandle, isAnchorOrControl } from '@weasel-js/routing';\nimport { hitPredicate } from '@weasel-js/gestures';\nimport type { Contribution } from '../../overlayBinding';\nimport type { UseMoveOptions } from '../../../interactions/actions/move/options';\nimport type { UseRotateOptions } from '../../../interactions/actions/rotate/options';\nimport { gestureLifecycleParams } from '../../../interactions/actions/gestureLifecycle';\n\n/** Options for {@link selectionMoveContribution}. */\nexport interface SelectionMoveOptions<TPose = unknown> {\n /** Move-action options: `behaviors` become the move bindings'\n * `opts.behaviors`, everything else their `opts.params`. */\n move?: UseMoveOptions<TPose>;\n /** Reparent-on-drop behavior for drag-to-move. `'off'` (default) keeps\n * translate-only commits. `'top'` lands the moved nodes at the top of the\n * container under the drop point; `'above'` lands them immediately above the\n * hit sibling. Requires the `nodeAtPoint` dep (`<SceneCanvas>` sources it). */\n reparentOnDrop?: 'off' | 'top' | 'above';\n}\n\n/** Id of the entry {@link selectionMoveContribution} builds. */\nexport const SELECTION_MOVE_ID = 'selection.move';\n/** Id of the entry {@link selectionTransformContribution} builds. */\nexport const SELECTION_TRANSFORM_ID = 'selection.transform';\n/** Id of the entry {@link selectionResizeContribution} builds. */\nexport const SELECTION_RESIZE_ID = 'selection.resize';\n/** Id of the entry {@link selectionRotateContribution} builds. */\nexport const SELECTION_ROTATE_ID = 'selection.rotate';\n\n/** Drag a body to move the selection; Alt-drag to clone it. */\nexport function selectionMoveBindings<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): GestureBinding[] {\n // Shared move-binding opts (params + behaviors). Applied to\n // both the selected-body and unselected-body move bindings so a\n // first-touch drag and a re-drag commit identically.\n const moveOpts: { opts?: BindingOpts } = (() => {\n const move = options.move ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...move, label: move.moveLabel });\n if (options.reparentOnDrop && options.reparentOnDrop !== 'off') params.reparentOnDrop = options.reparentOnDrop;\n if (move.dragThresholdPx !== undefined) params.dragThresholdPx = move.dragThresholdPx;\n if (move.expandIds) params.expandIds = move.expandIds;\n const withParams = Object.keys(params).length > 0 ? { params } : undefined;\n const behaviors = options.move?.behaviors?.length\n ? { behaviors: options.move.behaviors as BindingOpts['behaviors'] }\n : undefined;\n return withParams || behaviors\n ? { opts: { ...withParams, ...behaviors } satisfies BindingOpts }\n : {};\n })();\n\n return [\n // Alt-drag on a body → clone (Illustrator convention).\n // Listed BEFORE bare move so the strict-modifier dispatcher\n // picks this when Alt is held; bare move matches no-mod drags.\n // Both selected and unselected bodies are valid clone targets — the\n // select tool's pointerDown classifier calls `selection.applyClick(top, mods)`\n // on an unselected hit before the drag fires, so cloneAction's\n // `start` sees the hit node in `selection.get()` either way.\n { spec: { kind: 'drag' as const, target: 'selected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n { spec: { kind: 'drag' as const, target: 'unselected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n {\n // Body-drag → move, BUT defer when the pointerdown hit a path\n // anchor / control affordance. Anchors lie on the curve so the\n // body classifier still reports 'selected-body'; without this\n // opt-out, move's binding beats editAnchors's on every anchor drag.\n //\n // `isAnchorOrControl` is the SAME predicate `editAnchorsAction`\n // matches on. That is load-bearing: the two must agree on what\n // counts as an anchor hit or move steals the drag — which is\n // exactly the bug this opt-out exists to prevent.\n spec: {\n kind: 'drag' as const,\n target: {\n kindOf: hitPredicate((afford, body) =>\n body === 'selected-body' && !isAnchorOrControl(afford)),\n },\n },\n actionId: 'move',\n ...moveOpts,\n },\n // Body-drag on a NOT-yet-selected node → also move. The select tool's\n // pointerDown classifier selects the hit node before the drag fires (same\n // contract clone relies on), so by the time moveAction.start() runs the\n // node is in `selection.get()`. Without this binding an unselected-body\n // drag falls through to whatever ambient drag binding comes next — once\n // the `rotate` catch-all, which made the first drag rotate and later ones\n // move. Unselected nodes never carry anchor affordances (those gate on\n // selection), so the plain string-form target is sufficient here.\n {\n spec: { kind: 'drag' as const, target: 'unselected-body' as const },\n actionId: 'move',\n ...moveOpts,\n },\n ];\n}\n\n/** Options for {@link selectionRotateContribution}. */\nexport interface SelectionRotateOptions<TPose = unknown> {\n /** Rotate-action options: `behaviors` become the rotate binding's\n * `opts.behaviors`, everything else its `opts.params`. */\n rotate?: UseRotateOptions<TPose>;\n}\n\n/** Options for {@link selectionTransformContribution}. Resize takes its\n * options through the `resizePolicy` dep (`useResizePolicy`), not here. */\nexport type SelectionTransformOptions<TPose = unknown> = SelectionRotateOptions<TPose>;\n\n/** Drag a resize handle to resize the selection. Options come through the\n * `resizePolicy` dep (`useResizePolicy`). */\nexport function selectionResizeBindings(): GestureBinding[] {\n return [{ spec: { kind: 'drag' as const, target: { kindOf: isResizeHandle } }, actionId: 'resize' }];\n}\n\n/** Drag the rotation handle to rotate the selection. */\nexport function selectionRotateBindings<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): GestureBinding[] {\n const rotate = options.rotate ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...rotate, label: rotate.rotateLabel });\n if (rotate.pivot) params.pivot = rotate.pivot;\n const opts: BindingOpts = {\n ...(Object.keys(params).length > 0 ? { params } : {}),\n ...(rotate.behaviors?.length ? { behaviors: rotate.behaviors as BindingOpts['behaviors'] } : {}),\n };\n return [{\n spec: { kind: 'drag' as const, target: { kindOf: isRotateHandle } },\n actionId: 'rotate',\n ...(Object.keys(opts).length > 0 ? { opts } : {}),\n }];\n}\n\n/** Drag a resize handle to resize the selection, the rotation handle to rotate it. */\nexport function selectionTransformBindings<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): GestureBinding[] {\n return [...selectionResizeBindings(), ...selectionRotateBindings(options)];\n}\n\n/** An always-live entry carrying {@link selectionMoveBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['move']}>` does. */\nexport function selectionMoveContribution<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_MOVE_ID,\n eligibility: { always: true },\n bindings: selectionMoveBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionTransformBindings}: resize\n * and rotate in one entry, what `<SceneCanvas features={['transform']}>`\n * turns on. */\nexport function selectionTransformContribution<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_TRANSFORM_ID,\n eligibility: { always: true },\n bindings: selectionTransformBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionResizeBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['resize']}>` does. */\nexport function selectionResizeContribution(): Contribution {\n return {\n id: SELECTION_RESIZE_ID,\n eligibility: { always: true },\n bindings: selectionResizeBindings(),\n };\n}\n\n/** An always-live entry carrying {@link selectionRotateBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['rotate']}>` does. */\nexport function selectionRotateContribution<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_ROTATE_ID,\n eligibility: { always: true },\n bindings: selectionRotateBindings(options),\n };\n}\n\n/** Id of the entry {@link areaSelectContribution} builds. */\nexport const AREA_SELECT_ID = 'selection.areaSelect';\n\n/** A press on empty canvas: no hit, and not on chrome over it — the rotation\n * handle and the outer half of a resize handle sit off the body. */\nexport const onEmptyCanvas = hitPredicate((hit, body) => hit == null && body === 'empty');\n\n/** An always-live entry that marquee-selects on a drag across empty canvas,\n * under any tool that does not claim the drag itself. No preset installs it:\n * the select tool already marquees, and a canvas that wants it under every\n * tool adds this to its ambient list. */\nexport function areaSelectContribution(): Contribution {\n return {\n id: AREA_SELECT_ID,\n eligibility: { always: true },\n bindings: [{ spec: { kind: 'drag', target: { kindOf: onEmptyCanvas } }, actionId: 'areaSelect' }],\n };\n}\n"],"mappings":";;;;AA4BA,IAAaA,IAAoB,kBAEpBC,IAAyB,uBAEzBC,IAAsB,oBAEtBC,IAAsB;AAGnC,SAAgBC,EACd,IAAuC,CAAC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