@weasel-js/core 1.11.1 → 1.13.0-rc.0

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 (488) hide show
  1. package/CHANGELOG.md +275 -0
  2. package/dist/WeaselProvider.js +1 -1
  3. package/dist/affordances/pathAnchors.js +10 -6
  4. package/dist/affordances/pathAnchors.js.map +1 -1
  5. package/dist/animation/poseTarget.js +46 -15
  6. package/dist/animation/poseTarget.js.map +1 -1
  7. package/dist/animation/poseTransition.js +3 -3
  8. package/dist/animation/poseTransition.js.map +1 -1
  9. package/dist/animation/reflow.js +3 -6
  10. package/dist/animation/reflow.js.map +1 -1
  11. package/dist/animation/rig/bindRig.js +2 -2
  12. package/dist/animation/rig/bindRig.js.map +1 -1
  13. package/dist/animation/rig/skinBinding.js +2 -2
  14. package/dist/animation/rig/skinBinding.js.map +1 -1
  15. package/dist/barrel/canvas.js +5 -1
  16. package/dist/barrel/chrome.js +3 -1
  17. package/dist/barrel/paint.js +4 -4
  18. package/dist/barrel/paths.js +9 -4
  19. package/dist/barrel/renderer.js +3 -2
  20. package/dist/barrel/routing.js +4 -4
  21. package/dist/barrel/scene.js +7 -1
  22. package/dist/barrel/text.js +2 -2
  23. package/dist/barrel/viewport.js +6 -2
  24. package/dist/canvas/Canvas.js +2 -1
  25. package/dist/canvas/Canvas.js.map +1 -1
  26. package/dist/canvas/CanvasView.js +23 -34
  27. package/dist/canvas/CanvasView.js.map +1 -1
  28. package/dist/canvas/ModalityHud.js +1 -1
  29. package/dist/canvas/NodeShape.js +5 -1
  30. package/dist/canvas/NodeShape.js.map +1 -1
  31. package/dist/canvas/SceneCanvas/ActionsProviderIfRoot.js +1 -1
  32. package/dist/canvas/SceneCanvas/DepRegistryProviderIfRoot.js +1 -1
  33. package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js +1 -1
  34. package/dist/canvas/SceneCanvas/SceneCanvasInput.js +2 -0
  35. package/dist/canvas/SceneCanvas/SceneCanvasInput.js.map +1 -1
  36. package/dist/canvas/SceneCanvas/SurfaceDeclarations.js +23 -0
  37. package/dist/canvas/SceneCanvas/SurfaceDeclarations.js.map +1 -0
  38. package/dist/canvas/SceneCanvas/canvasPassThrough.js +2 -1
  39. package/dist/canvas/SceneCanvas/canvasPassThrough.js.map +1 -1
  40. package/dist/canvas/SceneCanvas/defaultNodeRouting.js +2 -2
  41. package/dist/canvas/SceneCanvas/defaultNodeRouting.js.map +1 -1
  42. package/dist/canvas/SceneCanvas/props.js.map +1 -1
  43. package/dist/canvas/SceneCanvas/scenePointQuery.js +27 -5
  44. package/dist/canvas/SceneCanvas/scenePointQuery.js.map +1 -1
  45. package/dist/canvas/SceneCanvas/useActionTunings.js +6 -1
  46. package/dist/canvas/SceneCanvas/useActionTunings.js.map +1 -1
  47. package/dist/canvas/SceneCanvas/useCanvasDevtoolsRoot.js +1 -0
  48. package/dist/canvas/SceneCanvas/useCanvasDevtoolsRoot.js.map +1 -1
  49. package/dist/canvas/SceneCanvas/useCanvasTools.js +10 -2
  50. package/dist/canvas/SceneCanvas/useCanvasTools.js.map +1 -1
  51. package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js +25 -19
  52. package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js.map +1 -1
  53. package/dist/canvas/SceneCanvas/useSceneCanvasHandle.js +9 -3
  54. package/dist/canvas/SceneCanvas/useSceneCanvasHandle.js.map +1 -1
  55. package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js +17 -2
  56. package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js.map +1 -1
  57. package/dist/canvas/SceneCanvas/useSceneCanvasTools.js +2 -0
  58. package/dist/canvas/SceneCanvas/useSceneCanvasTools.js.map +1 -1
  59. package/dist/canvas/SceneCanvas/useSceneGestureDispatcher.js +19 -4
  60. package/dist/canvas/SceneCanvas/useSceneGestureDispatcher.js.map +1 -1
  61. package/dist/canvas/SceneCanvas/useScenePicking.js +31 -6
  62. package/dist/canvas/SceneCanvas/useScenePicking.js.map +1 -1
  63. package/dist/canvas/SceneCanvas/useSceneSelectTool.js +4 -5
  64. package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -1
  65. package/dist/canvas/SceneCanvas/useSceneStandardActions.js +7 -4
  66. package/dist/canvas/SceneCanvas/useSceneStandardActions.js.map +1 -1
  67. package/dist/canvas/SceneCanvas.js +30 -12
  68. package/dist/canvas/SceneCanvas.js.map +1 -1
  69. package/dist/canvas/ViewMarker.js +35 -0
  70. package/dist/canvas/ViewMarker.js.map +1 -0
  71. package/dist/canvas/accentColor.js +26 -3
  72. package/dist/canvas/accentColor.js.map +1 -1
  73. package/dist/canvas/buildSceneTree.js +14 -20
  74. package/dist/canvas/buildSceneTree.js.map +1 -1
  75. package/dist/canvas/copiesAbove.js +1 -1
  76. package/dist/canvas/copiesAbove.js.map +1 -1
  77. package/dist/canvas/defaultDrawOne.js +11 -6
  78. package/dist/canvas/defaultDrawOne.js.map +1 -1
  79. package/dist/canvas/deps/areaSelect.js +5 -2
  80. package/dist/canvas/deps/areaSelect.js.map +1 -1
  81. package/dist/canvas/deps/booleans.js +3 -2
  82. package/dist/canvas/deps/booleans.js.map +1 -1
  83. package/dist/canvas/deps/enteredGroup.js +81 -0
  84. package/dist/canvas/deps/enteredGroup.js.map +1 -0
  85. package/dist/canvas/deps/hitTestArea.js +28 -16
  86. package/dist/canvas/deps/hitTestArea.js.map +1 -1
  87. package/dist/canvas/deps/insert.js +10 -38
  88. package/dist/canvas/deps/insert.js.map +1 -1
  89. package/dist/canvas/deps/insertSite.js +39 -0
  90. package/dist/canvas/deps/insertSite.js.map +1 -0
  91. package/dist/canvas/deps/lassoSelect.js +6 -3
  92. package/dist/canvas/deps/lassoSelect.js.map +1 -1
  93. package/dist/canvas/deps/pathEditCommits.js +3 -7
  94. package/dist/canvas/deps/pathEditCommits.js.map +1 -1
  95. package/dist/canvas/deps/pathLeaf.js +1 -1
  96. package/dist/canvas/deps/pathLeaf.js.map +1 -1
  97. package/dist/canvas/deps/slice.js +2 -1
  98. package/dist/canvas/deps/slice.js.map +1 -1
  99. package/dist/canvas/derivedPath.js +14 -6
  100. package/dist/canvas/derivedPath.js.map +1 -1
  101. package/dist/canvas/doubleClickTarget.js +9 -11
  102. package/dist/canvas/doubleClickTarget.js.map +1 -1
  103. package/dist/canvas/drawnBounds.js +26 -9
  104. package/dist/canvas/drawnBounds.js.map +1 -1
  105. package/dist/canvas/inheritedPaints.js +55 -0
  106. package/dist/canvas/inheritedPaints.js.map +1 -0
  107. package/dist/canvas/nodeShapes/derivedPainter.js +15 -16
  108. package/dist/canvas/nodeShapes/derivedPainter.js.map +1 -1
  109. package/dist/canvas/nodeShapes/nodePaint.js +7 -34
  110. package/dist/canvas/nodeShapes/nodePaint.js.map +1 -1
  111. package/dist/canvas/nodeShapes/pathPainter.js +7 -7
  112. package/dist/canvas/nodeShapes/pathPainter.js.map +1 -1
  113. package/dist/canvas/nodeShapes/rectFallbackPainter.js +4 -5
  114. package/dist/canvas/nodeShapes/rectFallbackPainter.js.map +1 -1
  115. package/dist/canvas/nodeShapes/shapePainter.js +9 -9
  116. package/dist/canvas/nodeShapes/shapePainter.js.map +1 -1
  117. package/dist/canvas/nodeShapes/textPainter.js +13 -12
  118. package/dist/canvas/nodeShapes/textPainter.js.map +1 -1
  119. package/dist/canvas/ownClip.js +24 -0
  120. package/dist/canvas/ownClip.js.map +1 -0
  121. package/dist/canvas/paintCull.js.map +1 -1
  122. package/dist/canvas/pickIndex/nodeBroadBox.js +86 -0
  123. package/dist/canvas/pickIndex/nodeBroadBox.js.map +1 -0
  124. package/dist/canvas/pickIndex/scenePickIndex.js +208 -0
  125. package/dist/canvas/pickIndex/scenePickIndex.js.map +1 -0
  126. package/dist/canvas/pickReach.js +3 -3
  127. package/dist/canvas/pickReach.js.map +1 -1
  128. package/dist/canvas/pickWalk.js +17 -91
  129. package/dist/canvas/pickWalk.js.map +1 -1
  130. package/dist/canvas/poseCascade.js +1 -1
  131. package/dist/canvas/poseCascade.js.map +1 -1
  132. package/dist/canvas/publishPreviews.js +97 -0
  133. package/dist/canvas/publishPreviews.js.map +1 -0
  134. package/dist/canvas/renderSceneToPixels.js +1 -1
  135. package/dist/canvas/renderSceneToPixels.js.map +1 -1
  136. package/dist/canvas/sceneAdapter.js +7 -5
  137. package/dist/canvas/sceneAdapter.js.map +1 -1
  138. package/dist/canvas/sceneClipboard.js +17 -10
  139. package/dist/canvas/sceneClipboard.js.map +1 -1
  140. package/dist/canvas/scenePickReads.js +37 -0
  141. package/dist/canvas/scenePickReads.js.map +1 -0
  142. package/dist/canvas/scenePickSource.js +74 -0
  143. package/dist/canvas/scenePickSource.js.map +1 -0
  144. package/dist/canvas/sceneSlotWiring.js +9 -3
  145. package/dist/canvas/sceneSlotWiring.js.map +1 -1
  146. package/dist/canvas/sceneViewRender.js +9 -4
  147. package/dist/canvas/sceneViewRender.js.map +1 -1
  148. package/dist/canvas/shownNodes.js +15 -0
  149. package/dist/canvas/shownNodes.js.map +1 -0
  150. package/dist/canvas/surfaceContribution.js +12 -8
  151. package/dist/canvas/surfaceContribution.js.map +1 -1
  152. package/dist/canvas/useCanvasView.js +4 -2
  153. package/dist/canvas/useCanvasView.js.map +1 -1
  154. package/dist/canvas/useLayerStack.js +6 -2
  155. package/dist/canvas/useLayerStack.js.map +1 -1
  156. package/dist/canvas/useSceneAdapter.js +5 -3
  157. package/dist/canvas/useSceneAdapter.js.map +1 -1
  158. package/dist/canvas/useViewAim.js +121 -0
  159. package/dist/canvas/useViewAim.js.map +1 -0
  160. package/dist/canvas/useViewNesting.js +3 -2
  161. package/dist/canvas/useViewNesting.js.map +1 -1
  162. package/dist/canvas/useViewRegistrySurface.js +4 -2
  163. package/dist/canvas/useViewRegistrySurface.js.map +1 -1
  164. package/dist/canvas/viewMarkers.js +63 -0
  165. package/dist/canvas/viewMarkers.js.map +1 -0
  166. package/dist/canvas/viewRegistry.js +27 -1
  167. package/dist/canvas/viewRegistry.js.map +1 -1
  168. package/dist/clipboard.d.ts +2 -2
  169. package/dist/{clone-C3e0OTuF.d.ts → clone-qb2e1F5p.d.ts} +2 -2
  170. package/dist/clone.d.ts +3 -3
  171. package/dist/core/isPlainObject.js +2 -2
  172. package/dist/core/layers/layerGroup.js.map +1 -1
  173. package/dist/core/pages/pageEdits.js +2 -3
  174. package/dist/core/pages/pageEdits.js.map +1 -1
  175. package/dist/core/paint/meshKindLazy.js +59 -2
  176. package/dist/core/paint/meshKindLazy.js.map +1 -1
  177. package/dist/core/scene/NodeRouting.js.map +1 -1
  178. package/dist/core/scene/arrivalWindow.js +1 -1
  179. package/dist/core/scene/arrivalWindow.js.map +1 -1
  180. package/dist/core/scene/clipNothing.js +10 -0
  181. package/dist/core/scene/clipNothing.js.map +1 -0
  182. package/dist/core/scene/declaredFieldSetters.js +44 -0
  183. package/dist/core/scene/declaredFieldSetters.js.map +1 -0
  184. package/dist/core/scene/depMemo.js +14 -3
  185. package/dist/core/scene/depMemo.js.map +1 -1
  186. package/dist/core/scene/dependents.js +9 -1
  187. package/dist/core/scene/dependents.js.map +1 -1
  188. package/dist/core/scene/derivedParts.js +10 -11
  189. package/dist/core/scene/derivedParts.js.map +1 -1
  190. package/dist/core/scene/documentOf.js +43 -0
  191. package/dist/core/scene/documentOf.js.map +1 -0
  192. package/dist/core/scene/effectivePose.js +44 -15
  193. package/dist/core/scene/effectivePose.js.map +1 -1
  194. package/dist/core/scene/fieldEdits.js +17 -14
  195. package/dist/core/scene/fieldEdits.js.map +1 -1
  196. package/dist/core/scene/fontReads.js +37 -0
  197. package/dist/core/scene/fontReads.js.map +1 -0
  198. package/dist/core/scene/historyForm.js +4 -4
  199. package/dist/core/scene/historyForm.js.map +1 -1
  200. package/dist/core/scene/inheritedPaint.js +97 -0
  201. package/dist/core/scene/inheritedPaint.js.map +1 -0
  202. package/dist/core/scene/kitOps.js +3 -23
  203. package/dist/core/scene/kitOps.js.map +1 -1
  204. package/dist/core/scene/kitRegistry.js +5 -0
  205. package/dist/core/scene/kitRegistry.js.map +1 -1
  206. package/dist/core/scene/layoutPass.js +1 -2
  207. package/dist/core/scene/layoutPass.js.map +1 -1
  208. package/dist/core/scene/nodeAsShown.js +72 -0
  209. package/dist/core/scene/nodeAsShown.js.map +1 -0
  210. package/dist/core/scene/nodeFnFields.js +2 -10
  211. package/dist/core/scene/nodeFnFields.js.map +1 -1
  212. package/dist/core/scene/nodeMemo.js +21 -8
  213. package/dist/core/scene/nodeMemo.js.map +1 -1
  214. package/dist/core/scene/nodeStore.js +2 -4
  215. package/dist/core/scene/nodeStore.js.map +1 -1
  216. package/dist/core/scene/pathEffects/blend.js.map +1 -1
  217. package/dist/core/scene/pathEffects/derive.js +10 -4
  218. package/dist/core/scene/pathEffects/derive.js.map +1 -1
  219. package/dist/core/scene/pathEffects/effects.js +3 -1
  220. package/dist/core/scene/pathEffects/effects.js.map +1 -1
  221. package/dist/core/scene/pathEffects/foundHidden.js +35 -0
  222. package/dist/core/scene/pathEffects/foundHidden.js.map +1 -0
  223. package/dist/core/scene/pathEffects/textAlong.js +95 -0
  224. package/dist/core/scene/pathEffects/textAlong.js.map +1 -0
  225. package/dist/core/scene/plyStacks.js +89 -0
  226. package/dist/core/scene/plyStacks.js.map +1 -0
  227. package/dist/core/scene/poseHold.js +42 -24
  228. package/dist/core/scene/poseHold.js.map +1 -1
  229. package/dist/core/scene/poseOverrides.js +35 -38
  230. package/dist/core/scene/poseOverrides.js.map +1 -1
  231. package/dist/core/scene/posePlies.js +59 -0
  232. package/dist/core/scene/posePlies.js.map +1 -0
  233. package/dist/core/scene/reconcileSpecs.js +6 -15
  234. package/dist/core/scene/reconcileSpecs.js.map +1 -1
  235. package/dist/core/scene/renderOrder.js +10 -4
  236. package/dist/core/scene/renderOrder.js.map +1 -1
  237. package/dist/core/scene/sameValue.js +17 -0
  238. package/dist/core/scene/sameValue.js.map +1 -0
  239. package/dist/core/scene/scene.js +3 -3
  240. package/dist/core/scene/scene.js.map +1 -1
  241. package/dist/core/scene/sceneEdits.js +8 -0
  242. package/dist/core/scene/sceneEdits.js.map +1 -1
  243. package/dist/core/scene/sceneState.js +1 -2
  244. package/dist/core/scene/sceneState.js.map +1 -1
  245. package/dist/core/scene/serialization.js +45 -9
  246. package/dist/core/scene/serialization.js.map +1 -1
  247. package/dist/core/scene/staleReplay.js +5 -2
  248. package/dist/core/scene/staleReplay.js.map +1 -1
  249. package/dist/core/scene/statedFields.js +4 -2
  250. package/dist/core/scene/statedFields.js.map +1 -1
  251. package/dist/core/scene/treeEdits.js +2 -4
  252. package/dist/core/scene/treeEdits.js.map +1 -1
  253. package/dist/core/scene/treeOrder.js +3 -1
  254. package/dist/core/scene/treeOrder.js.map +1 -1
  255. package/dist/core/scene/treeReads.js +1 -2
  256. package/dist/core/scene/treeReads.js.map +1 -1
  257. package/dist/core/scene/treeShape.js +13 -0
  258. package/dist/core/scene/treeShape.js.map +1 -0
  259. package/dist/core/scene/types.js.map +1 -1
  260. package/dist/core/scene/useScene.js +1 -1
  261. package/dist/core/scene/useScene.js.map +1 -1
  262. package/dist/{cornerHandles-BHuoMs1o.d.ts → cornerHandles-CNCb7aTY.d.ts} +3 -2
  263. package/dist/{depSchema-BpZNOv7q.d.ts → depSchema-B1RS-IJx.d.ts} +39 -18
  264. package/dist/devtools/handlers.js +1 -1
  265. package/dist/devtools/handlers.js.map +1 -1
  266. package/dist/devtools/protocol.js.map +1 -1
  267. package/dist/devtools/registry.js +4 -4
  268. package/dist/devtools/registry.js.map +1 -1
  269. package/dist/devtools-protocol.d.ts +4 -3
  270. package/dist/devtools.d.ts +3 -2
  271. package/dist/features/measure/measureContribution.js +4 -2
  272. package/dist/features/measure/measureContribution.js.map +1 -1
  273. package/dist/features/measure/measureHit.js +5 -3
  274. package/dist/features/measure/measureHit.js.map +1 -1
  275. package/dist/features/measure/measurement.js +1 -1
  276. package/dist/features/measure/measurement.js.map +1 -1
  277. package/dist/features/modes/modeLayers.js +14 -7
  278. package/dist/features/modes/modeLayers.js.map +1 -1
  279. package/dist/features/modes/modeTriggers.js +10 -6
  280. package/dist/features/modes/modeTriggers.js.map +1 -1
  281. package/dist/features/pathEffects/effectSources.js +69 -0
  282. package/dist/features/pathEffects/effectSources.js.map +1 -0
  283. package/dist/features/pathEffects/readSource.js +18 -2
  284. package/dist/features/pathEffects/readSource.js.map +1 -1
  285. package/dist/features/pathEffects/textItems.js +53 -0
  286. package/dist/features/pathEffects/textItems.js.map +1 -0
  287. package/dist/features/pathEffects/useEffectSourcesLayer.js +53 -0
  288. package/dist/features/pathEffects/useEffectSourcesLayer.js.map +1 -0
  289. package/dist/features/paths/editablePath.js +1 -1
  290. package/dist/features/paths/editablePath.js.map +1 -1
  291. package/dist/features/paths/pathEditState.js +5 -2
  292. package/dist/features/paths/pathEditState.js.map +1 -1
  293. package/dist/features/paths/pathSnap/sceneIndex.js +1 -1
  294. package/dist/features/paths/pathSnap/sceneIndex.js.map +1 -1
  295. package/dist/features/selection/enteredGroupFrame.js +65 -0
  296. package/dist/features/selection/enteredGroupFrame.js.map +1 -0
  297. package/dist/features/selection/enteredGroupScope.js +44 -0
  298. package/dist/features/selection/enteredGroupScope.js.map +1 -0
  299. package/dist/features/text/sceneTextDrafts.js +64 -0
  300. package/dist/features/text/sceneTextDrafts.js.map +1 -0
  301. package/dist/features/text/textHitAt.js +34 -3
  302. package/dist/features/text/textHitAt.js.map +1 -1
  303. package/dist/features/text/useSceneTextEdit.js +23 -19
  304. package/dist/features/text/useSceneTextEdit.js.map +1 -1
  305. package/dist/features/viewports/aim.js +105 -0
  306. package/dist/features/viewports/aim.js.map +1 -0
  307. package/dist/features/viewports/viewMarker.js +82 -0
  308. package/dist/features/viewports/viewMarker.js.map +1 -0
  309. package/dist/features/viewports/viewMarkerDrag.js +55 -0
  310. package/dist/features/viewports/viewMarkerDrag.js.map +1 -0
  311. package/dist/index.d.ts +709 -258
  312. package/dist/index.js +33 -12
  313. package/dist/interactions/actions/admitsChild.js +11 -0
  314. package/dist/interactions/actions/admitsChild.js.map +1 -0
  315. package/dist/interactions/actions/booleans/booleans.js +2 -1
  316. package/dist/interactions/actions/booleans/booleans.js.map +1 -1
  317. package/dist/interactions/actions/booleans/operands.js +6 -5
  318. package/dist/interactions/actions/booleans/operands.js.map +1 -1
  319. package/dist/interactions/actions/clipboard/action.js +27 -17
  320. package/dist/interactions/actions/clipboard/action.js.map +1 -1
  321. package/dist/interactions/actions/defaults/anchorEditing.js +44 -23
  322. package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -1
  323. package/dist/interactions/actions/defaults/anchorJoin.js +12 -6
  324. package/dist/interactions/actions/defaults/anchorJoin.js.map +1 -1
  325. package/dist/interactions/actions/defaults/bendSegment.js +7 -4
  326. package/dist/interactions/actions/defaults/bendSegment.js.map +1 -1
  327. package/dist/interactions/actions/defaults/cancelGesture.js +11 -8
  328. package/dist/interactions/actions/defaults/cancelGesture.js.map +1 -1
  329. package/dist/interactions/actions/defaults/contextMenu.js +33 -11
  330. package/dist/interactions/actions/defaults/contextMenu.js.map +1 -1
  331. package/dist/interactions/actions/defaults/createPaintAction.js +5 -2
  332. package/dist/interactions/actions/defaults/createPaintAction.js.map +1 -1
  333. package/dist/interactions/actions/defaults/delete.js +28 -14
  334. package/dist/interactions/actions/defaults/delete.js.map +1 -1
  335. package/dist/interactions/actions/defaults/duplicate.js +11 -8
  336. package/dist/interactions/actions/defaults/duplicate.js.map +1 -1
  337. package/dist/interactions/actions/defaults/enterGroup.js +88 -0
  338. package/dist/interactions/actions/defaults/enterGroup.js.map +1 -0
  339. package/dist/interactions/actions/defaults/enterPathEdit.js +20 -10
  340. package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -1
  341. package/dist/interactions/actions/defaults/enterTextEdit.js +1 -1
  342. package/dist/interactions/actions/defaults/enterTextEdit.js.map +1 -1
  343. package/dist/interactions/actions/defaults/escape.js +11 -8
  344. package/dist/interactions/actions/defaults/escape.js.map +1 -1
  345. package/dist/interactions/actions/defaults/exitPathEdit.js +7 -4
  346. package/dist/interactions/actions/defaults/exitPathEdit.js.map +1 -1
  347. package/dist/interactions/actions/defaults/group.js +26 -20
  348. package/dist/interactions/actions/defaults/group.js.map +1 -1
  349. package/dist/interactions/actions/defaults/ingest.js +10 -4
  350. package/dist/interactions/actions/defaults/ingest.js.map +1 -1
  351. package/dist/interactions/actions/defaults/insertPathAnchor.js +7 -4
  352. package/dist/interactions/actions/defaults/insertPathAnchor.js.map +1 -1
  353. package/dist/interactions/actions/defaults/nudge.js +8 -2
  354. package/dist/interactions/actions/defaults/nudge.js.map +1 -1
  355. package/dist/interactions/actions/defaults/pathEditTools.js +11 -8
  356. package/dist/interactions/actions/defaults/pathEditTools.js.map +1 -1
  357. package/dist/interactions/actions/defaults/pinchZoom.js +7 -4
  358. package/dist/interactions/actions/defaults/pinchZoom.js.map +1 -1
  359. package/dist/interactions/actions/defaults/reorder.js +24 -6
  360. package/dist/interactions/actions/defaults/reorder.js.map +1 -1
  361. package/dist/interactions/actions/defaults/selectAll.js +15 -8
  362. package/dist/interactions/actions/defaults/selectAll.js.map +1 -1
  363. package/dist/interactions/actions/defaults/selectDeep.js +35 -0
  364. package/dist/interactions/actions/defaults/selectDeep.js.map +1 -0
  365. package/dist/interactions/actions/defaults/setFill.js +7 -3
  366. package/dist/interactions/actions/defaults/setFill.js.map +1 -1
  367. package/dist/interactions/actions/defaults/setFillOpacity.js +1 -1
  368. package/dist/interactions/actions/defaults/setStroke.js +12 -11
  369. package/dist/interactions/actions/defaults/setStroke.js.map +1 -1
  370. package/dist/interactions/actions/defaults/setStrokeOpacity.js +1 -1
  371. package/dist/interactions/actions/defaults/toolActivate.js +7 -1
  372. package/dist/interactions/actions/defaults/toolActivate.js.map +1 -1
  373. package/dist/interactions/actions/defaults/toolResetToDefault.js +7 -4
  374. package/dist/interactions/actions/defaults/toolResetToDefault.js.map +1 -1
  375. package/dist/interactions/actions/defaults/undoRedo.js +19 -13
  376. package/dist/interactions/actions/defaults/undoRedo.js.map +1 -1
  377. package/dist/interactions/actions/defaults/viewportWheelPan.js +16 -7
  378. package/dist/interactions/actions/defaults/viewportWheelPan.js.map +1 -1
  379. package/dist/interactions/actions/defaults/viewportZoom.js +24 -6
  380. package/dist/interactions/actions/defaults/viewportZoom.js.map +1 -1
  381. package/dist/interactions/actions/drawnBoxes.js +2 -1
  382. package/dist/interactions/actions/drawnBoxes.js.map +1 -1
  383. package/dist/interactions/actions/edit-anchors/action.js +7 -4
  384. package/dist/interactions/actions/edit-anchors/action.js.map +1 -1
  385. package/dist/interactions/actions/flip/action.js +8 -2
  386. package/dist/interactions/actions/flip/action.js.map +1 -1
  387. package/dist/interactions/actions/insert/action.js +1 -0
  388. package/dist/interactions/actions/insert/action.js.map +1 -1
  389. package/dist/interactions/actions/insert/parent.js +7 -5
  390. package/dist/interactions/actions/insert/parent.js.map +1 -1
  391. package/dist/interactions/actions/insert/placeAction.js +3 -2
  392. package/dist/interactions/actions/insert/placeAction.js.map +1 -1
  393. package/dist/interactions/actions/insert/repositionAction.js +2 -1
  394. package/dist/interactions/actions/insert/repositionAction.js.map +1 -1
  395. package/dist/interactions/actions/insert/session.js +2 -2
  396. package/dist/interactions/actions/insert/session.js.map +1 -1
  397. package/dist/interactions/actions/move/action.js +7 -4
  398. package/dist/interactions/actions/move/action.js.map +1 -1
  399. package/dist/interactions/actions/move/commit/reparent.js +1 -1
  400. package/dist/interactions/actions/move/commit/reparent.js.map +1 -1
  401. package/dist/interactions/actions/move/gestureAdapter.js +6 -7
  402. package/dist/interactions/actions/move/gestureAdapter.js.map +1 -1
  403. package/dist/interactions/actions/move/layout/exits.js +1 -1
  404. package/dist/interactions/actions/move/layout/exits.js.map +1 -1
  405. package/dist/interactions/actions/move/session.js +4 -4
  406. package/dist/interactions/actions/move/session.js.map +1 -1
  407. package/dist/interactions/actions/outlines/createOutlinesAction.js +8 -5
  408. package/dist/interactions/actions/outlines/createOutlinesAction.js.map +1 -1
  409. package/dist/interactions/actions/outlines/outlineStroke.js +5 -3
  410. package/dist/interactions/actions/outlines/outlineStroke.js.map +1 -1
  411. package/dist/interactions/actions/pathCommands/cutJoin.js +8 -5
  412. package/dist/interactions/actions/pathCommands/cutJoin.js.map +1 -1
  413. package/dist/interactions/actions/pathCommands/pathNodes.js +14 -5
  414. package/dist/interactions/actions/pathCommands/pathNodes.js.map +1 -1
  415. package/dist/interactions/actions/resize/cornerHandles.js +2 -1
  416. package/dist/interactions/actions/resize/cornerHandles.js.map +1 -1
  417. package/dist/interactions/actions/selectionSubtree.js +12 -7
  418. package/dist/interactions/actions/selectionSubtree.js.map +1 -1
  419. package/dist/interactions/actions/transform-again/action.js +8 -5
  420. package/dist/interactions/actions/transform-again/action.js.map +1 -1
  421. package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js +14 -2
  422. package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js.map +1 -1
  423. package/dist/json.d.ts +4 -0
  424. package/dist/json.js +3 -0
  425. package/dist/kitSettingsSchema.js +8 -1
  426. package/dist/kitSettingsSchema.js.map +1 -1
  427. package/dist/{math-CrJULaZI.d.ts → math-C_elShP_.d.ts} +7 -1
  428. package/dist/math.d.ts +1 -1
  429. package/dist/math.js +2 -1
  430. package/dist/move.d.ts +4 -4
  431. package/dist/{options-DBxEryYq.d.ts → options-ClEm3SEl.d.ts} +1 -1
  432. package/dist/resize.d.ts +4 -4
  433. package/dist/test-seams.d.ts +6 -6
  434. package/dist/tools/builtin/ellipse/useEllipseTool.js +1 -0
  435. package/dist/tools/builtin/ellipse/useEllipseTool.js.map +1 -1
  436. package/dist/tools/builtin/eyedropper/useEyedropperTool.js +2 -1
  437. package/dist/tools/builtin/eyedropper/useEyedropperTool.js.map +1 -1
  438. package/dist/tools/builtin/hand/dragPanContribution.js +4 -1
  439. package/dist/tools/builtin/hand/dragPanContribution.js.map +1 -1
  440. package/dist/tools/builtin/hand/useHandTool.js +7 -4
  441. package/dist/tools/builtin/hand/useHandTool.js.map +1 -1
  442. package/dist/tools/builtin/image/useImageTool.js +1 -0
  443. package/dist/tools/builtin/image/useImageTool.js.map +1 -1
  444. package/dist/tools/builtin/lasso/useLassoTool.js +1 -0
  445. package/dist/tools/builtin/lasso/useLassoTool.js.map +1 -1
  446. package/dist/tools/builtin/line/useLineTool.js +1 -0
  447. package/dist/tools/builtin/line/useLineTool.js.map +1 -1
  448. package/dist/tools/builtin/measure/useMeasureTool.js +12 -5
  449. package/dist/tools/builtin/measure/useMeasureTool.js.map +1 -1
  450. package/dist/tools/builtin/pen/usePenTool.js +14 -6
  451. package/dist/tools/builtin/pen/usePenTool.js.map +1 -1
  452. package/dist/tools/builtin/pencil/usePencilTool.js +1 -0
  453. package/dist/tools/builtin/pencil/usePencilTool.js.map +1 -1
  454. package/dist/tools/builtin/polygon/usePolygonTool.js +13 -4
  455. package/dist/tools/builtin/polygon/usePolygonTool.js.map +1 -1
  456. package/dist/tools/builtin/pressTarget.js +22 -0
  457. package/dist/tools/builtin/pressTarget.js.map +1 -0
  458. package/dist/tools/builtin/rect/useRectTool.js +1 -0
  459. package/dist/tools/builtin/rect/useRectTool.js.map +1 -1
  460. package/dist/tools/builtin/select/adapterPointQuery.js +6 -5
  461. package/dist/tools/builtin/select/adapterPointQuery.js.map +1 -1
  462. package/dist/tools/builtin/select/collapseDeferred.js +40 -0
  463. package/dist/tools/builtin/select/collapseDeferred.js.map +1 -0
  464. package/dist/tools/builtin/select/groupEntry.js +82 -0
  465. package/dist/tools/builtin/select/groupEntry.js.map +1 -0
  466. package/dist/tools/builtin/select/pressDecision.js +32 -0
  467. package/dist/tools/builtin/select/pressDecision.js.map +1 -0
  468. package/dist/tools/builtin/select/selectionContributions.js +22 -13
  469. package/dist/tools/builtin/select/selectionContributions.js.map +1 -1
  470. package/dist/tools/builtin/select/useSelectTool.js +74 -55
  471. package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
  472. package/dist/tools/builtin/slice/useSliceTool.js +22 -8
  473. package/dist/tools/builtin/slice/useSliceTool.js.map +1 -1
  474. package/dist/tools/builtin/star/useStarTool.js +13 -4
  475. package/dist/tools/builtin/star/useStarTool.js.map +1 -1
  476. package/dist/tools/builtin/sticky/stickyNode.js +4 -1
  477. package/dist/tools/builtin/sticky/stickyNode.js.map +1 -1
  478. package/dist/tools/builtin/sticky/useStickyTool.js +10 -5
  479. package/dist/tools/builtin/sticky/useStickyTool.js.map +1 -1
  480. package/dist/tools/builtin/text/useTextTool.js +3 -1
  481. package/dist/tools/builtin/text/useTextTool.js.map +1 -1
  482. package/dist/{types-7puAuVD2.d.ts → types-49uYJN3j.d.ts} +1 -1
  483. package/dist/{types-CniVctmk.d.ts → types-BEdRIhNc.d.ts} +272 -109
  484. package/dist/{types-oFeQ5VjV.d.ts → types-p2alu-R1.d.ts} +1 -1
  485. package/dist/util/paint.js +1 -3
  486. package/dist/util/paint.js.map +1 -1
  487. package/dist/version.js +1 -1
  488. package/package.json +29 -25
