@weasel-js/core 1.11.0 → 1.12.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 (586) hide show
  1. package/CHANGELOG.md +611 -0
  2. package/README.md +1 -1
  3. package/dist/WeaselProvider.js +1 -1
  4. package/dist/affordances/pathAnchors.js +10 -6
  5. package/dist/affordances/pathAnchors.js.map +1 -1
  6. package/dist/animation/index.js +3 -3
  7. package/dist/animation/rig/bindRig.js +1 -1
  8. package/dist/animation/rig/rigNode.js.map +1 -1
  9. package/dist/barrel/canvas.js +9 -3
  10. package/dist/barrel/interactions.js +5 -4
  11. package/dist/barrel/paint.js +4 -4
  12. package/dist/barrel/paths.js +10 -6
  13. package/dist/barrel/renderer.js +5 -3
  14. package/dist/barrel/routing.js +7 -12
  15. package/dist/barrel/scene.js +9 -5
  16. package/dist/barrel/text.js +2 -2
  17. package/dist/barrel/viewport.js +9 -4
  18. package/dist/canvas/Canvas.js +5 -2
  19. package/dist/canvas/Canvas.js.map +1 -1
  20. package/dist/canvas/CanvasView.js +23 -34
  21. package/dist/canvas/CanvasView.js.map +1 -1
  22. package/dist/canvas/ModalityHud.js +1 -1
  23. package/dist/canvas/NodeShape.js +4 -1
  24. package/dist/canvas/NodeShape.js.map +1 -1
  25. package/dist/canvas/SceneCanvas/ActionsProviderIfRoot.js +1 -1
  26. package/dist/canvas/SceneCanvas/DepRegistryProviderIfRoot.js +1 -1
  27. package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js +1 -1
  28. package/dist/canvas/SceneCanvas/SceneCanvasInput.js +17 -3
  29. package/dist/canvas/SceneCanvas/SceneCanvasInput.js.map +1 -1
  30. package/dist/canvas/SceneCanvas/SurfaceDeclarations.js +23 -0
  31. package/dist/canvas/SceneCanvas/SurfaceDeclarations.js.map +1 -0
  32. package/dist/canvas/SceneCanvas/builtinToolSets.js +30 -0
  33. package/dist/canvas/SceneCanvas/builtinToolSets.js.map +1 -0
  34. package/dist/canvas/SceneCanvas/canvasPassThrough.js +2 -0
  35. package/dist/canvas/SceneCanvas/canvasPassThrough.js.map +1 -1
  36. package/dist/canvas/SceneCanvas/coordTrace.js +5 -16
  37. package/dist/canvas/SceneCanvas/coordTrace.js.map +1 -1
  38. package/dist/canvas/SceneCanvas/defaultNodeProperties.js +5 -0
  39. package/dist/canvas/SceneCanvas/defaultNodeProperties.js.map +1 -1
  40. package/dist/canvas/SceneCanvas/features.js +45 -5
  41. package/dist/canvas/SceneCanvas/features.js.map +1 -1
  42. package/dist/canvas/SceneCanvas/props.js +1 -11
  43. package/dist/canvas/SceneCanvas/props.js.map +1 -1
  44. package/dist/canvas/SceneCanvas/scenePointQuery.js +7 -3
  45. package/dist/canvas/SceneCanvas/scenePointQuery.js.map +1 -1
  46. package/dist/canvas/SceneCanvas/toolRegistry.js +8 -4
  47. package/dist/canvas/SceneCanvas/toolRegistry.js.map +1 -1
  48. package/dist/canvas/SceneCanvas/useActionTunings.js +6 -1
  49. package/dist/canvas/SceneCanvas/useActionTunings.js.map +1 -1
  50. package/dist/canvas/SceneCanvas/useActionsPropResolver.js +1 -11
  51. package/dist/canvas/SceneCanvas/useActionsPropResolver.js.map +1 -1
  52. package/dist/canvas/SceneCanvas/useBuiltinShapeTools.js.map +1 -1
  53. package/dist/canvas/SceneCanvas/useBuiltinTools.js +2 -9
  54. package/dist/canvas/SceneCanvas/useBuiltinTools.js.map +1 -1
  55. package/dist/canvas/SceneCanvas/useCanvasDevtoolsRoot.js +94 -0
  56. package/dist/canvas/SceneCanvas/useCanvasDevtoolsRoot.js.map +1 -0
  57. package/dist/canvas/SceneCanvas/useCanvasSelection.js +7 -2
  58. package/dist/canvas/SceneCanvas/useCanvasSelection.js.map +1 -1
  59. package/dist/canvas/SceneCanvas/useCanvasTools.js +15 -10
  60. package/dist/canvas/SceneCanvas/useCanvasTools.js.map +1 -1
  61. package/dist/canvas/SceneCanvas/useNodeKinds.js +1 -1
  62. package/dist/canvas/SceneCanvas/useNodeKinds.js.map +1 -1
  63. package/dist/canvas/SceneCanvas/useSceneCanvasHandle.js +9 -3
  64. package/dist/canvas/SceneCanvas/useSceneCanvasHandle.js.map +1 -1
  65. package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js +23 -4
  66. package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js.map +1 -1
  67. package/dist/canvas/SceneCanvas/useSceneCanvasTools.js +2 -3
  68. package/dist/canvas/SceneCanvas/useSceneCanvasTools.js.map +1 -1
  69. package/dist/canvas/SceneCanvas/useSceneChrome.js +6 -7
  70. package/dist/canvas/SceneCanvas/useSceneChrome.js.map +1 -1
  71. package/dist/canvas/SceneCanvas/useSceneGestureDispatcher.js +24 -7
  72. package/dist/canvas/SceneCanvas/useSceneGestureDispatcher.js.map +1 -1
  73. package/dist/canvas/SceneCanvas/useScenePicking.js +2 -3
  74. package/dist/canvas/SceneCanvas/useScenePicking.js.map +1 -1
  75. package/dist/canvas/SceneCanvas/useSceneSelectTool.js +2 -1
  76. package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -1
  77. package/dist/canvas/SceneCanvas/useSceneStandardActions.js +5 -5
  78. package/dist/canvas/SceneCanvas/useSceneStandardActions.js.map +1 -1
  79. package/dist/canvas/SceneCanvas.js +27 -24
  80. package/dist/canvas/SceneCanvas.js.map +1 -1
  81. package/dist/canvas/SurfaceCanvas.js +5 -22
  82. package/dist/canvas/SurfaceCanvas.js.map +1 -1
  83. package/dist/canvas/ViewMarker.js +35 -0
  84. package/dist/canvas/ViewMarker.js.map +1 -0
  85. package/dist/canvas/canvasRenderer.js +9 -5
  86. package/dist/canvas/canvasRenderer.js.map +1 -1
  87. package/dist/canvas/contextAttributes.js +14 -0
  88. package/dist/canvas/contextAttributes.js.map +1 -0
  89. package/dist/canvas/defaultDrawOne.js +2 -0
  90. package/dist/canvas/defaultDrawOne.js.map +1 -1
  91. package/dist/canvas/deps/booleans.js +2 -1
  92. package/dist/canvas/deps/booleans.js.map +1 -1
  93. package/dist/canvas/deps/editAnchors.js +9 -113
  94. package/dist/canvas/deps/editAnchors.js.map +1 -1
  95. package/dist/canvas/deps/hitTestArea.js +2 -2
  96. package/dist/canvas/deps/hitTestArea.js.map +1 -1
  97. package/dist/canvas/deps/insert.js +10 -4
  98. package/dist/canvas/deps/insert.js.map +1 -1
  99. package/dist/canvas/deps/pathEditCommits.js +189 -0
  100. package/dist/canvas/deps/pathEditCommits.js.map +1 -0
  101. package/dist/canvas/deps/snap.js +12 -9
  102. package/dist/canvas/deps/snap.js.map +1 -1
  103. package/dist/canvas/deps/transformFollowers.js +20 -0
  104. package/dist/canvas/deps/transformFollowers.js.map +1 -0
  105. package/dist/canvas/derivedPath.js +20 -1
  106. package/dist/canvas/derivedPath.js.map +1 -1
  107. package/dist/canvas/drawnBounds.js +38 -4
  108. package/dist/canvas/drawnBounds.js.map +1 -1
  109. package/dist/canvas/inheritedPaints.js +44 -0
  110. package/dist/canvas/inheritedPaints.js.map +1 -0
  111. package/dist/canvas/nodeShapes/derivedPainter.js +23 -16
  112. package/dist/canvas/nodeShapes/derivedPainter.js.map +1 -1
  113. package/dist/canvas/nodeShapes/nodePaint.js +13 -34
  114. package/dist/canvas/nodeShapes/nodePaint.js.map +1 -1
  115. package/dist/canvas/nodeShapes/pathPainter.js +12 -10
  116. package/dist/canvas/nodeShapes/pathPainter.js.map +1 -1
  117. package/dist/canvas/nodeShapes/rectFallbackPainter.js +4 -5
  118. package/dist/canvas/nodeShapes/rectFallbackPainter.js.map +1 -1
  119. package/dist/canvas/nodeShapes/shapePainter.js +12 -11
  120. package/dist/canvas/nodeShapes/shapePainter.js.map +1 -1
  121. package/dist/canvas/nodeShapes/textPainter.js +13 -12
  122. package/dist/canvas/nodeShapes/textPainter.js.map +1 -1
  123. package/dist/canvas/overlayRoleStrokes.js +12 -0
  124. package/dist/canvas/overlayRoleStrokes.js.map +1 -1
  125. package/dist/canvas/pathOverlay.js +27 -7
  126. package/dist/canvas/pathOverlay.js.map +1 -1
  127. package/dist/canvas/pickReach.js +3 -3
  128. package/dist/canvas/pickReach.js.map +1 -1
  129. package/dist/canvas/pickWalk.js +3 -1
  130. package/dist/canvas/pickWalk.js.map +1 -1
  131. package/dist/canvas/renderDebugSnapshot.js +1 -0
  132. package/dist/canvas/renderDebugSnapshot.js.map +1 -1
  133. package/dist/canvas/renderSceneToPixels.js +7 -6
  134. package/dist/canvas/renderSceneToPixels.js.map +1 -1
  135. package/dist/canvas/sceneAdapter.js.map +1 -1
  136. package/dist/canvas/sceneSlotWiring.js +2 -1
  137. package/dist/canvas/sceneSlotWiring.js.map +1 -1
  138. package/dist/canvas/sceneViewRender.js +2 -1
  139. package/dist/canvas/sceneViewRender.js.map +1 -1
  140. package/dist/canvas/surfaceContribution.js +12 -8
  141. package/dist/canvas/surfaceContribution.js.map +1 -1
  142. package/dist/canvas/useCanvasPaint.js +2 -1
  143. package/dist/canvas/useCanvasPaint.js.map +1 -1
  144. package/dist/canvas/useCanvasView.js +4 -2
  145. package/dist/canvas/useCanvasView.js.map +1 -1
  146. package/dist/canvas/useInFlightBounds.js +52 -0
  147. package/dist/canvas/useInFlightBounds.js.map +1 -0
  148. package/dist/canvas/useLayerStack.js +6 -2
  149. package/dist/canvas/useLayerStack.js.map +1 -1
  150. package/dist/canvas/useViewAim.js +121 -0
  151. package/dist/canvas/useViewAim.js.map +1 -0
  152. package/dist/canvas/useViewHelpers.js +7 -9
  153. package/dist/canvas/useViewHelpers.js.map +1 -1
  154. package/dist/canvas/useViewNesting.js +3 -2
  155. package/dist/canvas/useViewNesting.js.map +1 -1
  156. package/dist/canvas/useViewRegistrySurface.js +4 -2
  157. package/dist/canvas/useViewRegistrySurface.js.map +1 -1
  158. package/dist/canvas/viewMarkers.js +63 -0
  159. package/dist/canvas/viewMarkers.js.map +1 -0
  160. package/dist/canvas/viewRegistry.js +27 -1
  161. package/dist/canvas/viewRegistry.js.map +1 -1
  162. package/dist/clipboard.d.ts +3 -2
  163. package/dist/{clone-DZDrfIlU.d.ts → clone-C3e0OTuF.d.ts} +8 -21
  164. package/dist/clone.d.ts +4 -3
  165. package/dist/core/geometry/autoPoseDescriptor.js +1 -1
  166. package/dist/core/ops/setDependsOn.js +37 -0
  167. package/dist/core/ops/setDependsOn.js.map +1 -0
  168. package/dist/core/ops/writtenBy.js +53 -0
  169. package/dist/core/ops/writtenBy.js.map +1 -0
  170. package/dist/core/pages/fitViewToPage.js +12 -1
  171. package/dist/core/pages/fitViewToPage.js.map +1 -1
  172. package/dist/core/pages/pageEdits.js +163 -0
  173. package/dist/core/pages/pageEdits.js.map +1 -0
  174. package/dist/core/pages/pages.js +30 -1
  175. package/dist/core/pages/pages.js.map +1 -1
  176. package/dist/core/paint/meshKindLazy.js +59 -2
  177. package/dist/core/paint/meshKindLazy.js.map +1 -1
  178. package/dist/core/scene/NodeRouting.js +8 -3
  179. package/dist/core/scene/NodeRouting.js.map +1 -1
  180. package/dist/core/scene/arrivalWindow.js.map +1 -1
  181. package/dist/core/scene/carryDescendants.js +51 -0
  182. package/dist/core/scene/carryDescendants.js.map +1 -0
  183. package/dist/core/scene/clipNothing.js +13 -0
  184. package/dist/core/scene/clipNothing.js.map +1 -0
  185. package/dist/core/scene/depMemo.js +11 -3
  186. package/dist/core/scene/depMemo.js.map +1 -1
  187. package/dist/core/scene/dependents.js +7 -1
  188. package/dist/core/scene/dependents.js.map +1 -1
  189. package/dist/core/scene/derivedParts.js +10 -11
  190. package/dist/core/scene/derivedParts.js.map +1 -1
  191. package/dist/core/scene/docValues.js +57 -0
  192. package/dist/core/scene/docValues.js.map +1 -0
  193. package/dist/core/scene/editPass.js +111 -0
  194. package/dist/core/scene/editPass.js.map +1 -0
  195. package/dist/core/scene/effectivePose.js +13 -2
  196. package/dist/core/scene/effectivePose.js.map +1 -1
  197. package/dist/core/scene/fieldEdits.js +4 -1
  198. package/dist/core/scene/fieldEdits.js.map +1 -1
  199. package/dist/core/scene/fontReads.js +37 -0
  200. package/dist/core/scene/fontReads.js.map +1 -0
  201. package/dist/core/scene/historyFacade.js +1 -0
  202. package/dist/core/scene/historyFacade.js.map +1 -1
  203. package/dist/core/scene/inheritedPaint.js +75 -0
  204. package/dist/core/scene/inheritedPaint.js.map +1 -0
  205. package/dist/core/scene/kitRegistry.js +5 -0
  206. package/dist/core/scene/kitRegistry.js.map +1 -1
  207. package/dist/core/scene/layoutPass.js +28 -3
  208. package/dist/core/scene/layoutPass.js.map +1 -1
  209. package/dist/core/scene/nodeMemo.js +15 -7
  210. package/dist/core/scene/nodeMemo.js.map +1 -1
  211. package/dist/core/scene/pathEffects/blend.js.map +1 -1
  212. package/dist/core/scene/pathEffects/derive.js +7 -2
  213. package/dist/core/scene/pathEffects/derive.js.map +1 -1
  214. package/dist/core/scene/pathEffects/effects.js +3 -1
  215. package/dist/core/scene/pathEffects/effects.js.map +1 -1
  216. package/dist/core/scene/pathEffects/textAlong.js +95 -0
  217. package/dist/core/scene/pathEffects/textAlong.js.map +1 -0
  218. package/dist/core/scene/recorder.js +28 -19
  219. package/dist/core/scene/recorder.js.map +1 -1
  220. package/dist/core/scene/scene.js +15 -9
  221. package/dist/core/scene/scene.js.map +1 -1
  222. package/dist/core/scene/sceneChanges.js +13 -0
  223. package/dist/core/scene/sceneChanges.js.map +1 -0
  224. package/dist/core/scene/sceneEdits.js +8 -1
  225. package/dist/core/scene/sceneEdits.js.map +1 -1
  226. package/dist/core/scene/sceneMutators.js +1 -0
  227. package/dist/core/scene/sceneMutators.js.map +1 -1
  228. package/dist/core/scene/sceneRecording.js +20 -3
  229. package/dist/core/scene/sceneRecording.js.map +1 -1
  230. package/dist/core/scene/sceneSelection.js +4 -1
  231. package/dist/core/scene/sceneSelection.js.map +1 -1
  232. package/dist/core/scene/sceneState.js +11 -5
  233. package/dist/core/scene/sceneState.js.map +1 -1
  234. package/dist/core/scene/serialization.js +5 -3
  235. package/dist/core/scene/serialization.js.map +1 -1
  236. package/dist/core/scene/types.js.map +1 -1
  237. package/dist/core/scene/unitScopes.js +19 -1
  238. package/dist/core/scene/unitScopes.js.map +1 -1
  239. package/dist/core/selection/usePublishSceneSelection.js +6 -12
  240. package/dist/core/selection/usePublishSceneSelection.js.map +1 -1
  241. package/dist/core/shapeKinds.js +25 -11
  242. package/dist/core/shapeKinds.js.map +1 -1
  243. package/dist/{cornerHandles-Camw_yeu.d.ts → cornerHandles-p8fDIAKt.d.ts} +3 -2
  244. package/dist/debug/createDebugOverlayLayer.js +16 -111
  245. package/dist/debug/createDebugOverlayLayer.js.map +1 -1
  246. package/dist/debug/createDebugSink.js +2 -1
  247. package/dist/debug/createDebugSink.js.map +1 -1
  248. package/dist/debug/defaultTheme.js +4 -2
  249. package/dist/debug/defaultTheme.js.map +1 -1
  250. package/dist/debug/features.js +17 -0
  251. package/dist/debug/features.js.map +1 -0
  252. package/dist/debug/overlayPanels.js +117 -0
  253. package/dist/debug/overlayPanels.js.map +1 -0
  254. package/dist/debug/parseDebugFlags.js +4 -13
  255. package/dist/debug/parseDebugFlags.js.map +1 -1
  256. package/dist/{depSchema-Cgfu_G9s.d.ts → depSchema-mG19aEdD.d.ts} +174 -904
  257. package/dist/devtools/handlers.js +112 -0
  258. package/dist/devtools/handlers.js.map +1 -0
  259. package/dist/devtools/history.js +71 -0
  260. package/dist/devtools/history.js.map +1 -0
  261. package/dist/devtools/hook.js +74 -0
  262. package/dist/devtools/hook.js.map +1 -0
  263. package/dist/devtools/label.js +25 -0
  264. package/dist/devtools/label.js.map +1 -0
  265. package/dist/devtools/notices.js +58 -0
  266. package/dist/devtools/notices.js.map +1 -0
  267. package/dist/devtools/protocol.js +7 -0
  268. package/dist/devtools/protocol.js.map +1 -0
  269. package/dist/devtools/registry.js +90 -0
  270. package/dist/devtools/registry.js.map +1 -0
  271. package/dist/devtools/root.js +80 -0
  272. package/dist/devtools/root.js.map +1 -0
  273. package/dist/devtools/serialize.js +86 -0
  274. package/dist/devtools/serialize.js.map +1 -0
  275. package/dist/devtools/session.js +111 -0
  276. package/dist/devtools/session.js.map +1 -0
  277. package/dist/devtools/transport.js +67 -0
  278. package/dist/devtools/transport.js.map +1 -0
  279. package/dist/devtools/useDevtoolsRoot.js +81 -0
  280. package/dist/devtools/useDevtoolsRoot.js.map +1 -0
  281. package/dist/devtools-protocol.d.ts +435 -0
  282. package/dist/devtools-protocol.js +7 -0
  283. package/dist/devtools.d.ts +8 -0
  284. package/dist/devtools.js +12 -0
  285. package/dist/devtools.js.map +1 -0
  286. package/dist/features/chrome-caps/useHoverTracking.js +16 -10
  287. package/dist/features/chrome-caps/useHoverTracking.js.map +1 -1
  288. package/dist/features/ingestion/contentHandlers.js +25 -2
  289. package/dist/features/ingestion/contentHandlers.js.map +1 -1
  290. package/dist/features/measure/measureCommands.js +7 -5
  291. package/dist/features/measure/measureCommands.js.map +1 -1
  292. package/dist/features/measure/measureContribution.js +4 -2
  293. package/dist/features/measure/measureContribution.js.map +1 -1
  294. package/dist/features/modes/modeTriggers.js +7 -3
  295. package/dist/features/modes/modeTriggers.js.map +1 -1
  296. package/dist/features/pathEffects/effectSources.js +60 -0
  297. package/dist/features/pathEffects/effectSources.js.map +1 -0
  298. package/dist/features/pathEffects/readSource.js +17 -1
  299. package/dist/features/pathEffects/readSource.js.map +1 -1
  300. package/dist/features/pathEffects/textItems.js +53 -0
  301. package/dist/features/pathEffects/textItems.js.map +1 -0
  302. package/dist/features/pathEffects/useEffectSourcesLayer.js +57 -0
  303. package/dist/features/pathEffects/useEffectSourcesLayer.js.map +1 -0
  304. package/dist/features/paths/index.js +2 -2
  305. package/dist/features/paths/pathEditExtension.js.map +1 -1
  306. package/dist/features/paths/pathEditState.js +5 -2
  307. package/dist/features/paths/pathEditState.js.map +1 -1
  308. package/dist/features/paths/pathSnap/pathSnapSource.js +5 -5
  309. package/dist/features/paths/pathSnap/pathSnapSource.js.map +1 -1
  310. package/dist/features/paths/pathSnap/sceneIndex.js +10 -3
  311. package/dist/features/paths/pathSnap/sceneIndex.js.map +1 -1
  312. package/dist/features/selection/selectionPose.js +4 -1
  313. package/dist/features/selection/selectionPose.js.map +1 -1
  314. package/dist/features/snap/gather.js +9 -1
  315. package/dist/features/snap/gather.js.map +1 -1
  316. package/dist/features/snap/lazySession.js +17 -0
  317. package/dist/features/snap/lazySession.js.map +1 -0
  318. package/dist/features/snap/marks.js.map +1 -1
  319. package/dist/features/snap/probes2d.js +27 -19
  320. package/dist/features/snap/probes2d.js.map +1 -1
  321. package/dist/features/snap/readoutLayer.js.map +1 -1
  322. package/dist/features/snap/roles.js +2 -1
  323. package/dist/features/snap/roles.js.map +1 -1
  324. package/dist/features/snap/rotationSource.js +25 -8
  325. package/dist/features/snap/rotationSource.js.map +1 -1
  326. package/dist/features/snap/sceneSession2d.js +6 -4
  327. package/dist/features/snap/sceneSession2d.js.map +1 -1
  328. package/dist/features/snap/session2d.js +37 -23
  329. package/dist/features/snap/session2d.js.map +1 -1
  330. package/dist/features/snap/spanSnap.js +5 -2
  331. package/dist/features/snap/spanSnap.js.map +1 -1
  332. package/dist/features/text/sceneTextDrafts.js +65 -0
  333. package/dist/features/text/sceneTextDrafts.js.map +1 -0
  334. package/dist/features/text/textHitAt.js +31 -2
  335. package/dist/features/text/textHitAt.js.map +1 -1
  336. package/dist/features/text/useSceneTextEdit.js +22 -18
  337. package/dist/features/text/useSceneTextEdit.js.map +1 -1
  338. package/dist/features/viewports/aim.js +105 -0
  339. package/dist/features/viewports/aim.js.map +1 -0
  340. package/dist/features/viewports/viewMarker.js +82 -0
  341. package/dist/features/viewports/viewMarker.js.map +1 -0
  342. package/dist/features/viewports/viewMarkerDrag.js +55 -0
  343. package/dist/features/viewports/viewMarkerDrag.js.map +1 -0
  344. package/dist/icons.table.js +1 -1
  345. package/dist/icons.table.js.map +1 -1
  346. package/dist/icons.table.json +0 -10
  347. package/dist/index.d.ts +1198 -894
  348. package/dist/index.js +55 -38
  349. package/dist/interactions/actions/align/action.js +6 -4
  350. package/dist/interactions/actions/align/action.js.map +1 -1
  351. package/dist/interactions/actions/align/align.js.map +1 -1
  352. package/dist/interactions/actions/booleans/action.js +7 -1
  353. package/dist/interactions/actions/booleans/action.js.map +1 -1
  354. package/dist/interactions/actions/booleans/booleans.js +2 -1
  355. package/dist/interactions/actions/booleans/booleans.js.map +1 -1
  356. package/dist/interactions/actions/booleans/operands.js +6 -5
  357. package/dist/interactions/actions/booleans/operands.js.map +1 -1
  358. package/dist/interactions/actions/clipboard/action.js +27 -17
  359. package/dist/interactions/actions/clipboard/action.js.map +1 -1
  360. package/dist/interactions/actions/clone/action.js +1 -1
  361. package/dist/interactions/actions/clone/behaviors.js +4 -4
  362. package/dist/interactions/actions/clone/behaviors.js.map +1 -1
  363. package/dist/interactions/actions/defaults/anchorEditing.js +44 -23
  364. package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -1
  365. package/dist/interactions/actions/defaults/anchorJoin.js +12 -6
  366. package/dist/interactions/actions/defaults/anchorJoin.js.map +1 -1
  367. package/dist/interactions/actions/defaults/bendSegment.js +8 -5
  368. package/dist/interactions/actions/defaults/bendSegment.js.map +1 -1
  369. package/dist/interactions/actions/defaults/cancelGesture.js +11 -8
  370. package/dist/interactions/actions/defaults/cancelGesture.js.map +1 -1
  371. package/dist/interactions/actions/defaults/contextMenu.js +17 -8
  372. package/dist/interactions/actions/defaults/contextMenu.js.map +1 -1
  373. package/dist/interactions/actions/defaults/createPaintAction.js +2 -2
  374. package/dist/interactions/actions/defaults/createPaintAction.js.map +1 -1
  375. package/dist/interactions/actions/defaults/delete.js +64 -41
  376. package/dist/interactions/actions/defaults/delete.js.map +1 -1
  377. package/dist/interactions/actions/defaults/duplicate.js +12 -9
  378. package/dist/interactions/actions/defaults/duplicate.js.map +1 -1
  379. package/dist/interactions/actions/defaults/enterPathEdit.js +19 -9
  380. package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -1
  381. package/dist/interactions/actions/defaults/escape.js +11 -8
  382. package/dist/interactions/actions/defaults/escape.js.map +1 -1
  383. package/dist/interactions/actions/defaults/exitPathEdit.js +7 -4
  384. package/dist/interactions/actions/defaults/exitPathEdit.js.map +1 -1
  385. package/dist/interactions/actions/defaults/group.js +21 -15
  386. package/dist/interactions/actions/defaults/group.js.map +1 -1
  387. package/dist/interactions/actions/defaults/ingest.js +17 -9
  388. package/dist/interactions/actions/defaults/ingest.js.map +1 -1
  389. package/dist/interactions/actions/defaults/insertPathAnchor.js +7 -4
  390. package/dist/interactions/actions/defaults/insertPathAnchor.js.map +1 -1
  391. package/dist/interactions/actions/defaults/nudge.js +21 -40
  392. package/dist/interactions/actions/defaults/nudge.js.map +1 -1
  393. package/dist/interactions/actions/defaults/pathEditTools.js +11 -8
  394. package/dist/interactions/actions/defaults/pathEditTools.js.map +1 -1
  395. package/dist/interactions/actions/defaults/pinchZoom.js +7 -4
  396. package/dist/interactions/actions/defaults/pinchZoom.js.map +1 -1
  397. package/dist/interactions/actions/defaults/reorder.js +24 -6
  398. package/dist/interactions/actions/defaults/reorder.js.map +1 -1
  399. package/dist/interactions/actions/defaults/selectAll.js +8 -5
  400. package/dist/interactions/actions/defaults/selectAll.js.map +1 -1
  401. package/dist/interactions/actions/defaults/setFill.js +7 -3
  402. package/dist/interactions/actions/defaults/setFill.js.map +1 -1
  403. package/dist/interactions/actions/defaults/setFillOpacity.js +1 -1
  404. package/dist/interactions/actions/defaults/setStroke.js +12 -11
  405. package/dist/interactions/actions/defaults/setStroke.js.map +1 -1
  406. package/dist/interactions/actions/defaults/setStrokeOpacity.js +1 -1
  407. package/dist/interactions/actions/defaults/toolActivate.js +7 -1
  408. package/dist/interactions/actions/defaults/toolActivate.js.map +1 -1
  409. package/dist/interactions/actions/defaults/toolResetToDefault.js +7 -4
  410. package/dist/interactions/actions/defaults/toolResetToDefault.js.map +1 -1
  411. package/dist/interactions/actions/defaults/undoRedo.js +19 -13
  412. package/dist/interactions/actions/defaults/undoRedo.js.map +1 -1
  413. package/dist/interactions/actions/defaults/viewportWheelPan.js +16 -7
  414. package/dist/interactions/actions/defaults/viewportWheelPan.js.map +1 -1
  415. package/dist/interactions/actions/defaults/viewportZoom.js +24 -6
  416. package/dist/interactions/actions/defaults/viewportZoom.js.map +1 -1
  417. package/dist/interactions/actions/distribute/action.js +6 -4
  418. package/dist/interactions/actions/distribute/action.js.map +1 -1
  419. package/dist/interactions/actions/drawnBoxes.js +2 -1
  420. package/dist/interactions/actions/drawnBoxes.js.map +1 -1
  421. package/dist/interactions/actions/edit-anchors/action.js +10 -10
  422. package/dist/interactions/actions/edit-anchors/action.js.map +1 -1
  423. package/dist/interactions/actions/edit-anchors/preview.js +41 -8
  424. package/dist/interactions/actions/edit-anchors/preview.js.map +1 -1
  425. package/dist/interactions/actions/flip/action.js +14 -6
  426. package/dist/interactions/actions/flip/action.js.map +1 -1
  427. package/dist/interactions/actions/gestureLifecycle.js +5 -2
  428. package/dist/interactions/actions/gestureLifecycle.js.map +1 -1
  429. package/dist/interactions/actions/insert/action.js +1 -2
  430. package/dist/interactions/actions/insert/action.js.map +1 -1
  431. package/dist/interactions/actions/insert/commit.js +1 -1
  432. package/dist/interactions/actions/insert/parent.js +11 -0
  433. package/dist/interactions/actions/insert/parent.js.map +1 -0
  434. package/dist/interactions/actions/insert/placeAction.js +7 -2
  435. package/dist/interactions/actions/insert/placeAction.js.map +1 -1
  436. package/dist/interactions/actions/insert/repositionAction.js +2 -1
  437. package/dist/interactions/actions/insert/repositionAction.js.map +1 -1
  438. package/dist/interactions/actions/insert/session.js +5 -1
  439. package/dist/interactions/actions/insert/session.js.map +1 -1
  440. package/dist/interactions/actions/move/action.js +15 -8
  441. package/dist/interactions/actions/move/action.js.map +1 -1
  442. package/dist/interactions/actions/move/behaviors/layoutDrop.js +0 -1
  443. package/dist/interactions/actions/move/behaviors/layoutDrop.js.map +1 -1
  444. package/dist/interactions/actions/move/behaviors/snapToContainer.js +1 -1
  445. package/dist/interactions/actions/move/capture.js +1 -1
  446. package/dist/interactions/actions/move/commit/index.js +0 -2
  447. package/dist/interactions/actions/move/commit/index.js.map +1 -1
  448. package/dist/interactions/actions/move/commit/layoutDrop.js +2 -2
  449. package/dist/interactions/actions/move/commit/layoutRelease.js +2 -2
  450. package/dist/interactions/actions/move/commit/reparent.js +11 -5
  451. package/dist/interactions/actions/move/commit/reparent.js.map +1 -1
  452. package/dist/interactions/actions/move/frame.js +4 -10
  453. package/dist/interactions/actions/move/frame.js.map +1 -1
  454. package/dist/interactions/actions/move/landedDescendants.js +20 -17
  455. package/dist/interactions/actions/move/landedDescendants.js.map +1 -1
  456. package/dist/interactions/actions/move/layout/container.js +2 -1
  457. package/dist/interactions/actions/move/layout/container.js.map +1 -1
  458. package/dist/interactions/actions/move/layout/dragged.js +1 -1
  459. package/dist/interactions/actions/move/layout/dropPass.js +18 -1
  460. package/dist/interactions/actions/move/layout/dropPass.js.map +1 -1
  461. package/dist/interactions/actions/move/layout/exits.js +5 -5
  462. package/dist/interactions/actions/move/layout/exits.js.map +1 -1
  463. package/dist/interactions/actions/move/session.js +14 -3
  464. package/dist/interactions/actions/move/session.js.map +1 -1
  465. package/dist/interactions/actions/move/translate.js +8 -37
  466. package/dist/interactions/actions/move/translate.js.map +1 -1
  467. package/dist/interactions/actions/moveNodes.js +87 -0
  468. package/dist/interactions/actions/moveNodes.js.map +1 -0
  469. package/dist/interactions/actions/outlines/createOutlinesAction.js +8 -5
  470. package/dist/interactions/actions/outlines/createOutlinesAction.js.map +1 -1
  471. package/dist/interactions/actions/outlines/outlineStroke.js +5 -3
  472. package/dist/interactions/actions/outlines/outlineStroke.js.map +1 -1
  473. package/dist/interactions/actions/pathCommands/cutJoin.js +8 -5
  474. package/dist/interactions/actions/pathCommands/cutJoin.js.map +1 -1
  475. package/dist/interactions/actions/planeInput.js.map +1 -1
  476. package/dist/interactions/actions/resize/action.js +83 -72
  477. package/dist/interactions/actions/resize/action.js.map +1 -1
  478. package/dist/interactions/actions/resize/commit.js +2 -1
  479. package/dist/interactions/actions/resize/commit.js.map +1 -1
  480. package/dist/interactions/actions/resize/cornerHandles.js +2 -1
  481. package/dist/interactions/actions/resize/cornerHandles.js.map +1 -1
  482. package/dist/interactions/actions/resize/session.js +2 -0
  483. package/dist/interactions/actions/resize/session.js.map +1 -1
  484. package/dist/interactions/actions/resolvePreviews.js +3 -3
  485. package/dist/interactions/actions/resolvePreviews.js.map +1 -1
  486. package/dist/interactions/actions/rotate/action.js +7 -4
  487. package/dist/interactions/actions/rotate/action.js.map +1 -1
  488. package/dist/interactions/actions/rotate/commit.js +2 -1
  489. package/dist/interactions/actions/rotate/commit.js.map +1 -1
  490. package/dist/interactions/actions/rotate/session.js +2 -0
  491. package/dist/interactions/actions/rotate/session.js.map +1 -1
  492. package/dist/interactions/actions/selectionSubtree.js +25 -9
  493. package/dist/interactions/actions/selectionSubtree.js.map +1 -1
  494. package/dist/interactions/actions/testUtils.js.map +1 -1
  495. package/dist/interactions/actions/transform-again/action.js +13 -11
  496. package/dist/interactions/actions/transform-again/action.js.map +1 -1
  497. package/dist/interactions/actions/transformFinish.js +106 -0
  498. package/dist/interactions/actions/transformFinish.js.map +1 -0
  499. package/dist/json.d.ts +4 -0
  500. package/dist/json.js +3 -0
  501. package/dist/kitSettingsSchema.js +8 -5
  502. package/dist/kitSettingsSchema.js.map +1 -1
  503. package/dist/{math-CrJULaZI.d.ts → math-B56zxVs5.d.ts} +10 -1
  504. package/dist/math.d.ts +1 -1
  505. package/dist/math.js +2 -1
  506. package/dist/move.d.ts +5 -4
  507. package/dist/{options-p9GZMXbY.d.ts → options-DBxEryYq.d.ts} +1 -1
  508. package/dist/resize.d.ts +4 -3
  509. package/dist/routing.d.ts +1 -1
  510. package/dist/routing.js +2 -2
  511. package/dist/test-hook/createTestHook.js +1 -1
  512. package/dist/test-hook/createTestHook.js.map +1 -1
  513. package/dist/test-hook/useTestHook.js +2 -1
  514. package/dist/test-hook/useTestHook.js.map +1 -1
  515. package/dist/test-seams.d.ts +9 -5
  516. package/dist/tools/builtin/ellipse/useEllipseTool.js +1 -0
  517. package/dist/tools/builtin/ellipse/useEllipseTool.js.map +1 -1
  518. package/dist/tools/builtin/eyedropper/useEyedropperTool.js +2 -1
  519. package/dist/tools/builtin/eyedropper/useEyedropperTool.js.map +1 -1
  520. package/dist/tools/builtin/hand/dragPanContribution.js +4 -1
  521. package/dist/tools/builtin/hand/dragPanContribution.js.map +1 -1
  522. package/dist/tools/builtin/hand/useHandTool.js +7 -4
  523. package/dist/tools/builtin/hand/useHandTool.js.map +1 -1
  524. package/dist/tools/builtin/image/useImageTool.js +1 -0
  525. package/dist/tools/builtin/image/useImageTool.js.map +1 -1
  526. package/dist/tools/builtin/lasso/useLassoTool.js +1 -0
  527. package/dist/tools/builtin/lasso/useLassoTool.js.map +1 -1
  528. package/dist/tools/builtin/line/useLineTool.js +1 -0
  529. package/dist/tools/builtin/line/useLineTool.js.map +1 -1
  530. package/dist/tools/builtin/measure/useMeasureTool.js +12 -5
  531. package/dist/tools/builtin/measure/useMeasureTool.js.map +1 -1
  532. package/dist/tools/builtin/pen/penHandle.js +3 -5
  533. package/dist/tools/builtin/pen/penHandle.js.map +1 -1
  534. package/dist/tools/builtin/pen/usePenTool.js +14 -6
  535. package/dist/tools/builtin/pen/usePenTool.js.map +1 -1
  536. package/dist/tools/builtin/pencil/usePencilTool.js +1 -0
  537. package/dist/tools/builtin/pencil/usePencilTool.js.map +1 -1
  538. package/dist/tools/builtin/polygon/usePolygonTool.js +13 -4
  539. package/dist/tools/builtin/polygon/usePolygonTool.js.map +1 -1
  540. package/dist/tools/builtin/rect/useRectTool.js +1 -0
  541. package/dist/tools/builtin/rect/useRectTool.js.map +1 -1
  542. package/dist/tools/builtin/select/adapterPointQuery.js +3 -2
  543. package/dist/tools/builtin/select/adapterPointQuery.js.map +1 -1
  544. package/dist/tools/builtin/select/pressDecision.js +32 -0
  545. package/dist/tools/builtin/select/pressDecision.js.map +1 -0
  546. package/dist/tools/builtin/select/selectionContributions.js +22 -13
  547. package/dist/tools/builtin/select/selectionContributions.js.map +1 -1
  548. package/dist/tools/builtin/select/useSelectTool.js +13 -10
  549. package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
  550. package/dist/tools/builtin/slice/useSliceTool.js +22 -8
  551. package/dist/tools/builtin/slice/useSliceTool.js.map +1 -1
  552. package/dist/tools/builtin/star/useStarTool.js +13 -4
  553. package/dist/tools/builtin/star/useStarTool.js.map +1 -1
  554. package/dist/tools/builtin/sticky/stickyNode.js +4 -1
  555. package/dist/tools/builtin/sticky/stickyNode.js.map +1 -1
  556. package/dist/tools/builtin/sticky/useStickyTool.js +10 -5
  557. package/dist/tools/builtin/sticky/useStickyTool.js.map +1 -1
  558. package/dist/tools/builtin/text/useTextTool.js +3 -1
  559. package/dist/tools/builtin/text/useTextTool.js.map +1 -1
  560. package/dist/tools/index.js +26 -0
  561. package/dist/{types-CHVXGfYm.d.ts → types-7puAuVD2.d.ts} +3 -262
  562. package/dist/types-BN9hbdMI.d.ts +184 -0
  563. package/dist/types-CniVctmk.d.ts +949 -0
  564. package/dist/types-oFeQ5VjV.d.ts +264 -0
  565. package/dist/util/paint.js +1 -3
  566. package/dist/util/paint.js.map +1 -1
  567. package/dist/version.js +1 -1
  568. package/package.json +39 -25
  569. package/dist/canvas/SceneCanvas/useBuiltinRigTools.js +0 -65
  570. package/dist/canvas/SceneCanvas/useBuiltinRigTools.js.map +0 -1
  571. package/dist/tools/builtin/bone/boneActions.js +0 -156
  572. package/dist/tools/builtin/bone/boneActions.js.map +0 -1
  573. package/dist/tools/builtin/bone/boneOverlay.js +0 -71
  574. package/dist/tools/builtin/bone/boneOverlay.js.map +0 -1
  575. package/dist/tools/builtin/bone/placedRig.js +0 -28
  576. package/dist/tools/builtin/bone/placedRig.js.map +0 -1
  577. package/dist/tools/builtin/bone/rigEditState.js +0 -30
  578. package/dist/tools/builtin/bone/rigEditState.js.map +0 -1
  579. package/dist/tools/builtin/bone/useBoneTool.js +0 -125
  580. package/dist/tools/builtin/bone/useBoneTool.js.map +0 -1
  581. package/dist/tools/builtin/weight/useWeightTool.js +0 -101
  582. package/dist/tools/builtin/weight/useWeightTool.js.map +0 -1
  583. package/dist/tools/builtin/weight/weightActions.js +0 -140
  584. package/dist/tools/builtin/weight/weightActions.js.map +0 -1
  585. package/dist/tools/builtin/weight/weightOverlay.js +0 -78
  586. package/dist/tools/builtin/weight/weightOverlay.js.map +0 -1
@@ -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';\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}\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 commands.push(...buildSceneViewCommands(\n args.scene, view, drawOne, undefined, args.alphaFor, undefined, 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 // Same context attributes as the screen path (Canvas.tsx).\n gl = (canvas.getContext('webgl2', { preserveDrawingBuffer: true, stencil: true }) 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,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;CAG7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e,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 = createRasterS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\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 /** 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":";;;;;;;;;;;;;;;;;;;;;;;AA6IA,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,MAAS;CAAE,IAAI;CAEnE,MAAM,UAAU,WAAW,OAAO,EAAE,SAAS,iBAAiB,OAAO,CAAC,EAAE;CAExE,MAAM,eAAwD;EAC5D;EACA;EACA,cAAc,OAAO,QAAQ,aAAa,EAAE;EAC5C,iBAAiB,OAAO,eAAe,SAAS,EAAE;EAClD;EACA;CACF;CAEA,MAAM,UAAoD;EACxD,GAAG,cAAc,KAAK;EAGtB,WAAW;GACT,MAAM,QAAQ,UAAU,KAAK;GAC7B,OAAO,MAAM,iBAAiB,CAAC,CAAC,QAAQ,MAAM,CAAC,MAAM,OAAO,EAAE,EAAE,CAAC;EACnE;EACA,QAAQ,IAAI;GACV,MAAM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AAmB,KAAK,CAC5B;EACF;EACA,aAAa,SAAS,MAAoB,MAAuB;GAC/D,OAAO,oBACL,OACA,SACA,MACA,YAAY,IAAI,GAChB,GACA,EAAE,mBAAmB,KAAK,CAC5B;EACF;EAKA,GAAI,QAAQ,eACR,EACE,eAAe,WAAoE;GACjF,MAAM,UAAU,QAAQ,aAAc,MAAM;GAC5C,IAAI,CAAC,SAAS,OAAO;GACrB,MAAM,QAAS,QAAQ,eAAgB;GAEvC,OAAO;IACL,MAAM;IACN,IAHS,QAAQ,OAAO,SAAY,MAAM,OAAO,IAAI,SAAS,QAAQ,EAAE;IAIxE;IACA,MAAM,QAAQ;IACd,MAAM,QAAQ;IACd,QAAQ;GACV;EACF,EACF,IACA,CAAC;EAEL,kBAAkB,KAAkC;GAClD,OAAO,uBAAuB,cAAc,GAAG;EACjD;EACA,YACE,WACA,QACA,KAC8B;GAC9B,OAAO,mBAAmB,cAAc,WAAW,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 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,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E;IACA,MAAM,QAAQ;IACd,MAAM,QAAQ;IACd,QAAQ;GACV;EACF,EACF,IACA,CAAC;EAEL,kBAAkB,KAAkC;GAClD,OAAO,uBAAuB,cAAc,GAAG;EACjD;EACA,YACE,WACA,QACA,KAC8B;GAC9B,OAAO,mBAAmB,cAAc,WAAW,QAAQ,GAAG;EAChE;EAGA,iBAA6C;GAC3C,OAAO;IAAE,IAAI;IAAI,IAAI;GAAG;EAC1B;CACF;CAEA,OAAO;AACT"}
@@ -1,3 +1,4 @@
1
+ import { withInheritedPaints } from "./inheritedPaints.js";
1
2
  import { sceneDerivedPathOf, sceneShownToPose, withDerivedPaths } from "./derivedPath.js";