@@ -1 +1 @@
1
- {"version":3,"file":"poseCascade.js","names":[],"sources":["../../src/canvas/poseCascade.ts"],"sourcesContent":["import { poseDescriptorForNode, translatePoseViaDescriptor, type PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport type { NodeId } from 'core/scene/types';\nimport type { PoseCascade } from '../animation/poseTarget';\n\n/** The part of a scene a container's cascade reads. */\ninterface CascadeScene<TPose> {\n get(id: NodeId): { pose: TPose; kind?: 'leaf' | 'container' } | undefined;\n childrenOf(id: NodeId): readonly NodeId[];\n}\n\n/** The part of a scene a cascading `setPose` writes. */\ninterface CascadeTarget<TPose> extends CascadeScene<TPose> {\n setPose(id: NodeId, pose: TPose): void;\n batch<T>(label: string, fn: () => T): T;\n}\n\n/** Every node under `id`, each after its parent. */\nexport function descendantsOf(scene: Pick<CascadeScene<unknown>, 'childrenOf'>, id: NodeId): NodeId[] {\n const out: NodeId[] = [];\n const collect = (root: NodeId): void => {\n for (const child of scene.childrenOf(root)) {\n out.push(child);\n collect(child);\n }\n };\n collect(id);\n return out;\n}\n\n/**\n * How container `id`'s pose target carries its descendants where each holds a pose of its own\n * in the same space: `write` commits a pose and moves them, and while the container shows\n * somewhere else each is shown moved by as much.\n */\nexport function containerCascade<TPose>(\n scene: CascadeScene<TPose>,\n id: NodeId,\n d: PoseDescriptor<TPose>,\n write: (pose: TPose) => void,\n): PoseCascade<TPose> {\n return {\n write,\n *beside(pose) {\n const node = scene.get(id);\n if (!node) return;\n const g = poseDescriptorForNode(d, node);\n const from = g.getBounds(node.pose);\n const to = g.getBounds(pose);\n for (const child of descendantsOf(scene, id)) {\n const n = scene.get(child);\n if (!n) continue;\n yield [child, translatePoseViaDescriptor(n.pose, to.x - from.x, to.y - from.y, poseDescriptorForNode(d, n))];\n }\n },\n };\n}\n\n/**\n * `setPose` for a scene of absolute poses: posing a container moves every\n * descendant by as much, in one undo step.\n */\nexport function cascadingSetPose<TPose>(\n scene: CascadeTarget<TPose>,\n d: PoseDescriptor<TPose>,\n): (id: NodeId, pose: TPose) => void {\n return (id, pose) => {\n const node = scene.get(id);\n if (!node || node.kind !== 'container') return scene.setPose(id, pose);\n const g = poseDescriptorForNode(d, node);\n const from = g.getBounds(node.pose);\n const to = g.getBounds(pose);\n const dx = to.x - from.x;\n const dy = to.y - from.y;\n if (dx === 0 && dy === 0) return scene.setPose(id, pose);\n scene.batch('move container', () => {\n scene.setPose(id, pose);\n for (const child of descendantsOf(scene, id)) {\n const n = scene.get(child);\n if (!n) continue;\n scene.setPose(child, translatePoseViaDescriptor(n.pose, dx, dy, poseDescriptorForNode(d, n)));\n }\n });\n };\n}\n"],"mappings":";;;;AAiBA,SAAgB,cAAc,OAAkD,IAAsB;CACpG,MAAM,MAAgB,CAAC;CACvB,MAAM,WAAW,SAAuB;EACtC,KAAK,MAAM,SAAS,MAAM,WAAW,IAAI,GAAG;GAC1C,IAAI,KAAK,KAAK;GACd,QAAQ,KAAK;EACf;CACF;CACA,QAAQ,EAAE;CACV,OAAO;AACT;;;;;;AAOA,SAAgB,iBACd,OACA,IACA,GACA,OACoB;CACpB,OAAO;EACL;EACA,CAAC,OAAO,MAAM;GACZ,MAAM,OAAO,MAAM,IAAI,EAAE;GACzB,IAAI,CAAC,MAAM;GACX,MAAM,IAAI,sBAAsB,GAAG,IAAI;GACvC,MAAM,OAAO,EAAE,UAAU,KAAK,IAAI;GAClC,MAAM,KAAK,EAAE,UAAU,IAAI;GAC3B,KAAK,MAAM,SAAS,cAAc,OAAO,EAAE,GAAG;IAC5C,MAAM,IAAI,MAAM,IAAI,KAAK;IACzB,IAAI,CAAC,GAAG;IACR,MAAM,CAAC,OAAO,2BAA2B,EAAE,MAAM,GAAG,IAAI,KAAK,GAAG,GAAG,IAAI,KAAK,GAAG,sBAAsB,GAAG,CAAC,CAAC,CAAC;GAC7G;EACF;CACF;AACF;;;;;AAMA,SAAgB,iBACd,OACA,GACmC;CACnC,QAAQ,IAAI,SAAS;EACnB,MAAM,OAAO,MAAM,IAAI,EAAE;EACzB,IAAI,CAAC,QAAQ,KAAK,SAAS,aAAa,OAAO,MAAM,QAAQ,IAAI,IAAI;EACrE,MAAM,IAAI,sBAAsB,GAAG,IAAI;EACvC,MAAM,OAAO,EAAE,UAAU,KAAK,IAAI;EAClC,MAAM,KAAK,EAAE,UAAU,IAAI;EAC3B,MAAM,KAAK,GAAG,IAAI,KAAK;EACvB,MAAM,KAAK,GAAG,IAAI,KAAK;EACvB,IAAI,OAAO,KAAK,OAAO,GAAG,OAAO,MAAM,QAAQ,IAAI,IAAI;EACvD,MAAM,MAAM,wBAAwB;GAClC,MAAM,QAAQ,IAAI,IAAI;GACtB,KAAK,MAAM,SAAS,cAAc,OAAO,EAAE,GAAG;IAC5C,MAAM,IAAI,MAAM,IAAI,KAAK;IACzB,IAAI,CAAC,GAAG;IACR,MAAM,QAAQ,OAAO,2BAA2B,EAAE,MAAM,IAAI,IAAI,sBAAsB,GAAG,CAAC,CAAC,CAAC;GAC9F;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"poseCascade.js","names":[],"sources":["../../src/canvas/poseCascade.ts"],"sourcesContent":["import { poseDescriptorForNode, translatePoseViaDescriptor, type PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport type { NodeId } from 'core/scene/types';\nimport type { PoseCascade } from '../animation/poseTarget';\n\n/** The part of a scene a container's cascade reads. */\ninterface CascadeScene<TPose> {\n get(id: NodeId): { pose: TPose; kind?: 'mark' | 'group' } | undefined;\n childrenOf(id: NodeId): readonly NodeId[];\n}\n\n/** The part of a scene a cascading `setPose` writes. */\ninterface CascadeTarget<TPose> extends CascadeScene<TPose> {\n setPose(id: NodeId, pose: TPose): void;\n batch<T>(label: string, fn: () => T): T;\n}\n\n/** Every node under `id`, each after its parent. */\nexport function descendantsOf(scene: Pick<CascadeScene<unknown>, 'childrenOf'>, id: NodeId): NodeId[] {\n const out: NodeId[] = [];\n const collect = (root: NodeId): void => {\n for (const child of scene.childrenOf(root)) {\n out.push(child);\n collect(child);\n }\n };\n collect(id);\n return out;\n}\n\n/**\n * How container `id`'s pose target carries its descendants where each holds a pose of its own\n * in the same space: `write` commits a pose and moves them, and while the container shows\n * somewhere else each is shown moved by as much.\n */\nexport function containerCascade<TPose>(\n scene: CascadeScene<TPose>,\n id: NodeId,\n d: PoseDescriptor<TPose>,\n write: (pose: TPose) => void,\n): PoseCascade<TPose> {\n return {\n write,\n *beside(pose) {\n const node = scene.get(id);\n if (!node) return;\n const g = poseDescriptorForNode(d, node);\n const from = g.getBounds(node.pose);\n const to = g.getBounds(pose);\n for (const child of descendantsOf(scene, id)) {\n const n = scene.get(child);\n if (!n) continue;\n yield [child, translatePoseViaDescriptor(n.pose, to.x - from.x, to.y - from.y, poseDescriptorForNode(d, n))];\n }\n },\n };\n}\n\n/**\n * `setPose` for a scene of absolute poses: posing a container moves every\n * descendant by as much, in one undo step.\n */\nexport function cascadingSetPose<TPose>(\n scene: CascadeTarget<TPose>,\n d: PoseDescriptor<TPose>,\n): (id: NodeId, pose: TPose) => void {\n return (id, pose) => {\n const node = scene.get(id);\n if (!node || node.kind !== 'group') return scene.setPose(id, pose);\n const g = poseDescriptorForNode(d, node);\n const from = g.getBounds(node.pose);\n const to = g.getBounds(pose);\n const dx = to.x - from.x;\n const dy = to.y - from.y;\n if (dx === 0 && dy === 0) return scene.setPose(id, pose);\n scene.batch('move container', () => {\n scene.setPose(id, pose);\n for (const child of descendantsOf(scene, id)) {\n const n = scene.get(child);\n if (!n) continue;\n scene.setPose(child, translatePoseViaDescriptor(n.pose, dx, dy, poseDescriptorForNode(d, n)));\n }\n });\n };\n}\n"],"mappings":";;;;AAiBA,SAAgB,cAAc,OAAkD,IAAsB;CACpG,MAAM,MAAgB,CAAC;CACvB,MAAM,WAAW,SAAuB;EACtC,KAAK,MAAM,SAAS,MAAM,WAAW,IAAI,GAAG;GAC1C,IAAI,KAAK,KAAK;GACd,QAAQ,KAAK;EACf;CACF;CACA,QAAQ,EAAE;CACV,OAAO;AACT;;;;;;AAOA,SAAgB,iBACd,OACA,IACA,GACA,OACoB;CACpB,OAAO;EACL;EACA,CAAC,OAAO,MAAM;GACZ,MAAM,OAAO,MAAM,IAAI,EAAE;GACzB,IAAI,CAAC,MAAM;GACX,MAAM,IAAI,sBAAsB,GAAG,IAAI;GACvC,MAAM,OAAO,EAAE,UAAU,KAAK,IAAI;GAClC,MAAM,KAAK,EAAE,UAAU,IAAI;GAC3B,KAAK,MAAM,SAAS,cAAc,OAAO,EAAE,GAAG;IAC5C,MAAM,IAAI,MAAM,IAAI,KAAK;IACzB,IAAI,CAAC,GAAG;IACR,MAAM,CAAC,OAAO,2BAA2B,EAAE,MAAM,GAAG,IAAI,KAAK,GAAG,GAAG,IAAI,KAAK,GAAG,sBAAsB,GAAG,CAAC,CAAC,CAAC;GAC7G;EACF;CACF;AACF;;;;;AAMA,SAAgB,iBACd,OACA,GACmC;CACnC,QAAQ,IAAI,SAAS;EACnB,MAAM,OAAO,MAAM,IAAI,EAAE;EACzB,IAAI,CAAC,QAAQ,KAAK,SAAS,SAAS,OAAO,MAAM,QAAQ,IAAI,IAAI;EACjE,MAAM,IAAI,sBAAsB,GAAG,IAAI;EACvC,MAAM,OAAO,EAAE,UAAU,KAAK,IAAI;EAClC,MAAM,KAAK,EAAE,UAAU,IAAI;EAC3B,MAAM,KAAK,GAAG,IAAI,KAAK;EACvB,MAAM,KAAK,GAAG,IAAI,KAAK;EACvB,IAAI,OAAO,KAAK,OAAO,GAAG,OAAO,MAAM,QAAQ,IAAI,IAAI;EACvD,MAAM,MAAM,wBAAwB;GAClC,MAAM,QAAQ,IAAI,IAAI;GACtB,KAAK,MAAM,SAAS,cAAc,OAAO,EAAE,GAAG;IAC5C,MAAM,IAAI,MAAM,IAAI,KAAK;IACzB,IAAI,CAAC,GAAG;IACR,MAAM,QAAQ,OAAO,2BAA2B,EAAE,MAAM,IAAI,IAAI,sBAAsB,GAAG,CAAC,CAAC,CAAC;GAC9F;EACF,CAAC;CACH;AACF"}
@@ -0,0 +1,97 @@
1
+ import { isPlainObject } from "@weasel-js/registry";
2
+
3
+ //#region src/canvas/publishPreviews.ts
4
+ /**
5
+ * `publishPreviews` — what in-flight handles propose, published to the scene.
6
+ *
7
+ * A handle answering `previewPose` / `previewData` shows its proposal in the
8
+ * preview ghost, which nothing else reads. Publishing it as the scene's pose
9
+ * and data overrides is what lets the scene's other readers see it: a path
10
+ * effect over a path whose anchors are being dragged, text laid along it, a
11
+ * second view of the same scene.
12
+ */
13
+ /**
14
+ * Publish every in-flight handle's `previewPose` and `previewData` to
15
+ * `scene`'s overrides each time `dispatcher` notifies, through one hold, and
16
+ * release them when the handles end. Returns the unsubscribe, which also
17
+ * releases what is still published.
18
+ *
19
+ * Previewed data is shown as the fields it changes from what the node stored
20
+ * when its preview began, laid over what the node stores now: a write made
21
+ * mid-gesture, or its undo, shows through, as it will be kept when the edit
22
+ * commits against the node as it then stands. Data that is not a plain
23
+ * object is shown as it is.
24
+ *
25
+ * A handle with `previewHidesSource: false` previews a copy rather than its
26
+ * source, so it is left out. On an id another writer's override already holds —
27
+ * a transform's own frame, a live route — the preview is a ply over it, so a
28
+ * field the handle does not propose shows what that writer says. The dispatcher
29
+ * notifies after a handle's `onEnd`, so a commit has landed before its preview
30
+ * goes.
31
+ */
32
+ function publishPreviews(scene, dispatcher) {
33
+ const hold = scene.overrides.hold();
34
+ const shownData = /* @__PURE__ */ new Map();
35
+ const dataFor = (id, value) => {
36
+ const held = shownData.get(id);
37
+ if (held !== void 0 && held.value === value) return held.data;
38
+ const origin = held !== void 0 ? held.origin : scene.get(id)?.data;
39
+ const data = changesOver(origin, value);
40
+ shownData.set(id, {
41
+ origin,
42
+ value,
43
+ data
44
+ });
45
+ return data;
46
+ };
47
+ const publish = () => {
48
+ const frame = /* @__PURE__ */ new Map();
49
+ for (const handle of dispatcher.getInFlightHandles()) {
50
+ if (handle.previewHidesSource === false) continue;
51
+ collect(handle, frame, (id) => scene.get(id) !== void 0, dataFor);
52
+ }
53
+ for (const id of shownData.keys()) if (frame.get(id)?.data === void 0) shownData.delete(id);
54
+ if (frame.size === 0) hold.drop();
55
+ else hold.show(frame);
56
+ };
57
+ const unsubscribe = dispatcher.subscribe(publish);
58
+ publish();
59
+ return () => {
60
+ unsubscribe();
61
+ hold.drop();
62
+ shownData.clear();
63
+ };
64
+ }
65
+ /** `(stored) => value`'s changes from `origin` laid over `stored`. */
66
+ function changesOver(origin, value) {
67
+ if (!isPlainObject(origin) || !isPlainObject(value)) return () => value;
68
+ const changed = /* @__PURE__ */ new Set();
69
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(origin), ...Object.keys(value)])) if (origin[key] !== value[key]) changed.add(key);
70
+ return (stored) => {
71
+ if (stored === origin || !isPlainObject(stored)) return value;
72
+ const out = { ...stored };
73
+ for (const key of changed) if (key in value) out[key] = value[key];
74
+ else delete out[key];
75
+ return out;
76
+ };
77
+ }
78
+ /** `handle`'s proposals into `frame`, first answer per id winning. */
79
+ function collect(handle, frame, exists, dataFor) {
80
+ const ids = handle.previewIds?.();
81
+ if (!ids) return;
82
+ for (const raw of ids) {
83
+ const id = raw;
84
+ if (frame.has(id) || !exists(id)) continue;
85
+ const pose = handle.previewPose?.(raw);
86
+ const data = handle.previewData?.(raw);
87
+ if (pose == null && data == null) continue;
88
+ frame.set(id, {
89
+ ...pose == null ? {} : { pose },
90
+ ...data == null ? {} : { data: dataFor(id, data) }
91
+ });
92
+ }
93
+ }
94
+
95
+ //#endregion
96
+ export { publishPreviews };
97
+ //# sourceMappingURL=publishPreviews.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publishPreviews.js","names":[],"sources":["../../src/canvas/publishPreviews.ts"],"sourcesContent":["/**\n * `publishPreviews` — what in-flight handles propose, published to the scene.\n *\n * A handle answering `previewPose` / `previewData` shows its proposal in the\n * preview ghost, which nothing else reads. Publishing it as the scene's pose\n * and data overrides is what lets the scene's other readers see it: a path\n * effect over a path whose anchors are being dragged, text laid along it, a\n * second view of the same scene.\n */\nimport { isPlainObject } from '@weasel-js/registry';\nimport type { Dispatcher, OngoingHandle } from '@weasel-js/routing';\nimport type { NodeId, Scene, ShownOverride } from 'core/scene/types';\n\ntype Fields = Record<string, unknown>;\n\n/** One id's previewed data and the function showing it, kept while the handle answers the same data. */\ninterface ShownData<TData> {\n /** What the node stored when its preview began: what the handle's data was worked out from. */\n origin: unknown;\n value: unknown;\n data: (stored: TData) => TData;\n}\n\n/**\n * Publish every in-flight handle's `previewPose` and `previewData` to\n * `scene`'s overrides each time `dispatcher` notifies, through one hold, and\n * release them when the handles end. Returns the unsubscribe, which also\n * releases what is still published.\n *\n * Previewed data is shown as the fields it changes from what the node stored\n * when its preview began, laid over what the node stores now: a write made\n * mid-gesture, or its undo, shows through, as it will be kept when the edit\n * commits against the node as it then stands. Data that is not a plain\n * object is shown as it is.\n *\n * A handle with `previewHidesSource: false` previews a copy rather than its\n * source, so it is left out. On an id another writer's override already holds —\n * a transform's own frame, a live route — the preview is a ply over it, so a\n * field the handle does not propose shows what that writer says. The dispatcher\n * notifies after a handle's `onEnd`, so a commit has landed before its preview\n * goes.\n */\nexport function publishPreviews<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n dispatcher: Pick<Dispatcher, 'getInFlightHandles' | 'subscribe'>,\n): () => void {\n const hold = scene.overrides.hold();\n const shownData = new Map<NodeId, ShownData<TData>>();\n\n const dataFor = (id: NodeId, value: unknown): ((stored: TData) => TData) => {\n const held = shownData.get(id);\n if (held !== undefined && held.value === value) return held.data;\n const origin = held !== undefined ? held.origin : scene.get(id)?.data;\n const data = changesOver(origin, value) as (stored: TData) => TData;\n shownData.set(id, { origin, value, data });\n return data;\n };\n\n const publish = (): void => {\n const frame = new Map<NodeId, ShownOverride<TPose, TData>>();\n for (const handle of dispatcher.getInFlightHandles()) {\n if (handle.previewHidesSource === false) continue;\n collect(handle, frame, (id) => scene.get(id) !== undefined, dataFor);\n }\n for (const id of shownData.keys()) {\n if (frame.get(id)?.data === undefined) shownData.delete(id);\n }\n if (frame.size === 0) hold.drop();\n else hold.show(frame);\n };\n\n const unsubscribe = dispatcher.subscribe(publish);\n publish();\n return () => {\n unsubscribe();\n hold.drop();\n shownData.clear();\n };\n}\n\n/** `(stored) => value`'s changes from `origin` laid over `stored`. */\nfunction changesOver(origin: unknown, value: unknown): (stored: unknown) => unknown {\n if (!isPlainObject(origin) || !isPlainObject(value)) return () => value;\n const changed = new Set<string>();\n for (const key of new Set([...Object.keys(origin), ...Object.keys(value)])) {\n if (origin[key] !== value[key]) changed.add(key);\n }\n return (stored) => {\n if (stored === origin || !isPlainObject(stored)) return value;\n const out: Fields = { ...stored };\n for (const key of changed) {\n if (key in value) out[key] = value[key];\n else delete out[key];\n }\n return out;\n };\n}\n\n/** `handle`'s proposals into `frame`, first answer per id winning. */\nfunction collect<TPose, TData>(\n handle: OngoingHandle,\n frame: Map<NodeId, ShownOverride<TPose, TData>>,\n exists: (id: NodeId) => boolean,\n dataFor: (id: NodeId, value: unknown) => (stored: TData) => TData,\n): void {\n const ids = handle.previewIds?.();\n if (!ids) return;\n for (const raw of ids) {\n const id = raw as NodeId;\n if (frame.has(id) || !exists(id)) continue;\n const pose = handle.previewPose?.(raw);\n const data = handle.previewData?.(raw);\n if (pose == null && data == null) continue;\n frame.set(id, {\n ...(pose == null ? {} : { pose: pose as TPose }),\n ...(data == null ? {} : { data: dataFor(id, data) }),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,gBACd,OACA,YACY;CACZ,MAAM,OAAO,MAAM,UAAU,KAAK;CAClC,MAAM,4BAAY,IAAI,IAA8B;CAEpD,MAAM,WAAW,IAAY,UAA+C;EAC1E,MAAM,OAAO,UAAU,IAAI,EAAE;EAC7B,IAAI,SAAS,UAAa,KAAK,UAAU,OAAO,OAAO,KAAK;EAC5D,MAAM,SAAS,SAAS,SAAY,KAAK,SAAS,MAAM,IAAI,EAAE,CAAC,EAAE;EACjE,MAAM,OAAO,YAAY,QAAQ,KAAK;EACtC,UAAU,IAAI,IAAI;GAAE;GAAQ;GAAO;EAAK,CAAC;EACzC,OAAO;CACT;CAEA,MAAM,gBAAsB;EAC1B,MAAM,wBAAQ,IAAI,IAAyC;EAC3D,KAAK,MAAM,UAAU,WAAW,mBAAmB,GAAG;GACpD,IAAI,OAAO,uBAAuB,OAAO;GACzC,QAAQ,QAAQ,QAAQ,OAAO,MAAM,IAAI,EAAE,MAAM,QAAW,OAAO;EACrE;EACA,KAAK,MAAM,MAAM,UAAU,KAAK,GAC9B,IAAI,MAAM,IAAI,EAAE,CAAC,EAAE,SAAS,QAAW,UAAU,OAAO,EAAE;EAE5D,IAAI,MAAM,SAAS,GAAG,KAAK,KAAK;OAC3B,KAAK,KAAK,KAAK;CACtB;CAEA,MAAM,cAAc,WAAW,UAAU,OAAO;CAChD,QAAQ;CACR,aAAa;EACX,YAAY;EACZ,KAAK,KAAK;EACV,UAAU,MAAM;CAClB;AACF;;AAGA,SAAS,YAAY,QAAiB,OAA8C;CAClF,IAAI,CAAC,cAAc,MAAM,KAAK,CAAC,cAAc,KAAK,GAAG,aAAa;CAClE,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,KAAK,CAAC,CAAC,GACvE,IAAI,OAAO,SAAS,MAAM,MAAM,QAAQ,IAAI,GAAG;CAEjD,QAAQ,WAAW;EACjB,IAAI,WAAW,UAAU,CAAC,cAAc,MAAM,GAAG,OAAO;EACxD,MAAM,MAAc,EAAE,GAAG,OAAO;EAChC,KAAK,MAAM,OAAO,SAChB,IAAI,OAAO,OAAO,IAAI,OAAO,MAAM;OAC9B,OAAO,IAAI;EAElB,OAAO;CACT;AACF;;AAGA,SAAS,QACP,QACA,OACA,QACA,SACM;CACN,MAAM,MAAM,OAAO,aAAa;CAChC,IAAI,CAAC,KAAK;CACV,KAAK,MAAM,OAAO,KAAK;EACrB,MAAM,KAAK;EACX,IAAI,MAAM,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG;EAClC,MAAM,OAAO,OAAO,cAAc,GAAG;EACrC,MAAM,OAAO,OAAO,cAAc,GAAG;EACrC,IAAI,QAAQ,QAAQ,QAAQ,MAAM;EAClC,MAAM,IAAI,IAAI;GACZ,GAAI,QAAQ,OAAO,CAAC,IAAI,EAAQ,KAAc;GAC9C,GAAI,QAAQ,OAAO,CAAC,IAAI,EAAE,MAAM,QAAQ,IAAI,IAAI,EAAE;EACpD,CAAC;CACH;AACF"}
@@ -151,7 +151,7 @@ function createRasterSession(options = {}) {
151
151
  });