2
3
  import { withColorOverrides } from "./colorOverrides.js";
3
4
 
@@ -15,7 +16,7 @@ function composeAlphaFor(scene, alphaFor) {
15
16
  return alphaFor ? (id) => alphaFor(id) * overrideAlphaFor(id) : overrideAlphaFor;
16
17
  }
17
18
  function wireSceneSlotToScene(slot, scene, alphaFor, colorOverrides) {
18
- const derived = withDerivedPaths(scene, slot.drawOne, slot.toPose);
19
+ const derived = withDerivedPaths(scene, withInheritedPaints(scene, slot.drawOne), slot.toPose);
19
20
  const derivedPathOf = sceneDerivedPathOf(scene, slot.toPose);
20
21
  return {
21
22
  ...slot,
@@ -1 +1 @@
1
- {"version":3,"file":"sceneSlotWiring.js","names":[],"sources":["../../src/canvas/sceneSlotWiring.ts"],"sourcesContent":["/**\n * What the scene slot needs from the `Scene` that `<Canvas>` cannot see.\n *\n * `<Canvas>` is scene-agnostic: it walks an adapter. Three things a node is\n * painted with are therefore invisible to it — an ephemeral override's alpha, a\n * derived path, which needs other nodes' poses to resolve, and animated vertex\n * colors, which live in an animator. `<SceneCanvas>` folds them into the slot\n * here; `buildSceneViewCommands` does the same for the headless walk.\n */\nimport type { SceneSlotConfig } from './buildSceneLayer';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport { withDerivedPaths, sceneDerivedPathOf, sceneShownToPose } from './derivedPath';\nimport { withColorOverrides } from './colorOverrides';\nimport type { ColorOverrideRegistry } from '@weasel-js/animator';\n\n/**\n * The alpha a view paints a node at: the view's own `alphaFor` times any\n * ephemeral override alpha.\n *\n * The hit path asks this too — a node painted at alpha 0 is not on screen and\n * must not claim clicks — so it is one function rather than the painter's and\n * picking's separate readings of the same two inputs.\n */\nexport function composeAlphaFor<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n alphaFor?: (id: string) => number,\n): (id: string) => number {\n const overrideAlphaFor = (id: string) => scene.overrides.read(id as NodeId)?.alpha ?? 1;\n return alphaFor ? (id: string) => alphaFor(id) * overrideAlphaFor(id) : overrideAlphaFor;\n}\n\nexport function wireSceneSlotToScene<TData, TLayer extends string, TPose>(\n slot: SceneSlotConfig<Node<TData, TLayer, TPose>, TPose>,\n scene: Scene<TData, TLayer, TPose>,\n alphaFor?: (id: string) => number,\n colorOverrides?: ColorOverrideRegistry,\n): SceneSlotConfig<Node<TData, TLayer, TPose>, TPose> {\n const derived = withDerivedPaths(scene, slot.drawOne, slot.toPose);\n const derivedPathOf = sceneDerivedPathOf(scene, slot.toPose);\n return {\n ...slot,\n ...(slot.toPose ? { toPose: sceneShownToPose(scene, slot.toPose) } : {}),\n drawOne: colorOverrides ? withColorOverrides(colorOverrides, derived) : derived,\n derivedPathOf,\n alphaFor: composeAlphaFor(scene, alphaFor),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,SAAgB,gBACd,OACA,UACwB;CACxB,MAAM,oBAAoB,OAAe,MAAM,UAAU,KAAK,EAAY,CAAC,EAAE,SAAS;CACtF,OAAO,YAAY,OAAe,SAAS,EAAE,IAAI,iBAAiB,EAAE,IAAI;AAC1E;AAEA,SAAgB,qBACd,MACA,OACA,UACA,gBACoD;CACpD,MAAM,UAAU,iBAAiB,OAAO,KAAK,SAAS,KAAK,MAAM;CACjE,MAAM,gBAAgB,mBAAmB,OAAO,KAAK,MAAM;CAC3D,OAAO;EACL,GAAG;EACH,GAAI,KAAK,SAAS,EAAE,QAAQ,iBAAiB,OAAO,KAAK,MAAM,EAAE,IAAI,CAAC;EACtE,SAAS,iBAAiB,mBAAmB,gBAAgB,OAAO,IAAI;EACxE;EACA,UAAU,gBAAgB,OAAO,QAAQ;CAC3C;AACF"}
1
+ {"version":3,"file":"sceneSlotWiring.js","names":[],"sources":["../../src/canvas/sceneSlotWiring.ts"],"sourcesContent":["/**\n * What the scene slot needs from the `Scene` that `<Canvas>` cannot see.\n *\n * `<Canvas>` is scene-agnostic: it walks an adapter. Four things a node is\n * painted with are therefore invisible to it — an ephemeral override's alpha, a\n * derived path, which needs other nodes' poses to resolve, the paint an\n * `'inherit'` field takes from its containers, and animated vertex colors,\n * which live in an animator. `<SceneCanvas>` folds them into the slot\n * here; `buildSceneViewCommands` does the same for the headless walk.\n */\nimport type { SceneSlotConfig } from './buildSceneLayer';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport { withInheritedPaints } from './inheritedPaints';\nimport { withDerivedPaths, sceneDerivedPathOf, sceneShownToPose } from './derivedPath';\nimport { withColorOverrides } from './colorOverrides';\nimport type { ColorOverrideRegistry } from '@weasel-js/animator';\n\n/**\n * The alpha a view paints a node at: the view's own `alphaFor` times any\n * ephemeral override alpha.\n *\n * The hit path asks this too — a node painted at alpha 0 is not on screen and\n * must not claim clicks — so it is one function rather than the painter's and\n * picking's separate readings of the same two inputs.\n */\nexport function composeAlphaFor<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n alphaFor?: (id: string) => number,\n): (id: string) => number {\n const overrideAlphaFor = (id: string) => scene.overrides.read(id as NodeId)?.alpha ?? 1;\n return alphaFor ? (id: string) => alphaFor(id) * overrideAlphaFor(id) : overrideAlphaFor;\n}\n\nexport function wireSceneSlotToScene<TData, TLayer extends string, TPose>(\n slot: SceneSlotConfig<Node<TData, TLayer, TPose>, TPose>,\n scene: Scene<TData, TLayer, TPose>,\n alphaFor?: (id: string) => number,\n colorOverrides?: ColorOverrideRegistry,\n): SceneSlotConfig<Node<TData, TLayer, TPose>, TPose> {\n const derived = withDerivedPaths(scene, withInheritedPaints(scene, slot.drawOne), slot.toPose);\n const derivedPathOf = sceneDerivedPathOf(scene, slot.toPose);\n return {\n ...slot,\n ...(slot.toPose ? { toPose: sceneShownToPose(scene, slot.toPose) } : {}),\n drawOne: colorOverrides ? withColorOverrides(colorOverrides, derived) : derived,\n derivedPathOf,\n alphaFor: composeAlphaFor(scene, alphaFor),\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,SAAgB,gBACd,OACA,UACwB;CACxB,MAAM,oBAAoB,OAAe,MAAM,UAAU,KAAK,EAAY,CAAC,EAAE,SAAS;CACtF,OAAO,YAAY,OAAe,SAAS,EAAE,IAAI,iBAAiB,EAAE,IAAI;AAC1E;AAEA,SAAgB,qBACd,MACA,OACA,UACA,gBACoD;CACpD,MAAM,UAAU,iBAAiB,OAAO,oBAAoB,OAAO,KAAK,OAAO,GAAG,KAAK,MAAM;CAC7F,MAAM,gBAAgB,mBAAmB,OAAO,KAAK,MAAM;CAC3D,OAAO;EACL,GAAG;EACH,GAAI,KAAK,SAAS,EAAE,QAAQ,iBAAiB,OAAO,KAAK,MAAM,EAAE,IAAI,CAAC;EACtE,SAAS,iBAAiB,mBAAmB,gBAAgB,OAAO,IAAI;EACxE;EACA,UAAU,gBAAgB,OAAO,QAAQ;CAC3C;AACF"}
@@ -1,3 +1,4 @@
1
+ import { withInheritedPaints } from "./inheritedPaints.js";
1
2
  import { paintedSceneLayers } from "./sceneLayerPaint.js";
2
3
  import { paintCanvas } from "./canvasRenderer.js";
3
4
  import { wrapNodeOutput } from "./wrapNodeOutput.js";
@@ -43,7 +44,7 @@ function sceneAsHierarchy(scene, layers = {}) {
43
44
  * `layers.layerOrder`), each holding one group per node on that layer.
44
45
  */
45
46
  function buildSceneViewCommands(scene, view, drawOne, extraCommands, alphaFor, layers, colorOverrides, cull) {
46
- const derivedOnly = withDerivedPaths(scene, drawOne);
47
+ const derivedOnly = withDerivedPaths(scene, withInheritedPaints(scene, drawOne));
47
48
  const derived = colorOverrides ? withColorOverrides(colorOverrides, derivedOnly) : derivedOnly;
48
49
  const derivedPathOf = sceneDerivedPathOf(scene);
49
50
  const wrappedDrawOne = (node, pose, v) => {
@@ -1 +1 @@
1
- {"version":3,"file":"sceneViewRender.js","names":["viewToMat3"],"sources":["../../src/canvas/sceneViewRender.ts"],"sourcesContent":["/**\n * `renderSceneToCanvas` — substrate for detached, read-only scene views\n * (`<SceneViewCanvas>` / `<MinimapCanvas>`). Given a `<canvas>`, a `Scene`,\n * a `View`, and a per-node `drawOne`, render one frame.\n */\n\nimport type { WeaselRenderer } from '@weasel-js/renderer';\nimport { cachedCanvasRenderer, paintCanvas } from './canvasRenderer';\nimport { viewToMat3 } from '@weasel-js/geom';\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { View } from '../core/viewport/view';\nimport type { Node, NodeId, Scene } from '../core/scene/types';\nimport { wrapNodeOutput } from './wrapNodeOutput';\nimport { buildSceneTree, type HierarchicalAdapter } from './buildSceneTree';\nimport { sceneToAdapter } from './sceneAdapter';\nimport { withDerivedPaths, sceneDerivedPathOf } from './derivedPath';\nimport { withColorOverrides } from './colorOverrides';\nimport type { ColorOverrideRegistry } from '@weasel-js/animator';\nimport type { SceneViewDrawOne } from './NodeShape';\nimport { paintedSceneLayers } from './sceneLayerPaint';\nimport { cullDrawCommands } from '@weasel-js/renderer';\nimport { paintMissesView, type PaintBoundsFn } from './paintCull';\nimport { paintBoundsFor } from './defaultDrawOne';\n\nexport type { SceneViewDrawOne } from './NodeShape';\n\n/**\n * Which scene layers a detached view paints, on top of each layer's own\n * `visible` flag. Keyed the way `<SceneCanvas>` keys its scene layers —\n * `scene:<layerId>` — so the map a main canvas takes serves its minimap too.\n */\nexport interface SceneViewLayers {\n /** `false` hides that layer in this view. It cannot show one the scene hides. */\n layerVisibility?: Record<string, boolean>;\n /** Paint order, bottom first. A listed order is the whole list: a scene\n * layer left out of it is not painted. */\n layerOrder?: readonly string[];\n}\n\n/** The view size `buildSceneViewCommands` culls to, and how it bounds a\n * node's paint before painting it. */\nexport interface SceneViewCull<TData, TLayer extends string, TPose> {\n width: number;\n height: number;\n paintBounds?: PaintBoundsFn<Node<TData, TLayer, TPose>, TPose>;\n}\n\n/** What to draw into an existing canvas: the scene, the view, and the same\n * painting hooks `<SceneCanvas>` takes. */\nexport interface RenderSceneToCanvasArgs<TData, TLayer extends string, TPose> {\n /** The DOM canvas to paint into. The first call on a given canvas creates\n * its renderer and later calls reuse it;\n * `releaseCanvasRenderer(canvas)` frees it. */\n canvas: HTMLCanvasElement;\n scene: Scene<TData, TLayer, TPose>;\n /** Camera view applied to scene and `extraCommands` alike. */\n view: View;\n /** CSS-pixel size. The drawing buffer is set to `width × dpr` and\n * `height × dpr`; the element's CSS size is the caller's to set. */\n width: number;\n height: number;\n drawOne: SceneViewDrawOne<TData, TLayer, TPose>;\n /** Commands appended after the scene-node output, wrapped in the same view\n * transform as scene commands. */\n extraCommands?: DrawCommand[];\n /** Per-id alpha multiplier, mirroring `<SceneCanvas>`'s scene-slot\n * `alphaFor`. Defaults to `() => 1`. */\n alphaFor?: (id: string) => number;\n /** Per-view layer visibility. See {@link SceneViewLayers}. */\n layerVisibility?: SceneViewLayers['layerVisibility'];\n /** Per-view layer order. See {@link SceneViewLayers}. */\n layerOrder?: SceneViewLayers['layerOrder'];\n /** Animated vertex colors to paint, typically an animator's\n * `colorOverrides` — see `NodePaintCtx.vertexColors`. */\n colorOverrides?: ColorOverrideRegistry;\n /** Skip what cannot reach the `width × height` view: nodes `paintBounds`\n * places outside it are not painted, and scene commands that cannot reach\n * it are dropped before the renderer — the scene slot's `cull`. Off by\n * default. `extraCommands` are never culled. */\n cull?: boolean;\n /** Where `drawOne`'s output for a node can reach, as on the scene slot.\n * Defaults to `defaultPaintBounds` when `drawOne` is `defaultDrawOne`. */\n paintBounds?: PaintBoundsFn<Node<TData, TLayer, TPose>, TPose>;\n /** Device-pixel ratio. Defaults to `window.devicePixelRatio || 1` when\n * available, otherwise 1. */\n dpr?: number;\n}\n\n/** Test seam: the renderer `renderSceneToCanvas` created for a canvas. Not\n * re-exported from the barrel. */\nexport function __getCachedRendererForTest(\n canvas: HTMLCanvasElement,\n): WeaselRenderer | undefined {\n return cachedCanvasRenderer(canvas);\n}\n\n/**\n * Present a `Scene` as the reading surface `buildSceneTree` walks: the scene\n * adapter's own reads, under this view's layer list.\n */\nfunction sceneAsHierarchy<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n layers: SceneViewLayers = {},\n): HierarchicalAdapter<Node<TData, TLayer, TPose>, TPose> {\n const { getNode, getChildren, getPose, composePose } = sceneToAdapter(scene);\n return {\n getLayers: () =>\n paintedSceneLayers(scene.layers, layers)\n .map((l) => ({ id: l.id, visible: l.visible, parallax: l.parallax })),\n getNode,\n getChildren,\n getPose,\n ...(composePose ? { composePose } : {}),\n };\n}\n\n/**\n * Build the DrawCommand list that `renderSceneToCanvas` would dispatch, in\n * screen space. Pure — no GL, no DOM. Walks the scene through `buildSceneTree`,\n * the same walk `<SceneCanvas>` uses, which is what keeps hidden layers\n * unpainted and container clips applied here.\n *\n * Each node's commands go through `wrapNodeOutput` — pose rotation, then the\n * `alphaFor` multiplier — so a `drawOne` that rotates its own output rotates\n * twice; emit unrotated geometry and let the pose drive it.\n *\n * Output is one group per **visible** layer, in scene-layer order (or\n * `layers.layerOrder`), each holding one group per node on that layer.\n */\nexport function buildSceneViewCommands<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n view: View,\n drawOne: SceneViewDrawOne<TData, TLayer, TPose>,\n extraCommands?: ReadonlyArray<DrawCommand>,\n alphaFor?: (id: string) => number,\n /** This view's own layer visibility and order. */\n layers?: SceneViewLayers,\n /** Animated vertex colors to paint, typically an animator's `colorOverrides`. */\n colorOverrides?: ColorOverrideRegistry,\n /** Cull the scene to this CSS-pixel view size — see\n * `RenderSceneToCanvasArgs.cull`. Omit to paint every node. */\n cull?: SceneViewCull<TData, TLayer, TPose>,\n): DrawCommand[] {\n const derivedOnly = withDerivedPaths(scene, drawOne);\n const derived = colorOverrides ? withColorOverrides(colorOverrides, derivedOnly) : derivedOnly;\n const derivedPathOf = sceneDerivedPathOf(scene);\n const wrappedDrawOne = (\n node: Node<TData, TLayer, TPose>,\n pose: TPose,\n v: View,\n ): DrawCommand[] => {\n const overrideAlpha = scene.overrides.read(node.id as NodeId)?.alpha ?? 1;\n return wrapNodeOutput(\n derived(node, pose, v),\n pose,\n (alphaFor ? alphaFor(node.id) : 1) * overrideAlpha,\n );\n };\n\n const hierarchy = sceneAsHierarchy(scene, layers);\n\n const cullRect = cull ? { x: 0, y: 0, width: cull.width, height: cull.height } : undefined;\n const culled = cullRect && cull?.paintBounds ? paintMissesView(cull.paintBounds, view, cullRect) : undefined;\n const tree: DrawCommand[] = buildSceneTree(\n hierarchy as Parameters<typeof buildSceneTree>[0],\n wrappedDrawOne as unknown as Parameters<typeof buildSceneTree>[1],\n view,\n undefined,\n derivedPathOf as unknown as Parameters<typeof buildSceneTree>[4],\n culled as Parameters<typeof buildSceneTree>[5],\n );\n const children = cullRect ? cullDrawCommands(tree, viewToMat3(view), cullRect) : tree;\n if (extraCommands && extraCommands.length > 0) {\n for (const cmd of extraCommands) children.push(cmd);\n }\n return [{\n kind: 'group',\n transform: viewToMat3(view),\n children,\n }];\n}\n\n/**\n * The commands `renderSceneToCanvas` paints for one frame — everything in\n * `args` but the canvas. `<SceneViewCanvas>` paints these through its own\n * renderer lease.\n */\nexport function sceneViewFrame<TData, TLayer extends string, TPose>(\n args: Omit<RenderSceneToCanvasArgs<TData, TLayer, TPose>, 'canvas'>,\n): DrawCommand[] {\n const {\n scene, view, width, height, drawOne, extraCommands, alphaFor, layerVisibility, layerOrder,\n colorOverrides, cull,\n } = args;\n return buildSceneViewCommands(\n scene, view, drawOne, extraCommands, alphaFor, { layerVisibility, layerOrder }, colorOverrides,\n cull ? { width, height, paintBounds: args.paintBounds ?? paintBoundsFor(drawOne) } : undefined,\n );\n}\n\n/**\n * Render one frame of `scene` at `view` into `canvas`. Where no WebGL2\n * context is available (jsdom) the call paints nothing. The canvas's renderer\n * lives until `releaseCanvasRenderer(canvas)`.\n */\nexport function renderSceneToCanvas<TData, TLayer extends string, TPose>(\n args: RenderSceneToCanvasArgs<TData, TLayer, TPose>,\n): void {\n const { canvas, view, width, height, dpr } = args;\n paintCanvas(canvas, sceneViewFrame(args), view, { width, height, dpr });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoGA,SAAS,iBACP,OACA,SAA0B,CAAC,GAC6B;CACxD,MAAM,EAAE,SAAS,aAAa,SAAS,gBAAgB,eAAe,KAAK;CAC3E,OAAO;EACL,iBACE,mBAAmB,MAAM,QAAQ,MAAM,CAAC,CACrC,KAAK,OAAO;GAAE,IAAI,EAAE;GAAI,SAAS,EAAE;GAAS,UAAU,EAAE;EAAS,EAAE;EACxE;EACA;EACA;EACA,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;CACvC;AACF;;;;;;;;;;;;;;AAeA,SAAgB,uBACd,OACA,MACA,SACA,eACA,UAEA,QAEA,gBAGA,MACe;CACf,MAAM,cAAc,iBAAiB,OAAO,OAAO;CACnD,MAAM,UAAU,iBAAiB,mBAAmB,gBAAgB,WAAW,IAAI;CACnF,MAAM,gBAAgB,mBAAmB,KAAK;CAC9C,MAAM,kBACJ,MACA,MACA,MACkB;EAClB,MAAM,gBAAgB,MAAM,UAAU,KAAK,KAAK,EAAY,CAAC,EAAE,SAAS;EACxE,OAAO,eACL,QAAQ,MAAM,MAAM,CAAC,GACrB,OACC,WAAW,SAAS,KAAK,EAAE,IAAI,KAAK,aACvC;CACF;CAEA,MAAM,YAAY,iBAAiB,OAAO,MAAM;CAEhD,MAAM,WAAW,OAAO;EAAE,GAAG;EAAG,GAAG;EAAG,OAAO,KAAK;EAAO,QAAQ,KAAK;CAAO,IAAI;CACjF,MAAM,SAAS,YAAY,MAAM,cAAc,gBAAgB,KAAK,aAAa,MAAM,QAAQ,IAAI;CACnG,MAAM,OAAsB,eAC1B,WACA,gBACA,MACA,QACA,eACA,MACF;CACA,MAAM,WAAW,WAAW,iBAAiB,MAAMA,aAAW,IAAI,GAAG,QAAQ,IAAI;CACjF,IAAI,iBAAiB,cAAc,SAAS,GAC1C,KAAK,MAAM,OAAO,eAAe,SAAS,KAAK,GAAG;CAEpD,OAAO,CAAC;EACN,MAAM;EACN,WAAWA,aAAW,IAAI;EAC1B;CACF,CAAC;AACH;;;;;;AAOA,SAAgB,eACd,MACe;CACf,MAAM,EACJ,OAAO,MAAM,OAAO,QAAQ,SAAS,eAAe,UAAU,iBAAiB,YAC/E,gBAAgB,SACd;CACJ,OAAO,uBACL,OAAO,MAAM,SAAS,eAAe,UAAU;EAAE;EAAiB;CAAW,GAAG,gBAChF,OAAO;EAAE;EAAO;EAAQ,aAAa,KAAK,eAAe,eAAe,OAAO;CAAE,IAAI,MACvF;AACF;;;;;;AAOA,SAAgB,oBACd,MACM;CACN,MAAM,EAAE,QAAQ,MAAM,OAAO,QAAQ,QAAQ;CAC7C,YAAY,QAAQ,eAAe,IAAI,GAAG,MAAM;EAAE;EAAO;EAAQ;CAAI,CAAC;AACxE"}
1
+ {"version":3,"file":"sceneViewRender.js","names":["viewToMat3"],"sources":["../../src/canvas/sceneViewRender.ts"],"sourcesContent":["/**\n * `renderSceneToCanvas` — substrate for detached, read-only scene views\n * (`<SceneViewCanvas>` / `<MinimapCanvas>`). Given a `<canvas>`, a `Scene`,\n * a `View`, and a per-node `drawOne`, render one frame.\n */\n\nimport type { WeaselRenderer } from '@weasel-js/renderer';\nimport { cachedCanvasRenderer, paintCanvas } from './canvasRenderer';\nimport { viewToMat3 } from '@weasel-js/geom';\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { View } from '../core/viewport/view';\nimport type { Node, NodeId, Scene } from '../core/scene/types';\nimport { wrapNodeOutput } from './wrapNodeOutput';\nimport { buildSceneTree, type HierarchicalAdapter } from './buildSceneTree';\nimport { sceneToAdapter } from './sceneAdapter';\nimport { withInheritedPaints } from './inheritedPaints';\nimport { withDerivedPaths, sceneDerivedPathOf } from './derivedPath';\nimport { withColorOverrides } from './colorOverrides';\nimport type { ColorOverrideRegistry } from '@weasel-js/animator';\nimport type { SceneViewDrawOne } from './NodeShape';\nimport { paintedSceneLayers } from './sceneLayerPaint';\nimport { cullDrawCommands } from '@weasel-js/renderer';\nimport { paintMissesView, type PaintBoundsFn } from './paintCull';\nimport { paintBoundsFor } from './defaultDrawOne';\n\nexport type { SceneViewDrawOne } from './NodeShape';\n\n/**\n * Which scene layers a detached view paints, on top of each layer's own\n * `visible` flag. Keyed the way `<SceneCanvas>` keys its scene layers —\n * `scene:<layerId>` — so the map a main canvas takes serves its minimap too.\n */\nexport interface SceneViewLayers {\n /** `false` hides that layer in this view. It cannot show one the scene hides. */\n layerVisibility?: Record<string, boolean>;\n /** Paint order, bottom first. A listed order is the whole list: a scene\n * layer left out of it is not painted. */\n layerOrder?: readonly string[];\n}\n\n/** The view size `buildSceneViewCommands` culls to, and how it bounds a\n * node's paint before painting it. */\nexport interface SceneViewCull<TData, TLayer extends string, TPose> {\n width: number;\n height: number;\n paintBounds?: PaintBoundsFn<Node<TData, TLayer, TPose>, TPose>;\n}\n\n/** What to draw into an existing canvas: the scene, the view, and the same\n * painting hooks `<SceneCanvas>` takes. */\nexport interface RenderSceneToCanvasArgs<TData, TLayer extends string, TPose> {\n /** The DOM canvas to paint into. The first call on a given canvas creates\n * its renderer and later calls reuse it;\n * `releaseCanvasRenderer(canvas)` frees it. */\n canvas: HTMLCanvasElement;\n scene: Scene<TData, TLayer, TPose>;\n /** Camera view applied to scene and `extraCommands` alike. */\n view: View;\n /** CSS-pixel size. The drawing buffer is set to `width × dpr` and\n * `height × dpr`; the element's CSS size is the caller's to set. */\n width: number;\n height: number;\n drawOne: SceneViewDrawOne<TData, TLayer, TPose>;\n /** Commands appended after the scene-node output, wrapped in the same view\n * transform as scene commands. */\n extraCommands?: DrawCommand[];\n /** Per-id alpha multiplier, mirroring `<SceneCanvas>`'s scene-slot\n * `alphaFor`. Defaults to `() => 1`. */\n alphaFor?: (id: string) => number;\n /** Per-view layer visibility. See {@link SceneViewLayers}. */\n layerVisibility?: SceneViewLayers['layerVisibility'];\n /** Per-view layer order. See {@link SceneViewLayers}. */\n layerOrder?: SceneViewLayers['layerOrder'];\n /** Animated vertex colors to paint, typically an animator's\n * `colorOverrides` — see `NodePaintCtx.vertexColors`. */\n colorOverrides?: ColorOverrideRegistry;\n /** Skip what cannot reach the `width × height` view: nodes `paintBounds`\n * places outside it are not painted, and scene commands that cannot reach\n * it are dropped before the renderer — the scene slot's `cull`. Off by\n * default. `extraCommands` are never culled. */\n cull?: boolean;\n /** Where `drawOne`'s output for a node can reach, as on the scene slot.\n * Defaults to `defaultPaintBounds` when `drawOne` is `defaultDrawOne`. */\n paintBounds?: PaintBoundsFn<Node<TData, TLayer, TPose>, TPose>;\n /** Device-pixel ratio. Defaults to `window.devicePixelRatio || 1` when\n * available, otherwise 1. */\n dpr?: number;\n}\n\n/** Test seam: the renderer `renderSceneToCanvas` created for a canvas. Not\n * re-exported from the barrel. */\nexport function __getCachedRendererForTest(\n canvas: HTMLCanvasElement,\n): WeaselRenderer | undefined {\n return cachedCanvasRenderer(canvas);\n}\n\n/**\n * Present a `Scene` as the reading surface `buildSceneTree` walks: the scene\n * adapter's own reads, under this view's layer list.\n */\nfunction sceneAsHierarchy<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n layers: SceneViewLayers = {},\n): HierarchicalAdapter<Node<TData, TLayer, TPose>, TPose> {\n const { getNode, getChildren, getPose, composePose } = sceneToAdapter(scene);\n return {\n getLayers: () =>\n paintedSceneLayers(scene.layers, layers)\n .map((l) => ({ id: l.id, visible: l.visible, parallax: l.parallax })),\n getNode,\n getChildren,\n getPose,\n ...(composePose ? { composePose } : {}),\n };\n}\n\n/**\n * Build the DrawCommand list that `renderSceneToCanvas` would dispatch, in\n * screen space. Pure — no GL, no DOM. Walks the scene through `buildSceneTree`,\n * the same walk `<SceneCanvas>` uses, which is what keeps hidden layers\n * unpainted and container clips applied here.\n *\n * Each node's commands go through `wrapNodeOutput` — pose rotation, then the\n * `alphaFor` multiplier — so a `drawOne` that rotates its own output rotates\n * twice; emit unrotated geometry and let the pose drive it.\n *\n * Output is one group per **visible** layer, in scene-layer order (or\n * `layers.layerOrder`), each holding one group per node on that layer.\n */\nexport function buildSceneViewCommands<TData, TLayer extends string, TPose>(\n scene: Scene<TData, TLayer, TPose>,\n view: View,\n drawOne: SceneViewDrawOne<TData, TLayer, TPose>,\n extraCommands?: ReadonlyArray<DrawCommand>,\n alphaFor?: (id: string) => number,\n /** This view's own layer visibility and order. */\n layers?: SceneViewLayers,\n /** Animated vertex colors to paint, typically an animator's `colorOverrides`. */\n colorOverrides?: ColorOverrideRegistry,\n /** Cull the scene to this CSS-pixel view size — see\n * `RenderSceneToCanvasArgs.cull`. Omit to paint every node. */\n cull?: SceneViewCull<TData, TLayer, TPose>,\n): DrawCommand[] {\n const derivedOnly = withDerivedPaths(scene, withInheritedPaints(scene, drawOne));\n const derived = colorOverrides ? withColorOverrides(colorOverrides, derivedOnly) : derivedOnly;\n const derivedPathOf = sceneDerivedPathOf(scene);\n const wrappedDrawOne = (\n node: Node<TData, TLayer, TPose>,\n pose: TPose,\n v: View,\n ): DrawCommand[] => {\n const overrideAlpha = scene.overrides.read(node.id as NodeId)?.alpha ?? 1;\n return wrapNodeOutput(\n derived(node, pose, v),\n pose,\n (alphaFor ? alphaFor(node.id) : 1) * overrideAlpha,\n );\n };\n\n const hierarchy = sceneAsHierarchy(scene, layers);\n\n const cullRect = cull ? { x: 0, y: 0, width: cull.width, height: cull.height } : undefined;\n const culled = cullRect && cull?.paintBounds ? paintMissesView(cull.paintBounds, view, cullRect) : undefined;\n const tree: DrawCommand[] = buildSceneTree(\n hierarchy as Parameters<typeof buildSceneTree>[0],\n wrappedDrawOne as unknown as Parameters<typeof buildSceneTree>[1],\n view,\n undefined,\n derivedPathOf as unknown as Parameters<typeof buildSceneTree>[4],\n culled as Parameters<typeof buildSceneTree>[5],\n );\n const children = cullRect ? cullDrawCommands(tree, viewToMat3(view), cullRect) : tree;\n if (extraCommands && extraCommands.length > 0) {\n for (const cmd of extraCommands) children.push(cmd);\n }\n return [{\n kind: 'group',\n transform: viewToMat3(view),\n children,\n }];\n}\n\n/**\n * The commands `renderSceneToCanvas` paints for one frame — everything in\n * `args` but the canvas. `<SceneViewCanvas>` paints these through its own\n * renderer lease.\n */\nexport function sceneViewFrame<TData, TLayer extends string, TPose>(\n args: Omit<RenderSceneToCanvasArgs<TData, TLayer, TPose>, 'canvas'>,\n): DrawCommand[] {\n const {\n scene, view, width, height, drawOne, extraCommands, alphaFor, layerVisibility, layerOrder,\n colorOverrides, cull,\n } = args;\n return buildSceneViewCommands(\n scene, view, drawOne, extraCommands, alphaFor, { layerVisibility, layerOrder }, colorOverrides,\n cull ? { width, height, paintBounds: args.paintBounds ?? paintBoundsFor(drawOne) } : undefined,\n );\n}\n\n/**\n * Render one frame of `scene` at `view` into `canvas`. Where no WebGL2\n * context is available (jsdom) the call paints nothing. The canvas's renderer\n * lives until `releaseCanvasRenderer(canvas)`.\n */\nexport function renderSceneToCanvas<TData, TLayer extends string, TPose>(\n args: RenderSceneToCanvasArgs<TData, TLayer, TPose>,\n): void {\n const { canvas, view, width, height, dpr } = args;\n paintCanvas(canvas, sceneViewFrame(args), view, { width, height, dpr });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqGA,SAAS,iBACP,OACA,SAA0B,CAAC,GAC6B;CACxD,MAAM,EAAE,SAAS,aAAa,SAAS,gBAAgB,eAAe,KAAK;CAC3E,OAAO;EACL,iBACE,mBAAmB,MAAM,QAAQ,MAAM,CAAC,CACrC,KAAK,OAAO;GAAE,IAAI,EAAE;GAAI,SAAS,EAAE;GAAS,UAAU,EAAE;EAAS,EAAE;EACxE;EACA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Ae,OAAO;CAAE,IAAI,MACvF;AACF;;;;;;AAOA,SAAgB,oBACd,MACM;CACN,MAAM,EAAE,QAAQ,MAAM,OAAO,QAAQ,QAAQ;CAC7C,YAAY,QAAQ,eAAe,IAAI,GAAG,MAAM;EAAE;EAAO;EAAQ;CAAI,CAAC;AACxE"}
@@ -8,19 +8,23 @@ import { mergeContributions } from "@weasel-js/routing";
8
8
  */
9
9
  /**
10
10
  * Concatenate contribution bundles into one registry, preserving order. Throws
11
- * on a duplicate entry id, dep name or view id — two features answering for
12
- * the same name is a bug in whichever was added second.
11
+ * on a duplicate entry id, dep name, view id or marker id — two features
12
+ * answering for the same name is a bug in whichever was added second.
13
13
  */
14
14
  function mergeContributions$1(...bundles) {
15
15
  const out = mergeContributions(...bundles);
16
- const viewOwner = /* @__PURE__ */ new Map();
17
- for (const entry of out) for (const view of entry.views ?? []) {
18
- const owner = viewOwner.get(view.id);
19
- if (owner !== void 0) throw new Error(`mergeContributions: view "${view.id}" is added by both "${owner}" and "${entry.id}". View ids are unique per surface; rename one.`);
20
- viewOwner.set(view.id, entry.id);
21
- }
16
+ claimIds(out, "view", (entry) => entry.views ?? []);
17
+ claimIds(out, "marker", (entry) => entry.markers ?? []);
22
18
  return out;
23
19
  }
20
+ function claimIds(entries, kind, of) {
21
+ const owners = /* @__PURE__ */ new Map();
22
+ for (const entry of entries) for (const { id } of of(entry)) {
23
+ const owner = owners.get(id);
24
+ if (owner !== void 0) throw new Error(`mergeContributions: ${kind} "${id}" is added by both "${owner}" and "${entry.id}". ${kind === "view" ? "View" : "Marker"} ids are unique per surface; rename one.`);
25
+ owners.set(id, entry.id);
26
+ }
27
+ }
24
28
 
25
29
  //#endregion
26
30
  export { mergeContributions$1 as mergeContributions };
@@ -1 +1 @@
1
- {"version":3,"file":"surfaceContribution.js","names":["mergeContributions","mergeRoutingContributions"],"sources":["../../src/canvas/surfaceContribution.ts"],"sourcesContent":["/**\n * The canvas's unit of extension: a routing `Contribution` plus the roles only\n * a surface can install — views on it, and whatever else needs the mounted\n * canvas.\n */\nimport { mergeContributions as mergeRoutingContributions } from '@weasel-js/routing';\nimport type { DepName, DepSchema } from 'interactions/actions/depSchema';\nimport type { Contribution } from '../tools/overlayBinding';\nimport type { CanvasExtensionApi } from './canvasExtension';\nimport type { CanvasViewProps } from './CanvasView';\nimport type { View } from '../core/viewport/view';\nimport type { KitRequirements } from './kitRequirements';\n\n/** Reads the surface's deps from inside `SurfaceContribution.attach`. */\nexport interface ContributionDepReader {\n get<K extends DepName>(name: K): DepSchema[K] | undefined;\n}\n\n/** What {@link SurfaceContribution.beforePaint} and `afterPaint` are handed. */\nexport interface ContributionFrameCtx {\n /** The frame's timestamp, on `performance.now()`'s clock. Both phases of one\n * frame see the same value. */\n readonly time: number;\n /** The surface camera this frame paints with. */\n readonly view: View;\n /** Ask for another frame. A hook animating something calls this every frame\n * it still has work for, and stops calling it to let the loop go idle. */\n requestFrame(): void;\n /** The surface's deps, as `attach` reads them. */\n readonly deps: ContributionDepReader;\n}\n\n/**\n * A feature a surface installs in one step. Every role is optional: `bindings`,\n * `actions`, `deps`, `overlay` and `presentation` from `Contribution`, plus\n * the ones below. Installing it installs every role it declares, and removing\n * it removes them.\n */\nexport interface SurfaceContribution extends Contribution {\n /** Views this entry adds to the surface, as `<SceneCanvas views>` takes. */\n views?: readonly CanvasViewProps[];\n /**\n * Runs once the surface mounts; returns its teardown. For what the roles\n * above cannot say — a registered (hit-testable) layer, a subscription.\n *\n * Keyed by the function's identity, so a contribution built once (in a\n * `useMemo`, or at module scope) attaches once however often the host\n * re-renders.\n */\n attach?: (api: CanvasExtensionApi, deps: ContributionDepReader) => () => void;\n /**\n * Runs on every frame the surface paints, before the paint — for state the\n * entry's layers read, advanced once per frame. Hooks run in the order the\n * surface lists its entries (registered tools, then `ambient` in array\n * order), and one that throws is reported and skipped without stopping the\n * frame.\n */\n beforePaint?: (ctx: ContributionFrameCtx) => void;\n /** Runs after a frame's pixels have landed, in the same order as\n * {@link beforePaint}. A frame that painted nothing runs no `afterPaint`. */\n afterPaint?: (ctx: ContributionFrameCtx) => void;\n /**\n * The kit versions this entry was written against, as semver ranges:\n * `{ core: '^1.7' }`. A mismatch warns in development, or throws where the\n * surface is set to `versionCheck=\"strict\"`.\n */\n requires?: KitRequirements;\n}\n\n/**\n * Concatenate contribution bundles into one registry, preserving order. Throws\n * on a duplicate entry id, dep name or view id — two features answering for\n * the same name is a bug in whichever was added second.\n */\nexport function mergeContributions<T extends SurfaceContribution>(\n ...bundles: readonly (readonly T[])[]\n): T[] {\n const out = mergeRoutingContributions<T>(...bundles);\n const viewOwner = new Map<string, string>();\n for (const entry of out) {\n for (const view of entry.views ?? []) {\n const owner = viewOwner.get(view.id);\n if (owner !== undefined) {\n throw new Error(\n `mergeContributions: view \"${view.id}\" is added by both \"${owner}\" and \"${entry.id}\". `\n + `View ids are unique per surface; rename one.`,\n );\n }\n viewOwner.set(view.id, entry.id);\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;AA0EA,SAAgBA,qBACd,GAAG,SACE;CACL,MAAM,MAAMC,mBAA6B,GAAG,OAAO;CACnD,MAAM,4BAAY,IAAI,IAAoB;CAC1C,KAAK,MAAM,SAAS,KAClB,KAAK,MAAM,QAAQ,MAAM,SAAS,CAAC,GAAG;EACpC,MAAM,QAAQ,UAAU,IAAI,KAAK,EAAE;EACnC,IAAI,UAAU,QACZ,MAAM,IAAI,MACR,6BAA6B,KAAK,GAAG,sBAAsB,MAAM,SAAS,MAAM,GAAG,gDAErF;EAEF,UAAU,IAAI,KAAK,IAAI,MAAM,EAAE;CACjC;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"surfaceContribution.js","names":["mergeContributions","mergeRoutingContributions"],"sources":["../../src/canvas/surfaceContribution.ts"],"sourcesContent":["/**\n * The canvas's unit of extension: a routing `Contribution` plus the roles only\n * a surface can install — views on it, and whatever else needs the mounted\n * canvas.\n */\nimport { mergeContributions as mergeRoutingContributions } from '@weasel-js/routing';\nimport type { DepName, DepSchema } from 'interactions/actions/depSchema';\nimport type { Contribution } from '../tools/overlayBinding';\nimport type { CanvasExtensionApi } from './canvasExtension';\nimport type { CanvasViewProps } from './CanvasView';\nimport type { ViewMarkerProps } from '../features/viewports/viewMarker';\nimport type { View } from '../core/viewport/view';\nimport type { KitRequirements } from './kitRequirements';\n\n/** Reads the surface's deps from inside `SurfaceContribution.attach`. */\nexport interface ContributionDepReader {\n get<K extends DepName>(name: K): DepSchema[K] | undefined;\n}\n\n/** What {@link SurfaceContribution.beforePaint} and `afterPaint` are handed. */\nexport interface ContributionFrameCtx {\n /** The frame's timestamp, on `performance.now()`'s clock. Both phases of one\n * frame see the same value. */\n readonly time: number;\n /** The surface camera this frame paints with. */\n readonly view: View;\n /** Ask for another frame. A hook animating something calls this every frame\n * it still has work for, and stops calling it to let the loop go idle. */\n requestFrame(): void;\n /** The surface's deps, as `attach` reads them. */\n readonly deps: ContributionDepReader;\n}\n\n/**\n * A feature a surface installs in one step. Every role is optional: `bindings`,\n * `actions`, `deps`, `overlay` and `presentation` from `Contribution`, plus\n * the ones below. Installing it installs every role it declares, and removing\n * it removes them.\n */\nexport interface SurfaceContribution extends Contribution {\n /** Views this entry adds to the surface, as `<SceneCanvas views>` takes. */\n views?: readonly CanvasViewProps[];\n /** Markers this entry draws, as `<ViewMarker>` elements would. */\n markers?: readonly ViewMarkerProps[];\n /**\n * Runs once the surface mounts; returns its teardown. For what the roles\n * above cannot say — a registered (hit-testable) layer, a subscription.\n *\n * Keyed by the function's identity, so a contribution built once (in a\n * `useMemo`, or at module scope) attaches once however often the host\n * re-renders.\n */\n attach?: (api: CanvasExtensionApi, deps: ContributionDepReader) => () => void;\n /**\n * Runs on every frame the surface paints, before the paint — for state the\n * entry's layers read, advanced once per frame. Hooks run in the order the\n * surface lists its entries (registered tools, then `ambient` in array\n * order), and one that throws is reported and skipped without stopping the\n * frame.\n */\n beforePaint?: (ctx: ContributionFrameCtx) => void;\n /** Runs after a frame's pixels have landed, in the same order as\n * {@link beforePaint}. A frame that painted nothing runs no `afterPaint`. */\n afterPaint?: (ctx: ContributionFrameCtx) => void;\n /**\n * The kit versions this entry was written against, as semver ranges:\n * `{ core: '^1.7' }`. A mismatch warns in development, or throws where the\n * surface is set to `versionCheck=\"strict\"`.\n */\n requires?: KitRequirements;\n}\n\n/**\n * Concatenate contribution bundles into one registry, preserving order. Throws\n * on a duplicate entry id, dep name, view id or marker id — two features\n * answering for the same name is a bug in whichever was added second.\n */\nexport function mergeContributions<T extends SurfaceContribution>(\n ...bundles: readonly (readonly T[])[]\n): T[] {\n const out = mergeRoutingContributions<T>(...bundles);\n claimIds(out, 'view', (entry) => entry.views ?? []);\n claimIds(out, 'marker', (entry) => entry.markers ?? []);\n return out;\n}\n\nfunction claimIds<T extends SurfaceContribution>(\n entries: readonly T[], kind: 'view' | 'marker', of: (entry: T) => readonly { id: string }[],\n): void {\n const owners = new Map<string, string>();\n for (const entry of entries) {\n for (const { id } of of(entry)) {\n const owner = owners.get(id);\n if (owner !== undefined) {\n throw new Error(\n `mergeContributions: ${kind} \"${id}\" is added by both \"${owner}\" and \"${entry.id}\". `\n + `${kind === 'view' ? 'View' : 'Marker'} ids are unique per surface; rename one.`,\n );\n }\n owners.set(id, entry.id);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA6EA,SAAgBA,qBACd,GAAG,SACE;CACL,MAAM,MAAMC,mBAA6B,GAAG,OAAO;CACnD,SAAS,KAAK,SAAS,UAAU,MAAM,SAAS,CAAC,CAAC;CAClD,SAAS,KAAK,WAAW,UAAU,MAAM,WAAW,CAAC,CAAC;CACtD,OAAO;AACT;AAEA,SAAS,SACP,SAAuB,MAAyB,IAC1C;CACN,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,SAAS,SAClB,KAAK,MAAM,EAAE,QAAQ,GAAG,KAAK,GAAG;EAC9B,MAAM,QAAQ,OAAO,IAAI,EAAE;EAC3B,IAAI,UAAU,QACZ,MAAM,IAAI,MACR,uBAAuB,KAAK,IAAI,GAAG,sBAAsB,MAAM,SAAS,MAAM,GAAG,KAC5E,SAAS,SAAS,SAAS,SAAS,yCAC3C;EAEF,OAAO,IAAI,IAAI,MAAM,EAAE;CACzB;AAEJ"}
@@ -39,7 +39,7 @@ function useCanvasPaint(paintRef, lease, target, frame, markPainted) {
39
39
  const c = paintTargetRef.current ?? ownCanvasRef.current;
40
40
  if (!c) return false;
41
41
  const rect = paintRectRef.current;
42
- const { layers: paintLayers, width: w, height: h, debugSink: sink, frameStats: timed, dpr: dprIn, flattenTolerance: paintFlattenTolerance, layerGroups: groups, shaders: paintShaders, retain } = inputsRef.current;
42
+ const { layers: paintLayers, width: w, height: h, debugSink: sink, frameStats: timed, dpr: dprIn, flattenTolerance: paintFlattenTolerance, layerGroups: groups, shaders: paintShaders, retain, imageMinification } = inputsRef.current;
43
43
  if (w === 0 || h === 0) return false;
44
44
  const debugFrame = beginDebugFrame(sink, timed, paintLayers);
45
45
  const renderer = lease.bind(c, {
@@ -50,6 +50,7 @@ function useCanvasPaint(paintRef, lease, target, frame, markPainted) {
50
50
  tile: rect,
51
51
  flattenTolerance: paintFlattenTolerance,
52
52
  retainBudget: retain ? retain.budget : void 0,
53
+ imageMinification,
53
54
  shaders: paintShaders
54
55
  });
55
56
  if (!renderer) return false;
@@ -1 +1 @@
1
- {"version":3,"file":"useCanvasPaint.js","names":[],"sources":["../../src/canvas/useCanvasPaint.ts"],"sourcesContent":["import { useCallback, useEffect, useInsertionEffect, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { viewToMat3 } from '@weasel-js/renderer';\nimport type { View } from 'core/viewport/view';\nimport {\n DEFAULT_LAYER_RETAIN, drawLayers, type LayerCommandCache, type LayerRetainPolicy, type RenderLayer,\n} from 'core/layers/render';\nimport type { CanvasDebugSink } from '../debug/types';\nimport { beginDebugFrame } from '../debug/useDebugSink';\nimport type { CanvasRendererLease } from './canvasRenderer';\nimport type { CanvasProps } from './canvasProps';\nimport type { CanvasElements } from './useCanvasElements';\nimport { NO_LAYER_VISIBILITY, type LayerGate } from './useExtraLayers';\n\n/** What a frame's paint reads that a React render owns. */\nexport interface PaintInputs extends Pick<CanvasProps<unknown>, 'dpr' | 'layerGroups' | 'shaders' | 'flattenTolerance' | 'retain'> {\n layers: RenderLayer<unknown>[];\n width: number;\n height: number;\n debugSink: CanvasDebugSink | null;\n frameStats: boolean;\n}\n\n/** What a frame's paint reads that changes outside a render. */\nexport interface PaintFrame {\n inputsRef: { readonly current: PaintInputs };\n viewRef: { readonly current: View };\n gateRef: { readonly current: LayerGate };\n helpersRef: { readonly current: unknown };\n}\n\n/**\n * Which content version the last paint showed. `markPainted` records the current one, read\n * from `contentVersion`'s latest committed value.\n */\nexport function usePaintedVersion(contentVersion: (() => number) | undefined): {\n getPaintedVersion: () => number;\n markPainted: () => void;\n} {\n const contentVersionRef = useLatest(contentVersion);\n const paintedVersionRef = useRef(0);\n const getPaintedVersion = useCallback(() => paintedVersionRef.current, []);\n const markPainted = useCallback(() => {\n paintedVersionRef.current = contentVersionRef.current?.() ?? 0;\n }, [contentVersionRef]);\n return { getPaintedVersion, markPainted };\n}\n\nfunction retainPolicy(retain: PaintInputs['retain']): LayerRetainPolicy | false {\n if (retain === false) return false;\n const minCommands = retain?.minCommands;\n return minCommands === undefined ? DEFAULT_LAYER_RETAIN : { minCommands };\n}\n\n/**\n * Publish the canvas's paint into `paintRef`, which the frame loop calls. The paint binds the\n * leased renderer to whichever canvas pixels go to and draws the layer stack through the\n * current view. The layer command cache lives as long as the canvas.\n */\nexport function useCanvasPaint(\n paintRef: { current: () => boolean },\n lease: CanvasRendererLease,\n target: Pick<CanvasElements, 'paintTargetRef' | 'ownCanvasRef' | 'paintRectRef'>,\n frame: PaintFrame,\n markPainted: () => void,\n): void {\n const { paintTargetRef, ownCanvasRef, paintRectRef } = target;\n const { inputsRef, viewRef, gateRef, helpersRef } = frame;\n const layerCacheRef = useRef<LayerCommandCache>(new Map());\n\n const paint = useCallback((): boolean => {\n const c = paintTargetRef.current ?? ownCanvasRef.current;\n if (!c) return false;\n const rect = paintRectRef.current;\n const {\n layers: paintLayers, width: w, height: h, debugSink: sink, frameStats: timed,\n dpr: dprIn,\n flattenTolerance: paintFlattenTolerance,\n layerGroups: groups, shaders: paintShaders, retain,\n } = inputsRef.current;\n if (w === 0 || h === 0) return false;\n\n const debugFrame = beginDebugFrame(sink, timed, paintLayers);\n\n const renderer = lease.bind(c, { width: w, height: h, dpr: dprIn }, {\n tile: rect,\n flattenTolerance: paintFlattenTolerance,\n retainBudget: retain ? retain.budget : undefined,\n shaders: paintShaders,\n });\n // No WebGL2 (jsdom), or a context that is lost for now: nothing to paint.\n if (!renderer) return false;\n\n const view = viewRef.current;\n const { layerVisibility: vis, layerOrder: order } = gateRef.current;\n const spans = debugFrame?.time();\n const commands = drawLayers(\n paintLayers,\n helpersRef.current,\n vis ?? NO_LAYER_VISIBILITY,\n order,\n view,\n { width: w, height: h },\n layerCacheRef.current,\n undefined,\n groups,\n spans,\n retainPolicy(retain),\n );\n renderer.render(commands, viewToMat3(view), spans ? { spans } : undefined);\n debugFrame?.end(renderer.lastFrameStats());\n markPainted();\n return true;\n }, [gateRef, helpersRef, inputsRef, lease, markPainted, ownCanvasRef, paintRectRef, paintTargetRef, viewRef]);\n useInsertionEffect(() => {\n paintRef.current = paint;\n });\n\n useEffect(() => {\n const layerCache = layerCacheRef.current;\n return () => { layerCache.clear(); };\n }, []);\n}\n"],"mappings":";;;;;;;;;;;;;AAmCA,SAAgB,kBAAkB,gBAGhC;CACA,MAAM,oBAAoB,UAAU,cAAc;CAClD,MAAM,oBAAoB,OAAO,CAAC;CAKlC,OAAO;EAAE,mBAJiB,kBAAkB,kBAAkB,SAAS,CAAC,CAI/D;EAAmB,aAHR,kBAAkB;GACpC,kBAAkB,UAAU,kBAAkB,UAAU,KAAK;EAC/D,GAAG,CAAC,iBAAiB,CACO;CAAY;AAC1C;AAEA,SAAS,aAAa,QAA0D;CAC9E,I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S;EAAY;EAAW;EAAO;EAAa;EAAc;EAAc;EAAgB;CAAO,CAAC;CAC5G,yBAAyB;EACvB,SAAS,UAAU;CACrB,CAAC;CAED,gBAAgB;EACd,MAAM,aAAa,cAAc;EACjC,aAAa;GAAE,WAAW,MAAM;EAAG;CACrC,GAAG,CAAC,CAAC;AACP"}
1
+ {"version":3,"file":"useCanvasPaint.js","names":[],"sources":["../../src/canvas/useCanvasPaint.ts"],"sourcesContent":["import { useCallback, useEffect, useInsertionEffect, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { viewToMat3 } from '@weasel-js/renderer';\nimport type { View } from 'core/viewport/view';\nimport {\n DEFAULT_LAYER_RETAIN, drawLayers, type LayerCommandCache, type LayerRetainPolicy, type RenderLayer,\n} from 'core/layers/render';\nimport type { CanvasDebugSink } from '../debug/types';\nimport { beginDebugFrame } from '../debug/useDebugSink';\nimport type { CanvasRendererLease } from './canvasRenderer';\nimport type { CanvasProps } from './canvasProps';\nimport type { CanvasElements } from './useCanvasElements';\nimport { NO_LAYER_VISIBILITY, type LayerGate } from './useExtraLayers';\n\n/** What a frame's paint reads that a React render owns. */\nexport interface PaintInputs extends Pick<CanvasProps<unknown>, 'dpr' | 'layerGroups' | 'shaders' | 'flattenTolerance' | 'imageMinification' | 'retain'> {\n layers: RenderLayer<unknown>[];\n width: number;\n height: number;\n debugSink: CanvasDebugSink | null;\n frameStats: boolean;\n}\n\n/** What a frame's paint reads that changes outside a render. */\nexport interface PaintFrame {\n inputsRef: { readonly current: PaintInputs };\n viewRef: { readonly current: View };\n gateRef: { readonly current: LayerGate };\n helpersRef: { readonly current: unknown };\n}\n\n/**\n * Which content version the last paint showed. `markPainted` records the current one, read\n * from `contentVersion`'s latest committed value.\n */\nexport function usePaintedVersion(contentVersion: (() => number) | undefined): {\n getPaintedVersion: () => number;\n markPainted: () => void;\n} {\n const contentVersionRef = useLatest(contentVersion);\n const paintedVersionRef = useRef(0);\n const getPaintedVersion = useCallback(() => paintedVersionRef.current, []);\n const markPainted = useCallback(() => {\n paintedVersionRef.current = contentVersionRef.current?.() ?? 0;\n }, [contentVersionRef]);\n return { getPaintedVersion, markPainted };\n}\n\nfunction retainPolicy(retain: PaintInputs['retain']): LayerRetainPolicy | false {\n if (retain === false) return false;\n const minCommands = retain?.minCommands;\n return minCommands === undefined ? DEFAULT_LAYER_RETAIN : { minCommands };\n}\n\n/**\n * Publish the canvas's paint into `paintRef`, which the frame loop calls. The paint binds the\n * leased renderer to whichever canvas pixels go to and draws the layer stack through the\n * current view. The layer command cache lives as long as the canvas.\n */\nexport function useCanvasPaint(\n paintRef: { current: () => boolean },\n lease: CanvasRendererLease,\n target: Pick<CanvasElements, 'paintTargetRef' | 'ownCanvasRef' | 'paintRectRef'>,\n frame: PaintFrame,\n markPainted: () => void,\n): void {\n const { paintTargetRef, ownCanvasRef, paintRectRef } = target;\n const { inputsRef, viewRef, gateRef, helpersRef } = frame;\n const layerCacheRef = useRef<LayerCommandCache>(new Map());\n\n const paint = useCallback((): boolean => {\n const c = paintTargetRef.current ?? ownCanvasRef.current;\n if (!c) return false;\n const rect = paintRectRef.current;\n const {\n layers: paintLayers, width: w, height: h, debugSink: sink, frameStats: timed,\n dpr: dprIn,\n flattenTolerance: paintFlattenTolerance,\n layerGroups: groups, shaders: paintShaders, retain, imageMinification,\n } = inputsRef.current;\n if (w === 0 || h === 0) return false;\n\n const debugFrame = beginDebugFrame(sink, timed, paintLayers);\n\n const renderer = lease.bind(c, { width: w, height: h, dpr: dprIn }, {\n tile: rect,\n flattenTolerance: paintFlattenTolerance,\n retainBudget: retain ? retain.budget : undefined,\n imageMinification,\n shaders: paintShaders,\n });\n // No WebGL2 (jsdom), or a context that is lost for now: nothing to paint.\n if (!renderer) return false;\n\n const view = viewRef.current;\n const { layerVisibility: vis, layerOrder: order } = gateRef.current;\n const spans = debugFrame?.time();\n const commands = drawLayers(\n paintLayers,\n helpersRef.current,\n vis ?? NO_LAYER_VISIBILITY,\n order,\n view,\n { width: w, height: h },\n layerCacheRef.current,\n undefined,\n groups,\n spans,\n retainPolicy(retain),\n );\n renderer.render(commands, viewToMat3(view), spans ? { spans } : undefined);\n debugFrame?.end(renderer.lastFrameStats());\n markPainted();\n return true;\n }, [gateRef, helpersRef, inputsRef, lease, markPainted, ownCanvasRef, paintRectRef, paintTargetRef, viewRef]);\n useInsertionEffect(() => {\n paintRef.current = paint;\n });\n\n useEffect(() => {\n const layerCache = layerCacheRef.current;\n return () => { layerCache.clear(); };\n }, []);\n}\n"],"mappings":";;;;;;;;;;;;;AAmCA,SAAgB,kBAAkB,gBAGhC;CACA,MAAM,oBAAoB,UAAU,cAAc;CAClD,MAAM,oBAAoB,OAAO,CAAC;CAKlC,OAAO;EAAE,mBAJiB,kBAAkB,kBAAkB,SAAS,CAAC,CAI/D;EAAmB,aAHR,kBAAkB;GACpC,kBAAkB,UAAU,kBAAkB,UAAU,KAAK;EAC/D,GAAG,CAAC,iBAAiB,CACO;CAAY;AAC1C;AAEA,SAAS,aAAa,QAA0D;CAC9E,IAAI,WAAW,OAAO,OAAO;CAC7B,MAAM,cAAc,QAAQ;CAC5B,OAAO,gBAAgB,SAAY,uBAAuB,EAAE,YAAY;AAC1E;;;;;;AAOA,SAAgB,eACd,UACA,OACA,QACA,OACA,aACM;CACN,MAAM,EAAE,gBAAgB,cAAc,iBAAiB;CACvD,MAAM,EAAE,WAAW,SAAS,SAAS,eAAe;CACpD,MAAM,gBAAgB,uBAA0B,IAAI,IAAI,CAAC;CAEzD,MAAM,QAAQ,kBAA2B;EACvC,MAAM,IAAI,eAAe,WAAW,aAAa;EACjD,IAAI,CAAC,GAAG,OAAO;EACf,MAAM,OAAO,aAAa;EAC1B,MAAM,EACJ,QAAQ,aAAa,OAAO,GAAG,QAAQ,GAAG,WAAW,MAAM,YAAY,OACvE,KAAK,OACL,kBAAkB,uBAClB,aAAa,QAAQ,SAAS,cAAc,QAAQ,sBAClD,UAAU;EACd,IAAI,MAAM,KAAK,MAAM,GAAG,OAAO;EAE/B,MAAM,aAAa,gBAAgB,MAAM,OAAO,WAAW;EAE3D,MAAM,WAAW,MAAM,KAAK,GAAG;GAAE,OAAO;GAAG,QAAQ;GAAG,KAAK;EAAM,GAAG;GAClE,MAAM;GACN,kBAAkB;GAClB,cAAc,SAAS,OAAO,SAAS;GACvC;GACA,SAAS;EACX,CAAC;EAED,IAAI,CAAC,UAAU,OAAO;EAEtB,MAAM,OAAO,QAAQ;EACrB,MAAM,EAAE,iBAAiB,KAAK,YAAY,UAAU,QAAQ;EAC5D,MAAM,QAAQ,YAAY,KAAK;EAC/B,MAAM,WAAW,WACf,aACA,WAAW,SACX,OAAO,qBACP,OACA,MACA;GAAE,OAAO;GAAG,QAAQ;EAAE,GACtB,cAAc,SACd,QACA,QACA,OACA,aAAa,MAAM,CACrB;EACA,SAAS,OAAO,UAAU,WAAW,IAAI,GAAG,QAAQ,EAAE,MAAM,IAAI,MAAS;EACzE,YAAY,IAAI,SAAS,eAAe,CAAC;EACzC,YAAY;EACZ,OAAO;CACT,GAAG;EAAC;EAAS;EAAY;EAAW;EAAO;EAAa;EAAc;EAAc;EAAgB;CAAO,CAAC;CAC5G,yBAAyB;EACvB,SAAS,UAAU;CACrB,CAAC;CAED,gBAAgB;EACd,MAAM,aAAa,cAAc;EACjC,aAAa;GAAE,WAAW,MAAM;EAAG;CACrC,GAAG,CAAC,CAAC;AACP"}
@@ -30,7 +30,8 @@ function useCanvasView(opts) {
30
30
  onViewChange,
31
31
  viewBounds,
32
32
  dims,
33
- requestRedraw
33
+ requestRedraw,
34
+ by: opts.controlledBy ?? "view"
34
35
  });
35
36
  const controlledWarnedRef = useRef(false);
36
37
  const getView = useCallback(() => {
@@ -44,7 +45,8 @@ function useCanvasView(opts) {
44
45
  if (controlled) {
45
46
  if (imperative && !controlledWarnedRef.current) {
46
47
  controlledWarnedRef.current = true;
47
- console.warn(forward ? "[weasel] setView not applied locally: this canvas is controlled by its `view` prop. The value was forwarded to `onViewChange` — update the prop from there, or drop it to take the imperative path." : "[weasel] setView ignored: this canvas is controlled by its `view` prop and has no `onViewChange`, so the value has nowhere to go. Update the prop, or drop it to take the imperative path.");
48
+ const [prop, cb] = live.current.by === "aim" ? ["aim", "onAimChange"] : ["view", "onViewChange"];
49
+ console.warn(forward ? `[weasel] setView not applied locally: this canvas is controlled by its \`${prop}\` prop. The value was forwarded to \`${cb}\` — update the prop from there, or drop it to take the imperative path.` : `[weasel] setView ignored: this canvas is controlled by its \`${prop}\` prop and has no \`${cb}\`, so the value has nowhere to go. Update the prop, or drop it to take the imperative path.`);
48
50
  }
49
51
  forward?.(clamped);
50
52
  if (derived) redraw();
@@ -1 +1 @@
1
- {"version":3,"file":"useCanvasView.js","names":[],"sources":["../../src/canvas/useCanvasView.ts"],"sourcesContent":["/**\n * A camera: held in a ref when uncontrolled, taken from the `view` option when\n * controlled, with one write path and one subscriber list over both.\n * `<SceneCanvas>` makes the one its `<Canvas>` looks through, and each\n * `<CanvasView>` makes its own.\n */\nimport { useCallback, useRef, type MutableRefObject } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { Dims } from 'core/layers/render';\nimport type { Bounds } from 'core/viewport/fitViewToBounds';\nimport { clampView } from 'core/viewport/clampView';\nimport { normalizeView, sameView, type View } from 'core/viewport/view';\n\n/** The view props a canvas takes for its camera. */\nexport interface CameraProps {\n /** Controlled viewport. When supplied, the canvas does not own the value —\n * the consumer must supply `onViewChange` and re-render with the new\n * view. See `View` JSDoc for the camera-position convention. */\n view?: View;\n /** Initial viewport for the uncontrolled path. Default `{x:0, y:0}`. */\n defaultView?: View;\n /** Fires whenever the viewport changes — in both controlled and\n * uncontrolled modes. */\n onViewChange?: (next: View) => void;\n /**\n * Optional world-space rect that constrains pan: every write to the view passes through\n * `clampView` first, keeping the visible rect inside `viewBounds`. An axis where the\n * visible rect is larger than the bounds is centered. Has no effect on `scale`.\n */\n viewBounds?: { x: number; y: number; width: number; height: number };\n}\n\n/** Inputs to {@link useCanvasView}: the camera's view props and what a write\n * needs from whatever the camera looks through. */\nexport interface CanvasViewOptions {\n /** Supplied, the camera is controlled. A thunk is a camera derived from\n * something else, read fresh at every {@link CanvasViewState.getView}. */\n view: View | (() => View) | undefined;\n defaultView: View | undefined;\n onViewChange: ((next: View) => void) | undefined;\n viewBounds: Bounds | undefined;\n /** The size the camera looks through, which `viewBounds` clamps against. */\n dims: () => Dims;\n requestRedraw: () => void;\n}\n\n/** What `useCanvasView` hands back. The owner decides when in a commit\n * the two controlled steps run, since they have to sit among its own effects. */\nexport interface CanvasViewState {\n /** The view in effect. Written by a write when uncontrolled and by\n * `adoptControlled` when controlled. A camera derived by a thunk is not\n * kept here: read `getView`. */\n viewRef: MutableRefObject<View>;\n /** This render's controlled view, absent when the camera is uncontrolled or\n * derived. A new object every render, so compare its numbers. */\n controlled: View | undefined;\n /** The imperative write. Controlled, it is forwarded to `onViewChange`\n * instead of applied, and says so once per mount. */\n setView: (next: View | ((current: View) => View)) => void;\n /** The write input makes. Controlled, forwarding it to `onViewChange` is how\n * the owner hears of a pan at all, so nothing is warned. */\n setViewFromInput: (next: View) => void;\n getView: () => View;\n subscribeView: (fn: (v: View) => void) => () => void;\n /** Take this render's controlled view into `viewRef`. Call from an insertion effect. */\n adoptControlled: () => void;\n /** Tell subscribers of a controlled view that moved since the last call.\n * A controlled view reaches the ref with no write, so this is where they\n * hear of it. Call from a layout effect. */\n announceControlled: () => void;\n /** Drop every subscriber, on unmount. */\n clearSubscribers: () => void;\n}\n\nconst IDENTITY: View = { x: 0, y: 0, scale: { x: 1, y: 1 } };\n\nexport function useCanvasView(opts: CanvasViewOptions): CanvasViewState {\n const { view: viewProp, defaultView, onViewChange, viewBounds, dims, requestRedraw } = opts;\n const derived = typeof viewProp === 'function' ? viewProp : undefined;\n const controlledView = viewProp === undefined || derived ? undefined : normalizeView(viewProp as View);\n // The uncontrolled view lives in a ref, not `useState`, so a camera moving\n // at 60 Hz costs no React render; DOM that mirrors it subscribes instead.\n const viewRef = useRef<View>(controlledView ?? normalizeView(defaultView ?? IDENTITY));\n const viewSubsRef = useRef<Set<(v: View) => void>>(new Set());\n const live = useLatest({\n controlled: viewProp !== undefined, derived, onViewChange, viewBounds, dims, requestRedraw,\n });\n const controlledWarnedRef = useRef(false);\n\n const getView = useCallback((): View => {\n const thunk = live.current.derived;\n return thunk ? normalizeView(thunk()) : viewRef.current;\n }, [live]);\n\n const write = useCallback((next: View, imperative: boolean): void => {\n const {\n controlled, derived, onViewChange: forward, viewBounds: bounds, dims: size, requestRedraw: redraw,\n } = live.current;\n const valid = normalizeView(next);\n const clamped = bounds ? clampView(valid, bounds, size()) : valid;\n if (controlled) {\n // The prop is the authority; writing the ref would put pixels and props\n // out of step with nothing to reconcile them.\n if (imperative && !controlledWarnedRef.current) {\n controlledWarnedRef.current = true;\n console.warn(forward\n ? '[weasel] setView not applied locally: this canvas is controlled by its `view` prop. The value was forwarded to `onViewChange` — update the prop from there, or drop it to take the imperative path.'\n : '[weasel] setView ignored: this canvas is controlled by its `view` prop and has no `onViewChange`, so the value has nowhere to go. Update the prop, or drop it to take the imperative path.');\n }\n forward?.(clamped);\n // A derived camera has no prop to change, so nothing else repaints it.\n if (derived) redraw();\n return;\n }\n viewRef.current = clamped;\n for (const fn of viewSubsRef.current) fn(clamped);\n forward?.(clamped);\n redraw();\n }, [live]);\n\n const setView = useCallback((next: View | ((current: View) => View)) => {\n write(typeof next === 'function' ? next(getView()) : next, true);\n }, [write, getView]);\n const setViewFromInput = useCallback((next: View) => { write(next, false); }, [write]);\n\n const subscribeView = useCallback((fn: (v: View) => void) => {\n viewSubsRef.current.add(fn);\n return () => { viewSubsRef.current.delete(fn); };\n }, []);\n\n const controlledMovedRef = useRef(false);\n // A closure over this render's prop, not a ref read: the owner calls it\n // from the same render's insertion effect.\n const adoptControlled = (): void => {\n if (!controlledView) return;\n controlledMovedRef.current ||= !sameView(viewRef.current, controlledView);\n viewRef.current = controlledView;\n };\n const announceControlled = useCallback(() => {\n if (!controlledMovedRef.current) return;\n controlledMovedRef.current = false;\n for (const fn of viewSubsRef.current) fn(viewRef.current);\n }, []);\n const clearSubscribers = useCallback(() => { viewSubsRef.current.clear(); }, []);\n\n return {\n viewRef, controlled: controlledView, setView, setViewFromInput, getView, subscribeView,\n adoptControlled, announceControlled, clearSubscribers,\n };\n}\n"],"mappings":";;;;;;;;;;;;AA0EA,IAAM,WAAiB;CAAE,GAAG;CAAG,GAAG;CAAG,OAAO;EAAE,GAAG;EAAG,GAAG;CAAE;AAAE;AAE3D,SAAgB,cAAc,MAA0C;CACtE,MAAM,EAAE,MAAM,UAAU,aAAa,cAAc,YAAY,MAAM,kBAAkB;CACvF,MAAM,UAAU,OAAO,aAAa,aAAa,WAAW;CAC5D,MAAM,iBAAiB,aAAa,UAAa,UAAU,SAAY,cAAc,QAAgB;CAGrG,MAAM,UAAU,OAAa,kBAAkB,cAAc,eAAe,QAAQ,CAAC;CACrF,MAAM,cAAc,uBAA+B,IAAI,IAAI,CAAC;CAC5D,MAAM,OAAO,UAAU;EACrB,YAAY,aAAa;EAAW;EAAS;EAAc;EAAY;EAAM;CAC/E,CAAC;CACD,MAAM,sBAAsB,OAAO,KAAK;CAExC,MAAM,UAAU,kBAAwB;EACtC,MAAM,QAAQ,KAAK,QAAQ;EAC3B,OAAO,QAAQ,cAAc,MAAM,CAAC,IAAI,QAAQ;CAClD,GAAG,CAAC,IAAI,CAAC;CAET,MAAM,QAAQ,aAAa,MAAY,eAA8B;EACnE,MAAM,EACJ,YAAY,SAAS,cAAc,SAAS,YAAY,QAAQ,MAAM,MAAM,eAAe,WACzF,KAAK;EACT,MAAM,QAAQ,cAAc,IAAI;EAChC,MAAM,UAAU,SAAS,UAAU,OAAO,QAAQ,KAAK,CAAC,IAAI;EAC5D,IAAI,YAAY;GAGd,IAAI,cAAc,CAAC,oBAAoB,SAAS;IAC9C,oBAAoB,UAAU;IAC9B,QAAQ,KAAK,UACT,wMACA,4LAA4L;GAClM;GACA,UAAU,OAAO;GAEjB,IAAI,SAAS,OAAO;GACpB;EACF;EACA,QAAQ,UAAU;EAClB,KAAK,MAAM,MAAM,YAAY,SAAS,GAAG,OAAO;EAChD,UAAU,OAAO;EACjB,OAAO;CACT,GAAG,CAAC,IAAI,CAAC;CAET,MAAM,UAAU,aAAa,SAA2C;EACtE,MAAM,OAAO,SAAS,aAAa,KAAK,QAAQ,CAAC,IAAI,MAAM,IAAI;CACjE,GAAG,CAAC,OAAO,OAAO,CAAC;CACnB,MAAM,mBAAmB,aAAa,SAAe;EAAE,MAAM,MAAM,KAAK;CAAG,GAAG,CAAC,KAAK,CAAC;CAErF,MAAM,gBAAgB,aAAa,OAA0B;EAC3D,YAAY,QAAQ,IAAI,EAAE;EAC1B,aAAa;GAAE,YAAY,QAAQ,OAAO,EAAE;EAAG;CACjD,GAAG,CAAC,CAAC;CAEL,MAAM,qBAAqB,OAAO,KAAK;CAGvC,MAAM,wBAA8B;EAClC,IAAI,CAAC,gBAAgB;EACrB,mBAAmB,YAAY,CAAC,SAAS,QAAQ,SAAS,cAAc;EACxE,QAAQ,UAAU;CACpB;CAQA,OAAO;EACL;EAAS,YAAY;EAAgB;EAAS;EAAkB;EAAS;EACzE;EAAiB,oBATQ,kBAAkB;GAC3C,IAAI,CAAC,mBAAmB,SAAS;GACjC,mBAAmB,UAAU;GAC7B,KAAK,MAAM,MAAM,YAAY,SAAS,GAAG,QAAQ,OAAO;EAC1D,GAAG,CAAC,CAKe;EAAoB,kBAJd,kBAAkB;GAAE,YAAY,QAAQ,MAAM;EAAG,GAAG,CAAC,CAIvC;CACvC;AACF"}
1
+ {"version":3,"file":"useCanvasView.js","names":[],"sources":["../../src/canvas/useCanvasView.ts"],"sourcesContent":["/**\n * A camera: held in a ref when uncontrolled, taken from the `view` option when\n * controlled, with one write path and one subscriber list over both.\n * `<SceneCanvas>` makes the one its `<Canvas>` looks through, and each\n * `<CanvasView>` makes its own.\n */\nimport { useCallback, useRef, type MutableRefObject } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { Dims } from 'core/layers/render';\nimport type { Bounds } from 'core/viewport/fitViewToBounds';\nimport { clampView } from 'core/viewport/clampView';\nimport { normalizeView, sameView, type View } from 'core/viewport/view';\n\n/** The view props a canvas takes for its camera. */\nexport interface CameraProps {\n /** Controlled viewport. When supplied, the canvas does not own the value —\n * the consumer must supply `onViewChange` and re-render with the new\n * view. See `View` JSDoc for the camera-position convention. */\n view?: View;\n /** Initial viewport for the uncontrolled path. Default `{x:0, y:0}`. */\n defaultView?: View;\n /** Fires whenever the viewport changes — in both controlled and\n * uncontrolled modes. */\n onViewChange?: (next: View) => void;\n /**\n * Optional world-space rect that constrains pan: every write to the view passes through\n * `clampView` first, keeping the visible rect inside `viewBounds`. An axis where the\n * visible rect is larger than the bounds is centered. Has no effect on `scale`.\n */\n viewBounds?: { x: number; y: number; width: number; height: number };\n}\n\n/** Inputs to {@link useCanvasView}: the camera's view props and what a write\n * needs from whatever the camera looks through. */\nexport interface CanvasViewOptions {\n /** Supplied, the camera is controlled. A thunk is a camera derived from\n * something else, read fresh at every {@link CanvasViewState.getView}. */\n view: View | (() => View) | undefined;\n defaultView: View | undefined;\n onViewChange: ((next: View) => void) | undefined;\n viewBounds: Bounds | undefined;\n /** The size the camera looks through, which `viewBounds` clamps against. */\n dims: () => Dims;\n requestRedraw: () => void;\n /** The prop a controlled camera answers to, which a warning names. Default `'view'`. */\n controlledBy?: 'view' | 'aim';\n}\n\n/** What `useCanvasView` hands back. The owner decides when in a commit\n * the two controlled steps run, since they have to sit among its own effects. */\nexport interface CanvasViewState {\n /** The view in effect. Written by a write when uncontrolled and by\n * `adoptControlled` when controlled. A camera derived by a thunk is not\n * kept here: read `getView`. */\n viewRef: MutableRefObject<View>;\n /** This render's controlled view, absent when the camera is uncontrolled or\n * derived. A new object every render, so compare its numbers. */\n controlled: View | undefined;\n /** The imperative write. Controlled, it is forwarded to `onViewChange`\n * instead of applied, and says so once per mount. */\n setView: (next: View | ((current: View) => View)) => void;\n /** The write input makes. Controlled, forwarding it to `onViewChange` is how\n * the owner hears of a pan at all, so nothing is warned. */\n setViewFromInput: (next: View) => void;\n getView: () => View;\n subscribeView: (fn: (v: View) => void) => () => void;\n /** Take this render's controlled view into `viewRef`. Call from an insertion effect. */\n adoptControlled: () => void;\n /** Tell subscribers of a controlled view that moved since the last call.\n * A controlled view reaches the ref with no write, so this is where they\n * hear of it. Call from a layout effect. */\n announceControlled: () => void;\n /** Drop every subscriber, on unmount. */\n clearSubscribers: () => void;\n}\n\nconst IDENTITY: View = { x: 0, y: 0, scale: { x: 1, y: 1 } };\n\nexport function useCanvasView(opts: CanvasViewOptions): CanvasViewState {\n const { view: viewProp, defaultView, onViewChange, viewBounds, dims, requestRedraw } = opts;\n const derived = typeof viewProp === 'function' ? viewProp : undefined;\n const controlledView = viewProp === undefined || derived ? undefined : normalizeView(viewProp as View);\n // The uncontrolled view lives in a ref, not `useState`, so a camera moving\n // at 60 Hz costs no React render; DOM that mirrors it subscribes instead.\n const viewRef = useRef<View>(controlledView ?? normalizeView(defaultView ?? IDENTITY));\n const viewSubsRef = useRef<Set<(v: View) => void>>(new Set());\n const live = useLatest({\n controlled: viewProp !== undefined, derived, onViewChange, viewBounds, dims, requestRedraw,\n by: opts.controlledBy ?? 'view',\n });\n const controlledWarnedRef = useRef(false);\n\n const getView = useCallback((): View => {\n const thunk = live.current.derived;\n return thunk ? normalizeView(thunk()) : viewRef.current;\n }, [live]);\n\n const write = useCallback((next: View, imperative: boolean): void => {\n const {\n controlled, derived, onViewChange: forward, viewBounds: bounds, dims: size, requestRedraw: redraw,\n } = live.current;\n const valid = normalizeView(next);\n const clamped = bounds ? clampView(valid, bounds, size()) : valid;\n if (controlled) {\n // The prop is the authority; writing the ref would put pixels and props\n // out of step with nothing to reconcile them.\n if (imperative && !controlledWarnedRef.current) {\n controlledWarnedRef.current = true;\n const [prop, cb] = live.current.by === 'aim' ? ['aim', 'onAimChange'] : ['view', 'onViewChange'];\n console.warn(forward\n ? `[weasel] setView not applied locally: this canvas is controlled by its \\`${prop}\\` prop. The value was forwarded to \\`${cb}\\` — update the prop from there, or drop it to take the imperative path.`\n : `[weasel] setView ignored: this canvas is controlled by its \\`${prop}\\` prop and has no \\`${cb}\\`, so the value has nowhere to go. Update the prop, or drop it to take the imperative path.`);\n }\n forward?.(clamped);\n // A derived camera has no prop to change, so nothing else repaints it.\n if (derived) redraw();\n return;\n }\n viewRef.current = clamped;\n for (const fn of viewSubsRef.current) fn(clamped);\n forward?.(clamped);\n redraw();\n }, [live]);\n\n const setView = useCallback((next: View | ((current: View) => View)) => {\n write(typeof next === 'function' ? next(getView()) : next, true);\n }, [write, getView]);\n const setViewFromInput = useCallback((next: View) => { write(next, false); }, [write]);\n\n const subscribeView = useCallback((fn: (v: View) => void) => {\n viewSubsRef.current.add(fn);\n return () => { viewSubsRef.current.delete(fn); };\n }, []);\n\n const controlledMovedRef = useRef(false);\n // A closure over this render's prop, not a ref read: the owner calls it\n // from the same render's insertion effect.\n const adoptControlled = (): void => {\n if (!controlledView) return;\n controlledMovedRef.current ||= !sameView(viewRef.current, controlledView);\n viewRef.current = controlledView;\n };\n const announceControlled = useCallback(() => {\n if (!controlledMovedRef.current) return;\n controlledMovedRef.current = false;\n for (const fn of viewSubsRef.current) fn(viewRef.current);\n }, []);\n const clearSubscribers = useCallback(() => { viewSubsRef.current.clear(); }, []);\n\n return {\n viewRef, controlled: controlledView, setView, setViewFromInput, getView, subscribeView,\n adoptControlled, announceControlled, clearSubscribers,\n };\n}\n"],"mappings":";;;;;;;;;;;;AA4EA,IAAM,WAAiB;CAAE,GAAG;CAAG,GAAG;CAAG,OAAO;EAAE,GAAG;EAAG,GAAG;CAAE;AAAE;AAE3D,SAAgB,cAAc,MAA0C;CACtE,MAAM,EAAE,MAAM,UAAU,aAAa,cAAc,YAAY,MAAM,kBAAkB;CACvF,MAAM,UAAU,OAAO,aAAa,aAAa,WAAW;CAC5D,MAAM,iBAAiB,aAAa,UAAa,UAAU,SAAY,cAAc,QAAgB;C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;EAAE,MAAM,MAAM,KAAK;CAAG,GAAG,CAAC,KAAK,CAAC;CAErF,MAAM,gBAAgB,aAAa,OAA0B;EAC3D,YAAY,QAAQ,IAAI,EAAE;EAC1B,aAAa;GAAE,YAAY,QAAQ,OAAO,EAAE;EAAG;CACjD,GAAG,CAAC,CAAC;CAEL,MAAM,qBAAqB,OAAO,KAAK;CAGvC,MAAM,wBAA8B;EAClC,IAAI,CAAC,gBAAgB;EACrB,mBAAmB,YAAY,CAAC,SAAS,QAAQ,SAAS,cAAc;EACxE,QAAQ,UAAU;CACpB;CAQA,OAAO;EACL;EAAS,YAAY;EAAgB;EAAS;EAAkB;EAAS;EACzE;EAAiB,oBATQ,kBAAkB;GAC3C,IAAI,CAAC,mBAAmB,SAAS;GACjC,mBAAmB,UAAU;GAC7B,KAAK,MAAM,MAAM,YAAY,SAAS,GAAG,QAAQ,OAAO;EAC1D,GAAG,CAAC,CAKe;EAAoB,kBAJd,kBAAkB;GAAE,YAAY,QAAQ,MAAM;EAAG,GAAG,CAAC,CAIvC;CACvC;AACF"}
@@ -0,0 +1,52 @@
1
+ import { useCallback, useRef } from "react";
2
+ import { useLatest } from "@weasel-js/react";
3
+
4
+ //#region src/canvas/useInFlightBounds.ts
5
+ /**
6
+ * Where a view boxes the nodes an in-flight gesture names: at the pose a
7
+ * source previews, else at the node's effective pose — a transform's poses
8
+ * live in the scene's overrides, not on its handle. Boxed through `boxOf`
9
+ * either way, since a consumer `boundsOf` answers for the document pose only.
10
+ */
11
+ function useInFlightBounds(args) {
12
+ const { gestureSource, boxOf, committedPoseOf } = args;
13
+ const previewPoseExtraRef = useLatest(args.previewPoseExtra);
14
+ const previewPoseOf = useCallback((id) => {
15
+ const p = previewPoseExtraRef.current?.(id);
16
+ return p != null ? p : null;
17
+ }, [previewPoseExtraRef]);
18
+ const inFlight = useRef(null);
19
+ const isInFlight = useCallback((id) => {
20
+ if (!gestureSource) return false;
21
+ const version = gestureSource.getVersion();
22
+ let entry = inFlight.current;
23
+ if (entry === null || entry.source !== gestureSource || entry.version !== version) {
24
+ entry = {
25
+ source: gestureSource,
26
+ version,
27
+ ids: new Set(gestureSource.ids() ?? [])
28
+ };
29
+ inFlight.current = entry;
30
+ }
31
+ return entry.ids.has(id);
32
+ }, [gestureSource]);
33
+ return {
34
+ previewPoseOf,
35
+ previewBoundsOf: useCallback((id) => {
36
+ const p = previewPoseOf(id);
37
+ if (p != null) return boxOf(id, p);
38
+ if (!isInFlight(id)) return null;
39
+ const shown = committedPoseOf(id);
40
+ return shown != null ? boxOf(id, shown) : null;
41
+ }, [
42
+ previewPoseOf,
43
+ boxOf,
44
+ isInFlight,
45
+ committedPoseOf
46
+ ])
47
+ };
48
+ }
49
+
50
+ //#endregion
51
+ export { useInFlightBounds };
52
+ //# sourceMappingURL=useInFlightBounds.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useInFlightBounds.js","names":[],"sources":["../../src/canvas/useInFlightBounds.ts"],"sourcesContent":["import { useCallback, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { GestureSource } from './gestureBounds';\nimport type { Bounds } from 'core/viewport/fitViewToBounds';\n\n/**\n * Where a view boxes the nodes an in-flight gesture names: at the pose a\n * source previews, else at the node's effective pose — a transform's poses\n * live in the scene's overrides, not on its handle. Boxed through `boxOf`\n * either way, since a consumer `boundsOf` answers for the document pose only.\n */\nexport function useInFlightBounds<TPose>(args: {\n gestureSource: GestureSource | undefined;\n /** Read through a ref, so a change mid-gesture rebuilds nothing. */\n previewPoseExtra: ((id: string) => unknown) | undefined;\n boxOf: (id: string, pose: TPose) => Bounds | null;\n /** The node's effective world pose. */\n committedPoseOf: (id: string) => TPose | null;\n}): {\n previewPoseOf: (id: string) => TPose | null;\n previewBoundsOf: (id: string) => Bounds | null;\n} {\n const { gestureSource, boxOf, committedPoseOf } = args;\n const previewPoseExtraRef = useLatest(args.previewPoseExtra);\n const previewPoseOf = useCallback((id: string): TPose | null => {\n const p = previewPoseExtraRef.current?.(id);\n return p != null ? (p as TPose) : null;\n }, [previewPoseExtraRef]);\n\n // The source's ids, re-read only when its version moves.\n const inFlight = useRef<{ source: GestureSource; version: number; ids: ReadonlySet<string> } | null>(null);\n const isInFlight = useCallback((id: string): boolean => {\n if (!gestureSource) return false;\n const version = gestureSource.getVersion();\n let entry = inFlight.current;\n if (entry === null || entry.source !== gestureSource || entry.version !== version) {\n entry = { source: gestureSource, version, ids: new Set(gestureSource.ids() ?? []) };\n inFlight.current = entry;\n }\n return entry.ids.has(id);\n }, [gestureSource]);\n\n const previewBoundsOf = useCallback((id: string): Bounds | null => {\n const p = previewPoseOf(id);\n if (p != null) return boxOf(id, p);\n if (!isInFlight(id)) return null;\n const shown = committedPoseOf(id);\n return shown != null ? boxOf(id, shown) : null;\n }, [previewPoseOf, boxOf, isInFlight, committedPoseOf]);\n\n return { previewPoseOf, previewBoundsOf };\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgB,kBAAyB,MAUvC;CACA,MAAM,EAAE,eAAe,OAAO,oBAAoB;CAClD,MAAM,sBAAsB,UAAU,KAAK,gBAAgB;CAC3D,MAAM,gBAAgB,aAAa,OAA6B;EAC9D,MAAM,IAAI,oBAAoB,UAAU,EAAE;EAC1C,OAAO,KAAK,OAAQ,IAAc;CACpC,GAAG,CAAC,mBAAmB,CAAC;CAGxB,MAAM,WAAW,OAAoF,IAAI;CACzG,MAAM,aAAa,aAAa,OAAwB;EACtD,IAAI,CAAC,eAAe,OAAO;EAC3B,MAAM,UAAU,cAAc,WAAW;EACzC,IAAI,QAAQ,SAAS;EACrB,IAAI,UAAU,QAAQ,MAAM,WAAW,iBAAiB,MAAM,YAAY,SAAS;GACjF,QAAQ;IAAE,QAAQ;IAAe;IAAS,KAAK,IAAI,IAAI,cAAc,IAAI,KAAK,CAAC,CAAC;GAAE;GAClF,SAAS,UAAU;EACrB;EACA,OAAO,MAAM,IAAI,IAAI,EAAE;CACzB,GAAG,CAAC,aAAa,CAAC;CAUlB,OAAO;EAAE;EAAe,iBARA,aAAa,OAA8B;GACjE,MAAM,IAAI,cAAc,EAAE;GAC1B,IAAI,KAAK,MAAM,OAAO,MAAM,IAAI,CAAC;GACjC,IAAI,CAAC,WAAW,EAAE,GAAG,OAAO;GAC5B,MAAM,QAAQ,gBAAgB,EAAE;GAChC,OAAO,SAAS,OAAO,MAAM,IAAI,KAAK,IAAI;EAC5C,GAAG;GAAC;GAAe;GAAO;GAAY;EAAe,CAE7B;CAAgB;AAC1C"}
@@ -32,7 +32,7 @@ function useSlotLayers(layersMap, tools, backgroundFill, decorationLayer) {
32
32
  ]);
33
33
  }
34
34
  /**
35
- * The full stack the canvas paints: its slot layers, then registered views, the debug overlay,
35
+ * The full stack the canvas paints: its slot layers, then root view markers, registered views, the debug overlay,
36
36
  * externally registered layers, and the cursor. Every layer that can change on its own
37
37
  * repaints the canvas through `requestRedraw`.
38
38
  */
@@ -40,7 +40,11 @@ function useComposedLayers(layers, above, requestRedraw) {
40
40
  const { viewRegistry, debugOverlay, extrasRef, extrasVersion, cursorLayer } = above;
41
41
  const viewRegistryVersion = useSyncExternalStore(useCallback((cb) => viewRegistry?.subscribe(cb) ?? (() => {}), [viewRegistry]), () => viewRegistry?.getVersion() ?? 0, () => 0);
42
42
  const composed = useMemo(() => {
43
- const withViews = viewRegistry ? [...layers, ...viewRegistry.list().filter((r) => r.paint).map((r) => r.layer)] : layers;
43
+ const withViews = viewRegistry ? [
44
+ ...layers,
45
+ ...viewRegistry.markerLayers(null),
46
+ ...viewRegistry.list().filter((r) => r.paint).map((r) => r.layer)
47
+ ] : layers;
44
48
  return [
45
49
  ...debugOverlay ? [...withViews, debugOverlay] : withViews,
46
50
  ...extrasRef.current,