152
152
  renderer.setFlattenTolerance(flattenTolerance);
153
153
  }
154
- renderer.render(plan.commands, viewToMat3$1(plan.view));
154
+ renderer.render(plan.commands, viewToMat3$1(plan.view), { screen: args.screen });
155
155
  if (isLost(ctx)) throw new Error("raster session: the WebGL2 context was lost during render");
156
156
  const raw = new Uint8Array(width * height * 4);
157
157
  ctx.readPixels(0, 0, width, height, ctx.RGBA, ctx.UNSIGNED_BYTE, raw);
@@ -1 +1 @@
1
- {"version":3,"file":"renderSceneToPixels.js","names":["viewToMat3"],"sources":["../../src/canvas/renderSceneToPixels.ts"],"sourcesContent":["/**\n * `renderSceneToPixels` — headless rasterization of a scene-space rect to raw RGBA pixels at an\n * explicit, per-axis scale. It drives the same WebGL2 pipeline (`WeaselRenderer` +\n * `buildSceneViewCommands`) as the on-screen view, so print, thumbnail, and export callers get\n * the same pixels the screen would produce at that scale.\n *\n * Environment contract:\n * - Density arrives exclusively via `scale`; this function never reads\n * `window.devicePixelRatio`.\n * - Rounding: output width = max(1, round(sourceRect.width × |scale.x|)), height analogously.\n * When round() lands below rect × scale, the rightmost/bottom sub-pixel band of scene content\n * is cropped; when it rounds up, that band is padded (the `background` fill, or transparent).\n * - Context lifetime: a caller-supplied `gl` is caller-owned. It is never disposed here, and\n * its drawing buffer must be at least width × height pixels (the render targets the\n * bottom-left region). Auto-created canvases are discarded with the session.\n * - Context loss: throws — a lost context cannot produce pixels, and the silent-noop\n * convention of the screen path would return all-zero bytes.\n * - Output: top-down row order, NON-premultiplied (\"straight\") RGBA. The GL framebuffer is\n * premultiplied and bottom-up; readback flips and unpremultiplies.\n * - Determinism: same context + same inputs → same bytes. Cross-driver / cross-machine byte\n * equality is NOT guaranteed; do not build golden-image tests on committed bytes.\n * - Image quality: image textures upload with mipmaps so minified bitmaps don't moiré, and\n * curve tessellation runs at an output-scale tolerance (`flattenTolerancePx`, default 0.25\n * output px).\n */\nimport { WeaselRenderer } from '@weasel-js/renderer';\nimport { viewToMat3 } from '@weasel-js/geom';\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { View } from '../core/viewport/view';\nimport type { Node, Scene } from 'core/scene/types';\nimport { buildSceneViewCommands, type SceneViewDrawOne } from './sceneViewRender';\nimport type { ColorOverrideRegistry } from '@weasel-js/animator';\nimport { defaultDrawOne } from './defaultDrawOne';\nimport { warmFonts, type FontRequest } from '@weasel-js/font';\nimport { isPaintKindKnown, warmPaintKinds } from '@weasel-js/renderer';\nimport { renderNeeds } from './renderNeeds';\nimport { straightTopDown } from './rasterReadback';\nimport { annotationLayerIds } from 'core/scene/annotation';\nimport { sceneLayerKey } from './sceneLayerPaint';\nimport { CANVAS_CONTEXT_ATTRIBUTES } from './contextAttributes';\n\n/** Plain RGBA raster — structurally `ImageData`-compatible ({ width, height,\n * data }), deliberately free of printer/dpi/physical-unit concepts. */\nexport interface RasterImage {\n width: number;\n height: number;\n /** Top-down, straight (non-premultiplied) RGBA, 4 bytes per pixel. */\n data: Uint8ClampedArray;\n}\n\n/** Minimal canvas contract for `createCanvas` injection: `OffscreenCanvas`,\n * an HTML canvas, or a test fake. */\nexport interface HeadlessCanvasLike {\n width: number;\n height: number;\n getContext(contextId: 'webgl2', options?: WebGLContextAttributes): unknown;\n}\n\n/** What to render, at what resolution, and with which quality settings. */\nexport interface RenderSceneToPixelsArgs<TData, TLayer extends string, TPose> {\n scene: Scene<TData, TLayer, TPose>;\n /** Scene-space rect to render (origin + size in scene units). Output pixel\n * dimensions follow from rect × scale (round, min 1 — see module doc). */\n sourceRect: { x: number; y: number; width: number; height: number };\n /** Output pixels per scene unit, per axis. Anisotropic values supported. A\n * negative axis is flipped: the output is sized from its magnitude, and the\n * rect's far edge on that axis lands on the output's top or left. */\n scale: { x: number; y: number };\n /** Per-node draw callback. Default: `defaultDrawOne` with `resolveImage`\n * merged into the `NodePaintCtx` the scene walk supplies. Custom `drawOne`\n * callers that still want resolver injection should call\n * `defaultDrawOne(node, pose, view, { ...ctx, resolveImage })` themselves —\n * dropping the walk's `ctx` drops derived geometry with it. */\n drawOne?: SceneViewDrawOne<TData, TLayer, TPose>;\n /** Bitmap resolver for image nodes — lets consumers reuse their own decode\n * caches. `undefined` results paint the deterministic grey placeholder\n * outline (see `NodePaintCtx.resolveImage`). */\n resolveImage?: (node: Node<TData, TLayer, TPose>) => ImageBitmap | undefined;\n /** Per-id alpha multiplier, mirroring `<SceneCanvas>`'s scene-slot\n * `alphaFor`. Pass the same function the on-screen canvas uses so an\n * export matches what the user is looking at. Defaults to `() => 1`. */\n alphaFor?: (id: string) => number;\n /** Animated vertex colors to paint, typically an animator's\n * `colorOverrides`, so an export shows the frame on screen. */\n colorOverrides?: ColorOverrideRegistry;\n /** Background fill (any CSS color accepted by the renderer). Default:\n * fully transparent. Passing a color is always valid. */\n background?: string;\n /** Caller-owned WebGL2 context to render with. Mutually exclusive with\n * `createCanvas`. Never disposed by this call. */\n gl?: WebGL2RenderingContext;\n /** One-shot canvas factory (DOM canvas, OffscreenCanvas, or test fake).\n * Mutually exclusive with `gl`. Default: `OffscreenCanvas` when\n * available, else `document.createElement('canvas')`. */\n createCanvas?: (widthPx: number, heightPx: number) => HeadlessCanvasLike;\n /** Max curve-flattening error in OUTPUT pixels. Default 0.25. Measured\n * along each path's most stretched axis. */\n flattenTolerancePx?: number;\n /** Commands drawn over the scene in output-pixel space — origin at the\n * output's top-left, one unit per output pixel. Annotations, watermarks,\n * and `renderDebugSnapshot`'s overlay ride here. */\n overlay?: readonly DrawCommand[];\n /** Draw the scene's annotation layers (`isAnnotationLayer`). Default\n * `false`: a raster is an export, which leaves them out as the SVG export\n * does. Pass `true` to reproduce the canvas as it looked. */\n annotations?: boolean;\n}\n\n/** The result of planning a headless render: how big the output is, the view\n * that maps the source rect onto it, and the commands to draw. */\nexport interface PixelRenderPlan {\n width: number;\n height: number;\n view: View;\n commands: DrawCommand[];\n}\n\n/** Pure planning half of `renderSceneToPixels`: output dimensions, the\n * anisotropic `View`, and the full command list (background + view-wrapped\n * scene). Exported for tests and for callers targeting their own renderer. */\nexport function planPixelRender<TData, TLayer extends string, TPose>(\n args: Omit<RenderSceneToPixelsArgs<TData, TLayer, TPose>, 'gl' | 'createCanvas' | 'flattenTolerancePx'>,\n): PixelRenderPlan {\n const { sourceRect, scale } = args;\n for (const [label, v] of [\n ['sourceRect.width', sourceRect.width], ['sourceRect.height', sourceRect.height],\n ] as const) {\n if (!Number.isFinite(v) || v <= 0) {\n throw new Error(`renderSceneToPixels: ${label} must be a positive finite number, got ${v}`);\n }\n }\n for (const [label, v] of [['scale.x', scale.x], ['scale.y', scale.y]] as const) {\n if (!Number.isFinite(v) || v === 0) {\n throw new Error(`renderSceneToPixels: ${label} must be a nonzero finite number, got ${v}`);\n }\n }\n for (const [label, v] of [\n ['sourceRect.x', sourceRect.x], ['sourceRect.y', sourceRect.y],\n ] as const) {\n if (!Number.isFinite(v)) {\n throw new Error(`renderSceneToPixels: ${label} must be a finite number, got ${v}`);\n }\n }\n const width = Math.max(1, Math.round(sourceRect.width * Math.abs(scale.x)));\n const height = Math.max(1, Math.round(sourceRect.height * Math.abs(scale.y)));\n const view: View = {\n x: scale.x < 0 ? sourceRect.x + sourceRect.width : sourceRect.x,\n y: scale.y < 0 ? sourceRect.y + sourceRect.height : sourceRect.y,\n scale: { x: scale.x, y: scale.y },\n };\n\n const resolveImage = args.resolveImage as ((n: Node<unknown, string, unknown>) => ImageBitmap | undefined) | undefined;\n const drawOne: SceneViewDrawOne<TData, TLayer, TPose> =\n args.drawOne ?? ((node, pose, view, ctx) => defaultDrawOne(node, pose, view, { ...ctx, resolveImage }));\n\n const commands: DrawCommand[] = [];\n if (args.background !== undefined) {\n // Screen-space (pre-view) fill so rounding can never leave uncovered\n // edge pixels.\n commands.push({\n kind: 'path',\n path: { kind: 'rect', x: 0, y: 0, width, height },\n fill: { paint: { kind: 'solid', color: args.background } },\n });\n }\n const layers = args.annotations ? undefined : {\n layerVisibility: Object.fromEntries([...annotationLayerIds(args.scene.layers)].map((id) => [sceneLayerKey(id), false])),\n };\n commands.push(...buildSceneViewCommands(\n args.scene, view, drawOne, undefined, args.alphaFor, layers, args.colorOverrides,\n ));\n if (args.overlay) commands.push(...args.overlay);\n return { width, height, view, commands };\n}\n\nfunction defaultCreateCanvas(width: number, height: number): HeadlessCanvasLike {\n if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(width, height);\n }\n if (typeof document !== 'undefined') {\n const c = document.createElement('canvas');\n c.width = width;\n c.height = height;\n return c;\n }\n throw new Error('renderSceneToPixels: no canvas source in this environment — supply `gl` or `createCanvas`');\n}\n\n/** Where a {@link RasterSession} draws. Pass `gl` or `createCanvas`, or\n * neither for the default canvas source. */\nexport interface RasterSessionOptions {\n /** Caller-owned WebGL2 context. The session never disposes it. Its drawing\n * buffer must be at least as large as every render the session does. */\n gl?: WebGL2RenderingContext;\n /** Canvas factory, called once, at the size of the first render. The\n * session grows the canvas when a later render needs more room and never\n * shrinks it. Default: `OffscreenCanvas` when available, else a detached\n * DOM canvas. */\n createCanvas?: (widthPx: number, heightPx: number) => HeadlessCanvasLike;\n}\n\n/** One render through a {@link RasterSession}: everything\n * `renderSceneToPixels` takes except where to draw. */\nexport type RasterRenderArgs<TData, TLayer extends string, TPose> =\n Omit<RenderSceneToPixelsArgs<TData, TLayer, TPose>, 'gl' | 'createCanvas'>;\n\n/** One renderer and its GPU caches, kept across any number of headless\n * renders. Scenes, source rects and scales may differ per render. */\nexport interface RasterSession {\n /** Same contract as `renderSceneToPixels`. Throws once disposed. */\n render<TData, TLayer extends string, TPose>(args: RasterRenderArgs<TData, TLayer, TPose>): RasterImage;\n /** Free every GL resource the session created — programs, geometry, and\n * the texture and mesh caches — and drop its own canvas. A caller-owned\n * context stays open. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Open a raster session: one `WeaselRenderer` that many headless renders\n * share, for a consumer producing thumbnails or pages in bulk. Programs\n * compile once, and a bitmap or recurring mesh uploads once, rather than per\n * render. `renderSceneToPixels` is a session opened for one render.\n *\n * The renderer is created on the first render, so opening a session costs\n * nothing and fails nothing. Each render draws into the bottom-left\n * `width × height` of the buffer and reads that region back.\n */\nexport function createRasterSession(options: RasterSessionOptions = {}): RasterSession {\n if (options.gl && options.createCanvas) {\n throw new Error('raster session: `gl` and `createCanvas` are mutually exclusive');\n }\n let canvas: HeadlessCanvasLike | null = null;\n let gl: WebGL2RenderingContext | undefined = options.gl;\n let renderer: WeaselRenderer | null = null;\n let disposed = false;\n\n function contextFor(width: number, height: number): WebGL2RenderingContext {\n if (!options.gl) {\n if (!canvas) {\n canvas = (options.createCanvas ?? defaultCreateCanvas)(width, height);\n canvas.width = width;\n canvas.height = height;\n gl = (canvas.getContext('webgl2', CANVAS_CONTEXT_ATTRIBUTES) as WebGL2RenderingContext | null) ?? undefined;\n } else {\n if (canvas.width < width) canvas.width = width;\n if (canvas.height < height) canvas.height = height;\n }\n }\n if (!gl || typeof (gl as Partial<WebGL2RenderingContext>).enable !== 'function') {\n throw new Error('raster session: WebGL2 is unavailable — supply `gl` or a WebGL2-capable `createCanvas`');\n }\n if (isLost(gl)) {\n throw new Error('raster session: the WebGL2 context is lost — dispose this session and open another');\n }\n // A context clamps a drawing buffer it cannot allocate, and reading past\n // the real one returns transparent pixels rather than failing.\n const { drawingBufferWidth: bufferW, drawingBufferHeight: bufferH } = gl;\n if (bufferW < width || bufferH < height) {\n throw new Error(\n `raster session: a ${width} × ${height} render does not fit the context's `\n + `${bufferW} × ${bufferH} drawing buffer — lower \\`scale\\` or render the source rect in tiles`,\n );\n }\n return gl;\n }\n\n return {\n render(args) {\n if (disposed) throw new Error('raster session: render() on a disposed session');\n const plan = planPixelRender(args);\n const { width, height } = plan;\n const ctx = contextFor(width, height);\n const flattenTolerance = { px: args.flattenTolerancePx ?? 0.25 };\n if (!renderer) {\n renderer = new WeaselRenderer({\n gl: ctx,\n width,\n height,\n dpr: 1,\n imageMinification: 'mipmap',\n flattenTolerance,\n // Dynamic canvas-SDF glyphs must all bake inline — this path is\n // synchronous with no notify-and-redraw, and print must be complete.\n bakeBudget: Infinity,\n });\n } else {\n renderer.resize({ width, height, dpr: 1 });\n renderer.setFlattenTolerance(flattenTolerance);\n }\n renderer.render(plan.commands, viewToMat3(plan.view));\n if (isLost(ctx)) {\n throw new Error('raster session: the WebGL2 context was lost during render');\n }\n const raw = new Uint8Array(width * height * 4);\n ctx.readPixels(0, 0, width, height, ctx.RGBA, ctx.UNSIGNED_BYTE, raw);\n return { width, height, data: straightTopDown(raw, width, height) };\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n renderer?.dispose();\n renderer = null;\n // A browser caps live contexts per page and evicts the oldest, which is\n // a canvas on screen; a dropped reference frees nothing until collected.\n if (canvas && !options.createCanvas) gl?.getExtension('WEBGL_lose_context')?.loseContext();\n canvas = null;\n gl = undefined;\n },\n };\n}\n\nfunction isLost(gl: WebGL2RenderingContext): boolean {\n return typeof gl.isContextLost === 'function' && gl.isContextLost() === true;\n}\n\n/** What {@link warmRender} loads. */\nexport interface WarmRenderOptions<TData = unknown, TLayer extends string = string, TPose = unknown> {\n /** The render about to happen, as `renderSceneToPixels` or\n * `RasterSession.render` will take it. Its commands are built the way the\n * render builds them, and only the faces and paint kinds they draw with\n * load. */\n render?: RasterRenderArgs<TData, TLayer, TPose>;\n /** Commands about to be drawn, read the same way as `render`'s. Both may be\n * given; what either needs loads. */\n commands?: readonly DrawCommand[];\n /** Fonts to load in place of the ones derived — family names or single\n * variants, as `warmFonts` takes them. */\n families?: readonly (string | FontRequest)[];\n /** Paint kinds to load in place of the ones derived, as `warmPaintKinds`\n * takes them. */\n paintKinds?: readonly string[];\n}\n\n/**\n * Load everything a synchronous render would otherwise draw as nothing — the\n * lazily registered font atlases and the paint kinds loaded on demand — so\n * that a `renderSceneToPixels` or `RasterSession.render` issued after it\n * resolves is complete.\n *\n * Pass the render (`{ render: args }`) or its commands, and only what they\n * draw with loads: each face their text is set in, through the same\n * resolution the renderer does, and each paint kind they name. A rejection\n * then means something this render needs failed to load. `families` and\n * `paintKinds` replace either derived list.\n *\n * With neither `render` nor `commands`, an omitted list loads everything\n * registered: every font family and every kind that has a loader — which\n * fails when any one of them does, and fetches what nothing draws.\n */\nexport function warmRender<TData, TLayer extends string, TPose>(\n opts: WarmRenderOptions<TData, TLayer, TPose> = {},\n): Promise<void> {\n let { families, paintKinds } = opts;\n if (opts.render || opts.commands) {\n let planned: DrawCommand[];\n try {\n planned = opts.render ? planPixelRender(opts.render).commands : [];\n } catch (err) {\n return Promise.reject(err);\n }\n const needs = renderNeeds([...planned, ...(opts.commands ?? [])]);\n families ??= needs.fonts;\n // A kind nothing registered draws nothing whether or not this waits.\n paintKinds ??= needs.paintKinds.filter(isPaintKindKnown);\n }\n return Promise.all([warmFonts(families), warmPaintKinds(paintKinds)]).then(() => undefined);\n}\n\n/**\n * Render part of a scene to raw pixels, with no canvas mounted and no React\n * involved — for export, thumbnails, print, and pixel-diff tests.\n *\n * Output size follows from the source rect and the requested scale, so\n * rendering the same region at a higher scale is a real resolution increase\n * rather than an upscale: curves are re-flattened and glyphs re-rasterized for\n * the output resolution.\n *\n * Synchronous, so nothing lands mid-render: a paint kind loaded on demand\n * (`mesh-gradient`, or one declared with `registerPaintKindLoader`) that has\n * not loaded yet draws nothing, and neither does text set in a font atlas\n * still fetching — one registered `{ lazy: true }` is not fetched until text\n * first asks for it. `await warmRender({ render: args })` first.\n *\n * Each call opens a {@link RasterSession} and disposes it before returning.\n * Rendering many scenes, open one with `createRasterSession` instead.\n */\nexport function renderSceneToPixels<TData, TLayer extends string, TPose>(\n args: RenderSceneToPixelsArgs<TData, TLayer, TPose>,\n): RasterImage {\n const { gl, createCanvas, ...renderArgs } = args;\n const session = createRasterSession({ gl, createCanvas });\n try {\n return session.render(renderArgs);\n } finally {\n session.dispose();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwHA,SAAgB,gBACd,MACiB;CACjB,MAAM,EAAE,YAAY,UAAU;CAC9B,KAAK,MAAM,CAAC,OAAO,MAAM,CACvB,CAAC,oBAAoB,WAAW,KAAK,GAAG,CAAC,qBAAqB,WAAW,MAAM,CACjF,GACE,IAAI,CAAC,OAAO,SAAS,CAAC,KAAK,KAAK,GAC9B,MAAM,IAAI,MAAM,wBAAwB,MAAM,yCAAyC,GAAG;CAG9F,KAAK,MAAM,CAAC,OAAO,MAAM,CAAC,CAAC,WAAW,MAAM,CAAC,GAAG,CAAC,WAAW,MAAM,CAAC,CAAC,GAClE,IAAI,C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EACJ,IAAI;GACF,UAAU,KAAK,SAAS,gBAAgB,KAAK,MAAM,CAAC,CAAC,WAAW,CAAC;EACnE,SAAS,KAAK;GACZ,OAAO,QAAQ,OAAO,GAAG;EAC3B;EACA,MAAM,QAAQ,YAAY,CAAC,GAAG,SAAS,GAAI,KAAK,YAAY,CAAC,CAAE,CAAC;EAChE,aAAa,MAAM;EAEnB,eAAe,MAAM,WAAW,OAAO,gBAAgB;CACzD;CACA,OAAO,QAAQ,IAAI,CAAC,UAAU,QAAQ,GAAG,eAAe,UAAU,CAAC,CAAC,CAAC,CAAC,WAAW,MAAS;AAC5F;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,oBACd,MACa;CACb,MAAM,EAAE,IAAI,cAAc,GAAG,eAAe;CAC5C,MAAM,UAAU,oBAAoB;EAAE;EAAI;CAAa,CAAC;CACxD,IAAI;EACF,OAAO,QAAQ,OAAO,UAAU;CAClC,UAAU;EACR,QAAQ,QAAQ;CAClB;AACF"}
1
+ {"version":3,"file":"renderSceneToPixels.js","names":["viewToMat3"],"sources":["../../src/canvas/renderSceneToPixels.ts"],"sourcesContent":["/**\n * `renderSceneToPixels` — headless rasterization of a scene-space rect to raw RGBA pixels at an\n * explicit, per-axis scale. It drives the same WebGL2 pipeline (`WeaselRenderer` +\n * `buildSceneViewCommands`) as the on-screen view, so print, thumbnail, and export callers get\n * the same pixels the screen would produce at that scale.\n *\n * Environment contract:\n * - Density arrives exclusively via `scale`; this function never reads\n * `window.devicePixelRatio`.\n * - Rounding: output width = max(1, round(sourceRect.width × |scale.x|)), height analogously.\n * When round() lands below rect × scale, the rightmost/bottom sub-pixel band of scene content\n * is cropped; when it rounds up, that band is padded (the `background` fill, or transparent).\n * - Context lifetime: a caller-supplied `gl` is caller-owned. It is never disposed here, and\n * its drawing buffer must be at least width × height pixels (the render targets the\n * bottom-left region). Auto-created canvases are discarded with the session.\n * - Context loss: throws — a lost context cannot produce pixels, and the silent-noop\n * convention of the screen path would return all-zero bytes.\n * - Output: top-down row order, NON-premultiplied (\"straight\") RGBA. The GL framebuffer is\n * premultiplied and bottom-up; readback flips and unpremultiplies.\n * - Determinism: same context + same inputs → same bytes. Cross-driver / cross-machine byte\n * equality is NOT guaranteed; do not build golden-image tests on committed bytes.\n * - Image quality: image textures upload with mipmaps so minified bitmaps don't moiré, and\n * curve tessellation runs at an output-scale tolerance (`flattenTolerancePx`, default 0.25\n * output px).\n */\nimport { WeaselRenderer } from '@weasel-js/renderer';\nimport { viewToMat3, type GlMat3 } from '@weasel-js/geom';\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { View } from '../core/viewport/view';\nimport type { Node, Scene } from 'core/scene/types';\nimport { buildSceneViewCommands, type SceneViewDrawOne } from './sceneViewRender';\nimport type { ColorOverrideRegistry } from '@weasel-js/animator';\nimport { defaultDrawOne } from './defaultDrawOne';\nimport { warmFonts, type FontRequest } from '@weasel-js/font';\nimport { isPaintKindKnown, warmPaintKinds } from '@weasel-js/renderer';\nimport { renderNeeds } from './renderNeeds';\nimport { straightTopDown } from './rasterReadback';\nimport { annotationLayerIds } from 'core/scene/annotation';\nimport { sceneLayerKey } from './sceneLayerPaint';\nimport { CANVAS_CONTEXT_ATTRIBUTES } from './contextAttributes';\n\n/** Plain RGBA raster — structurally `ImageData`-compatible ({ width, height,\n * data }), deliberately free of printer/dpi/physical-unit concepts. */\nexport interface RasterImage {\n width: number;\n height: number;\n /** Top-down, straight (non-premultiplied) RGBA, 4 bytes per pixel. */\n data: Uint8ClampedArray;\n}\n\n/** Minimal canvas contract for `createCanvas` injection: `OffscreenCanvas`,\n * an HTML canvas, or a test fake. */\nexport interface HeadlessCanvasLike {\n width: number;\n height: number;\n getContext(contextId: 'webgl2', options?: WebGLContextAttributes): unknown;\n}\n\n/** What to render, at what resolution, and with which quality settings. */\nexport interface RenderSceneToPixelsArgs<TData, TLayer extends string, TPose> {\n scene: Scene<TData, TLayer, TPose>;\n /** Scene-space rect to render (origin + size in scene units). Output pixel\n * dimensions follow from rect × scale (round, min 1 — see module doc). */\n sourceRect: { x: number; y: number; width: number; height: number };\n /** Output pixels per scene unit, per axis. Anisotropic values supported. A\n * negative axis is flipped: the output is sized from its magnitude, and the\n * rect's far edge on that axis lands on the output's top or left. */\n scale: { x: number; y: number };\n /** Per-node draw callback. Default: `defaultDrawOne` with `resolveImage`\n * merged into the `NodePaintCtx` the scene walk supplies. Custom `drawOne`\n * callers that still want resolver injection should call\n * `defaultDrawOne(node, pose, view, { ...ctx, resolveImage })` themselves —\n * dropping the walk's `ctx` drops derived geometry with it. */\n drawOne?: SceneViewDrawOne<TData, TLayer, TPose>;\n /** Bitmap resolver for image nodes — lets consumers reuse their own decode\n * caches. `undefined` results paint the deterministic grey placeholder\n * outline (see `NodePaintCtx.resolveImage`). */\n resolveImage?: (node: Node<TData, TLayer, TPose>) => ImageBitmap | undefined;\n /** Per-id alpha multiplier, mirroring `<SceneCanvas>`'s scene-slot\n * `alphaFor`. Pass the same function the on-screen canvas uses so an\n * export matches what the user is looking at. Defaults to `() => 1`. */\n alphaFor?: (id: string) => number;\n /** Animated vertex colors to paint, typically an animator's\n * `colorOverrides`, so an export shows the frame on screen. */\n colorOverrides?: ColorOverrideRegistry;\n /** Background fill (any CSS color accepted by the renderer). Default:\n * fully transparent. Passing a color is always valid. */\n background?: string;\n /** Caller-owned WebGL2 context to render with. Mutually exclusive with\n * `createCanvas`. Never disposed by this call. */\n gl?: WebGL2RenderingContext;\n /** One-shot canvas factory (DOM canvas, OffscreenCanvas, or test fake).\n * Mutually exclusive with `gl`. Default: `OffscreenCanvas` when\n * available, else `document.createElement('canvas')`. */\n createCanvas?: (widthPx: number, heightPx: number) => HeadlessCanvasLike;\n /** Max curve-flattening error in OUTPUT pixels. Default 0.25. Measured\n * along each path's most stretched axis. */\n flattenTolerancePx?: number;\n /** Commands drawn over the scene in output-pixel space — origin at the\n * output's top-left, one unit per output pixel. Annotations, watermarks,\n * and `renderDebugSnapshot`'s overlay ride here. */\n overlay?: readonly DrawCommand[];\n /** Draw the scene's annotation layers (`isAnnotationLayer`). Default\n * `false`: a raster is an export, which leaves them out as the SVG export\n * does. Pass `true` to reproduce the canvas as it looked. */\n annotations?: boolean;\n /** Screen space → output pixels, which `'screen'`-unit paint is measured in. Default: output pixels. A\n * raster standing in for part of a larger surface, such as an export's page, names the whole here. */\n screen?: GlMat3;\n}\n\n/** The result of planning a headless render: how big the output is, the view\n * that maps the source rect onto it, and the commands to draw. */\nexport interface PixelRenderPlan {\n width: number;\n height: number;\n view: View;\n commands: DrawCommand[];\n}\n\n/** Pure planning half of `renderSceneToPixels`: output dimensions, the\n * anisotropic `View`, and the full command list (background + view-wrapped\n * scene). Exported for tests and for callers targeting their own renderer. */\nexport function planPixelRender<TData, TLayer extends string, TPose>(\n args: Omit<RenderSceneToPixelsArgs<TData, TLayer, TPose>, 'gl' | 'createCanvas' | 'flattenTolerancePx'>,\n): PixelRenderPlan {\n const { sourceRect, scale } = args;\n for (const [label, v] of [\n ['sourceRect.width', sourceRect.width], ['sourceRect.height', sourceRect.height],\n ] as const) {\n if (!Number.isFinite(v) || v <= 0) {\n throw new Error(`renderSceneToPixels: ${label} must be a positive finite number, got ${v}`);\n }\n }\n for (const [label, v] of [['scale.x', scale.x], ['scale.y', scale.y]] as const) {\n if (!Number.isFinite(v) || v === 0) {\n throw new Error(`renderSceneToPixels: ${label} must be a nonzero finite number, got ${v}`);\n }\n }\n for (const [label, v] of [\n ['sourceRect.x', sourceRect.x], ['sourceRect.y', sourceRect.y],\n ] as const) {\n if (!Number.isFinite(v)) {\n throw new Error(`renderSceneToPixels: ${label} must be a finite number, got ${v}`);\n }\n }\n const width = Math.max(1, Math.round(sourceRect.width * Math.abs(scale.x)));\n const height = Math.max(1, Math.round(sourceRect.height * Math.abs(scale.y)));\n const view: View = {\n x: scale.x < 0 ? sourceRect.x + sourceRect.width : sourceRect.x,\n y: scale.y < 0 ? sourceRect.y + sourceRect.height : sourceRect.y,\n scale: { x: scale.x, y: scale.y },\n };\n\n const resolveImage = args.resolveImage as ((n: Node<unknown, string, unknown>) => ImageBitmap | undefined) | undefined;\n const drawOne: SceneViewDrawOne<TData, TLayer, TPose> =\n args.drawOne ?? ((node, pose, view, ctx) => defaultDrawOne(node, pose, view, { ...ctx, resolveImage }));\n\n const commands: DrawCommand[] = [];\n if (args.background !== undefined) {\n // Screen-space (pre-view) fill so rounding can never leave uncovered\n // edge pixels.\n commands.push({\n kind: 'path',\n path: { kind: 'rect', x: 0, y: 0, width, height },\n fill: { paint: { kind: 'solid', color: args.background } },\n });\n }\n const layers = args.annotations ? undefined : {\n layerVisibility: Object.fromEntries([...annotationLayerIds(args.scene.layers)].map((id) => [sceneLayerKey(id), false])),\n };\n commands.push(...buildSceneViewCommands(\n args.scene, view, drawOne, undefined, args.alphaFor, layers, args.colorOverrides,\n ));\n if (args.overlay) commands.push(...args.overlay);\n return { width, height, view, commands };\n}\n\nfunction defaultCreateCanvas(width: number, height: number): HeadlessCanvasLike {\n if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(width, height);\n }\n if (typeof document !== 'undefined') {\n const c = document.createElement('canvas');\n c.width = width;\n c.height = height;\n return c;\n }\n throw new Error('renderSceneToPixels: no canvas source in this environment — supply `gl` or `createCanvas`');\n}\n\n/** Where a {@link RasterSession} draws. Pass `gl` or `createCanvas`, or\n * neither for the default canvas source. */\nexport interface RasterSessionOptions {\n /** Caller-owned WebGL2 context. The session never disposes it. Its drawing\n * buffer must be at least as large as every render the session does. */\n gl?: WebGL2RenderingContext;\n /** Canvas factory, called once, at the size of the first render. The\n * session grows the canvas when a later render needs more room and never\n * shrinks it. Default: `OffscreenCanvas` when available, else a detached\n * DOM canvas. */\n createCanvas?: (widthPx: number, heightPx: number) => HeadlessCanvasLike;\n}\n\n/** One render through a {@link RasterSession}: everything\n * `renderSceneToPixels` takes except where to draw. */\nexport type RasterRenderArgs<TData, TLayer extends string, TPose> =\n Omit<RenderSceneToPixelsArgs<TData, TLayer, TPose>, 'gl' | 'createCanvas'>;\n\n/** One renderer and its GPU caches, kept across any number of headless\n * renders. Scenes, source rects and scales may differ per render. */\nexport interface RasterSession {\n /** Same contract as `renderSceneToPixels`. Throws once disposed. */\n render<TData, TLayer extends string, TPose>(args: RasterRenderArgs<TData, TLayer, TPose>): RasterImage;\n /** Free every GL resource the session created — programs, geometry, and\n * the texture and mesh caches — and drop its own canvas. A caller-owned\n * context stays open. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Open a raster session: one `WeaselRenderer` that many headless renders\n * share, for a consumer producing thumbnails or pages in bulk. Programs\n * compile once, and a bitmap or recurring mesh uploads once, rather than per\n * render. `renderSceneToPixels` is a session opened for one render.\n *\n * The renderer is created on the first render, so opening a session costs\n * nothing and fails nothing. Each render draws into the bottom-left\n * `width × height` of the buffer and reads that region back.\n */\nexport function createRasterSession(options: RasterSessionOptions = {}): RasterSession {\n if (options.gl && options.createCanvas) {\n throw new Error('raster session: `gl` and `createCanvas` are mutually exclusive');\n }\n let canvas: HeadlessCanvasLike | null = null;\n let gl: WebGL2RenderingContext | undefined = options.gl;\n let renderer: WeaselRenderer | null = null;\n let disposed = false;\n\n function contextFor(width: number, height: number): WebGL2RenderingContext {\n if (!options.gl) {\n if (!canvas) {\n canvas = (options.createCanvas ?? defaultCreateCanvas)(width, height);\n canvas.width = width;\n canvas.height = height;\n gl = (canvas.getContext('webgl2', CANVAS_CONTEXT_ATTRIBUTES) as WebGL2RenderingContext | null) ?? undefined;\n } else {\n if (canvas.width < width) canvas.width = width;\n if (canvas.height < height) canvas.height = height;\n }\n }\n if (!gl || typeof (gl as Partial<WebGL2RenderingContext>).enable !== 'function') {\n throw new Error('raster session: WebGL2 is unavailable — supply `gl` or a WebGL2-capable `createCanvas`');\n }\n if (isLost(gl)) {\n throw new Error('raster session: the WebGL2 context is lost — dispose this session and open another');\n }\n // A context clamps a drawing buffer it cannot allocate, and reading past\n // the real one returns transparent pixels rather than failing.\n const { drawingBufferWidth: bufferW, drawingBufferHeight: bufferH } = gl;\n if (bufferW < width || bufferH < height) {\n throw new Error(\n `raster session: a ${width} × ${height} render does not fit the context's `\n + `${bufferW} × ${bufferH} drawing buffer — lower \\`scale\\` or render the source rect in tiles`,\n );\n }\n return gl;\n }\n\n return {\n render(args) {\n if (disposed) throw new Error('raster session: render() on a disposed session');\n const plan = planPixelRender(args);\n const { width, height } = plan;\n const ctx = contextFor(width, height);\n const flattenTolerance = { px: args.flattenTolerancePx ?? 0.25 };\n if (!renderer) {\n renderer = new WeaselRenderer({\n gl: ctx,\n width,\n height,\n dpr: 1,\n imageMinification: 'mipmap',\n flattenTolerance,\n // Dynamic canvas-SDF glyphs must all bake inline — this path is\n // synchronous with no notify-and-redraw, and print must be complete.\n bakeBudget: Infinity,\n });\n } else {\n renderer.resize({ width, height, dpr: 1 });\n renderer.setFlattenTolerance(flattenTolerance);\n }\n renderer.render(plan.commands, viewToMat3(plan.view), { screen: args.screen });\n if (isLost(ctx)) {\n throw new Error('raster session: the WebGL2 context was lost during render');\n }\n const raw = new Uint8Array(width * height * 4);\n ctx.readPixels(0, 0, width, height, ctx.RGBA, ctx.UNSIGNED_BYTE, raw);\n return { width, height, data: straightTopDown(raw, width, height) };\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n renderer?.dispose();\n renderer = null;\n // A browser caps live contexts per page and evicts the oldest, which is\n // a canvas on screen; a dropped reference frees nothing until collected.\n if (canvas && !options.createCanvas) gl?.getExtension('WEBGL_lose_context')?.loseContext();\n canvas = null;\n gl = undefined;\n },\n };\n}\n\nfunction isLost(gl: WebGL2RenderingContext): boolean {\n return typeof gl.isContextLost === 'function' && gl.isContextLost() === true;\n}\n\n/** What {@link warmRender} loads. */\nexport interface WarmRenderOptions<TData = unknown, TLayer extends string = string, TPose = unknown> {\n /** The render about to happen, as `renderSceneToPixels` or\n * `RasterSession.render` will take it. Its commands are built the way the\n * render builds them, and only the faces and paint kinds they draw with\n * load. */\n render?: RasterRenderArgs<TData, TLayer, TPose>;\n /** Commands about to be drawn, read the same way as `render`'s. Both may be\n * given; what either needs loads. */\n commands?: readonly DrawCommand[];\n /** Fonts to load in place of the ones derived — family names or single\n * variants, as `warmFonts` takes them. */\n families?: readonly (string | FontRequest)[];\n /** Paint kinds to load in place of the ones derived, as `warmPaintKinds`\n * takes them. */\n paintKinds?: readonly string[];\n}\n\n/**\n * Load everything a synchronous render would otherwise draw as nothing — the\n * lazily registered font atlases and the paint kinds loaded on demand — so\n * that a `renderSceneToPixels` or `RasterSession.render` issued after it\n * resolves is complete.\n *\n * Pass the render (`{ render: args }`) or its commands, and only what they\n * draw with loads: each face their text is set in, through the same\n * resolution the renderer does, and each paint kind they name. A rejection\n * then means something this render needs failed to load. `families` and\n * `paintKinds` replace either derived list.\n *\n * With neither `render` nor `commands`, an omitted list loads everything\n * registered: every font family and every kind that has a loader — which\n * fails when any one of them does, and fetches what nothing draws.\n */\nexport function warmRender<TData, TLayer extends string, TPose>(\n opts: WarmRenderOptions<TData, TLayer, TPose> = {},\n): Promise<void> {\n let { families, paintKinds } = opts;\n if (opts.render || opts.commands) {\n let planned: DrawCommand[];\n try {\n planned = opts.render ? planPixelRender(opts.render).commands : [];\n } catch (err) {\n return Promise.reject(err);\n }\n const needs = renderNeeds([...planned, ...(opts.commands ?? [])]);\n families ??= needs.fonts;\n // A kind nothing registered draws nothing whether or not this waits.\n paintKinds ??= needs.paintKinds.filter(isPaintKindKnown);\n }\n return Promise.all([warmFonts(families), warmPaintKinds(paintKinds)]).then(() => undefined);\n}\n\n/**\n * Render part of a scene to raw pixels, with no canvas mounted and no React\n * involved — for export, thumbnails, print, and pixel-diff tests.\n *\n * Output size follows from the source rect and the requested scale, so\n * rendering the same region at a higher scale is a real resolution increase\n * rather than an upscale: curves are re-flattened and glyphs re-rasterized for\n * the output resolution.\n *\n * Synchronous, so nothing lands mid-render: a paint kind loaded on demand\n * (`mesh-gradient`, or one declared with `registerPaintKindLoader`) that has\n * not loaded yet draws nothing, and neither does text set in a font atlas\n * still fetching — one registered `{ lazy: true }` is not fetched until text\n * first asks for it. `await warmRender({ render: args })` first.\n *\n * Each call opens a {@link RasterSession} and disposes it before returning.\n * Rendering many scenes, open one with `createRasterSession` instead.\n */\nexport function renderSceneToPixels<TData, TLayer extends string, TPose>(\n args: RenderSceneToPixelsArgs<TData, TLayer, TPose>,\n): RasterImage {\n const { gl, createCanvas, ...renderArgs } = args;\n const session = createRasterSession({ gl, createCanvas });\n try {\n return session.render(renderArgs);\n } finally {\n session.dispose();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,SAAgB,gBACd,MACiB;CACjB,MAAM,EAAE,YAAY,UAAU;CAC9B,KAAK,MAAM,CAAC,OAAO,MAAM,CACvB,CAAC,oBAAoB,WAAW,KAAK,GAAG,CAAC,qBAAqB,WAAW,MAAM,CACjF,GACE,IAAI,CAAC,OAAO,SAAS,CAAC,KAAK,KAAK,GAC9B,MAAM,IAAI,MAAM,wBAAwB,MAAM,yCAAyC,GAAG;CAG9F,KAAK,MAAM,CAAC,OAAO,MAAM,CAAC,CAAC,WAAW,MAAM,CAAC,GAAG,CAAC,WAAW,MAAM,CAAC,CAAC,GAClE,IAAI,CAAC,OAAO,SAAS,CAAC,KAAK,MAAM,GAC/B,MAAM,IAAI,MAAM,wBAAwB,MAAM,wCAAwC,GAAG;CAG7F,KAAK,MAAM,CAAC,OAAO,MAAM,CACvB,CAAC,gBAAgB,WAAW,CAAC,GAAG,CAAC,gBAAgB,WAAW,CAAC,CAC/D,GACE,IAAI,CAAC,OAAO,SAAS,CAAC,GACpB,MAAM,IAAI,MAAM,wBAAwB,MAAM,gCAAgC,GAAG;CAGrF,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,WAAW,QAAQ,KAAK,IAAI,MAAM,CAAC,CAAC,CAAC;CAC1E,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,MAAM,WAAW,SAAS,KAAK,IAAI,MAAM,CAAC,CAAC,CAAC;CAC5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c,GAAG,eAAe;CAC5C,MAAM,UAAU,oBAAoB;EAAE;EAAI;CAAa,CAAC;CACxD,IAAI;EACF,OAAO,QAAQ,OAAO,UAAU;CAClC,UAAU;EACR,QAAQ,QAAQ;CAClB;AACF"}
@@ -7,6 +7,7 @@ import { nodeGates } from "../core/scene/nodeGates.js";
7
7
  import { sceneMutators } from "../core/scene/sceneMutators.js";
8
8
  import { applyOpsTo } from "../core/applyOps.js";
9
9
  import { hitTestArea, hitTestLassoPolygon, regionPickOptions } from "./deps/hitTestArea.js";
10
+ import { insertSite } from "./deps/insertSite.js";
10
11
  import { scenePoseTarget } from "../animation/poseTarget.js";
11
12
  import { cascadingSetPose, containerCascade } from "./poseCascade.js";
12
13
  import { pasteSceneSnapshot, snapshotSceneSelection } from "./sceneClipboard.js";
@@ -42,7 +43,8 @@ function sceneToAdapter(scene, options = {}) {
42
43
  worldPoseOf: (id) => adapter.getWorldPose(id),
43
44
  frameAtOrAbove: (id) => frameAtOrAbove(adapter, id),
44
45
  poseBounds,
45
- translate
46
+ translate,
47
+ ...options.pasteInto ? { landing: () => insertSite(scene, options.pasteInto()) } : {}
46
48
  };
47
49
  const adapter = {
48
50
  ...sceneMutators(scene),
@@ -67,7 +69,7 @@ function sceneToAdapter(scene, options = {}) {
67
69
  ...composes ? { composePose: composition.compose } : {},
68
70
  ...cascade ? { setPose: (id, pose) => cascade.setPose(asNodeId(id), pose) } : {},
69
71
  poseTarget(id, descriptor) {
70
- if (cascade === null || scene.get(asNodeId(id))?.kind !== "container") return scenePoseTarget(scene, id, descriptor ?? d);
72
+ if (cascade === null || scene.get(asNodeId(id))?.kind !== "group") return scenePoseTarget(scene, id, descriptor ?? d);
71
73
  const carried = containerCascade(scene, asNodeId(id), d, (pose) => adapter.setPose(id, pose));
72
74
  return scenePoseTarget(scene, id, descriptor ?? d, carried);
73
75
  },
@@ -85,17 +87,17 @@ function sceneToAdapter(scene, options = {}) {
85
87
  getSelection,
86
88
  setSelection,
87
89
  hitTestArea(rect, view) {
88
- return hitTestArea(scene, rect, pickOptsFor(view), d, { includeContainers: true });
90
+ return hitTestArea(scene, rect, pickOptsFor(view), d, { includeGroups: true });
89
91
  },
90
92
  hitTestLasso(polygon, mode, view) {
91
- return hitTestLassoPolygon(scene, polygon, mode, pickOptsFor(view), d, { includeContainers: true });
93
+ return hitTestLassoPolygon(scene, polygon, mode, pickOptsFor(view), d, { includeGroups: true });
92
94
  },
93
95
  ...options.commitInsert ? { commitInsert: (bounds) => {
94
96
  const created = options.commitInsert(bounds);
95
97
  if (!created) return null;
96
98
  const layer = options.insertLayer ?? "default";
97
99
  return {
98
- kind: "leaf",
100
+ kind: "mark",
99
101
  id: created.id === void 0 ? scene.mintId() : asNodeId(created.id),
100
102
  layer,
101
103
  pose: created.pose,
@@ -1 +1 @@
1
- {"version":3,"file":"sceneAdapter.js","names":[],"sources":["../../src/canvas/sceneAdapter.ts"],"sourcesContent":["/**\n * Synthesize a `<Canvas>`-compatible adapter from a `Scene` primitive.\n * `getPose` / `setPose` return / write **local** coordinates (relative to\n * parent); world composition is the renderer's job via `composeWorldPose`.\n */\nimport type {\n AreaSelectAdapter,\n ClipboardSnapshot,\n InsertAdapter,\n PasteCtx,\n LassoHitMode,\n LassoSelectAdapter,\n RegionPickView,\n LayerEnumerableAdapter,\n MoveAdapter,\n ResizeAdapter,\n RotateAdapter,\n} from 'core/adapters/types';\nimport type { LayoutStrategy } from '../layout/types';\nimport type { Op } from 'core/ops/types';\nimport type { Node, Scene } from 'core/scene/types';\nimport { definesFrame, effectivePose } from 'core/scene/effectivePose';\nimport { sceneMutators } from 'core/scene/sceneMutators';\nimport { asNodeId } from 'core/scene/types';\nimport { nodeGates } from 'core/scene/nodeGates';\nimport { applyOpsTo } from 'core/applyOps';\nimport { hitTestArea, hitTestLassoPolygon, regionPickOptions } from 'canvas/deps/hitTestArea';\nimport type { ScenePickSourceOptions } from 'canvas/pickWalk';\nimport {\n poseDescriptorForNode,\n translatePoseViaDescriptor,\n visualBoundsViaDescriptor,\n type PoseDescriptor,\n} from 'interactions/actions/resize/geometry';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport { composesFrames, composeWorldPose, frameAtOrAbove } from 'core/scene/composePose';\nimport type { Bounds } from '../core/viewport/fitViewToBounds';\nimport { scenePoseTarget } from '../animation/poseTarget';\nimport { cascadingSetPose, containerCascade } from './poseCascade';\nimport { pasteSceneSnapshot, snapshotSceneSelection, type SceneClipboardEnv } from './sceneClipboard';\n\n/** Minimal selection contract `sceneToAdapter` needs to wire `getSelection` /\n * `setSelection`. Matches `useSelection().adapterMethods` plus an imperative\n * read; pass `useSelection()` itself or `selection.adapterMethods`. */\nexport interface SceneAdapterSelection {\n get?(): string[];\n set?(ids: string[]): void;\n getSelection?(): string[];\n setSelection?(ids: string[]): void;\n}\n\n/** Sibling z-order surface used by reorder ops. Inlined here (rather than\n * pulled from `core/ops/reorder` to avoid import cycles); the `null` parent\n * channel addresses the root sibling list. */\n/** @internal */\ninterface ReorderAdapter {\n getChildren(parentId: string | null): string[];\n setChildOrder(parentId: string | null, ids: string[]): void;\n}\n\n/** Everything the interaction layer can ask of a scene, as one type: the\n * move, resize, rotate, selection, layer and reorder contracts combined.\n * `<SceneCanvas>` synthesizes one of these, which is why most consumers never\n * touch an adapter directly. */\nexport type SceneCanvasAdapter<TData, TLayer extends string, TPose> =\n & MoveAdapter<Node<TData, TLayer, TPose>, TPose>\n & ResizeAdapter<Node<TData, TLayer, TPose>, TPose>\n & RotateAdapter<Node<TData, TLayer, TPose>, TPose>\n & AreaSelectAdapter\n & LassoSelectAdapter\n & LayerEnumerableAdapter<TLayer>\n & ReorderAdapter\n & Partial<InsertAdapter<Node<TData, TLayer, TPose>>>\n // Optional on the underlying adapter contracts, but unconditionally\n // provided by a scene-backed adapter.\n & {\n getParent(id: string): string | null;\n getLayers: NonNullable<LayerEnumerableAdapter<TLayer>['getLayers']>;\n /** The node's pose with every ancestor's frame folded in. Equal to\n * `getPose` unless the scene composes poses. */\n getWorldPose(id: string): TPose;\n /** Whether `id`'s pose is a frame its children are expressed in — see\n * `definesFrame`. */\n definesFrame(id: string): boolean;\n /** Present only when a composing strategy is configured; the render\n * walk feature-detects it. */\n composePose?(parent: TPose, child: TPose): TPose;\n getSelection(): string[];\n setSelection(ids: string[]): void;\n insertNode(node: Node<TData, TLayer, TPose>, index?: number): void;\n removeNode(id: string): void;\n /** Replace a node's `data` — what a `setData` op writes through. */\n setData(id: string, data: TData): void;\n /** Swap a container's layout — what a `setLayout` op writes through. */\n setLayout(id: string, layout: LayoutStrategy<TPose> | string | null): void;\n /** Move a node to another layer — what a `setLayer` op writes through. */\n setLayer(id: string, layer: TLayer): void;\n /** Retarget a derived node's sources — what a `setDependsOn` op writes through. */\n setDependsOn(id: string, dependsOn: readonly string[] | 'children' | undefined): void;\n /** Hide or show a node — what a `setHidden` op writes through. */\n setHidden(id: string, hidden: boolean): void;\n /** Lock or unlock a node — what a `setLocked` op writes through. */\n setLocked(id: string, locked: boolean): void;\n getRemovalClosure(ids: readonly string[]): string[];\n applyOps(ops: Op[], label?: string): void;\n snapshotSelection(ids: string[]): ClipboardSnapshot;\n commitPaste(\n clipboard: ClipboardSnapshot,\n offset: { dx: number; dy: number },\n ctx?: PasteCtx,\n ): Node<TData, TLayer, TPose>[];\n getPasteOffset(clipboard: ClipboardSnapshot): { dx: number; dy: number };\n };\n\n/** Optional extras for the synthesized adapter. Pass `commitInsert` to wire\n * the insert gesture into a Scene-owned canvas; the returned object becomes\n * a leaf on the layer named by `layer` (default `'default'`). */\nexport interface SceneToAdapterOptions<TData, TLayer extends string, TPose> {\n /** Factory for new objects. Returning `null` aborts the insert. */\n commitInsert?: (bounds: Bounds) => {\n pose: TPose;\n data: TData;\n id?: string;\n } | null;\n /** Layer to place inserted nodes on. Defaults to the trivial-form layer. */\n insertLayer?: TLayer;\n /** Selection source: the result of `useSelection()` (or its\n * `adapterMethods`). When omitted, `getSelection` returns `[]` and\n * `setSelection` is a noop, so the marquee gesture updates nothing. */\n selection?: SceneAdapterSelection;\n /** How to read and rewrite this scene's poses. Default `AUTO_POSE_DESCRIPTOR`. */\n poseDescriptor?: PoseDescriptor<TPose>;\n}\n\n/** Derive the adapter for a scene. Reads go straight to the scene; writes are\n * ops applied through its history, so anything done through the adapter is\n * undoable.\n *\n * Moving a container carries its contents either way the scene composes\n * poses. Under a frame (`scene.composition`) the one pose written moves them.\n * Under the absolute-pose model `setPose` on a container translates every\n * descendant by the same delta, and a batch that poses descendants too undoes\n * exactly only when it goes through this adapter's `applyOps`. */\nexport function sceneToAdapter<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n options: SceneToAdapterOptions<TData, TLayer, TPose> = {},\n): SceneCanvasAdapter<TData, TLayer, TPose> {\n const sel = options.selection;\n const getSelection = sel?.getSelection ?? sel?.get ?? (() => [] as string[]);\n const setSelection = sel?.setSelection ?? sel?.set ?? (() => {});\n const d = (options.poseDescriptor ?? AUTO_POSE_DESCRIPTOR) as PoseDescriptor<TPose>;\n const poseBounds = (p: TPose, node: unknown): Bounds =>\n visualBoundsViaDescriptor(p, poseDescriptorForNode(d, node));\n const translate = (p: TPose, dx: number, dy: number, node?: unknown): TPose =>\n translatePoseViaDescriptor(\n p, dx, dy, node === undefined ? d : poseDescriptorForNode(d, node),\n );\n\n const composition = scene.composition;\n const composes = composesFrames(composition);\n const pickOpts: ScenePickSourceOptions<unknown> = {};\n // The asking view's layer gate and camera, over the adapter's own options.\n const pickOptsFor = (view: RegionPickView | undefined): ScenePickSourceOptions<unknown> =>\n (view ? { ...pickOpts, ...regionPickOptions(view, undefined) } : pickOpts);\n\n const cascade = composes ? null : { setPose: cascadingSetPose(scene, d) };\n\n const clipboardEnv: SceneClipboardEnv<TData, TLayer, TPose> = {\n scene,\n composes,\n worldPoseOf: (id) => adapter.getWorldPose(id),\n frameAtOrAbove: (id) => frameAtOrAbove(adapter, id),\n poseBounds,\n translate,\n };\n\n const adapter: SceneCanvasAdapter<TData, TLayer, TPose> = {\n ...sceneMutators(scene),\n // What is shown, where the mutators' other users read the document:\n // the nodes not hidden, and the effective pose.\n getNodes() {\n const gates = nodeGates(scene);\n return scene.renderOrderNodes().filter((n) => !gates.hidden(n.id));\n },\n getPose(id) {\n const nid = asNodeId(id);\n const n = scene.get(nid);\n if (!n) throw new Error(`sceneToAdapter: unknown node \"${id}\"`);\n return effectivePose(scene, n);\n },\n definesFrame(id) {\n const n = scene.get(asNodeId(id));\n return n === undefined || definesFrame(n);\n },\n getWorldPose(id) {\n if (!composes) return adapter.getPose(id);\n return composeWorldPose(adapter, id, composition.compose);\n },\n // Only present when it would do something: the render walk skips the fold\n // entirely when this is absent, which is the absolute-pose path.\n ...(composes ? { composePose: composition.compose } : {}),\n ...(cascade ? { setPose: (id: string, pose: TPose) => cascade.setPose(asNodeId(id), pose) } : {}),\n poseTarget(id, descriptor) {\n if (cascade === null || scene.get(asNodeId(id))?.kind !== 'container') {\n return scenePoseTarget(scene, id, descriptor ?? d);\n }\n // Its descendants hold poses of their own: a commit moves them, and they are shown beside it.\n const carried = containerCascade(scene, asNodeId(id), d, (pose) => adapter.setPose(id, pose));\n return scenePoseTarget(scene, id, descriptor ?? d, carried);\n },\n getLayers: () => scene.layers.map((l) => ({ id: l.id, visible: l.visible, parallax: l.parallax })),\n subscribeLayers: (listener) => scene.subscribe(listener),\n getLayout: (id) => scene.layoutOf(asNodeId(id)),\n // With a label the ops are one batch checkpoint; without one they are\n // applied transiently, with no checkpoint (the AreaSelectAdapter contract).\n applyOps(ops: Op[], label?: string) {\n if (label !== undefined) {\n scene.applyBatch(ops, label, this);\n } else {\n applyOpsTo(this, ops);\n }\n },\n getSelection,\n setSelection,\n // The live marquee's and lasso's own hit-tests. Containers come back:\n // this adapter's consumer has nothing to fold children into them.\n hitTestArea(rect: Bounds, view?: RegionPickView) {\n return hitTestArea(\n scene,\n rect,\n pickOptsFor(view),\n d as PoseDescriptor<unknown>,\n { includeContainers: true },\n );\n },\n hitTestLasso(polygon, mode: LassoHitMode, view?: RegionPickView) {\n return hitTestLassoPolygon(\n scene,\n polygon,\n mode,\n pickOptsFor(view),\n d as PoseDescriptor<unknown>,\n { includeContainers: true },\n );\n },\n // A pure factory: it constructs a Node spec but does NOT touch the scene.\n // The `InsertOp` → `adapter.insertNode` → `scene.add` path is the sole\n // insertion path. Calling `scene.add` here too would double-insert, and\n // the second add throws on id collision.\n ...(options.commitInsert\n ? {\n commitInsert: (bounds: { x: number; y: number; width: number; height: number }) => {\n const created = options.commitInsert!(bounds);\n if (!created) return null;\n const layer = (options.insertLayer ?? ('default' as TLayer));\n const id = created.id === undefined ? scene.mintId() : asNodeId(created.id);\n return {\n kind: 'leaf',\n id,\n layer,\n pose: created.pose,\n data: created.data,\n parent: null,\n } as Node<TData, TLayer, TPose>;\n },\n }\n : {}),\n // Clipboard seam (`useClipboardOps` / the paste ingestion path).\n snapshotSelection(ids: string[]): ClipboardSnapshot {\n return snapshotSceneSelection(clipboardEnv, ids);\n },\n commitPaste(\n clipboard: ClipboardSnapshot,\n offset: { dx: number; dy: number },\n ctx?: PasteCtx,\n ): Node<TData, TLayer, TPose>[] {\n return pasteSceneSnapshot(clipboardEnv, clipboard, offset, ctx);\n },\n // Constant cascade: the hook re-snapshots the just-created items, so\n // repeated pastes stack +12/+12 each time.\n getPasteOffset(): { dx: number; dy: number } {\n return { dx: 12, dy: 12 };\n },\n };\n\n return adapter;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+IA,SAAgB,eACd,OACA,UAAuD,CAAC,GACd;CAC1C,MAAM,MAAM,QAAQ;CACpB,MAAM,eAAe,KAAK,gBAAgB,KAAK,cAAc,CAAC;CAC9D,MAAM,eAAe,KAAK,gBAAgB,KAAK,cAAc,CAAC;CAC9D,MAAM,IAAK,QAAQ,kBAAkB;CACrC,MAAM,cAAc,GAAU,SAC5B,0BAA0B,GAAG,sBAAsB,GAAG,IAAI,CAAC;CAC7D,MAAM,aAAa,GAAU,I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AAW,QAAQ,GAAG;EAChE;EAGA,iBAA6C;GAC3C,OAAO;IAAE,IAAI;IAAI,IAAI;GAAG;EAC1B;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"sceneAdapter.js","names":[],"sources":["../../src/canvas/sceneAdapter.ts"],"sourcesContent":["/**\n * Synthesize a `<Canvas>`-compatible adapter from a `Scene` primitive.\n * `getPose` / `setPose` return / write **local** coordinates (relative to\n * parent); world composition is the renderer's job via `composeWorldPose`.\n */\nimport type {\n AreaSelectAdapter,\n ClipboardSnapshot,\n InsertAdapter,\n PasteCtx,\n LassoHitMode,\n LassoSelectAdapter,\n RegionPickView,\n LayerEnumerableAdapter,\n MoveAdapter,\n ResizeAdapter,\n RotateAdapter,\n} from 'core/adapters/types';\nimport type { LayoutStrategy } from '../layout/types';\nimport type { Op } from 'core/ops/types';\nimport type { Node, Scene } from 'core/scene/types';\nimport { definesFrame, effectivePose } from 'core/scene/effectivePose';\nimport { sceneMutators } from 'core/scene/sceneMutators';\nimport { asNodeId } from 'core/scene/types';\nimport { nodeGates } from 'core/scene/nodeGates';\nimport { applyOpsTo } from 'core/applyOps';\nimport { hitTestArea, hitTestLassoPolygon, regionPickOptions } from 'canvas/deps/hitTestArea';\nimport type { ScenePickSourceOptions } from 'canvas/pickWalk';\nimport {\n poseDescriptorForNode,\n translatePoseViaDescriptor,\n visualBoundsViaDescriptor,\n type PoseDescriptor,\n} from 'interactions/actions/resize/geometry';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport { composesFrames, composeWorldPose, frameAtOrAbove } from 'core/scene/composePose';\nimport { insertSite } from './deps/insertSite';\nimport type { Bounds } from '../core/viewport/fitViewToBounds';\nimport { scenePoseTarget } from '../animation/poseTarget';\nimport { cascadingSetPose, containerCascade } from './poseCascade';\nimport { pasteSceneSnapshot, snapshotSceneSelection, type SceneClipboardEnv } from './sceneClipboard';\n\n/** Minimal selection contract `sceneToAdapter` needs to wire `getSelection` /\n * `setSelection`. Matches `useSelection().adapterMethods` plus an imperative\n * read; pass `useSelection()` itself or `selection.adapterMethods`. */\nexport interface SceneAdapterSelection {\n get?(): string[];\n set?(ids: string[]): void;\n getSelection?(): string[];\n setSelection?(ids: string[]): void;\n}\n\n/** Sibling z-order surface used by reorder ops. Inlined here (rather than\n * pulled from `core/ops/reorder` to avoid import cycles); the `null` parent\n * channel addresses the root sibling list. */\n/** @internal */\ninterface ReorderAdapter {\n getChildren(parentId: string | null): string[];\n setChildOrder(parentId: string | null, ids: string[]): void;\n}\n\n/** Everything the interaction layer can ask of a scene, as one type: the\n * move, resize, rotate, selection, layer and reorder contracts combined.\n * `<SceneCanvas>` synthesizes one of these, which is why most consumers never\n * touch an adapter directly. */\nexport type SceneCanvasAdapter<TData, TLayer extends string, TPose> =\n & MoveAdapter<Node<TData, TLayer, TPose>, TPose>\n & ResizeAdapter<Node<TData, TLayer, TPose>, TPose>\n & RotateAdapter<Node<TData, TLayer, TPose>, TPose>\n & AreaSelectAdapter\n & LassoSelectAdapter\n & LayerEnumerableAdapter<TLayer>\n & ReorderAdapter\n & Partial<InsertAdapter<Node<TData, TLayer, TPose>>>\n // Optional on the underlying adapter contracts, but unconditionally\n // provided by a scene-backed adapter.\n & {\n getParent(id: string): string | null;\n getLayers: NonNullable<LayerEnumerableAdapter<TLayer>['getLayers']>;\n /** The node's pose with every ancestor's frame folded in. Equal to\n * `getPose` unless the scene composes poses. */\n getWorldPose(id: string): TPose;\n /** Whether `id`'s pose is a frame its children are expressed in — see\n * `definesFrame`. */\n definesFrame(id: string): boolean;\n /** Present only when a composing strategy is configured; the render\n * walk feature-detects it. */\n composePose?(parent: TPose, child: TPose): TPose;\n getSelection(): string[];\n setSelection(ids: string[]): void;\n insertNode(node: Node<TData, TLayer, TPose>, index?: number): void;\n removeNode(id: string): void;\n /** Replace a node's `data` — what a `setData` op writes through. */\n setData(id: string, data: TData): void;\n /** Swap a container's layout — what a `setLayout` op writes through. */\n setLayout(id: string, layout: LayoutStrategy<TPose> | string | null): void;\n /** Move a node to another layer — what a `setLayer` op writes through. */\n setLayer(id: string, layer: TLayer): void;\n /** Retarget a derived node's sources — what a `setDependsOn` op writes through. */\n setDependsOn(id: string, dependsOn: readonly string[] | 'children' | undefined): void;\n /** Hide or show a node — what a `setHidden` op writes through. */\n setHidden(id: string, hidden: boolean): void;\n /** Lock or unlock a node — what a `setLocked` op writes through. */\n setLocked(id: string, locked: boolean): void;\n getRemovalClosure(ids: readonly string[]): string[];\n applyOps(ops: Op[], label?: string): void;\n snapshotSelection(ids: string[]): ClipboardSnapshot;\n commitPaste(\n clipboard: ClipboardSnapshot,\n offset: { dx: number; dy: number },\n ctx?: PasteCtx,\n ): Node<TData, TLayer, TPose>[];\n getPasteOffset(clipboard: ClipboardSnapshot): { dx: number; dy: number };\n };\n\n/** Optional extras for the synthesized adapter. Pass `commitInsert` to wire\n * the insert gesture into a Scene-owned canvas; the returned object becomes\n * a leaf on the layer named by `layer` (default `'default'`). */\nexport interface SceneToAdapterOptions<TData, TLayer extends string, TPose> {\n /** Factory for new objects. Returning `null` aborts the insert. */\n commitInsert?: (bounds: Bounds) => {\n pose: TPose;\n data: TData;\n id?: string;\n } | null;\n /** Layer to place inserted nodes on. Defaults to the trivial-form layer. */\n insertLayer?: TLayer;\n /** Selection source: the result of `useSelection()` (or its\n * `adapterMethods`). When omitted, `getSelection` returns `[]` and\n * `setSelection` is a noop, so the marquee gesture updates nothing. */\n selection?: SceneAdapterSelection;\n /** How to read and rewrite this scene's poses. Default `AUTO_POSE_DESCRIPTOR`. */\n poseDescriptor?: PoseDescriptor<TPose>;\n /** The container a paste lands in, read at each paste: `<SceneCanvas>` passes the `insertInto` dep's. */\n pasteInto?: () => string | null;\n}\n\n/** Derive the adapter for a scene. Reads go straight to the scene; writes are\n * ops applied through its history, so anything done through the adapter is\n * undoable.\n *\n * Moving a container carries its contents either way the scene composes\n * poses. Under a frame (`scene.composition`) the one pose written moves them.\n * Under the absolute-pose model `setPose` on a container translates every\n * descendant by the same delta, and a batch that poses descendants too undoes\n * exactly only when it goes through this adapter's `applyOps`. */\nexport function sceneToAdapter<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n options: SceneToAdapterOptions<TData, TLayer, TPose> = {},\n): SceneCanvasAdapter<TData, TLayer, TPose> {\n const sel = options.selection;\n const getSelection = sel?.getSelection ?? sel?.get ?? (() => [] as string[]);\n const setSelection = sel?.setSelection ?? sel?.set ?? (() => {});\n const d = (options.poseDescriptor ?? AUTO_POSE_DESCRIPTOR) as PoseDescriptor<TPose>;\n const poseBounds = (p: TPose, node: unknown): Bounds =>\n visualBoundsViaDescriptor(p, poseDescriptorForNode(d, node));\n const translate = (p: TPose, dx: number, dy: number, node?: unknown): TPose =>\n translatePoseViaDescriptor(\n p, dx, dy, node === undefined ? d : poseDescriptorForNode(d, node),\n );\n\n const composition = scene.composition;\n const composes = composesFrames(composition);\n const pickOpts: ScenePickSourceOptions<unknown> = {};\n // The asking view's layer gate and camera, over the adapter's own options.\n const pickOptsFor = (view: RegionPickView | undefined): ScenePickSourceOptions<unknown> =>\n (view ? { ...pickOpts, ...regionPickOptions(view, undefined) } : pickOpts);\n\n const cascade = composes ? null : { setPose: cascadingSetPose(scene, d) };\n\n const clipboardEnv: SceneClipboardEnv<TData, TLayer, TPose> = {\n scene,\n composes,\n worldPoseOf: (id) => adapter.getWorldPose(id),\n frameAtOrAbove: (id) => frameAtOrAbove(adapter, id),\n poseBounds,\n translate, ...(options.pasteInto ? { landing: () => insertSite(scene as never, options.pasteInto!()) } : {}),\n };\n\n const adapter: SceneCanvasAdapter<TData, TLayer, TPose> = {\n ...sceneMutators(scene),\n // What is shown, where the mutators' other users read the document:\n // the nodes not hidden, and the effective pose.\n getNodes() {\n const gates = nodeGates(scene);\n return scene.renderOrderNodes().filter((n) => !gates.hidden(n.id));\n },\n getPose(id) {\n const nid = asNodeId(id);\n const n = scene.get(nid);\n if (!n) throw new Error(`sceneToAdapter: unknown node \"${id}\"`);\n return effectivePose(scene, n);\n },\n definesFrame(id) {\n const n = scene.get(asNodeId(id));\n return n === undefined || definesFrame(n);\n },\n getWorldPose(id) {\n if (!composes) return adapter.getPose(id);\n return composeWorldPose(adapter, id, composition.compose);\n },\n // Only present when it would do something: the render walk skips the fold\n // entirely when this is absent, which is the absolute-pose path.\n ...(composes ? { composePose: composition.compose } : {}),\n ...(cascade ? { setPose: (id: string, pose: TPose) => cascade.setPose(asNodeId(id), pose) } : {}),\n poseTarget(id, descriptor) {\n if (cascade === null || scene.get(asNodeId(id))?.kind !== 'group') {\n return scenePoseTarget(scene, id, descriptor ?? d);\n }\n // Its descendants hold poses of their own: a commit moves them, and they are shown beside it.\n const carried = containerCascade(scene, asNodeId(id), d, (pose) => adapter.setPose(id, pose));\n return scenePoseTarget(scene, id, descriptor ?? d, carried);\n },\n getLayers: () => scene.layers.map((l) => ({ id: l.id, visible: l.visible, parallax: l.parallax })),\n subscribeLayers: (listener) => scene.subscribe(listener),\n getLayout: (id) => scene.layoutOf(asNodeId(id)),\n // With a label the ops are one batch checkpoint; without one they are\n // applied transiently, with no checkpoint (the AreaSelectAdapter contract).\n applyOps(ops: Op[], label?: string) {\n if (label !== undefined) {\n scene.applyBatch(ops, label, this);\n } else {\n applyOpsTo(this, ops);\n }\n },\n getSelection,\n setSelection,\n // The live marquee's and lasso's own hit-tests. Groups come back:\n // this adapter's consumer has nothing to fold children into them.\n hitTestArea(rect: Bounds, view?: RegionPickView) {\n return hitTestArea(\n scene,\n rect,\n pickOptsFor(view),\n d as PoseDescriptor<unknown>,\n { includeGroups: true },\n );\n },\n hitTestLasso(polygon, mode: LassoHitMode, view?: RegionPickView) {\n return hitTestLassoPolygon(\n scene,\n polygon,\n mode,\n pickOptsFor(view),\n d as PoseDescriptor<unknown>,\n { includeGroups: true },\n );\n },\n // A pure factory: it constructs a Node spec but does NOT touch the scene.\n // The `InsertOp` → `adapter.insertNode` → `scene.add` path is the sole\n // insertion path. Calling `scene.add` here too would double-insert, and\n // the second add throws on id collision.\n ...(options.commitInsert\n ? {\n commitInsert: (bounds: { x: number; y: number; width: number; height: number }) => {\n const created = options.commitInsert!(bounds);\n if (!created) return null;\n const layer = (options.insertLayer ?? ('default' as TLayer));\n const id = created.id === undefined ? scene.mintId() : asNodeId(created.id);\n return {\n kind: 'mark',\n id,\n layer,\n pose: created.pose,\n data: created.data,\n parent: null,\n } as Node<TData, TLayer, TPose>;\n },\n }\n : {}),\n // Clipboard seam (`useClipboardOps` / the paste ingestion path).\n snapshotSelection(ids: string[]): ClipboardSnapshot {\n return snapshotSceneSelection(clipboardEnv, ids);\n },\n commitPaste(\n clipboard: ClipboardSnapshot,\n offset: { dx: number; dy: number },\n ctx?: PasteCtx,\n ): Node<TData, TLayer, TPose>[] {\n return pasteSceneSnapshot(clipboardEnv, clipboard, offset, ctx);\n },\n // Constant cascade: the hook re-snapshots the just-created items, so\n // repeated pastes stack +12/+12 each time.\n getPasteOffset(): { dx: number; dy: number } {\n return { dx: 12, dy: 12 };\n },\n };\n\n return adapter;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkJA,SAAgB,eACd,OACA,UAAuD,CAAC,GACd;CAC1C,MAAM,MAAM,QAAQ;CACpB,MAAM,eAAe,KAAK,gBAAgB,KAAK,cAAc,CAAC;CAC9D,MAAM,eAAe,KAAK,gBAAgB,KAAK,cAAc,CAAC;CAC9D,MAAM,IAAK,QAAQ,kBAAkB;CACrC,MAAM,cAAc,GAAU,SAC5B,0BAA0B,GAAG,sBAAsB,GAAG,IAAI,CAAC;CAC7D,MAAM,aAAa,GAAU,IAAY,IAAY,SACnD,2BACE,GAAG,IAAI,IAAI,SAAS,SAAY,IAAI,sBAAsB,GAAG,IAAI,CACnE;CAEF,MAAM,cAAc,MAAM;CAC1B,MAAM,WAAW,eAAe,WAAW;CAC3C,MAAM,WAA4C,CAAC;CAEnD,MAAM,eAAe,SAClB,OAAO;EAAE,GAAG;EAAU,GAAG,kBAAkB,MAAM,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scene/dependents.js";
1
2
  import { definesFrame } from "../core/scene/effectivePose.js";
2
3
  import { asNodeId } from "../core/scene/types.js";
3
4
  import { NODE_FN_FIELDS, createNodeFnFields, fnFieldsOfNode, fnKeysOf } from "../core/scene/nodeFnFields.js";
4
5
  import { statedFields } from "../core/scene/statedFields.js";
6
+ import { hasChildren } from "../core/scene/treeShape.js";
5
7
 
6
8
  //#region src/canvas/sceneClipboard.ts
7
9
  function copyField(value) {
@@ -9,7 +11,6 @@ function copyField(value) {
9
11
  if (value !== null && typeof value === "object") return { ...value };
10
12
  return value;
11
13
  }
12
- var dependencyList = (item) => Array.isArray(item.dependsOn) ? item.dependsOn : [];
13
14
  function snapshotSceneSelection(env, ids) {
14
15
  const { scene } = env;
15
16
  const fnFields = createNodeFnFields(scene.registry);
@@ -34,13 +35,13 @@ function snapshotSceneSelection(env, ids) {
34
35
  parent: n.parent,
35
36
  pose: copyField(poseFor(n, isRoot)),
36
37
  data: copyField(n.data),
37
- ...n.kind === "container" ? { children: [...n.children] } : {},
38
+ ...n.children !== void 0 ? { children: [...n.children] } : {},
38
39
  ...statedFields(n),
39
40
  ...n.dependsOn !== void 0 ? { dependsOn: copyField(n.dependsOn) } : {},
40
41
  ...fnFieldsOfNode(n),
41
42
  ...fnKeysOf(fnFields, n, "jsonKey")
42
43
  });
43
- if (n.kind === "container") for (const cid of scene.childrenOf(asNodeId(id))) capture(cid);
44
+ if (hasChildren(n)) for (const cid of scene.childrenOf(asNodeId(id))) capture(cid);
44
45
  };
45
46
  for (const id of ids) {
46
47
  if (scene.ancestorsOf(asNodeId(id)).some((a) => idSet.has(a))) continue;
@@ -57,7 +58,6 @@ function restoredFnFields(scene, item) {
57
58
  const out = {};
58
59
  const registry = scene.registry;
59
60
  for (const spec of NODE_FN_FIELDS) {
60
- if (spec.containersOnly && item.kind !== "container") continue;
61
61
  const key = item[spec.jsonKey];
62
62
  const fn = (typeof key === "string" ? registry[spec.field]?.[key] : void 0) ?? (isLive(item[spec.field]) ? item[spec.field] : void 0);
63
63
  if (fn !== void 0) out[spec.field] = fn;
@@ -79,7 +79,7 @@ function omissions(src, fns) {
79
79
  for (const item of src) {
80
80
  if (out.has(item.id)) continue;
81
81
  let omission;
82
- const deps = dependencyList(item);
82
+ const deps = sourcesOf(item);
83
83
  const missing = deps.filter((dep) => !present.has(dep));
84
84
  const fn = fns.get(item.id);
85
85
  if (item.parent !== null && out.has(item.parent)) omission = {
@@ -142,16 +142,23 @@ function pasteSceneSnapshot(env, clipboard, offset, ctx) {
142
142
  dy = ctx.dropPoint.worldY - minY;
143
143
  }
144
144
  }
145
+ const site = env.landing?.();
146
+ const into = site?.parent != null ? site : null;
147
+ const placed = (item) => {
148
+ if (ridesPastedFrame(item)) return copyField(item.pose);
149
+ const moved = env.translate(copyField(item.pose), dx, dy, item);
150
+ return into && isRoot(item) ? into.local(moved) : moved;
151
+ };
145
152
  return src.map((item) => ({
146
153
  id: idMap.get(item.id),
147
154
  kind: item.kind,
148
- layer: item.layer,
149
- parent: isRoot(item) ? null : idMap.get(item.parent),
150
- pose: ridesPastedFrame(item) ? copyField(item.pose) : env.translate(copyField(item.pose), dx, dy, item),
155
+ layer: into && isRoot(item) ? into.layer : item.layer,
156
+ parent: isRoot(item) ? into?.parent ?? null : idMap.get(item.parent),
157
+ pose: placed(item),
151
158
  data: copyField(item.data),
152
159
  ...statedFields(item),
153
- ...item.kind === "container" ? { children: item.children.filter((c) => idMap.has(c)).map((c) => idMap.get(c)) } : {},
154
- ...item.dependsOn === "children" ? { dependsOn: "children" } : dependencyList(item).length > 0 ? { dependsOn: dependencyList(item).map((dep) => idMap.get(dep)) } : {},
160
+ ...item.children !== void 0 ? { children: item.children.filter((c) => idMap.has(c)).map((c) => idMap.get(c)) } : {},
161
+ ...item.dependsOn === "children" ? { dependsOn: "children" } : sourcesOf(item).length > 0 ? { dependsOn: sourcesOf(item).map((dep) => idMap.get(dep)) } : {},
155
162
  ...fns.get(item.id)
156
163
  }));
157
164
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sceneClipboard.js","names":[],"sources":["../../src/canvas/sceneClipboard.ts"],"sourcesContent":["/**\n * The scene adapter's clipboard seam: what a copy captures and what a paste\n * mints from it.\n *\n * `pasteSceneSnapshot` is a pure factory — it mints fresh nodes and never\n * touches the scene. Insertion happens through the caller's InsertOps (one per\n * created node, parents before children).\n *\n * A snapshot item carries its node's function fields twice: live, for a paste\n * in the same session, and as the scene's registry keys, for a snapshot that\n * crossed JSON on the way back.\n */\nimport type { ClipboardSnapshot, PasteCtx, PasteOmission } from 'core/adapters/types';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport { asNodeId } from 'core/scene/types';\nimport { definesFrame } from 'core/scene/effectivePose';\nimport {\n NODE_FN_FIELDS, createNodeFnFields, fnFieldsOfNode, fnKeysOf, type FnBearingNode,\n} from 'core/scene/nodeFnFields';\nimport { statedFields } from 'core/scene/statedFields';\nimport type { Bounds } from '../core/viewport/fitViewToBounds';\n\n/** What the seam needs from the adapter it serves. */\nexport interface SceneClipboardEnv<TData, TLayer extends string, TPose> {\n scene: Scene<TData, TLayer, TPose>;\n /** Whether a stored pose is relative to its container's frame. */\n composes: boolean;\n worldPoseOf(id: string): TPose;\n /** The nearest frame-defining container at or above `id`. */\n frameAtOrAbove(id: string | null): string | null;\n poseBounds(pose: TPose, node: unknown): Bounds;\n translate(pose: TPose, dx: number, dy: number, node?: unknown): TPose;\n}\n\n// Spread-level copy per the clipboard contract: mutating a snapshot's\n// pose/data/children must not touch the scene.\nfunction copyField<T>(value: T): T {\n if (Array.isArray(value)) return [...value] as T;\n if (value !== null && typeof value === 'object') return { ...(value as object) } as T;\n return value;\n}\n\ntype Item<TData, TLayer extends string, TPose> =\n Node<TData, TLayer, TPose> & Record<string, unknown>;\n\nconst dependencyList = (item: { dependsOn?: readonly NodeId[] | 'children' }): readonly NodeId[] =>\n (Array.isArray(item.dependsOn) ? item.dependsOn : []);\n\nexport function snapshotSceneSelection<TData, TLayer extends string, TPose>(\n env: SceneClipboardEnv<TData, TLayer, TPose>,\n ids: string[],\n): ClipboardSnapshot {\n const { scene } = env;\n const fnFields = createNodeFnFields<TPose>(scene.registry as never);\n const idSet = new Set(ids);\n const taken = new Set<string>();\n const items: Node<TData, TLayer, TPose>[] = [];\n // A stored pose is relative to its frame, and a node whose frame is not\n // copied with it lands somewhere else entirely on paste. Capture those in\n // world coordinates: every root, and under an envelope root, the nodes\n // sharing the frame the root left behind.\n const poseFor = (n: Node<TData, TLayer, TPose>, isRoot: boolean): TPose => {\n if (!env.composes) return n.pose;\n if (isRoot) return env.worldPoseOf(n.id);\n const frame = env.frameAtOrAbove(n.parent);\n return frame !== null && taken.has(frame) ? n.pose : env.worldPoseOf(n.id);\n };\n\n // DFS from one snapshot root: push the node, then its subtree —\n // parents-before-children, so paste can re-insert in array order.\n const capture = (id: string, isRoot = false): void => {\n if (taken.has(id)) return;\n const n = scene.get(asNodeId(id));\n if (!n) return;\n taken.add(id);\n items.push({\n kind: n.kind,\n id: n.id,\n layer: n.layer,\n parent: n.parent,\n pose: copyField(poseFor(n, isRoot)),\n data: copyField(n.data),\n ...(n.kind === 'container' ? { children: [...n.children] } : {}),\n ...statedFields(n),\n ...(n.dependsOn !== undefined ? { dependsOn: copyField(n.dependsOn) } : {}),\n ...fnFieldsOfNode(n),\n ...fnKeysOf(fnFields, n as unknown as FnBearingNode, 'jsonKey'),\n } as Node<TData, TLayer, TPose>);\n if (n.kind === 'container') {\n for (const cid of scene.childrenOf(asNodeId(id))) capture(cid);\n }\n };\n for (const id of ids) {\n // Dedupe: an id whose ancestor is also selected is already covered\n // by that ancestor's subtree walk.\n if (scene.ancestorsOf(asNodeId(id)).some((a) => idSet.has(a))) continue;\n capture(id, true);\n }\n return { items };\n}\n\n// JSON drops a function, and turns a layout strategy into an object with no\n// methods on it: neither is something a pasted node can run.\nconst isLive = (value: unknown): boolean =>\n typeof value === 'function'\n || (typeof value === 'object' && value !== null\n && Object.values(value).some((member) => typeof member === 'function'));\n\n/**\n * The item's function fields: for each, what its registry key names in this\n * scene, else the live one it carries, else nothing.\n */\nfunction restoredFnFields<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n item: Item<TData, TLayer, TPose>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const registry = scene.registry as Record<string, Record<string, unknown> | undefined>;\n for (const spec of NODE_FN_FIELDS) {\n if (spec.containersOnly && item.kind !== 'container') continue;\n const key = item[spec.jsonKey];\n const registered = typeof key === 'string' ? registry[spec.field]?.[key] : undefined;\n const fn = registered ?? (isLive(item[spec.field]) ? item[spec.field] : undefined);\n if (fn !== undefined) out[spec.field] = fn;\n }\n return out;\n}\n\n/**\n * Which items a paste leaves out, and why. A node deriving from an id list is\n * pasted only with everything it depends on, since a copy still naming the\n * originals would follow them rather than the copies beside it; and only with\n * a derivation to run, since without one it is a placeholder that paints\n * nothing. Leaving one out can strand another, so this runs to a fixed point.\n */\nfunction omissions<TData, TLayer extends string, TPose>(\n src: readonly Item<TData, TLayer, TPose>[],\n fns: ReadonlyMap<string, Record<string, unknown>>,\n): Map<string, PasteOmission> {\n const out = new Map<string, PasteOmission>();\n const present = new Set(src.map((item) => item.id as string));\n for (let changed = true; changed;) {\n changed = false;\n for (const item of src) {\n if (out.has(item.id)) continue;\n let omission: PasteOmission | undefined;\n const deps = dependencyList(item);\n const missing = deps.filter((dep) => !present.has(dep));\n const fn = fns.get(item.id)!;\n if (item.parent !== null && out.has(item.parent)) {\n omission = { id: item.id, reason: 'container-not-pasted' };\n } else if (missing.length > 0) {\n omission = { id: item.id, reason: 'dependency-not-copied', missing };\n } else if (deps.length > 0 && fn.derivePath === undefined && fn.derivePose === undefined) {\n omission = { id: item.id, reason: 'derivation-not-registered' };\n }\n if (omission === undefined) continue;\n out.set(item.id, omission);\n present.delete(item.id);\n changed = true;\n }\n }\n return out;\n}\n\nexport function pasteSceneSnapshot<TData, TLayer extends string, TPose>(\n env: SceneClipboardEnv<TData, TLayer, TPose>,\n clipboard: ClipboardSnapshot,\n offset: { dx: number; dy: number },\n ctx?: PasteCtx,\n): Node<TData, TLayer, TPose>[] {\n const all = clipboard.items as Item<TData, TLayer, TPose>[];\n if (all.length === 0) return [];\n const fns = new Map(all.map((item) => [item.id as string, restoredFnFields(env.scene, item)]));\n const omitted = omissions(all, fns);\n if (ctx?.onOmit) for (const item of all) {\n const omission = omitted.get(item.id);\n if (omission) ctx.onOmit(omission);\n }\n const src = omitted.size === 0 ? all : all.filter((item) => !omitted.has(item.id));\n\n const idMap = new Map<string, NodeId>();\n for (const item of src) idMap.set(item.id, env.scene.mintId());\n // Items whose captured parent isn't part of the snapshot become roots\n // of the pasted cluster.\n const isRoot = (item: Node<TData, TLayer, TPose>): boolean =>\n item.parent === null || !idMap.has(item.parent);\n // Under a composing strategy a node inside a pasted frame rides it, and\n // offsetting it as well would move it twice.\n const byId = new Map(src.map((item) => [item.id as string, item]));\n const ridesPastedFrame = (item: Node<TData, TLayer, TPose>): boolean => {\n if (!env.composes) return false;\n let p = item.parent === null ? undefined : byId.get(item.parent);\n while (p !== undefined) {\n if (definesFrame(p)) return true;\n p = p.parent === null ? undefined : byId.get(p.parent);\n }\n return false;\n };\n // Without composition poses are absolute, so the delta applies to EVERY\n // pasted node.\n let dx = offset.dx;\n let dy = offset.dy;\n if (ctx?.dropPoint) {\n // Drop-point policy: land the cluster origin (min corner of the root\n // items' bounds) on the drop point; `offset` is ignored.\n let minX = Infinity;\n let minY = Infinity;\n for (const item of src) {\n if (!isRoot(item)) continue;\n const b = env.poseBounds(item.pose, item);\n if (b.x < minX) minX = b.x;\n if (b.y < minY) minY = b.y;\n }\n if (Number.isFinite(minX) && Number.isFinite(minY)) {\n dx = ctx.dropPoint.worldX - minX;\n dy = ctx.dropPoint.worldY - minY;\n }\n }\n // `src` is parents-before-children and this keeps it, so children re-attach\n // to freshly inserted parents when the caller's InsertOps apply in order.\n return src.map((item) => ({\n id: idMap.get(item.id)!,\n kind: item.kind,\n layer: item.layer,\n parent: isRoot(item) ? null : idMap.get(item.parent as string)!,\n pose: ridesPastedFrame(item)\n ? copyField(item.pose)\n : env.translate(copyField(item.pose), dx, dy, item),\n data: copyField(item.data),\n ...statedFields(item),\n ...(item.kind === 'container'\n ? { children: item.children.filter((c) => idMap.has(c)).map((c) => idMap.get(c)!) }\n : {}),\n ...(item.dependsOn === 'children'\n ? { dependsOn: 'children' as const }\n : dependencyList(item).length > 0\n ? { dependsOn: dependencyList(item).map((dep) => idMap.get(dep)!) }\n : {}),\n ...fns.get(item.id),\n } as Node<TData, TLayer, TPose>));\n}\n"],"mappings":";;;;;;AAoCA,SAAS,UAAa,OAAa;CACjC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,GAAG,KAAK;CAC1C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,EAAE,GAAI,MAAiB;CAC/E,OAAO;AACT;AAKA,IAAM,kBAAkB,SACrB,MAAM,QAAQ,KAAK,SAAS,IAAI,KAAK,YAAY,CAAC;AAErD,SAAgB,uBACd,KACA,KACmB;CACnB,MAAM,EAAE,UAAU;CAClB,MAAM,WAAW,mBAA0B,MAAM,QAAiB;CAClE,MAAM,QAAQ,IAAI,IAAI,GAAG;CACzB,MAAM,wBAAQ,IAAI,IAAY;CAC9B,MAAM,QAAsC,CAAC;CAK7C,MAAM,WAAW,GAA+B,WAA2B;EACzE,IAAI,CAAC,IAAI,UAAU,OAAO,EAAE;EAC5B,IAAI,QAAQ,OAAO,IAAI,YAAY,EAAE,EAAE;EACvC,MAAM,QAAQ,IAAI,eAAe,EAAE,MAAM;EACzC,OAAO,UAAU,QAAQ,MAAM,IAAI,KAAK,IAAI,EAAE,OAAO,IAAI,YAAY,EAAE,EAAE;CAC3E;CAIA,MAAM,WAAW,IAAY,SAAS,UAAgB;EACpD,IAAI,MAAM,IAAI,EAAE,GAAG;EACnB,MAAM,IAAI,MAAM,IAAI,SAAS,EAAE,CAAC;EAChC,IAAI,CAAC,GAAG;EACR,MAAM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,IAAI,IAAI,OAAO,MAAM,IAAI,KAAK,MAAgB;EAC7D,MAAM,iBAAiB,IAAI,IACvB,UAAU,KAAK,IAAI,IACnB,IAAI,UAAU,UAAU,KAAK,IAAI,GAAG,IAAI,IAAI,IAAI;EACpD,MAAM,UAAU,KAAK,IAAI;EACzB,GAAG,aAAa,IAAI;EACpB,GAAI,KAAK,SAAS,cACd,EAAE,UAAU,KAAK,SAAS,QAAQ,MAAM,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,MAAM,IAAI,CAAC,CAAE,EAAE,IAChF,CAAC;EACL,GAAI,KAAK,cAAc,aACnB,EAAE,WAAW,WAAoB,IACjC,eAAe,IAAI,CAAC,CAAC,SAAS,IAC5B,EAAE,WAAW,eAAe,IAAI,CAAC,CAAC,KAAK,QAAQ,MAAM,IAAI,GAAG,CAAE,EAAE,IAChE,CAAC;EACP,GAAG,IAAI,IAAI,KAAK,EAAE;CACpB,EAAgC;AAClC"}
1
+ {"version":3,"file":"sceneClipboard.js","names":[],"sources":["../../src/canvas/sceneClipboard.ts"],"sourcesContent":["/**\n * The scene adapter's clipboard seam: what a copy captures and what a paste\n * mints from it.\n *\n * `pasteSceneSnapshot` is a pure factory — it mints fresh nodes and never\n * touches the scene. Insertion happens through the caller's InsertOps (one per\n * created node, parents before children).\n *\n * A snapshot item carries its node's function fields twice: live, for a paste\n * in the same session, and as the scene's registry keys, for a snapshot that\n * crossed JSON on the way back.\n */\nimport type { ClipboardSnapshot, PasteCtx, PasteOmission } from 'core/adapters/types';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport { asNodeId } from 'core/scene/types';\nimport { hasChildren } from 'core/scene/treeShape';\nimport { sourcesOf } from 'core/scene/dependents';\nimport { definesFrame } from 'core/scene/effectivePose';\nimport {\n NODE_FN_FIELDS, createNodeFnFields, fnFieldsOfNode, fnKeysOf, type FnBearingNode,\n} from 'core/scene/nodeFnFields';\nimport { statedFields } from 'core/scene/statedFields';\nimport type { Bounds } from '../core/viewport/fitViewToBounds';\nimport type { InsertSite } from './deps/insertSite';\n\n/** What the seam needs from the adapter it serves. */\nexport interface SceneClipboardEnv<TData, TLayer extends string, TPose> {\n scene: Scene<TData, TLayer, TPose>;\n /** Whether a stored pose is relative to its container's frame. */\n composes: boolean;\n worldPoseOf(id: string): TPose;\n /** The nearest frame-defining container at or above `id`. */\n frameAtOrAbove(id: string | null): string | null;\n poseBounds(pose: TPose, node: unknown): Bounds;\n translate(pose: TPose, dx: number, dy: number, node?: unknown): TPose;\n /** Where the pasted cluster's roots land; absent, or naming no parent, they keep their layer at the top of the tree. */\n landing?: () => InsertSite;\n}\n\n// Spread-level copy per the clipboard contract: mutating a snapshot's\n// pose/data/children must not touch the scene.\nfunction copyField<T>(value: T): T {\n if (Array.isArray(value)) return [...value] as T;\n if (value !== null && typeof value === 'object') return { ...(value as object) } as T;\n return value;\n}\n\ntype Item<TData, TLayer extends string, TPose> =\n Node<TData, TLayer, TPose> & Record<string, unknown>;\n\nexport function snapshotSceneSelection<TData, TLayer extends string, TPose>(\n env: SceneClipboardEnv<TData, TLayer, TPose>,\n ids: string[],\n): ClipboardSnapshot {\n const { scene } = env;\n const fnFields = createNodeFnFields<TPose>(scene.registry as never);\n const idSet = new Set(ids);\n const taken = new Set<string>();\n const items: Node<TData, TLayer, TPose>[] = [];\n // A stored pose is relative to its frame, and a node whose frame is not\n // copied with it lands somewhere else entirely on paste. Capture those in\n // world coordinates: every root, and under an envelope root, the nodes\n // sharing the frame the root left behind.\n const poseFor = (n: Node<TData, TLayer, TPose>, isRoot: boolean): TPose => {\n if (!env.composes) return n.pose;\n if (isRoot) return env.worldPoseOf(n.id);\n const frame = env.frameAtOrAbove(n.parent);\n return frame !== null && taken.has(frame) ? n.pose : env.worldPoseOf(n.id);\n };\n\n // DFS from one snapshot root: push the node, then its subtree —\n // parents-before-children, so paste can re-insert in array order.\n const capture = (id: string, isRoot = false): void => {\n if (taken.has(id)) return;\n const n = scene.get(asNodeId(id));\n if (!n) return;\n taken.add(id);\n items.push({\n kind: n.kind,\n id: n.id,\n layer: n.layer,\n parent: n.parent,\n pose: copyField(poseFor(n, isRoot)),\n data: copyField(n.data),\n ...(n.children !== undefined ? { children: [...n.children] } : {}),\n ...statedFields(n),\n ...(n.dependsOn !== undefined ? { dependsOn: copyField(n.dependsOn) } : {}),\n ...fnFieldsOfNode(n),\n ...fnKeysOf(fnFields, n as unknown as FnBearingNode, 'jsonKey'),\n } as Node<TData, TLayer, TPose>);\n if (hasChildren(n)) {\n for (const cid of scene.childrenOf(asNodeId(id))) capture(cid);\n }\n };\n for (const id of ids) {\n // Dedupe: an id whose ancestor is also selected is already covered\n // by that ancestor's subtree walk.\n if (scene.ancestorsOf(asNodeId(id)).some((a) => idSet.has(a))) continue;\n capture(id, true);\n }\n return { items };\n}\n\n// JSON drops a function, and turns a layout strategy into an object with no\n// methods on it: neither is something a pasted node can run.\nconst isLive = (value: unknown): boolean =>\n typeof value === 'function'\n || (typeof value === 'object' && value !== null\n && Object.values(value).some((member) => typeof member === 'function'));\n\n/**\n * The item's function fields: for each, what its registry key names in this\n * scene, else the live one it carries, else nothing.\n */\nfunction restoredFnFields<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n item: Item<TData, TLayer, TPose>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const registry = scene.registry as Record<string, Record<string, unknown> | undefined>;\n for (const spec of NODE_FN_FIELDS) {\n const key = item[spec.jsonKey];\n const registered = typeof key === 'string' ? registry[spec.field]?.[key] : undefined;\n const fn = registered ?? (isLive(item[spec.field]) ? item[spec.field] : undefined);\n if (fn !== undefined) out[spec.field] = fn;\n }\n return out;\n}\n\n/**\n * Which items a paste leaves out, and why. A node deriving from an id list is\n * pasted only with everything it depends on, since a copy still naming the\n * originals would follow them rather than the copies beside it; and only with\n * a derivation to run, since without one it is a placeholder that paints\n * nothing. Leaving one out can strand another, so this runs to a fixed point.\n */\nfunction omissions<TData, TLayer extends string, TPose>(\n src: readonly Item<TData, TLayer, TPose>[],\n fns: ReadonlyMap<string, Record<string, unknown>>,\n): Map<string, PasteOmission> {\n const out = new Map<string, PasteOmission>();\n const present = new Set(src.map((item) => item.id as string));\n for (let changed = true; changed;) {\n changed = false;\n for (const item of src) {\n if (out.has(item.id)) continue;\n let omission: PasteOmission | undefined;\n const deps = sourcesOf(item);\n const missing = deps.filter((dep) => !present.has(dep));\n const fn = fns.get(item.id)!;\n if (item.parent !== null && out.has(item.parent)) {\n omission = { id: item.id, reason: 'container-not-pasted' };\n } else if (missing.length > 0) {\n omission = { id: item.id, reason: 'dependency-not-copied', missing };\n } else if (deps.length > 0 && fn.derivePath === undefined && fn.derivePose === undefined) {\n omission = { id: item.id, reason: 'derivation-not-registered' };\n }\n if (omission === undefined) continue;\n out.set(item.id, omission);\n present.delete(item.id);\n changed = true;\n }\n }\n return out;\n}\n\nexport function pasteSceneSnapshot<TData, TLayer extends string, TPose>(\n env: SceneClipboardEnv<TData, TLayer, TPose>,\n clipboard: ClipboardSnapshot,\n offset: { dx: number; dy: number },\n ctx?: PasteCtx,\n): Node<TData, TLayer, TPose>[] {\n const all = clipboard.items as Item<TData, TLayer, TPose>[];\n if (all.length === 0) return [];\n const fns = new Map(all.map((item) => [item.id as string, restoredFnFields(env.scene, item)]));\n const omitted = omissions(all, fns);\n if (ctx?.onOmit) for (const item of all) {\n const omission = omitted.get(item.id);\n if (omission) ctx.onOmit(omission);\n }\n const src = omitted.size === 0 ? all : all.filter((item) => !omitted.has(item.id));\n\n const idMap = new Map<string, NodeId>();\n for (const item of src) idMap.set(item.id, env.scene.mintId());\n // Items whose captured parent isn't part of the snapshot become roots\n // of the pasted cluster.\n const isRoot = (item: Node<TData, TLayer, TPose>): boolean =>\n item.parent === null || !idMap.has(item.parent);\n // Under a composing strategy a node inside a pasted frame rides it, and\n // offsetting it as well would move it twice.\n const byId = new Map(src.map((item) => [item.id as string, item]));\n const ridesPastedFrame = (item: Node<TData, TLayer, TPose>): boolean => {\n if (!env.composes) return false;\n let p = item.parent === null ? undefined : byId.get(item.parent);\n while (p !== undefined) {\n if (definesFrame(p)) return true;\n p = p.parent === null ? undefined : byId.get(p.parent);\n }\n return false;\n };\n // Without composition poses are absolute, so the delta applies to EVERY\n // pasted node.\n let dx = offset.dx;\n let dy = offset.dy;\n if (ctx?.dropPoint) {\n // Drop-point policy: land the cluster origin (min corner of the root\n // items' bounds) on the drop point; `offset` is ignored.\n let minX = Infinity;\n let minY = Infinity;\n for (const item of src) {\n if (!isRoot(item)) continue;\n const b = env.poseBounds(item.pose, item);\n if (b.x < minX) minX = b.x;\n if (b.y < minY) minY = b.y;\n }\n if (Number.isFinite(minX) && Number.isFinite(minY)) {\n dx = ctx.dropPoint.worldX - minX;\n dy = ctx.dropPoint.worldY - minY;\n }\n }\n const site = env.landing?.();\n const into = site?.parent != null ? site : null;\n const placed = (item: Item<TData, TLayer, TPose>): TPose => {\n if (ridesPastedFrame(item)) return copyField(item.pose);\n const moved = env.translate(copyField(item.pose), dx, dy, item);\n return into && isRoot(item) ? into.local(moved) as TPose : moved;\n };\n // `src` is parents-before-children and this keeps it, so children re-attach\n // to freshly inserted parents when the caller's InsertOps apply in order.\n return src.map((item) => ({\n id: idMap.get(item.id)!,\n kind: item.kind,\n layer: into && isRoot(item) ? into.layer as TLayer : item.layer,\n parent: isRoot(item) ? into?.parent ?? null : idMap.get(item.parent as string)!,\n pose: placed(item),\n data: copyField(item.data),\n ...statedFields(item),\n ...(item.children !== undefined\n ? { children: item.children.filter((c) => idMap.has(c)).map((c) => idMap.get(c)!) }\n : {}),\n ...(item.dependsOn === 'children'\n ? { dependsOn: 'children' as const }\n : sourcesOf(item).length > 0\n ? { dependsOn: sourcesOf(item).map((dep) => idMap.get(dep)!) }\n : {}),\n ...fns.get(item.id),\n } as Node<TData, TLayer, TPose>));\n}\n"],"mappings":";;;;;;;;AAyCA,SAAS,UAAa,OAAa;CACjC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,C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C,CAAC,CAAC,KAAK,MAAM,MAAM,IAAI,CAAC,CAAE,EAAE,IAChF,CAAC;EACL,GAAI,KAAK,cAAc,aACnB,EAAE,WAAW,WAAoB,IACjC,UAAU,IAAI,CAAC,CAAC,SAAS,IACvB,EAAE,WAAW,UAAU,IAAI,CAAC,CAAC,KAAK,QAAQ,MAAM,IAAI,GAAG,CAAE,EAAE,IAC3D,CAAC;EACP,GAAG,IAAI,IAAI,KAAK,EAAE;CACpB,EAAgC;AAClC"}
@@ -0,0 +1,37 @@
1
+ import { asNodeId } from "../core/scene/types.js";
2
+ import { sceneDerivedPathOf, showsComputedPath } from "./derivedPath.js";
3
+
4
+ //#region src/canvas/scenePickReads.ts
5
+ /** Shared, never mutated: most scenes are flat and every node returns it. */
6
+ var EMPTY_PARENTS = [];
7
+ /** `(node) => its ancestors, innermost first`, stopping at a cycle or a missing parent. */
8
+ function sceneParentsOf(scene) {
9
+ return (node) => {
10
+ let parentId = node.parent ?? null;
11
+ if (parentId === null) return EMPTY_PARENTS;
12
+ const chain = [];
13
+ const seen = /* @__PURE__ */ new Set();
14
+ while (parentId !== null) {
15
+ if (seen.has(parentId)) break;
16
+ seen.add(parentId);
17
+ const parent = scene.get(asNodeId(parentId));
18
+ if (!parent) break;
19
+ chain.push(parent);
20
+ parentId = parent.parent ?? null;
21
+ }
22
+ return chain;
23
+ };
24
+ }
25
+ /** `(node) => the path it shows in place of its pose`, or null: an override's
26
+ * path or the one it derives, at the poses the scene paints its dependencies. */
27
+ function sceneShownPathOf(scene) {
28
+ const derived = sceneDerivedPathOf(scene);
29
+ return (node) => {
30
+ const n = node;
31
+ return showsComputedPath(scene, n) ? derived(n) : null;
32
+ };
33
+ }
34
+
35
+ //#endregion
36
+ export { sceneParentsOf, sceneShownPathOf };
37
+ //# sourceMappingURL=scenePickReads.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scenePickReads.js","names":[],"sources":["../../src/canvas/scenePickReads.ts"],"sourcesContent":["/** What a scene-backed pick reads per node, shared by `scenePickSource` and the\n * pick index so the two cannot disagree about a node's ancestors or path. */\nimport type { Path } from '@weasel-js/geom';\nimport { asNodeId, type Node, type Scene } from 'core/scene/types';\nimport { sceneDerivedPathOf, showsComputedPath } from './derivedPath';\nimport type { PickCandidate } from './pickWalk';\n\n/** Shared, never mutated: most scenes are flat and every node returns it. */\nconst EMPTY_PARENTS: readonly never[] = [];\n\n/** `(node) => its ancestors, innermost first`, stopping at a cycle or a missing parent. */\nexport function sceneParentsOf<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n): (node: PickCandidate<TPose>) => readonly PickCandidate<TPose>[] {\n return (node) => {\n let parentId = (node as { parent?: string | null }).parent ?? null;\n if (parentId === null) return EMPTY_PARENTS;\n const chain: PickCandidate<TPose>[] = [];\n const seen = new Set<string>();\n while (parentId !== null) {\n if (seen.has(parentId)) break;\n seen.add(parentId);\n const parent = scene.get(asNodeId(parentId));\n if (!parent) break;\n chain.push(parent as unknown as PickCandidate<TPose>);\n parentId = parent.parent ?? null;\n }\n return chain;\n };\n}\n\n/** `(node) => the path it shows in place of its pose`, or null: an override's\n * path or the one it derives, at the poses the scene paints its dependencies. */\nexport function sceneShownPathOf<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n): (node: PickCandidate<TPose>) => Path | null {\n const derived = sceneDerivedPathOf(scene);\n return (node) => {\n const n = node as unknown as Node<TData, TLayer, TPose>;\n return showsComputedPath(scene, n) ? derived(n) : null;\n };\n}\n"],"mappings":";;;;;AAQA,IAAM,gBAAkC,CAAC;;AAGzC,SAAgB,eACd,OACiE;CACjE,QAAQ,SAAS;EACf,IAAI,WAAY,KAAoC,UAAU;EAC9D,IAAI,aAAa,MAAM,OAAO;EAC9B,MAAM,QAAgC,CAAC;EACvC,MAAM,uBAAO,IAAI,IAAY;EAC7B,OAAO,aAAa,MAAM;GACxB,IAAI,KAAK,IAAI,QAAQ,GAAG;GACxB,KAAK,IAAI,QAAQ;GACjB,MAAM,SAAS,MAAM,IAAI,SAAS,QAAQ,CAAC;GAC3C,IAAI,CAAC,QAAQ;GACb,MAAM,KAAK,MAAyC;GACpD,WAAW,OAAO,UAAU;EAC9B;EACA,OAAO;CACT;AACF;;;AAIA,SAAgB,iBACd,OAC6C;CAC7C,MAAM,UAAU,mBAAmB,KAAK;CACxC,QAAQ,SAAS;EACf,MAAM,IAAI;EACV,OAAO,kBAAkB,OAAO,CAAC,IAAI,QAAQ,CAAC,IAAI;CACpD;AACF"}