@weasel-js/core 1.7.0 → 1.7.2
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.
- package/CHANGELOG.md +794 -0
- package/README.md +14 -8
- package/dist/WeaselProvider.js +15 -0
- package/dist/WeaselProvider.js.map +1 -0
- package/dist/affordances/composeAffordanceLayer.js +224 -0
- package/dist/affordances/composeAffordanceLayer.js.map +1 -0
- package/dist/affordances/cornerResize.js +69 -0
- package/dist/affordances/cornerResize.js.map +1 -0
- package/dist/affordances/hitAffordanceRegions.js +138 -0
- package/dist/affordances/hitAffordanceRegions.js.map +1 -0
- package/dist/affordances/pathAnchors.js +66 -0
- package/dist/affordances/pathAnchors.js.map +1 -0
- package/dist/affordances/rotationHandle.js +103 -0
- package/dist/affordances/rotationHandle.js.map +1 -0
- package/dist/animation/behaviors/momentum.js +118 -0
- package/dist/animation/behaviors/momentum.js.map +1 -0
- package/dist/animation/colorHelpers.js +135 -0
- package/dist/animation/colorHelpers.js.map +1 -0
- package/dist/animation/colorRegistry.js +37 -0
- package/dist/animation/colorRegistry.js.map +1 -0
- package/dist/animation/index.js +20 -0
- package/dist/animation/loop.js +62 -0
- package/dist/animation/loop.js.map +1 -0
- package/dist/animation/observe.js +23 -0
- package/dist/animation/observe.js.map +1 -0
- package/dist/animation/poseHelpers.js +50 -0
- package/dist/animation/poseHelpers.js.map +1 -0
- package/dist/animation/reflow.js +121 -0
- package/dist/animation/reflow.js.map +1 -0
- package/dist/animation/rig/bindRig.js +74 -0
- package/dist/animation/rig/bindRig.js.map +1 -0
- package/dist/animation/rig/blendPoses.js +43 -0
- package/dist/animation/rig/blendPoses.js.map +1 -0
- package/dist/animation/rig/mirrorPose.js +19 -0
- package/dist/animation/rig/mirrorPose.js.map +1 -0
- package/dist/animation/rig/resolveSkeleton.js +33 -0
- package/dist/animation/rig/resolveSkeleton.js.map +1 -0
- package/dist/animation/rig/solveIk.js +103 -0
- package/dist/animation/rig/solveIk.js.map +1 -0
- package/dist/animation/rig/types.js +12 -0
- package/dist/animation/rig/types.js.map +1 -0
- package/dist/animation/rig/useRig.js +23 -0
- package/dist/animation/rig/useRig.js.map +1 -0
- package/dist/animation/slew.js +27 -0
- package/dist/animation/slew.js.map +1 -0
- package/dist/animation/stagger.js +138 -0
- package/dist/animation/stagger.js.map +1 -0
- package/dist/animation/timeline/booking.js +106 -0
- package/dist/animation/timeline/booking.js.map +1 -0
- package/dist/animation/timeline/createTimeline.js +116 -0
- package/dist/animation/timeline/createTimeline.js.map +1 -0
- package/dist/animation/timeline/sampleTrack.js +29 -0
- package/dist/animation/timeline/sampleTrack.js.map +1 -0
- package/dist/animation/useAnimator.js +329 -0
- package/dist/animation/useAnimator.js.map +1 -0
- package/dist/animation/wrappers/animateLifecycle.js +40 -0
- package/dist/animation/wrappers/animateLifecycle.js.map +1 -0
- package/dist/animation/wrappers/animateOnSetPose.js +44 -0
- package/dist/animation/wrappers/animateOnSetPose.js.map +1 -0
- package/dist/{autoPoseDescriptor-_XOyF7t4.d.ts → autoPoseDescriptor-vCdt55xm.d.ts} +2 -2
- package/dist/{builtins-DLn2lCr_.d.ts → builtins-C-gRyVRx.d.ts} +742 -513
- package/dist/canvas/Canvas.js +608 -0
- package/dist/canvas/Canvas.js.map +1 -0
- package/dist/canvas/CanvasView.js +255 -0
- package/dist/canvas/CanvasView.js.map +1 -0
- package/dist/canvas/CursorCoordsHud.js +102 -0
- package/dist/canvas/CursorCoordsHud.js.map +1 -0
- package/dist/canvas/DrawCanvas.js +67 -0
- package/dist/canvas/DrawCanvas.js.map +1 -0
- package/dist/canvas/MinimapCanvas.js +139 -0
- package/dist/canvas/MinimapCanvas.js.map +1 -0
- package/dist/canvas/ModalityHud.js +66 -0
- package/dist/canvas/ModalityHud.js.map +1 -0
- package/dist/canvas/NodeShape.js +391 -0
- package/dist/canvas/NodeShape.js.map +1 -0
- package/dist/canvas/PickHud.js +93 -0
- package/dist/canvas/PickHud.js.map +1 -0
- package/dist/canvas/SceneCanvas/ActionsProviderIfRoot.js +10 -0
- package/dist/canvas/SceneCanvas/ActionsProviderIfRoot.js.map +1 -0
- package/dist/canvas/SceneCanvas/DepRegistryProviderIfRoot.js +10 -0
- package/dist/canvas/SceneCanvas/DepRegistryProviderIfRoot.js.map +1 -0
- package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js +51 -0
- package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js.map +1 -0
- package/dist/canvas/SceneCanvas/contributionFrameHooks.js +42 -0
- package/dist/canvas/SceneCanvas/contributionFrameHooks.js.map +1 -0
- package/dist/canvas/SceneCanvas/defaultNodeProperties.js +549 -0
- package/dist/canvas/SceneCanvas/defaultNodeProperties.js.map +1 -0
- package/dist/canvas/SceneCanvas/defaultNodeRouting.js +26 -0
- package/dist/canvas/SceneCanvas/defaultNodeRouting.js.map +1 -0
- package/dist/canvas/SceneCanvas/dispatcherGestureBounds.js +69 -0
- package/dist/canvas/SceneCanvas/dispatcherGestureBounds.js.map +1 -0
- package/dist/canvas/SceneCanvas/features.js +97 -0
- package/dist/canvas/SceneCanvas/features.js.map +1 -0
- package/dist/canvas/SceneCanvas/poseGeometry.js +46 -0
- package/dist/canvas/SceneCanvas/poseGeometry.js.map +1 -0
- package/dist/canvas/SceneCanvas/useActionsPropResolver.js +48 -0
- package/dist/canvas/SceneCanvas/useActionsPropResolver.js.map +1 -0
- package/dist/canvas/SceneCanvas/useBuiltinShapeTools.js +70 -0
- package/dist/canvas/SceneCanvas/useBuiltinShapeTools.js.map +1 -0
- package/dist/canvas/SceneCanvas/useContributionRoles.js +75 -0
- package/dist/canvas/SceneCanvas/useContributionRoles.js.map +1 -0
- package/dist/canvas/SceneCanvas/useDispatcherOverlayLayer.js +172 -0
- package/dist/canvas/SceneCanvas/useDispatcherOverlayLayer.js.map +1 -0
- package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js +69 -0
- package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js.map +1 -0
- package/dist/canvas/SceneCanvas/useSceneSelectTool.js +127 -0
- package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -0
- package/dist/canvas/SceneCanvas/useViewportActions.js +30 -0
- package/dist/canvas/SceneCanvas/useViewportActions.js.map +1 -0
- package/dist/canvas/SceneCanvas.js +992 -0
- package/dist/canvas/SceneCanvas.js.map +1 -0
- package/dist/canvas/SceneViewCanvas.js +54 -0
- package/dist/canvas/SceneViewCanvas.js.map +1 -0
- package/dist/canvas/accentColor.js +9 -0
- package/dist/canvas/accentColor.js.map +1 -0
- package/dist/canvas/affordanceAt.js +63 -0
- package/dist/canvas/affordanceAt.js.map +1 -0
- package/dist/canvas/buildSceneTree.js +65 -0
- package/dist/canvas/buildSceneTree.js.map +1 -0
- package/dist/canvas/canvasRenderer.js +89 -0
- package/dist/canvas/canvasRenderer.js.map +1 -0
- package/dist/canvas/colorOverrides.js +16 -0
- package/dist/canvas/colorOverrides.js.map +1 -0
- package/dist/canvas/defaultDrawOne.js +43 -0
- package/dist/canvas/defaultDrawOne.js.map +1 -0
- package/dist/canvas/deps/areaSelect.js +19 -0
- package/dist/canvas/deps/areaSelect.js.map +1 -0
- package/dist/canvas/deps/debug.js +9 -0
- package/dist/canvas/deps/debug.js.map +1 -0
- package/dist/canvas/deps/dispatcher.js +11 -0
- package/dist/canvas/deps/dispatcher.js.map +1 -0
- package/dist/canvas/deps/editAnchors.js +101 -0
- package/dist/canvas/deps/editAnchors.js.map +1 -0
- package/dist/canvas/deps/geometryProjection.js +11 -0
- package/dist/canvas/deps/geometryProjection.js.map +1 -0
- package/dist/canvas/deps/hitTestArea.js +51 -0
- package/dist/canvas/deps/hitTestArea.js.map +1 -0
- package/dist/canvas/deps/ingestion.js +31 -0
- package/dist/canvas/deps/ingestion.js.map +1 -0
- package/dist/canvas/deps/insert.js +116 -0
- package/dist/canvas/deps/insert.js.map +1 -0
- package/dist/canvas/deps/lassoSelect.js +20 -0
- package/dist/canvas/deps/lassoSelect.js.map +1 -0
- package/dist/canvas/deps/layout.js +34 -0
- package/dist/canvas/deps/layout.js.map +1 -0
- package/dist/canvas/deps/nodeAtPoint.js +19 -0
- package/dist/canvas/deps/nodeAtPoint.js.map +1 -0
- package/dist/canvas/deps/poseComposition.js +11 -0
- package/dist/canvas/deps/poseComposition.js.map +1 -0
- package/dist/canvas/deps/poseDescriptor.js +12 -0
- package/dist/canvas/deps/poseDescriptor.js.map +1 -0
- package/dist/canvas/deps/resizePolicy.js +35 -0
- package/dist/canvas/deps/resizePolicy.js.map +1 -0
- package/dist/canvas/deps/slice.js +99 -0
- package/dist/canvas/deps/slice.js.map +1 -0
- package/dist/canvas/deps/snap.js +11 -0
- package/dist/canvas/deps/snap.js.map +1 -0
- package/dist/canvas/deps/textEdit.js +21 -0
- package/dist/canvas/deps/textEdit.js.map +1 -0
- package/dist/canvas/deps/view.js +43 -0
- package/dist/canvas/deps/view.js.map +1 -0
- package/dist/canvas/derivedPath.js +47 -0
- package/dist/canvas/derivedPath.js.map +1 -0
- package/dist/canvas/drawEnvelope.js +22 -0
- package/dist/canvas/drawEnvelope.js.map +1 -0
- package/dist/canvas/getNodeAtPoint.js +18 -0
- package/dist/canvas/getNodeAtPoint.js.map +1 -0
- package/dist/canvas/hostAnchor.js +29 -0
- package/dist/canvas/hostAnchor.js.map +1 -0
- package/dist/canvas/hud.module.js +18 -0
- package/dist/canvas/hud.module.js.map +1 -0
- package/dist/canvas/insertPreviewExtent.js +103 -0
- package/dist/canvas/insertPreviewExtent.js.map +1 -0
- package/dist/canvas/kitRequirements.js +177 -0
- package/dist/canvas/kitRequirements.js.map +1 -0
- package/dist/canvas/layerOrder.js +66 -0
- package/dist/canvas/layerOrder.js.map +1 -0
- package/dist/canvas/layerSlots.js +14 -0
- package/dist/canvas/layerSlots.js.map +1 -0
- package/dist/canvas/minimapMath.js +80 -0
- package/dist/canvas/minimapMath.js.map +1 -0
- package/dist/canvas/mountedCanvases.js +20 -0
- package/dist/canvas/mountedCanvases.js.map +1 -0
- package/dist/canvas/overlayRoleStrokes.js +17 -0
- package/dist/canvas/overlayRoleStrokes.js.map +1 -0
- package/dist/canvas/paintCull.js +20 -0
- package/dist/canvas/paintCull.js.map +1 -0
- package/dist/canvas/pickWalk.js +158 -0
- package/dist/canvas/pickWalk.js.map +1 -0
- package/dist/canvas/planeClips.js +30 -0
- package/dist/canvas/planeClips.js.map +1 -0
- package/dist/canvas/poseRotation.js +35 -0
- package/dist/canvas/poseRotation.js.map +1 -0
- package/dist/canvas/rasterToPng.js +21 -0
- package/dist/canvas/rasterToPng.js.map +1 -0
- package/dist/canvas/renderDebugSnapshot.js +32 -0
- package/dist/canvas/renderDebugSnapshot.js.map +1 -0
- package/dist/canvas/renderNeeds.js +25 -0
- package/dist/canvas/renderNeeds.js.map +1 -0
- package/dist/canvas/renderSceneToPixels.js +143 -0
- package/dist/canvas/renderSceneToPixels.js.map +1 -0
- package/dist/canvas/sceneAdapter.js +270 -0
- package/dist/canvas/sceneAdapter.js.map +1 -0
- package/dist/canvas/sceneLayerPaint.js +37 -0
- package/dist/canvas/sceneLayerPaint.js.map +1 -0
- package/dist/canvas/sceneSlotWiring.js +20 -0
- package/dist/canvas/sceneSlotWiring.js.map +1 -0
- package/dist/canvas/sceneViewRender.js +72 -0
- package/dist/canvas/sceneViewRender.js.map +1 -0
- package/dist/canvas/slopsDebugLayer.js +61 -0
- package/dist/canvas/slopsDebugLayer.js.map +1 -0
- package/dist/canvas/surfaceContribution.js +15 -0
- package/dist/canvas/surfaceContribution.js.map +1 -0
- package/dist/canvas/toolPreview.js +39 -0
- package/dist/canvas/toolPreview.js.map +1 -0
- package/dist/canvas/useCanvasRenderer.js +11 -0
- package/dist/canvas/useCanvasRenderer.js.map +1 -0
- package/dist/canvas/useFrameLoop.js +60 -0
- package/dist/canvas/useFrameLoop.js.map +1 -0
- package/dist/canvas/useHostAnchor.js +71 -0
- package/dist/canvas/useHostAnchor.js.map +1 -0
- package/dist/canvas/useLateContentRedraw.js +21 -0
- package/dist/canvas/useLateContentRedraw.js.map +1 -0
- package/dist/canvas/useRedrawOn.js +21 -0
- package/dist/canvas/useRedrawOn.js.map +1 -0
- package/dist/canvas/useViewHelpers.js +120 -0
- package/dist/canvas/useViewHelpers.js.map +1 -0
- package/dist/canvas/viewInputs.js +17 -0
- package/dist/canvas/viewInputs.js.map +1 -0
- package/dist/canvas/viewRegistry.js +61 -0
- package/dist/canvas/viewRegistry.js.map +1 -0
- package/dist/canvas/wrapNodeOutput.js +14 -0
- package/dist/canvas/wrapNodeOutput.js.map +1 -0
- package/dist/clipboard.d.ts +10 -5
- package/dist/clipboard.js +3 -5
- package/dist/clone.d.ts +3 -3
- package/dist/clone.js +2 -5
- package/dist/core/adapters/arrayAdapter.js +85 -0
- package/dist/core/adapters/arrayAdapter.js.map +1 -0
- package/dist/core/adapters/useArrayAdapter.js +13 -0
- package/dist/core/adapters/useArrayAdapter.js.map +1 -0
- package/dist/core/applyOps.js +12 -0
- package/dist/core/applyOps.js.map +1 -0
- package/dist/core/device/index.js +4 -0
- package/dist/core/device/targets.js +17 -0
- package/dist/core/device/targets.js.map +1 -0
- package/dist/core/device/useDeviceProfile.js +75 -0
- package/dist/core/device/useDeviceProfile.js.map +1 -0
- package/dist/core/fillInPoseFrame.js +102 -0
- package/dist/core/fillInPoseFrame.js.map +1 -0
- package/dist/core/geometry/poseDescriptor.js +93 -0
- package/dist/core/geometry/poseDescriptor.js.map +1 -0
- package/dist/core/geometry/poseRotation.js +58 -0
- package/dist/core/geometry/poseRotation.js.map +1 -0
- package/dist/core/geometry/regionHit.js +102 -0
- package/dist/core/geometry/regionHit.js.map +1 -0
- package/dist/core/geometry/unionBounds.js +60 -0
- package/dist/core/geometry/unionBounds.js.map +1 -0
- package/dist/core/gradient.js +136 -0
- package/dist/core/gradient.js.map +1 -0
- package/dist/core/isPlainObject.js +11 -0
- package/dist/core/isPlainObject.js.map +1 -0
- package/dist/core/layers/render.js +150 -0
- package/dist/core/layers/render.js.map +1 -0
- package/dist/core/markerInset.js +24 -0
- package/dist/core/markerInset.js.map +1 -0
- package/dist/core/mixed.js +6 -0
- package/dist/core/mixed.js.map +1 -0
- package/dist/core/ops/arrange.js +31 -0
- package/dist/core/ops/arrange.js.map +1 -0
- package/dist/core/ops/create.js +32 -0
- package/dist/core/ops/create.js.map +1 -0
- package/dist/core/ops/createHistory.js +20 -0
- package/dist/core/ops/createHistory.js.map +1 -0
- package/dist/core/ops/delete.js +89 -0
- package/dist/core/ops/delete.js.map +1 -0
- package/dist/core/ops/registry.js +17 -0
- package/dist/core/ops/registry.js.map +1 -0
- package/dist/core/ops/reorder/algorithms.js +55 -0
- package/dist/core/ops/reorder/algorithms.js.map +1 -0
- package/dist/core/ops/reorder/index.js +140 -0
- package/dist/core/ops/reorder/index.js.map +1 -0
- package/dist/core/ops/reparent.js +52 -0
- package/dist/core/ops/reparent.js.map +1 -0
- package/dist/core/ops/select.js +34 -0
- package/dist/core/ops/select.js.map +1 -0
- package/dist/core/ops/setData.js +34 -0
- package/dist/core/ops/setData.js.map +1 -0
- package/dist/core/ops/setLayer.js +34 -0
- package/dist/core/ops/setLayer.js.map +1 -0
- package/dist/core/ops/setLayout.js +31 -0
- package/dist/core/ops/setLayout.js.map +1 -0
- package/dist/core/ops/setPath.js +57 -0
- package/dist/core/ops/setPath.js.map +1 -0
- package/dist/core/ops/setText.js +34 -0
- package/dist/core/ops/setText.js.map +1 -0
- package/dist/core/ops/slot.js +37 -0
- package/dist/core/ops/slot.js.map +1 -0
- package/dist/core/ops/transform.js +42 -0
- package/dist/core/ops/transform.js.map +1 -0
- package/dist/core/paintKinds.js +156 -0
- package/dist/core/paintKinds.js.map +1 -0
- package/dist/core/scene/NodeProperties.js +20 -0
- package/dist/core/scene/NodeProperties.js.map +1 -0
- package/dist/core/scene/NodeRouting.js +24 -0
- package/dist/core/scene/NodeRouting.js.map +1 -0
- package/dist/core/scene/arrivals.js +12 -0
- package/dist/core/scene/arrivals.js.map +1 -0
- package/dist/core/scene/composeFrame.js +29 -0
- package/dist/core/scene/composeFrame.js.map +1 -0
- package/dist/core/scene/depMemo.js +18 -0
- package/dist/core/scene/depMemo.js.map +1 -0
- package/dist/core/scene/dependents.js +66 -0
- package/dist/core/scene/dependents.js.map +1 -0
- package/dist/core/scene/derivedPath.js +31 -0
- package/dist/core/scene/derivedPath.js.map +1 -0
- package/dist/core/scene/effectivePose.js +78 -0
- package/dist/core/scene/effectivePose.js.map +1 -0
- package/dist/core/scene/kitRegistry.js +33 -0
- package/dist/core/scene/kitRegistry.js.map +1 -0
- package/dist/core/scene/layoutPass.js +96 -0
- package/dist/core/scene/layoutPass.js.map +1 -0
- package/dist/core/scene/nodeFnFields.js +83 -0
- package/dist/core/scene/nodeFnFields.js.map +1 -0
- package/dist/core/scene/nodeMemo.js +28 -0
- package/dist/core/scene/nodeMemo.js.map +1 -0
- package/dist/core/scene/poseFeed.js +87 -0
- package/dist/core/scene/poseFeed.js.map +1 -0
- package/dist/core/scene/poseOverrides.js +52 -0
- package/dist/core/scene/poseOverrides.js.map +1 -0
- package/dist/core/scene/poseSnapshot.js +54 -0
- package/dist/core/scene/poseSnapshot.js.map +1 -0
- package/dist/core/scene/scene.js +1271 -0
- package/dist/core/scene/scene.js.map +1 -0
- package/dist/core/scene/types.js +6 -0
- package/dist/core/scene/types.js.map +1 -0
- package/dist/core/scene/useScene.js +32 -0
- package/dist/core/scene/useScene.js.map +1 -0
- package/dist/core/selection/chromeState.js +31 -0
- package/dist/core/selection/chromeState.js.map +1 -0
- package/dist/core/selection/selectionTarget.js +6 -0
- package/dist/core/selection/selectionTarget.js.map +1 -0
- package/dist/core/selection/useSelection.js +71 -0
- package/dist/core/selection/useSelection.js.map +1 -0
- package/dist/core/shapeKinds.js +54 -0
- package/dist/core/shapeKinds.js.map +1 -0
- package/dist/core/strokeMarkerShapes.js +139 -0
- package/dist/core/strokeMarkerShapes.js.map +1 -0
- package/dist/core/strokeMarkers.js +28 -0
- package/dist/core/strokeMarkers.js.map +1 -0
- package/dist/core/stylus/stylus.js +39 -0
- package/dist/core/stylus/stylus.js.map +1 -0
- package/dist/core/stylus/usePointerStylus.js +51 -0
- package/dist/core/stylus/usePointerStylus.js.map +1 -0
- package/dist/core/usePaintKinds.js +17 -0
- package/dist/core/usePaintKinds.js.map +1 -0
- package/dist/core/viewport/clampView.js +24 -0
- package/dist/core/viewport/clampView.js.map +1 -0
- package/dist/core/viewport/clientToWorld.js +8 -0
- package/dist/core/viewport/clientToWorld.js.map +1 -0
- package/dist/core/viewport/createVelocityTracker.js +39 -0
- package/dist/core/viewport/createVelocityTracker.js.map +1 -0
- package/dist/core/viewport/fitToBounds.js +18 -0
- package/dist/core/viewport/fitToBounds.js.map +1 -0
- package/dist/core/viewport/fitViewToBounds.js +36 -0
- package/dist/core/viewport/fitViewToBounds.js.map +1 -0
- package/dist/core/viewport/interpolateView.js +34 -0
- package/dist/core/viewport/interpolateView.js.map +1 -0
- package/dist/core/viewport/meanScale.js +8 -0
- package/dist/core/viewport/meanScale.js.map +1 -0
- package/dist/core/viewport/parallax.js +111 -0
- package/dist/core/viewport/parallax.js.map +1 -0
- package/dist/core/viewport/pxExtent.js +42 -0
- package/dist/core/viewport/pxExtent.js.map +1 -0
- package/dist/core/viewport/sceneNodeClientRect.js +18 -0
- package/dist/core/viewport/sceneNodeClientRect.js.map +1 -0
- package/dist/core/viewport/screenSlop.js +27 -0
- package/dist/core/viewport/screenSlop.js.map +1 -0
- package/dist/core/viewport/useAutoCenter.js +32 -0
- package/dist/core/viewport/useAutoCenter.js.map +1 -0
- package/dist/core/viewport/useCanvasSize.js +29 -0
- package/dist/core/viewport/useCanvasSize.js.map +1 -0
- package/dist/core/viewport/useDecayLoop.js +63 -0
- package/dist/core/viewport/useDecayLoop.js.map +1 -0
- package/dist/core/viewport/useVelocityTracker.js +10 -0
- package/dist/core/viewport/useVelocityTracker.js.map +1 -0
- package/dist/core/viewport/useViewAnimation.js +63 -0
- package/dist/core/viewport/useViewAnimation.js.map +1 -0
- package/dist/core/viewport/view.js +37 -0
- package/dist/core/viewport/view.js.map +1 -0
- package/dist/core/viewport/viewTransform.js +11 -0
- package/dist/core/viewport/viewTransform.js.map +1 -0
- package/dist/core/viewport/viewportWorldRect.js +13 -0
- package/dist/core/viewport/viewportWorldRect.js.map +1 -0
- package/dist/core/viewport/wheelHandler.js +30 -0
- package/dist/core/viewport/wheelHandler.js.map +1 -0
- package/dist/core/viewport/zoomAt.js +22 -0
- package/dist/core/viewport/zoomAt.js.map +1 -0
- package/dist/core/viewport/zoomBounds.js +20 -0
- package/dist/core/viewport/zoomBounds.js.map +1 -0
- package/dist/{pointSnapToGrid-Dp2IxLGb.d.ts → cornerHandles-BCrDp_mH.d.ts} +3 -13
- package/dist/debug/createDebugOverlayLayer.js +358 -0
- package/dist/debug/createDebugOverlayLayer.js.map +1 -0
- package/dist/debug/createDebugSink.js +83 -0
- package/dist/debug/createDebugSink.js.map +1 -0
- package/dist/debug/defaultTheme.js +31 -0
- package/dist/debug/defaultTheme.js.map +1 -0
- package/dist/debug/flag.js +41 -0
- package/dist/debug/flag.js.map +1 -0
- package/dist/debug/frameStats.js +16 -0
- package/dist/debug/frameStats.js.map +1 -0
- package/dist/debug/parseDebugFlags.js +32 -0
- package/dist/debug/parseDebugFlags.js.map +1 -0
- package/dist/features/chrome-caps/buildChromeCtx.js +16 -0
- package/dist/features/chrome-caps/buildChromeCtx.js.map +1 -0
- package/dist/features/chrome-caps/conditions.js +36 -0
- package/dist/features/chrome-caps/conditions.js.map +1 -0
- package/dist/features/chrome-caps/defaults.js +26 -0
- package/dist/features/chrome-caps/defaults.js.map +1 -0
- package/dist/features/chrome-caps/index.js +7 -0
- package/dist/features/chrome-caps/resolve.js +23 -0
- package/dist/features/chrome-caps/resolve.js.map +1 -0
- package/dist/features/chrome-caps/useHoverTracking.js +27 -0
- package/dist/features/chrome-caps/useHoverTracking.js.map +1 -0
- package/dist/features/cursor/paintedCursorLayer.js +60 -0
- package/dist/features/cursor/paintedCursorLayer.js.map +1 -0
- package/dist/features/focus/gateLayer.js +14 -0
- package/dist/features/focus/gateLayer.js.map +1 -0
- package/dist/features/focus/useCanvasFocus.js +29 -0
- package/dist/features/focus/useCanvasFocus.js.map +1 -0
- package/dist/features/groups/children.js +23 -0
- package/dist/features/groups/children.js.map +1 -0
- package/dist/features/groups/composePose.js +67 -0
- package/dist/features/groups/composePose.js.map +1 -0
- package/dist/features/groups/nestedHit.js +40 -0
- package/dist/features/groups/nestedHit.js.map +1 -0
- package/dist/features/groups/unionOfChildren.js +15 -0
- package/dist/features/groups/unionOfChildren.js.map +1 -0
- package/dist/features/images/imageCache.js +94 -0
- package/dist/features/images/imageCache.js.map +1 -0
- package/dist/features/ingestion/contentHandlers.js +37 -0
- package/dist/features/ingestion/contentHandlers.js.map +1 -0
- package/dist/features/ingestion/imageHandler.js +45 -0
- package/dist/features/ingestion/imageHandler.js.map +1 -0
- package/dist/features/ingestion/index.js +8 -0
- package/dist/features/ingestion/openFilePicker.js +15 -0
- package/dist/features/ingestion/openFilePicker.js.map +1 -0
- package/dist/features/ingestion/registerKitHandlers.js +26 -0
- package/dist/features/ingestion/registerKitHandlers.js.map +1 -0
- package/dist/features/ingestion/svgHandler.js +58 -0
- package/dist/features/ingestion/svgHandler.js.map +1 -0
- package/dist/features/ingestion/weaselJsonHandler.js +39 -0
- package/dist/features/ingestion/weaselJsonHandler.js.map +1 -0
- package/dist/features/longPress/longPressFeedback.js +96 -0
- package/dist/features/longPress/longPressFeedback.js.map +1 -0
- package/dist/features/meshPaint/bake.js +79 -0
- package/dist/features/meshPaint/bake.js.map +1 -0
- package/dist/features/meshPaint/bakeCache.js +59 -0
- package/dist/features/meshPaint/bakeCache.js.map +1 -0
- package/dist/features/meshPaint/handles.js +86 -0
- package/dist/features/meshPaint/handles.js.map +1 -0
- package/dist/features/meshPaint/lazyKind.js +1298 -0
- package/dist/features/meshPaint/lazyKind.js.map +1 -0
- package/dist/features/meshPaint/meshPaint.js +236 -0
- package/dist/features/meshPaint/meshPaint.js.map +1 -0
- package/dist/features/meshPaint/meshShader.js +6 -0
- package/dist/features/meshPaint/meshShader.js.map +1 -0
- package/dist/features/meshPaint/register.js +7 -0
- package/dist/features/meshPaint/register.js.map +1 -0
- package/dist/features/meshPaint/surface.js +110 -0
- package/dist/features/meshPaint/surface.js.map +1 -0
- package/dist/features/minimap/actions.js +53 -0
- package/dist/features/minimap/actions.js.map +1 -0
- package/dist/features/minimap/createMinimapContribution.js +96 -0
- package/dist/features/minimap/createMinimapContribution.js.map +1 -0
- package/dist/features/minimap/layers.js +103 -0
- package/dist/features/minimap/layers.js.map +1 -0
- package/dist/features/modes/modeLayers.js +113 -0
- package/dist/features/modes/modeLayers.js.map +1 -0
- package/dist/features/overlays/useNodeOverlayFrame.js +103 -0
- package/dist/features/overlays/useNodeOverlayFrame.js.map +1 -0
- package/dist/features/parallax/createParallaxLayer.js +26 -0
- package/dist/features/parallax/createParallaxLayer.js.map +1 -0
- package/dist/features/parallax/createParallaxPlane.js +26 -0
- package/dist/features/parallax/createParallaxPlane.js.map +1 -0
- package/dist/features/paths/anchorEdits.js +156 -0
- package/dist/features/paths/anchorEdits.js.map +1 -0
- package/dist/features/paths/anchors.js +154 -0
- package/dist/features/paths/anchors.js.map +1 -0
- package/dist/features/paths/booleans.js +2 -0
- package/dist/features/paths/index.js +15 -0
- package/dist/features/paths/markerCommands.js +116 -0
- package/dist/features/paths/markerCommands.js.map +1 -0
- package/dist/features/paths/markerSites.js +59 -0
- package/dist/features/paths/markerSites.js.map +1 -0
- package/dist/features/paths/markers.js +95 -0
- package/dist/features/paths/markers.js.map +1 -0
- package/dist/features/paths/nearestAnchor.js +36 -0
- package/dist/features/paths/nearestAnchor.js.map +1 -0
- package/dist/features/paths/originProjection.js +16 -0
- package/dist/features/paths/originProjection.js.map +1 -0
- package/dist/features/paths/pathEditingOverlayLayer.js +137 -0
- package/dist/features/paths/pathEditingOverlayLayer.js.map +1 -0
- package/dist/features/paths/pathInWorld.js +41 -0
- package/dist/features/paths/pathInWorld.js.map +1 -0
- package/dist/features/paths/pathLayer.js +44 -0
- package/dist/features/paths/pathLayer.js.map +1 -0
- package/dist/features/paths/penPreviewLayer.js +220 -0
- package/dist/features/paths/penPreviewLayer.js.map +1 -0
- package/dist/features/paths/poseDescriptor.js +39 -0
- package/dist/features/paths/poseDescriptor.js.map +1 -0
- package/dist/features/paths/tessellate/stroke.js +230 -0
- package/dist/features/paths/tessellate/stroke.js.map +1 -0
- package/dist/features/patterns/index.js +23 -0
- package/dist/features/patterns/index.js.map +1 -0
- package/dist/features/patterns/patterns-builtin.js +38 -0
- package/dist/features/patterns/patterns-builtin.js.map +1 -0
- package/dist/features/patterns/resolveSpec.js +57 -0
- package/dist/features/patterns/resolveSpec.js.map +1 -0
- package/dist/features/patterns/tileGeometry.js +158 -0
- package/dist/features/patterns/tileGeometry.js.map +1 -0
- package/dist/features/pointer/PointerContext.js +45 -0
- package/dist/features/pointer/PointerContext.js.map +1 -0
- package/dist/features/poseRun/usePoseRun.js +70 -0
- package/dist/features/poseRun/usePoseRun.js.map +1 -0
- package/dist/features/selection/SelectionContext.js +46 -0
- package/dist/features/selection/SelectionContext.js.map +1 -0
- package/dist/features/selection/overlay.js +442 -0
- package/dist/features/selection/overlay.js.map +1 -0
- package/dist/features/simulation/createSimulation.js +61 -0
- package/dist/features/simulation/createSimulation.js.map +1 -0
- package/dist/features/simulation/types.js +6 -0
- package/dist/features/simulation/types.js.map +1 -0
- package/dist/features/simulation/useSimulation.js +74 -0
- package/dist/features/simulation/useSimulation.js.map +1 -0
- package/dist/features/text/domRuns.js +258 -0
- package/dist/features/text/domRuns.js.map +1 -0
- package/dist/features/text/fitTextPose.js +38 -0
- package/dist/features/text/fitTextPose.js.map +1 -0
- package/dist/features/text/hitTest.js +45 -0
- package/dist/features/text/hitTest.js.map +1 -0
- package/dist/features/text/renderLabel.js +14 -0
- package/dist/features/text/renderLabel.js.map +1 -0
- package/dist/features/text/runs/effectiveRangeStyle.js +66 -0
- package/dist/features/text/runs/effectiveRangeStyle.js.map +1 -0
- package/dist/features/text/runs/flagRange.js +53 -0
- package/dist/features/text/runs/flagRange.js.map +1 -0
- package/dist/features/text/runs/rangeStyle.js +135 -0
- package/dist/features/text/runs/rangeStyle.js.map +1 -0
- package/dist/features/text/textCommand.js +59 -0
- package/dist/features/text/textCommand.js.map +1 -0
- package/dist/features/text/textLayer.js +35 -0
- package/dist/features/text/textLayer.js.map +1 -0
- package/dist/features/text/textToPath.js +181 -0
- package/dist/features/text/textToPath.js.map +1 -0
- package/dist/features/text/useSceneTextEdit.js +138 -0
- package/dist/features/text/useSceneTextEdit.js.map +1 -0
- package/dist/features/text/useTextEdit.js +465 -0
- package/dist/features/text/useTextEdit.js.map +1 -0
- package/dist/features/tiling/createTiledLayer.js +63 -0
- package/dist/features/tiling/createTiledLayer.js.map +1 -0
- package/dist/features/tiling/tiledProject.js +14 -0
- package/dist/features/tiling/tiledProject.js.map +1 -0
- package/dist/features/viewports/viewResolver.js +59 -0
- package/dist/features/viewports/viewResolver.js.map +1 -0
- package/dist/features/viewports/viewportLayer.js +58 -0
- package/dist/features/viewports/viewportLayer.js.map +1 -0
- package/dist/icons/ArrowIcon.js +23 -0
- package/dist/icons/ArrowIcon.js.map +1 -0
- package/dist/icons/EllipseIcon.js +21 -0
- package/dist/icons/EllipseIcon.js.map +1 -0
- package/dist/icons/EyedropperIcon.js +49 -0
- package/dist/icons/EyedropperIcon.js.map +1 -0
- package/dist/icons/HandIcon.js +59 -0
- package/dist/icons/HandIcon.js.map +1 -0
- package/dist/icons/ImageIcon.js +34 -0
- package/dist/icons/ImageIcon.js.map +1 -0
- package/dist/icons/LassoIcon.js +22 -0
- package/dist/icons/LassoIcon.js.map +1 -0
- package/dist/icons/LineIcon.js +22 -0
- package/dist/icons/LineIcon.js.map +1 -0
- package/dist/icons/PenIcon.js +36 -0
- package/dist/icons/PenIcon.js.map +1 -0
- package/dist/icons/PencilIcon.js +25 -0
- package/dist/icons/PencilIcon.js.map +1 -0
- package/dist/icons/PolygonIcon.js +19 -0
- package/dist/icons/PolygonIcon.js.map +1 -0
- package/dist/icons/RectIcon.js +37 -0
- package/dist/icons/RectIcon.js.map +1 -0
- package/dist/icons/SelectIcon.js +20 -0
- package/dist/icons/SelectIcon.js.map +1 -0
- package/dist/icons/StarIcon.js +19 -0
- package/dist/icons/StarIcon.js.map +1 -0
- package/dist/icons/TextIcon.js +19 -0
- package/dist/icons/TextIcon.js.map +1 -0
- package/dist/icons/UnknownIcon.js +33 -0
- package/dist/icons/UnknownIcon.js.map +1 -0
- package/dist/icons/_base.js +12 -0
- package/dist/icons/_base.js.map +1 -0
- package/dist/index.d.ts +1960 -1891
- package/dist/index.js +312 -13
- package/dist/input/keyState.js +76 -0
- package/dist/input/keyState.js.map +1 -0
- package/dist/input/useKeyState.js +22 -0
- package/dist/input/useKeyState.js.map +1 -0
- package/dist/interactions/actions/actionShortcuts.js +32 -0
- package/dist/interactions/actions/actionShortcuts.js.map +1 -0
- package/dist/interactions/actions/align/align.js +81 -0
- package/dist/interactions/actions/align/align.js.map +1 -0
- package/dist/interactions/actions/booleans/booleans.js +120 -0
- package/dist/interactions/actions/booleans/booleans.js.map +1 -0
- package/dist/interactions/actions/booleans/useBooleans.js +20 -0
- package/dist/interactions/actions/booleans/useBooleans.js.map +1 -0
- package/dist/interactions/actions/booleans/useBooleansAdapter.js +9 -0
- package/dist/interactions/actions/booleans/useBooleansAdapter.js.map +1 -0
- package/dist/interactions/actions/clipboard/clipboardOps.js +94 -0
- package/dist/interactions/actions/clipboard/clipboardOps.js.map +1 -0
- package/dist/interactions/actions/clipboard/materializePaste.js +25 -0
- package/dist/interactions/actions/clipboard/materializePaste.js.map +1 -0
- package/dist/interactions/actions/clipboard/wireFormat.js +43 -0
- package/dist/interactions/actions/clipboard/wireFormat.js.map +1 -0
- package/dist/interactions/actions/clone/behaviors/cloneByAltDrag.js +26 -0
- package/dist/interactions/actions/clone/behaviors/cloneByAltDrag.js.map +1 -0
- package/dist/interactions/actions/defaultCommitAdapter.js +42 -0
- package/dist/interactions/actions/defaultCommitAdapter.js.map +1 -0
- package/dist/interactions/actions/defaults/align.js +71 -0
- package/dist/interactions/actions/defaults/align.js.map +1 -0
- package/dist/interactions/actions/defaults/anchorEditing.js +235 -0
- package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -0
- package/dist/interactions/actions/defaults/areaSelect.js +75 -0
- package/dist/interactions/actions/defaults/areaSelect.js.map +1 -0
- package/dist/interactions/actions/defaults/booleans.js +52 -0
- package/dist/interactions/actions/defaults/booleans.js.map +1 -0
- package/dist/interactions/actions/defaults/cancelGesture.js +24 -0
- package/dist/interactions/actions/defaults/cancelGesture.js.map +1 -0
- package/dist/interactions/actions/defaults/clearSelection.js +19 -0
- package/dist/interactions/actions/defaults/clearSelection.js.map +1 -0
- package/dist/interactions/actions/defaults/clipboard.js +78 -0
- package/dist/interactions/actions/defaults/clipboard.js.map +1 -0
- package/dist/interactions/actions/defaults/clone.js +107 -0
- package/dist/interactions/actions/defaults/clone.js.map +1 -0
- package/dist/interactions/actions/defaults/createOutlines.js +47 -0
- package/dist/interactions/actions/defaults/createOutlines.js.map +1 -0
- package/dist/interactions/actions/defaults/createPaintAction.js +85 -0
- package/dist/interactions/actions/defaults/createPaintAction.js.map +1 -0
- package/dist/interactions/actions/defaults/delete.js +61 -0
- package/dist/interactions/actions/defaults/delete.js.map +1 -0
- package/dist/interactions/actions/defaults/distribute.js +66 -0
- package/dist/interactions/actions/defaults/distribute.js.map +1 -0
- package/dist/interactions/actions/defaults/duplicate.js +83 -0
- package/dist/interactions/actions/defaults/duplicate.js.map +1 -0
- package/dist/interactions/actions/defaults/editAnchors.js +100 -0
- package/dist/interactions/actions/defaults/editAnchors.js.map +1 -0
- package/dist/interactions/actions/defaults/enterPathEdit.js +29 -0
- package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -0
- package/dist/interactions/actions/defaults/enterTextEdit.js +20 -0
- package/dist/interactions/actions/defaults/enterTextEdit.js.map +1 -0
- package/dist/interactions/actions/defaults/escape.js +26 -0
- package/dist/interactions/actions/defaults/escape.js.map +1 -0
- package/dist/interactions/actions/defaults/exitPathEdit.js +22 -0
- package/dist/interactions/actions/defaults/exitPathEdit.js.map +1 -0
- package/dist/interactions/actions/defaults/flip.js +119 -0
- package/dist/interactions/actions/defaults/flip.js.map +1 -0
- package/dist/interactions/actions/defaults/freshNodeId.js +10 -0
- package/dist/interactions/actions/defaults/freshNodeId.js.map +1 -0
- package/dist/interactions/actions/defaults/group.js +131 -0
- package/dist/interactions/actions/defaults/group.js.map +1 -0
- package/dist/interactions/actions/defaults/icons/actionGlyphIcons.js +40 -0
- package/dist/interactions/actions/defaults/icons/actionGlyphIcons.js.map +1 -0
- package/dist/interactions/actions/defaults/icons/actionGlyphs.js +10 -0
- package/dist/interactions/actions/defaults/icons/actionGlyphs.js.map +1 -0
- package/dist/interactions/actions/defaults/icons/alignIcons.js +173 -0
- package/dist/interactions/actions/defaults/icons/alignIcons.js.map +1 -0
- package/dist/interactions/actions/defaults/icons/booleanIcons.js +171 -0
- package/dist/interactions/actions/defaults/icons/booleanIcons.js.map +1 -0
- package/dist/interactions/actions/defaults/icons/distributeIcons.js +63 -0
- package/dist/interactions/actions/defaults/icons/distributeIcons.js.map +1 -0
- package/dist/interactions/actions/defaults/icons/editIcons.js +280 -0
- package/dist/interactions/actions/defaults/icons/editIcons.js.map +1 -0
- package/dist/interactions/actions/defaults/icons/outlineIcons.js +53 -0
- package/dist/interactions/actions/defaults/icons/outlineIcons.js.map +1 -0
- package/dist/interactions/actions/defaults/ingest.js +58 -0
- package/dist/interactions/actions/defaults/ingest.js.map +1 -0
- package/dist/interactions/actions/defaults/insert.js +288 -0
- package/dist/interactions/actions/defaults/insert.js.map +1 -0
- package/dist/interactions/actions/defaults/insertPathAnchor.js +50 -0
- package/dist/interactions/actions/defaults/insertPathAnchor.js.map +1 -0
- package/dist/interactions/actions/defaults/lassoSelect.js +156 -0
- package/dist/interactions/actions/defaults/lassoSelect.js.map +1 -0
- package/dist/interactions/actions/defaults/move.js +760 -0
- package/dist/interactions/actions/defaults/move.js.map +1 -0
- package/dist/interactions/actions/defaults/nudge.js +110 -0
- package/dist/interactions/actions/defaults/nudge.js.map +1 -0
- package/dist/interactions/actions/defaults/pinchZoom.js +63 -0
- package/dist/interactions/actions/defaults/pinchZoom.js.map +1 -0
- package/dist/interactions/actions/defaults/reorder.js +143 -0
- package/dist/interactions/actions/defaults/reorder.js.map +1 -0
- package/dist/interactions/actions/defaults/requiresSelection.js +10 -0
- package/dist/interactions/actions/defaults/requiresSelection.js.map +1 -0
- package/dist/interactions/actions/defaults/resize.js +335 -0
- package/dist/interactions/actions/defaults/resize.js.map +1 -0
- package/dist/interactions/actions/defaults/rotate.js +184 -0
- package/dist/interactions/actions/defaults/rotate.js.map +1 -0
- package/dist/interactions/actions/defaults/selectAll.js +27 -0
- package/dist/interactions/actions/defaults/selectAll.js.map +1 -0
- package/dist/interactions/actions/defaults/setFill.js +27 -0
- package/dist/interactions/actions/defaults/setFill.js.map +1 -0
- package/dist/interactions/actions/defaults/setFillOpacity.js +15 -0
- package/dist/interactions/actions/defaults/setFillOpacity.js.map +1 -0
- package/dist/interactions/actions/defaults/setStroke.js +36 -0
- package/dist/interactions/actions/defaults/setStroke.js.map +1 -0
- package/dist/interactions/actions/defaults/setStrokeOpacity.js +21 -0
- package/dist/interactions/actions/defaults/setStrokeOpacity.js.map +1 -0
- package/dist/interactions/actions/defaults/slice.js +39 -0
- package/dist/interactions/actions/defaults/slice.js.map +1 -0
- package/dist/interactions/actions/defaults/sliceOps.js +60 -0
- package/dist/interactions/actions/defaults/sliceOps.js.map +1 -0
- package/dist/interactions/actions/defaults/toolActivate.js +35 -0
- package/dist/interactions/actions/defaults/toolActivate.js.map +1 -0
- package/dist/interactions/actions/defaults/toolResetToDefault.js +26 -0
- package/dist/interactions/actions/defaults/toolResetToDefault.js.map +1 -0
- package/dist/interactions/actions/defaults/undoRedo.js +51 -0
- package/dist/interactions/actions/defaults/undoRedo.js.map +1 -0
- package/dist/interactions/actions/defaults/viewportDragPan.js +88 -0
- package/dist/interactions/actions/defaults/viewportDragPan.js.map +1 -0
- package/dist/interactions/actions/defaults/viewportWheelPan.js +57 -0
- package/dist/interactions/actions/defaults/viewportWheelPan.js.map +1 -0
- package/dist/interactions/actions/defaults/viewportZoom.js +143 -0
- package/dist/interactions/actions/defaults/viewportZoom.js.map +1 -0
- package/dist/interactions/actions/distribute/distribute.js +42 -0
- package/dist/interactions/actions/distribute/distribute.js.map +1 -0
- package/dist/interactions/actions/distribute/plan.js +29 -0
- package/dist/interactions/actions/distribute/plan.js.map +1 -0
- package/dist/interactions/actions/edit-anchors/geometry.js +61 -0
- package/dist/interactions/actions/edit-anchors/geometry.js.map +1 -0
- package/dist/interactions/actions/edit-anchors/handles.js +43 -0
- package/dist/interactions/actions/edit-anchors/handles.js.map +1 -0
- package/dist/interactions/actions/flip/helpers.js +35 -0
- package/dist/interactions/actions/flip/helpers.js.map +1 -0
- package/dist/interactions/actions/geometryProjection.js +18 -0
- package/dist/interactions/actions/geometryProjection.js.map +1 -0
- package/dist/interactions/actions/gestureLifecycle.js +44 -0
- package/dist/interactions/actions/gestureLifecycle.js.map +1 -0
- package/dist/interactions/actions/lasso-select/behaviors/selectFromLasso.js +39 -0
- package/dist/interactions/actions/lasso-select/behaviors/selectFromLasso.js.map +1 -0
- package/dist/interactions/actions/move/behaviors/snapBackOrDelete.js +36 -0
- package/dist/interactions/actions/move/behaviors/snapBackOrDelete.js.map +1 -0
- package/dist/interactions/actions/move/behaviors/snapToContainer.js +67 -0
- package/dist/interactions/actions/move/behaviors/snapToContainer.js.map +1 -0
- package/dist/interactions/actions/move/gestureAdapter.js +37 -0
- package/dist/interactions/actions/move/gestureAdapter.js.map +1 -0
- package/dist/interactions/actions/outlines/createOutlines.js +84 -0
- package/dist/interactions/actions/outlines/createOutlines.js.map +1 -0
- package/dist/interactions/actions/outlines/useCreateOutlinesAdapter.js +9 -0
- package/dist/interactions/actions/outlines/useCreateOutlinesAdapter.js.map +1 -0
- package/dist/interactions/actions/planeInput.js +181 -0
- package/dist/interactions/actions/planeInput.js.map +1 -0
- package/dist/interactions/actions/poseDescriptorDep.js +9 -0
- package/dist/interactions/actions/poseDescriptorDep.js.map +1 -0
- package/dist/interactions/actions/poseFrame.js +38 -0
- package/dist/interactions/actions/poseFrame.js.map +1 -0
- package/dist/interactions/actions/previewOverrides.js +25 -0
- package/dist/interactions/actions/previewOverrides.js.map +1 -0
- package/dist/interactions/actions/resize/autoPoseDescriptor.js +31 -0
- package/dist/interactions/actions/resize/autoPoseDescriptor.js.map +1 -0
- package/dist/interactions/actions/resize/behaviors/clampMinSize.js +18 -0
- package/dist/interactions/actions/resize/behaviors/clampMinSize.js.map +1 -0
- package/dist/interactions/actions/resize/behaviors/index.js +8 -0
- package/dist/interactions/actions/resize/behaviors/index.js.map +1 -0
- package/dist/interactions/actions/resize/behaviors/lockAspect.js +24 -0
- package/dist/interactions/actions/resize/behaviors/lockAspect.js.map +1 -0
- package/dist/interactions/actions/resize/cornerHandles.js +72 -0
- package/dist/interactions/actions/resize/cornerHandles.js.map +1 -0
- package/dist/interactions/actions/resolveOverlays.js +60 -0
- package/dist/interactions/actions/resolveOverlays.js.map +1 -0
- package/dist/interactions/actions/resolvePreviews.js +61 -0
- package/dist/interactions/actions/resolvePreviews.js.map +1 -0
- package/dist/interactions/actions/rotate/geometry.js +46 -0
- package/dist/interactions/actions/rotate/geometry.js.map +1 -0
- package/dist/interactions/actions/rotate/handle.js +27 -0
- package/dist/interactions/actions/rotate/handle.js.map +1 -0
- package/dist/interactions/actions/spatialReference.js +42 -0
- package/dist/interactions/actions/spatialReference.js.map +1 -0
- package/dist/interactions/actions/useStandardActions.js +142 -0
- package/dist/interactions/actions/useStandardActions.js.map +1 -0
- package/dist/interactions/gestures/dragGesture/dragGesture.js +111 -0
- package/dist/interactions/gestures/dragGesture/dragGesture.js.map +1 -0
- package/dist/interactions/gestures/dragRadial/dragRadial.js +117 -0
- package/dist/interactions/gestures/dragRadial/dragRadial.js.map +1 -0
- package/dist/interactions/gestures/dragRect/dragRect.js +164 -0
- package/dist/interactions/gestures/dragRect/dragRect.js.map +1 -0
- package/dist/interactions/gestures/handleDrag/handleDrag.js +46 -0
- package/dist/interactions/gestures/handleDrag/handleDrag.js.map +1 -0
- package/dist/interactions/gestures/pointerDrag/pointerDrag.js +118 -0
- package/dist/interactions/gestures/pointerDrag/pointerDrag.js.map +1 -0
- package/dist/interactions/gestures/shared/originProjection.js +42 -0
- package/dist/interactions/gestures/shared/originProjection.js.map +1 -0
- package/dist/interactions/gestures/shared/screenTolerance.js +21 -0
- package/dist/interactions/gestures/shared/screenTolerance.js.map +1 -0
- package/dist/interactions/gestures/shared/snap.js +24 -0
- package/dist/interactions/gestures/shared/snap.js.map +1 -0
- package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js +30 -0
- package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js.map +1 -0
- package/dist/layout/arrivals.js +36 -0
- package/dist/layout/arrivals.js.map +1 -0
- package/dist/{math-MCQcf_gc.d.ts → math-Drrw4ewZ.d.ts} +8 -116
- package/dist/math.d.ts +4 -5
- package/dist/math.js +6 -4
- package/dist/mesh.d.ts +268 -0
- package/dist/mesh.js +7 -0
- package/dist/move.d.ts +7 -49
- package/dist/move.js +3 -142
- package/dist/originProjection-DEklpDc_.d.ts +57 -0
- package/dist/patterns-builtin.js +3 -3
- package/dist/{poseDescriptor-rZa9W5hJ.d.ts → poseDescriptor-D-OH-tu5.d.ts} +0 -4
- package/dist/registerProgram-ateHDGjw.d.ts +193 -0
- package/dist/renderer/DrawCommand.js +6 -0
- package/dist/renderer/DrawCommand.js.map +1 -0
- package/dist/renderer/WeaselRenderer.js +328 -0
- package/dist/renderer/WeaselRenderer.js.map +1 -0
- package/dist/renderer/cache/GLImageCache.js +64 -0
- package/dist/renderer/cache/GLImageCache.js.map +1 -0
- package/dist/renderer/cache/GLMeshCache.js +102 -0
- package/dist/renderer/cache/GLMeshCache.js.map +1 -0
- package/dist/renderer/cache/GLTextureCache.js +51 -0
- package/dist/renderer/cache/GLTextureCache.js.map +1 -0
- package/dist/renderer/cache/GradientRampAtlas.js +82 -0
- package/dist/renderer/cache/GradientRampAtlas.js.map +1 -0
- package/dist/renderer/cache/cache.js +13 -0
- package/dist/renderer/cache/cache.js.map +1 -0
- package/dist/renderer/cache/markerCommandCache.js +59 -0
- package/dist/renderer/cache/markerCommandCache.js.map +1 -0
- package/dist/renderer/cache/outlineMeshCache.js +15 -0
- package/dist/renderer/cache/outlineMeshCache.js.map +1 -0
- package/dist/renderer/cache/outlineStrokeMeshCache.js +31 -0
- package/dist/renderer/cache/outlineStrokeMeshCache.js.map +1 -0
- package/dist/renderer/cache/strokeMeshCache.js +44 -0
- package/dist/renderer/cache/strokeMeshCache.js.map +1 -0
- package/dist/renderer/cullDrawCommands.js +89 -0
- package/dist/renderer/cullDrawCommands.js.map +1 -0
- package/dist/renderer/draw.js +1109 -0
- package/dist/renderer/draw.js.map +1 -0
- package/dist/renderer/drawBatch.js +168 -0
- package/dist/renderer/drawBatch.js.map +1 -0
- package/dist/renderer/effects/EffectTargets.js +45 -0
- package/dist/renderer/effects/EffectTargets.js.map +1 -0
- package/dist/renderer/effects/builtins.js +31 -0
- package/dist/renderer/effects/builtins.js.map +1 -0
- package/dist/renderer/effects/composite.js +9 -0
- package/dist/renderer/effects/composite.js.map +1 -0
- package/dist/renderer/effects/effectPrelude.js +10 -0
- package/dist/renderer/effects/effectPrelude.js.map +1 -0
- package/dist/renderer/effects/types.js +10 -0
- package/dist/renderer/effects/types.js.map +1 -0
- package/dist/renderer/index.js +19 -0
- package/dist/renderer/math/color.js +341 -0
- package/dist/renderer/math/color.js.map +1 -0
- package/dist/renderer/math/mat3.js +71 -0
- package/dist/renderer/math/mat3.js.map +1 -0
- package/dist/renderer/math/patternSpace.js +22 -0
- package/dist/renderer/math/patternSpace.js.map +1 -0
- package/dist/renderer/math/viewToMat3.js +19 -0
- package/dist/renderer/math/viewToMat3.js.map +1 -0
- package/dist/renderer/paintResources.js +18 -0
- package/dist/renderer/paintResources.js.map +1 -0
- package/dist/renderer/paintScratch.js +37 -0
- package/dist/renderer/paintScratch.js.map +1 -0
- package/dist/renderer/shaders/ShaderProgram.js +74 -0
- package/dist/renderer/shaders/ShaderProgram.js.map +1 -0
- package/dist/renderer/shaders/batchFill.js +118 -0
- package/dist/renderer/shaders/batchFill.js.map +1 -0
- package/dist/renderer/shaders/customPrelude.js +34 -0
- package/dist/renderer/shaders/customPrelude.js.map +1 -0
- package/dist/renderer/shaders/extractUniformNames.js +184 -0
- package/dist/renderer/shaders/extractUniformNames.js.map +1 -0
- package/dist/renderer/shaders/glyphPaint.js +61 -0
- package/dist/renderer/shaders/glyphPaint.js.map +1 -0
- package/dist/renderer/shaders/gradFill.js +30 -0
- package/dist/renderer/shaders/gradFill.js.map +1 -0
- package/dist/renderer/shaders/imageFill.js +14 -0
- package/dist/renderer/shaders/imageFill.js.map +1 -0
- package/dist/renderer/shaders/pathFill.js +13 -0
- package/dist/renderer/shaders/pathFill.js.map +1 -0
- package/dist/renderer/shaders/patternFill.js +24 -0
- package/dist/renderer/shaders/patternFill.js.map +1 -0
- package/dist/renderer/shaders/registerProgram.js +18 -0
- package/dist/renderer/shaders/registerProgram.js.map +1 -0
- package/dist/renderer/spriteSheet.js +14 -0
- package/dist/renderer/spriteSheet.js.map +1 -0
- package/dist/renderer/state/GroupState.js +77 -0
- package/dist/renderer/state/GroupState.js.map +1 -0
- package/dist/renderer/syntheticItalic.js +6 -0
- package/dist/renderer/syntheticItalic.js.map +1 -0
- package/dist/renderer/textures/registerTexture.js +14 -0
- package/dist/renderer/textures/registerTexture.js.map +1 -0
- package/dist/renderer.d.ts +11 -21
- package/dist/renderer.js +18 -13
- package/dist/resize.d.ts +10 -46
- package/dist/resize.js +7 -5
- package/dist/routing.js +2 -3
- package/dist/scheduling/useVisibleRaf.js +69 -0
- package/dist/scheduling/useVisibleRaf.js.map +1 -0
- package/dist/style.css +2 -0
- package/dist/test-hook/createTestHook.js +39 -0
- package/dist/test-hook/createTestHook.js.map +1 -0
- package/dist/test-hook/install.js +12 -0
- package/dist/test-hook/install.js.map +1 -0
- package/dist/test-seams-fYf6m5pu.d.ts +356 -0
- package/dist/test-seams.d.ts +6 -0
- package/dist/test-seams.js +3 -0
- package/dist/tools/builtin/ellipse/useEllipseTool.js +33 -0
- package/dist/tools/builtin/ellipse/useEllipseTool.js.map +1 -0
- package/dist/tools/builtin/eyedropper/useEyedropperTool.js +55 -0
- package/dist/tools/builtin/eyedropper/useEyedropperTool.js.map +1 -0
- package/dist/tools/builtin/hand/dragPanContribution.js +17 -0
- package/dist/tools/builtin/hand/dragPanContribution.js.map +1 -0
- package/dist/tools/builtin/hand/useHandTool.js +31 -0
- package/dist/tools/builtin/hand/useHandTool.js.map +1 -0
- package/dist/tools/builtin/image/useImageTool.js +41 -0
- package/dist/tools/builtin/image/useImageTool.js.map +1 -0
- package/dist/tools/builtin/lasso/useLassoTool.js +42 -0
- package/dist/tools/builtin/lasso/useLassoTool.js.map +1 -0
- package/dist/tools/builtin/line/useLineTool.js +33 -0
- package/dist/tools/builtin/line/useLineTool.js.map +1 -0
- package/dist/tools/builtin/pen/usePenTool.js +414 -0
- package/dist/tools/builtin/pen/usePenTool.js.map +1 -0
- package/dist/tools/builtin/pencil/usePencilTool.js +36 -0
- package/dist/tools/builtin/pencil/usePencilTool.js.map +1 -0
- package/dist/tools/builtin/pickTopMostHit.js +45 -0
- package/dist/tools/builtin/pickTopMostHit.js.map +1 -0
- package/dist/tools/builtin/polygon/usePolygonTool.js +81 -0
- package/dist/tools/builtin/polygon/usePolygonTool.js.map +1 -0
- package/dist/tools/builtin/rect/useRectTool.js +32 -0
- package/dist/tools/builtin/rect/useRectTool.js.map +1 -0
- package/dist/tools/builtin/select/selectionContributions.js +109 -0
- package/dist/tools/builtin/select/selectionContributions.js.map +1 -0
- package/dist/tools/builtin/select/useSelectTool.js +162 -0
- package/dist/tools/builtin/select/useSelectTool.js.map +1 -0
- package/dist/tools/builtin/shared/insertToolOptions.js +8 -0
- package/dist/tools/builtin/shared/insertToolOptions.js.map +1 -0
- package/dist/tools/builtin/slice/useSliceTool.js +263 -0
- package/dist/tools/builtin/slice/useSliceTool.js.map +1 -0
- package/dist/tools/builtin/star/useStarTool.js +82 -0
- package/dist/tools/builtin/star/useStarTool.js.map +1 -0
- package/dist/tools/builtin/text/useTextTool.js +177 -0
- package/dist/tools/builtin/text/useTextTool.js.map +1 -0
- package/dist/tools/overlayBinding.js +8 -0
- package/dist/tools/overlayBinding.js.map +1 -0
- package/dist/tools/prefs.js +47 -0
- package/dist/tools/prefs.js.map +1 -0
- package/dist/tools/useKeybindings.js +66 -0
- package/dist/tools/useKeybindings.js.map +1 -0
- package/dist/{types-D-9QWBy5.d.ts → types-A37hYkeR.d.ts} +185 -15
- package/dist/{types-qYpyTAiZ.d.ts → types-B_9g6hMM.d.ts} +32 -6
- package/dist/util/color.js +26 -0
- package/dist/util/color.js.map +1 -0
- package/dist/util/constrainTo45.js +17 -0
- package/dist/util/constrainTo45.js.map +1 -0
- package/dist/util/paint.js +72 -0
- package/dist/util/paint.js.map +1 -0
- package/dist/version.js +6 -0
- package/dist/version.js.map +1 -0
- package/package.json +31 -19
- package/dist/chunk-3TY6FHAF.js +0 -170
- package/dist/chunk-3TY6FHAF.js.map +0 -1
- package/dist/chunk-DGWNNKGD.js +0 -248
- package/dist/chunk-DGWNNKGD.js.map +0 -1
- package/dist/chunk-G4ZGQMY7.js +0 -33372
- package/dist/chunk-G4ZGQMY7.js.map +0 -1
- package/dist/chunk-L5YNZYEG.js +0 -648
- package/dist/chunk-L5YNZYEG.js.map +0 -1
- package/dist/chunk-LU4IJ52W.js +0 -111
- package/dist/chunk-LU4IJ52W.js.map +0 -1
- package/dist/chunk-M24CLARN.js +0 -28
- package/dist/chunk-M24CLARN.js.map +0 -1
- package/dist/chunk-NE27EOLP.js +0 -146
- package/dist/chunk-NE27EOLP.js.map +0 -1
- package/dist/chunk-PNNZSYRD.js +0 -318
- package/dist/chunk-PNNZSYRD.js.map +0 -1
- package/dist/chunk-UPZY4ART.js +0 -29
- package/dist/chunk-UPZY4ART.js.map +0 -1
- package/dist/chunk-WPNA6L5O.js +0 -250
- package/dist/chunk-WPNA6L5O.js.map +0 -1
- package/dist/chunk-XMAWPGTK.js +0 -128
- package/dist/chunk-XMAWPGTK.js.map +0 -1
- package/dist/clipboard.js.map +0 -1
- package/dist/clone.js.map +0 -1
- package/dist/grid-CY5UKlZh.d.ts +0 -98
- package/dist/index.css +0 -62
- package/dist/index.css.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/insert.d.ts +0 -36
- package/dist/insert.js +0 -81
- package/dist/insert.js.map +0 -1
- package/dist/math.js.map +0 -1
- package/dist/move.js.map +0 -1
- package/dist/path-JEV2c5If.d.ts +0 -48
- package/dist/patterns-builtin.js.map +0 -1
- package/dist/renderer.css +0 -62
- package/dist/renderer.css.map +0 -1
- package/dist/renderer.js.map +0 -1
- package/dist/resize.js.map +0 -1
- package/dist/routing.js.map +0 -1
- package/dist/types-D2tTKEU0.d.ts +0 -18
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scene.js","names":["rebuildGlobalOp","defaultIdCounter","defaultGenerateId","asNodeId","setParallax","to","record","layerFromSerialized","base","spec","createScene","options","state","registry","withKitRegistry","fnFields","createNodeFnFields","fnField","f","name","layoutFrame","resolveLayoutFrame","hasLayouts","field","write","node","fn","layoutOfInternal","id","dependents","createDependentsIndex","childDerived","invalidateDependents","invalidateChildDerivedFrom","subtree","src","dep","dropPoseKeyedMemoSlots","cursor","start","d","trackChildDerived","dependsOn","retarget","requireNode","i","generateId","listeners","registered","historyAdapterAccessor","bindOpToHistoryAdapter","op","get","dwarn","err","selection","overrides","createPoseOverrides","history","createHistory","reachable","ids","notify","pruneCacheForDroppedOps","entry","makeOp","args","createArrangeOp","writePose","rebuilt","rebuildOp","version","incarnations","nextIncarnation","batchDepth","currentBatch","suppressRecording","untrackedDepth","lockBypass","appliedLog","batchDirty","activeJournalAccessor","arrivalHandler","arrivals","departures","changed","reflowDue","reflowListeners","declaredLayouts","runLayoutPass","scene","arrived","touched","departed","activeHandler","noteArrival","parent","from","list","noteDeparture","noteChange","bareLayoutEdit","openArrivals","always","emitReflow","moves","listener","settleArrivals","pending","handler","landed","still","left","gone","poses","SceneArrivalRefused","out","pose","givesLayout","withArrivalOps","ops","runArrivalEdit","all","run","owned","isLockedInternal","l","cur","refuseUntracked","verb","refuseLocked","refuseLockedLayer","layer","withLocksLifted","atomically","outer","log","selectionBefore","result","ownsEntry","kind","payload","n","requireLayerIndex","rebuildLayerIndex","invalidateOrder","assertSubtreeLayer","nodeLayer","parentLayer","action","nodeId","parentId","siblingsOf","p","detach","sibs","idx","attach","index","descendants","c","removalClosure","removing","take","sub","s","root","rootIds","patchNodeFunctions","cacheForRedo","restoreNodeFunctions","keys","target","key","restoreFn","registerKitOp","cached","k","clone","layoutRefs","placeLayout","live","side","layout","rec","runOp","coalesceKeyFor","dir","bindOpToAdapter","adapter","token","withRecordingSuppressed","prevSuppress","prevDirty","executeAndLog","label","h","renderOrderInternal","renderOrderFlat","renderOrderBucketed","renderOrderNodesInternal","renderOrderNodesFlat","renderOrderNodesBucketed","structureGeneration","orderCache","EMPTY_NODES","currentOrderCache","only","stack","buckets","bucket","rawJournals","wrapJournal","wrapped","raw","sceneHistory","opts","snapshot","journal","applyBatchNow","byLayer","fnKeysOf","nid","detached","r","fnKeys","patch","resized","parentNode","curId","sid","fromKey","toKey","desc","fromSibs","fromIndex","toSibs","toIndex","visible","locked","parallax","clamped","tagged","finalIndex","proposed","tempIndex","e","undo","redo","total","targetIndex","outermost","ownsArrivals","finished","versionBefore","nodes","specs","specsFromSerialized","json","applyConstructionSpecs","serialized","NODE_FN_FIELDS","sceneSelectionStore","sceneFromJSON"],"sources":["../../../src/core/scene/scene.ts"],"sourcesContent":["import { createHistory, type History, type HistorySelection, type Journal, type SerializedHistory } from '@weasel-js/history';\nimport type { Op } from 'core/ops/types';\nimport type { ParallaxOpts } from 'core/viewport/parallax';\nimport { rebuildOp as rebuildGlobalOp } from 'core/ops/registry';\nimport { createArrangeOp, type ArrangeArgs, type ArrangedPose } from 'core/ops/arrange';\nimport { SceneArrivalRefused } from './arrivals';\nimport { dwarn } from 'debug/flag';\nimport { createDependentsIndex, sameDependsOn } from './dependents';\nimport { withKitRegistry } from './kitRegistry';\nimport { dropPoseKeyedMemoSlots } from './nodeMemo';\nimport {\n createNodeFnFields,\n fnKeysOf,\n restoreFn,\n NODE_FN_FIELDS,\n type FnBearingNode,\n type NodeFn,\n type NodeFnField,\n} from './nodeFnFields';\nimport { createPoseOverrides } from './poseOverrides';\nimport { resized, resolveLayoutFrame, runLayoutPass } from './layoutPass';\nimport type { LayoutStrategy } from '../../layout/types';\nimport {\n asNodeId,\n type LayoutMove,\n type AddNodeSpec,\n type ContainerNode,\n type LayerRecord,\n type LeafNode,\n type Node,\n type NodeId,\n type RegisteredOp,\n type Scene,\n type SceneArrivalHandler,\n type SceneRegistry,\n type SerializedNode,\n type SerializedScene,\n type SerializedLayer,\n type UseSceneOptions,\n type UserLayerRecord,\n} from './types';\n\ninterface SceneState<TData, TLayer extends string, TPose> {\n nodes: Map<NodeId, Node<TData, TLayer, TPose>>;\n roots: NodeId[];\n layers: LayerRecord<TLayer>[];\n layerIndex: Map<TLayer, number>;\n}\n\nlet defaultIdCounter = 0;\nconst defaultGenerateId = (): NodeId =>\n asNodeId(`n${(defaultIdCounter++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`);\n\n/** One layer record from its snapshot form. A snapshot with no `kind` predates\n * user layers, so everything in it was a system layer. */\nfunction setParallax(record: { parallax?: ParallaxOpts }, to: ParallaxOpts | undefined): void {\n if (to === undefined) delete record.parallax;\n else record.parallax = to;\n}\n\nfunction layerFromSerialized<TLayer extends string>(\n spec: SerializedLayer<TLayer>,\n): LayerRecord<TLayer> {\n const base = {\n id: spec.id,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n };\n return spec.kind === 'user'\n ? { ...base, kind: 'user', name: spec.name ?? spec.id }\n : { ...base, kind: 'system' };\n}\n\n/** Build a scene outside React. `useScene` is the usual entry point; reach for\n * this in tests, in headless rendering, or wherever a scene must outlive a\n * component. Throws if no system layers are declared. */\nexport function createScene<TData, TLayer extends string, TPose = import('../../features/groups/composePose').RectPose>(\n options: UseSceneOptions<TData, TLayer, TPose>,\n): Scene<TData, TLayer, TPose> {\n if (!options.systemLayers || options.systemLayers.length === 0) {\n throw new Error('useScene: systemLayers must declare at least one layer');\n }\n\n // ── State ──────────────────────────────────────────────────────────────\n const state: SceneState<TData, TLayer, TPose> = {\n nodes: new Map(),\n roots: [],\n layers: [],\n layerIndex: new Map(),\n };\n\n // The kit's own registry entries sit under the consumer's, so a snapshot\n // carrying a kit-attached function (a grouped container's derived pose)\n // reloads in any scene, not only one whose consumer registered the key.\n const registry = withKitRegistry(options.registry ?? {});\n\n /**\n * The registry-keyed function fields — `clipFromPose`, `derivePath`,\n * `derivePose` — each with its key maps and the side-channel cache the\n * `kit:add` redo path re-attaches from. A function cannot travel through a\n * serializable op payload, so `scene.add` and the `initial` loader stash it\n * here and the replayed op reads it back.\n *\n * Those caches are pruned at two hook points, both delivered via the history\n * engine's `onEvict`, to prevent unbounded growth:\n * 1. When the redo stack is cleared by a new op (branch-on-edit): any\n * kit:add in the discarded entries that references a node absent from\n * `state.nodes` is permanently unreachable — its cache entry is dropped.\n * 2. When the undo stack overflows `historyLimit` and evicts the oldest\n * entry: same reasoning applies to the evicted entries.\n * Invariant: after pruning, no entry remains for a node that is both absent\n * from `state.nodes` AND unreachable via any remaining undo/redo log entry.\n */\n const fnFields = createNodeFnFields<TPose>(registry);\n const fnField = (name: 'clipFromPose' | 'derivePath' | 'derivePose' | 'layout'): NodeFnField =>\n fnFields.find((f) => f.spec.field === name)!;\n\n /** How declared layouts are measured; see `LayoutFrame`. */\n const layoutFrame = resolveLayoutFrame(options.layoutFrame);\n /** Latched on the first layout a container is given, so a scene that never\n * declares one records exactly the entries it did before layouts existed. */\n let hasLayouts = false;\n {\n const field = fnField('layout');\n const write = field.write;\n (field as { write: NodeFnField['write'] }).write = (node, fn) => {\n if (node.kind === 'container') hasLayouts = true;\n write(node, fn);\n };\n }\n\n function layoutOfInternal(id: NodeId) {\n const node = state.nodes.get(id);\n return node?.kind === 'container' ? (node.layout ?? null) : null;\n }\n\n /** Maintained from `kit:add` / `kit:remove` — the only two places a node is\n * created or destroyed, and unlike `add`/`remove` they replay on undo/redo.\n * Only explicit `dependsOn` id lists are registered here; `'children'` is\n * the ancestor walk in `invalidateDependents` instead. */\n const dependents = createDependentsIndex();\n\n /** Nodes carrying `dependsOn: 'children'`. Empty in every scene that has no\n * container hugging its contents, which is what keeps the ancestor walk off\n * the hot path. */\n const childDerived = new Set<NodeId>();\n\n /** Walks `id`'s whole subtree. Not required while `Scene` stores absolute\n * poses and the render walks compose nothing; it is here so `derivePath`'s\n * world-pose contract still holds if they ever do. */\n function invalidateDependents(id: NodeId): void {\n invalidateChildDerivedFrom(state.nodes.get(id)?.parent ?? null);\n if (dependents.isEmpty()) return;\n const subtree: NodeId[] = [id];\n descendants(id, subtree);\n for (const src of subtree) {\n for (const dep of dependents.transitiveDependentsOf(src)) {\n const node = state.nodes.get(dep);\n if (node !== undefined) dropPoseKeyedMemoSlots(node);\n }\n }\n }\n\n /** A `dependsOn: 'children'` container derives from nodes the reverse index\n * never sees, so its invalidation runs the other way: up the parent chain\n * from `start` inclusive, and on to each such ancestor's own dependents.\n *\n * Callers that removed or reparented a node pass the parent explicitly —\n * a gone node cannot say who its parent was. */\n function invalidateChildDerivedFrom(start: NodeId | null): void {\n if (childDerived.size === 0) return;\n let cursor = start;\n while (cursor !== null) {\n const node = state.nodes.get(cursor);\n if (node === undefined) return;\n if (childDerived.has(cursor)) {\n dropPoseKeyedMemoSlots(node);\n for (const dep of dependents.transitiveDependentsOf(cursor)) {\n const d = state.nodes.get(dep);\n if (d !== undefined) dropPoseKeyedMemoSlots(d);\n }\n }\n cursor = node.parent;\n }\n }\n\n /** Track (or forget) a node whose `dependsOn` is `'children'`. Paired with\n * `dependents.add` / `.remove` at every site a node is created or destroyed. */\n function trackChildDerived(id: NodeId, dependsOn: Node<TData, TLayer, TPose>['dependsOn']): void {\n if (dependsOn === 'children') childDerived.add(id);\n else childDerived.delete(id);\n }\n\n /** Point `id` at a different set of dependencies, keeping both indices and\n * every memo that reads them in step. Shared by `kit:setDependsOn`'s two\n * directions, which differ only in which value they install.\n *\n * `id`'s own memo is dropped as well as its dependents': its derivation now\n * reads different sources, and nothing else would clear it. */\n function retarget(id: NodeId, dependsOn: Node<TData, TLayer, TPose>['dependsOn']): void {\n const node = requireNode(id) as { dependsOn?: readonly NodeId[] | 'children' };\n if (dependsOn === undefined) delete node.dependsOn;\n else node.dependsOn = dependsOn;\n dependents.add(id, dependsOn === undefined || dependsOn === 'children' ? [] : dependsOn);\n trackChildDerived(id, dependsOn);\n dropPoseKeyedMemoSlots(requireNode(id));\n invalidateDependents(id);\n }\n\n for (let i = 0; i < options.systemLayers.length; i++) {\n const spec = options.systemLayers[i];\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`useScene: duplicate system layer id \"${spec.id}\"`);\n }\n state.layers.push({\n kind: 'system',\n id: spec.id,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n });\n state.layerIndex.set(spec.id, i);\n }\n\n const generateId = options.generateId ?? defaultGenerateId;\n\n const listeners = new Set<() => void>();\n const registered = new Map<string, RegisteredOp<unknown>>();\n\n // Accessor for the adapter restored external ops apply against.\n let historyAdapterAccessor: (() => unknown) | null = null;\n\n /** Wrap a globally-rebuilt external op so apply resolves the history\n * adapter lazily — wiring order vs restoreHistory doesn't matter. An\n * unset accessor makes the op a debug-warned no-op, and an apply that\n * throws (e.g. the wired adapter lacks a method the op calls) degrades\n * the same way — never throws mid-undo, matching the placeholder\n * degradation policy. (The engine pops entries before applying, so an\n * uncaught throw would corrupt the stacks.) See `bindOpToAdapter` for\n * the live `applyBatch` path (fixed call-site adapter). */\n function bindOpToHistoryAdapter(op: Op): Op {\n return {\n name: op.name,\n args: op.args,\n label: op.label,\n coalesceKey: op.coalesceKey,\n apply: () => {\n const get = historyAdapterAccessor;\n if (!get) {\n dwarn('scene', `restored op \"${op.name ?? '?'}\" has no history adapter — skipping (setHistoryAdapter was not wired)`);\n return 'noop';\n }\n try {\n return op.apply(get());\n } catch (err) {\n dwarn('scene', `restored op \"${op.name ?? '?'}\" failed against the history adapter — skipping: ${String(err)}`);\n return 'noop';\n }\n },\n invert: () => bindOpToHistoryAdapter(op.invert()),\n };\n }\n\n // The scene's undo/redo engine. Recorded ops are `makeOp` wrappers over\n // `registered` handlers, so the engine's adapter argument is unused (the\n /** The transient set of active ids. Deliberately not part of `state`:\n * selection is not document content and never reaches `toJSON`. It is\n * handed to the history engine so entries can restore it. */\n let selection: readonly NodeId[] = [];\n\n /** Ephemeral per-node overrides. Deliberately not part of `state`, for the\n * same reason `selection` isn't: not document content, never reaches\n * `toJSON`, and never touches history. */\n const overrides = createPoseOverrides<TPose>(\n (id) => state.nodes.get(id),\n invalidateDependents,\n );\n\n // wrappers close over their payloads). Eviction (branch-edit redo-clears\n // + historyLimit overflow) drives function-field cache pruning via onEvict.\n const history = createHistory(undefined, {\n selection: {\n get: () => selection,\n set: (ids) => { selection = reachable(ids as readonly NodeId[]); notify(); },\n },\n ...(options.coalesceWindowMs !== undefined ? { coalesceWindowMs: options.coalesceWindowMs } : {}),\n ...(options.historyLimit !== undefined ? { historyLimit: options.historyLimit } : {}),\n onEvict: (entry) => {\n // forwardOps and baseOps are the same array until a coalesce splits\n // them, so the double scan is cheap today and correct later.\n pruneCacheForDroppedOps(entry.forwardOps);\n pruneCacheForDroppedOps(entry.baseOps);\n },\n // Restore-time rebuild: scene-registered kinds (kit:* + consumer\n // registerOp) rebuild via makeOp; external ops rebuild via the global\n // op-factory registry, wrapped in the lazy history-adapter binding.\n // Return null only when the global registry also misses — the engine\n // then places its no-op placeholder. (The engine's own global-registry\n // fallback never fires for scene histories: this hook already\n // consulted it.)\n rebuildOp: (name, args) => {\n if (registered.has(name)) return makeOp(name, args);\n // Its writes are the scene's own, so it replays without an adapter.\n if (name === 'arrange') return createArrangeOp(args as ArrangeArgs, undefined, writePose);\n const rebuilt = rebuildGlobalOp(name, args);\n return rebuilt === null ? null : bindOpToHistoryAdapter(rebuilt);\n },\n });\n\n let version = 0;\n // Keyed by node object: every entry into `state.nodes` is a fresh object and\n // every edit mutates it in place, which is exactly an incarnation's lifetime.\n const incarnations = new WeakMap<object, number>();\n let nextIncarnation = 1;\n let batchDepth = 0;\n let currentBatch: { label: string; ops: Op[]; selectionBefore: readonly NodeId[] } | null = null;\n /** True while the history engine drives mutations (undo/redo/goto, journal\n * routing) — suppresses scene-side history recording so engine-applied\n * ops that re-enter scene mutation methods don't record twice. */\n let suppressRecording = false;\n /** Above zero inside `scene.untracked`, where the APIs that exist to\n * record refuse rather than record. */\n let untrackedDepth = 0;\n /** Above zero while the lock guard is lifted: `unlocked()`, `removeLayer`,\n * and every replay — undo, redo, a journal stepping, a rollback — which\n * restores a state that was legal when it was recorded. */\n let lockBypass = 0;\n /** Every kit op applied since the innermost `atomically` opened, so a\n * refused batch can revert what it already did. Null outside one. */\n let appliedLog: { kind: string; payload: unknown }[] | null = null;\n\n // ── Helpers ────────────────────────────────────────────────────────────\n // When `batchDepth > 0` the per-op `notify()` is coalesced: we still bump\n // the version so getVersion() reflects in-progress mutations, but we defer\n // listener dispatch until the outermost batch closes. This avoids one\n // React re-render per op during high-frequency gestures (e.g. snap moves\n // that emit ~10 transform ops per pointer-move).\n let batchDirty = false;\n // Mutable accessor for the active journal — seeded from options and\n // swappable via `scene.setActiveJournalAccessor(fn)` so mode machines that\n // depend on `scene.history` can wire it after construction.\n let activeJournalAccessor: (() => Journal | null) | null =\n options.getActiveJournal ?? null;\n\n // Container layout. `arrivals` is open (non-null) while a live edit is\n // collecting the nodes that joined a container, and `changed` every\n // container whose children or size it changed; whoever opened the window\n // settles it before the edit closes. Undo, redo and journal replays never\n // open it: they restore an arrangement that was already decided.\n let arrivalHandler: SceneArrivalHandler<TPose> | null = null;\n let arrivals: Map<NodeId, NodeId[]> | null = null;\n let departures = new Map<NodeId, NodeId[]>();\n let changed = new Set<NodeId>();\n /** What the last settle wrote, reported to `onReflow` once its edit lands. */\n let reflowDue: LayoutMove<TPose>[] | null = null;\n const reflowListeners = new Set<(moves: readonly LayoutMove<TPose>[]) => void>();\n\n /** The pass a scene runs over its declared layouts when nothing else is\n * installed. */\n const declaredLayouts: SceneArrivalHandler<TPose> = (arrived, touched, departed) =>\n runLayoutPass(scene, layoutOfInternal, arrived, touched, layoutFrame, departed);\n\n function activeHandler(): SceneArrivalHandler<TPose> | null {\n return arrivalHandler ?? (hasLayouts ? declaredLayouts : null);\n }\n\n function noteArrival(id: NodeId, parent: NodeId | null, from: NodeId | null): void {\n if (arrivals === null || parent === null || parent === from) return;\n changed.add(parent);\n const list = arrivals.get(parent);\n if (list === undefined) arrivals.set(parent, [id]);\n else if (!list.includes(id)) list.push(id);\n }\n\n function noteDeparture(id: NodeId, from: NodeId | null, to: NodeId | null): void {\n if (arrivals === null || from === null || from === to) return;\n changed.add(from);\n // One that joined earlier in this edit was never there to leave.\n if (arrivals.get(from)?.includes(id)) return;\n const list = departures.get(from);\n if (list === undefined) departures.set(from, [id]);\n else if (!list.includes(id)) list.push(id);\n }\n\n /** A container's child set or order changed, or it changed size. */\n function noteChange(id: NodeId | null): void {\n if (arrivals !== null && id !== null) changed.add(id);\n }\n\n /** Whether a bare scene call has to run as a batch of its own, so the\n * layout pass it triggers lands in its undo step. */\n function bareLayoutEdit(): boolean {\n return activeHandler() !== null && arrivals === null && batchDepth === 0 && !suppressRecording;\n }\n\n /** Open the arrival window when a handler wants one — or `always`, for an\n * edit that may give the scene its first layout partway through — and no\n * enclosing edit holds it already; true when this caller now owns it. */\n function openArrivals(always = false): boolean {\n if (arrivals !== null || (!always && activeHandler() === null)) return false;\n arrivals = new Map();\n departures = new Map();\n changed = new Set();\n reflowDue = null;\n return true;\n }\n\n /** Report what the settled edit wrote, now that it has landed. */\n function emitReflow(): void {\n const moves = reflowDue;\n reflowDue = null;\n if (moves === null || moves.length === 0) return;\n for (const listener of [...reflowListeners]) listener(moves);\n }\n\n /** Close the window and ask the handler what the arrivals get. Throws\n * `SceneArrivalRefused` when it refuses, which reverts the edit. */\n function settleArrivals(): ArrangedPose[] {\n const pending = arrivals;\n arrivals = null;\n const handler = activeHandler();\n if (pending === null || handler === null) return [];\n // Only what is still there once the edit's other mutations have landed.\n const landed = new Map<NodeId, NodeId[]>();\n for (const [parent, ids] of pending) {\n const still = ids.filter((id) => state.nodes.get(id)?.parent === parent);\n if (still.length > 0 && state.nodes.has(parent)) landed.set(parent, still);\n }\n // Only what is gone from the container once the edit has landed: a child\n // that left and came back did not depart.\n const left = new Map<NodeId, NodeId[]>();\n for (const [parent, ids] of departures) {\n const gone = ids.filter((id) => state.nodes.get(id)?.parent !== parent);\n if (gone.length > 0 && state.nodes.has(parent)) left.set(parent, gone);\n }\n departures = new Map();\n const touched = new Set([...changed].filter((id) => state.nodes.get(id)?.kind === 'container'));\n if (landed.size === 0 && touched.size === 0) return [];\n const poses = handler(landed, touched, left);\n if (poses === null) throw new SceneArrivalRefused(landed);\n const out: ArrangedPose[] = [];\n for (const [id, to] of poses) {\n const node = state.nodes.get(id);\n if (node) out.push({ id, from: node.pose, to });\n }\n reflowDue = out as LayoutMove<TPose>[];\n return out;\n }\n\n function writePose(id: string, pose: unknown): void {\n scene.setPose(asNodeId(id), pose as TPose);\n }\n\n /** Whether `op` is a `createSetLayoutOp` giving a container a layout. An\n * edit's op list is fixed before it runs, so a layout-less scene has to see\n * this coming to append the arrange op its first layout needs. */\n function givesLayout(op: Op): boolean {\n return op.name === 'setLayout' && (op.args as { to?: unknown } | undefined)?.to != null;\n }\n\n /** `ops` plus the op that settles their arrivals, when this call owns the\n * window; `ops` unchanged otherwise. */\n function withArrivalOps(ops: Op[]): { ops: Op[]; owned: boolean } {\n if (!openArrivals(ops.some(givesLayout))) return { ops, owned: false };\n return { ops: [...ops, createArrangeOp({}, settleArrivals, writePose)], owned: true };\n }\n\n /** Run an op-driven edit that may carry arrivals: a refusal reverts it and\n * is swallowed, the way a drop onto a full container is — nothing lands. */\n function runArrivalEdit(ops: Op[], run: (ops: Op[]) => void): void {\n const { ops: all, owned } = withArrivalOps(ops);\n try {\n run(all);\n if (owned) emitReflow();\n } catch (err) {\n if (!(err instanceof SceneArrivalRefused)) throw err;\n } finally {\n if (owned) {\n arrivals = null;\n reflowDue = null;\n }\n }\n }\n\n function isLockedInternal(id: NodeId): boolean {\n if (!state.layers.some((l) => l.locked)) return false;\n let cur = state.nodes.get(id);\n while (cur !== undefined) {\n if (state.layers[state.layerIndex.get(cur.layer) ?? -1]?.locked) return true;\n cur = cur.parent === null ? undefined : state.nodes.get(cur.parent);\n }\n return false;\n }\n\n function refuseUntracked(verb: string): void {\n if (untrackedDepth > 0) throw new Error(`Scene: cannot ${verb} inside untracked() — it records`);\n }\n\n function refuseLocked(id: NodeId, verb: string): void {\n if (lockBypass > 0 || !isLockedInternal(id)) return;\n throw new Error(`Scene: cannot ${verb} \"${id}\" — it is on a locked layer`);\n }\n\n function refuseLockedLayer(layer: TLayer, verb: string): void {\n if (lockBypass > 0 || !state.layers[state.layerIndex.get(layer) ?? -1]?.locked) return;\n throw new Error(`Scene: cannot ${verb} layer \"${layer}\" — it is locked`);\n }\n\n /** The scene's selection never holds a locked node, whoever writes it. */\n function reachable(ids: readonly NodeId[]): readonly NodeId[] {\n if (!state.layers.some((l) => l.locked)) return ids;\n return ids.filter((id) => !isLockedInternal(id));\n }\n\n function withLocksLifted<T>(fn: () => T): T {\n lockBypass++;\n try {\n return fn();\n } finally {\n lockBypass--;\n }\n }\n\n /**\n * Run `fn` as all-or-nothing: if it throws, every kit op it applied is\n * reverted, newest first, and the selection goes back to where it was.\n * The log is at kit-op grain rather than per external op, because one\n * external op can issue several scene mutations (a container move cascading\n * to its children) and fail halfway through its own.\n *\n * On success the ops join an enclosing log only when `ownsEntry` says no\n * history entry holds them: reverting ops an entry still claims would leave\n * undo replaying a change that is no longer there.\n */\n function atomically<T>(fn: () => T, ownsEntry: () => boolean): T {\n const outer = appliedLog;\n const log: { kind: string; payload: unknown }[] = [];\n const selectionBefore = selection;\n appliedLog = log;\n try {\n const result = fn();\n if (outer && !ownsEntry()) outer.push(...log);\n return result;\n } catch (err) {\n appliedLog = null;\n withLocksLifted(() => {\n for (let i = log.length - 1; i >= 0; i--) {\n const { kind, payload } = log[i];\n registered.get(kind)!.revert(payload);\n }\n });\n selection = selectionBefore;\n if (log.length > 0) notify();\n throw err;\n } finally {\n appliedLog = outer;\n }\n }\n\n function notify(): void {\n version++;\n if (batchDepth > 0) {\n batchDirty = true;\n return;\n }\n for (const listener of listeners) listener();\n }\n\n /**\n * Prune the function-field caches of nodes referenced only by ops in entries\n * that just became permanently unreachable (redo entries dropped by a branch\n * edit, or undo entries evicted by `historyLimit`) — wired to the engine's\n * `onEvict`. An entry is safe to drop when the node is absent from\n * `state.nodes`: its only path back into the scene was through these\n * now-unreachable ops.\n */\n function pruneCacheForDroppedOps(ops: readonly Op[]): void {\n if (fnFields.every((f) => f.pending.size === 0)) return;\n for (const op of ops) {\n if (op.name !== 'kit:add') continue;\n const id = (op.args as { id?: NodeId } | null)?.id;\n if (id && !state.nodes.has(id)) {\n for (const field of fnFields) field.pending.delete(id);\n }\n }\n }\n\n function requireNode(id: NodeId): Node<TData, TLayer, TPose> {\n const n = state.nodes.get(id);\n if (!n) throw new Error(`Scene: unknown node id \"${id}\"`);\n return n;\n }\n\n function requireLayerIndex(layer: TLayer): number {\n const i = state.layerIndex.get(layer);\n if (i === undefined) throw new Error(`Scene: unknown layer \"${layer}\"`);\n return i;\n }\n\n /** Repopulate `state.layerIndex` from the current `state.layers` order.\n * Call after any op that inserts, removes, or reorders a layer record. */\n function rebuildLayerIndex(): void {\n invalidateOrder();\n state.layerIndex.clear();\n for (let i = 0; i < state.layers.length; i++) {\n state.layerIndex.set(state.layers[i].id, i);\n }\n }\n\n /**\n * A child may sit on its parent's layer **or any layer above it** (higher\n * render index) — never below. `renderOrder()` / `toJSON()` are layer-major\n * (each node yielded in its OWN layer's pass) and `buildSceneTree` buckets by\n * each node's own layer, so a child on a higher layer than its parent renders\n * correctly on top while staying a tree child for hit-testing / move /\n * reparent (e.g. plantings tagged into a top `plantings` layer while remaining\n * children of their container). Rejecting only the *below* case keeps the\n * sensible invariant that a child never paints under its own parent.\n */\n function assertSubtreeLayer(\n nodeId: string | undefined,\n nodeLayer: TLayer,\n parentId: NodeId,\n parentLayer: TLayer,\n verb: 'place' | 'relayer' = 'place',\n ): void {\n if (requireLayerIndex(nodeLayer) < requireLayerIndex(parentLayer)) {\n const action = verb === 'place'\n ? `cannot place node '${nodeId ?? '<new>'}' on layer '${nodeLayer}' under parent '${parentId}' on layer '${parentLayer}'`\n : `cannot setLayer('${nodeId ?? '<new>'}', '${nodeLayer}') — node has parent '${parentId}' on layer '${parentLayer}'`;\n throw new Error(`Scene: ${action} — a child may not render below its parent's layer`);\n }\n }\n\n function siblingsOf(parent: NodeId | null): NodeId[] {\n if (parent === null) return state.roots;\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n return p.children;\n }\n\n function detach(id: NodeId): { parent: NodeId | null; index: number } {\n const node = requireNode(id);\n const sibs = siblingsOf(node.parent);\n const idx = sibs.indexOf(id);\n if (idx < 0) throw new Error(`Scene: node \"${id}\" not found in its parent's children`);\n sibs.splice(idx, 1);\n invalidateOrder();\n return { parent: node.parent, index: idx };\n }\n\n function attach(id: NodeId, parent: NodeId | null, index: number): void {\n const sibs = siblingsOf(parent);\n const i = Math.max(0, Math.min(index, sibs.length));\n sibs.splice(i, 0, id);\n const node = requireNode(id);\n (node as { parent: NodeId | null }).parent = parent;\n invalidateOrder();\n }\n\n function descendants(id: NodeId, out: NodeId[]): void {\n const n = state.nodes.get(id);\n if (!n || n.kind !== 'container') return;\n for (const c of n.children) {\n out.push(c);\n descendants(c, out);\n }\n }\n\n /** Everything removing `rootIds` takes with it: each root's subtree, then\n * every node deriving from any of those, then those nodes' subtrees in turn.\n * A dependent is not a descendant, so the second pass is a separate\n * reachability walk; `ids` grows as it runs, which is what carries the\n * cascade transitively and upward through a dependent's own ancestors.\n *\n * Published as {@link Scene.removalClosure}, which is what the delete op and\n * `buildDeleteOps` ask instead of rebuilding the walk from `dependsOn` and\n * `children` — a third cascade relation is then added here alone. */\n function removalClosure(rootIds: readonly NodeId[]): {\n ids: NodeId[];\n removing: Set<NodeId>;\n } {\n const ids: NodeId[] = [];\n const removing = new Set<NodeId>();\n function take(id: NodeId): void {\n if (removing.has(id)) return;\n removing.add(id);\n ids.push(id);\n const sub: NodeId[] = [];\n descendants(id, sub);\n for (const s of sub) {\n if (removing.has(s)) continue;\n removing.add(s);\n ids.push(s);\n }\n }\n for (const root of rootIds) take(root);\n for (let i = 0; i < ids.length; i++) {\n for (const dep of dependents.transitiveDependentsOf(ids[i])) take(dep);\n }\n return { ids, removing };\n }\n\n /** Post-patch the registry-keyed function fields onto a node after its\n * `kit:add` op runs. A function cannot travel through the serializable op\n * payload, so it is attached to the live node here. `cacheForRedo` also\n * keeps the reference in the field's pending map, which is where the\n * `kit:add` redo path reads it from — redo replays the op without a spec.\n * `dependsOn` is plain data and rides the payload instead. */\n function patchNodeFunctions(\n spec: AddNodeSpec<TData, TLayer, TPose>,\n id: NodeId,\n { cacheForRedo }: { cacheForRedo: boolean },\n ): void {\n const node = state.nodes.get(id) as FnBearingNode | undefined;\n if (node === undefined) return;\n for (const field of fnFields) {\n const fn = (spec as unknown as Record<string, unknown>)[field.spec.field] as NodeFn | undefined;\n if (fn === undefined) continue;\n if (field.spec.containersOnly && spec.kind !== 'container') continue;\n field.write(node, fn);\n if (cacheForRedo) field.pending.set(id, fn);\n }\n }\n\n /** Re-attach those fields to a node restored from a `kit:remove` snapshot.\n * In-session the clone already carries them; a persisted history does not,\n * so the registry keys are what is left. */\n function restoreNodeFunctions(\n node: Node<TData, TLayer, TPose>,\n keys: Record<string, string | undefined> | undefined,\n ): void {\n if (!keys) return;\n const target = node as unknown as FnBearingNode;\n for (const field of fnFields) {\n if (field.read(target) !== undefined) continue;\n const key = keys[field.spec.opKey];\n if (key === undefined) continue;\n restoreFn(field, target, key, 'kit:remove', dwarn);\n }\n }\n\n // ── Internal kit op kinds ──────────────────────────────────────────────\n // These are registered like any other op; the kit's mutation methods build\n // serializable payloads and route through the same log/replay machinery.\n function registerKitOp<P>(kind: string, handler: RegisteredOp<P>): void {\n registered.set(kind, handler as RegisteredOp<unknown>);\n }\n\n registerKitOp<{\n id: NodeId; kind: 'leaf' | 'container'; layer: TLayer; pose: TPose; data: TData;\n parent: NodeId | null; index: number;\n dependsOn?: readonly NodeId[] | 'children';\n pickable?: boolean;\n } & Record<string, unknown>>('kit:add', {\n apply: (p) => {\n if (state.nodes.has(p.id)) {\n throw new Error(`Scene: id collision on \"${p.id}\"`);\n }\n const node: Node<TData, TLayer, TPose> = p.kind === 'container'\n ? ({ kind: 'container', id: p.id, layer: p.layer, pose: p.pose, data: p.data, parent: p.parent, children: [] } as ContainerNode<TData, TLayer, TPose>)\n : ({ kind: 'leaf', id: p.id, layer: p.layer, pose: p.pose, data: p.data, parent: p.parent } as LeafNode<TData, TLayer, TPose>);\n state.nodes.set(p.id, node);\n attach(p.id, p.parent, p.index);\n if (p.dependsOn !== undefined) node.dependsOn = p.dependsOn;\n if (p.pickable !== undefined) node.pickable = p.pickable;\n dependents.add(p.id, p.dependsOn === 'children' ? [] : p.dependsOn ?? []);\n trackChildDerived(p.id, p.dependsOn);\n // Two ways a function field comes back. The redo path reads the\n // side-channel cache the original `scene.add` filled, because redo\n // replays the op without a spec. The restore path — a fresh session,\n // empty cache — resolves the registry key the payload carries, and\n // seeds the cache so later undo/redo cycles behave like the live one.\n const target = node as unknown as FnBearingNode;\n for (const field of fnFields) {\n const cached = field.pending.get(p.id);\n if (cached !== undefined) {\n field.write(target, cached);\n continue;\n }\n const key = p[field.spec.opKey] as string | undefined;\n if (key !== undefined) restoreFn(field, target, key, 'kit:add', dwarn);\n }\n invalidateDependents(p.id);\n },\n revert: (p) => {\n detach(p.id);\n state.nodes.delete(p.id);\n dependents.remove(p.id);\n childDerived.delete(p.id);\n invalidateChildDerivedFrom(p.parent);\n invalidateDependents(p.id);\n // Note: we intentionally do NOT delete the pending function-field\n // entries — redo re-applies the node and re-attaches from them.\n },\n });\n\n /**\n * Snapshot of every node a removal deletes, so revert restores it exactly.\n *\n * A cascade unlinks several disjoint subtrees, not one, so `detached` names\n * each node the tree has to re-link; everything else in `nodes` has a parent\n * that is also going and rides back in that parent's cloned `children`.\n * Entries are sorted by ascending sibling index — globally rather than\n * per-parent, because only same-parent order constrains re-insertion and\n * entries under different parents never interact.\n */\n interface RemoveSnapshot {\n nodes: Node<TData, TLayer, TPose>[];\n detached: { id: NodeId; parent: NodeId | null; index: number }[];\n /** Registry keys for the function-valued fields on `nodes`. The functions\n * themselves do not survive a persisted history, so revert re-resolves\n * them the way `kit:add` does. */\n fnKeys?: ({ id: NodeId } & Record<string, string | undefined>)[];\n }\n // Neither half invalidates dependents: removal's closure takes every live one.\n registerKitOp<RemoveSnapshot>('kit:remove', {\n apply: (p) => {\n for (const d of p.detached) detach(d.id);\n for (const n of p.nodes) {\n state.nodes.delete(n.id);\n dependents.remove(n.id);\n childDerived.delete(n.id);\n }\n // A `dependsOn: 'children'` container the removal did not take is now\n // hugging a smaller set.\n for (const d of p.detached) invalidateChildDerivedFrom(d.parent);\n },\n revert: (p) => {\n const keys = new Map((p.fnKeys ?? []).map((k) => [k.id, k]));\n // Order-independent: every clone carries its own parent and children.\n for (const n of p.nodes) {\n const clone: Node<TData, TLayer, TPose> = n.kind === 'container'\n ? { ...n, children: [...n.children] }\n : { ...n };\n restoreNodeFunctions(clone, keys.get(n.id));\n state.nodes.set(n.id, clone);\n dependents.add(n.id, clone.dependsOn === 'children' ? [] : clone.dependsOn ?? []);\n trackChildDerived(n.id, clone.dependsOn);\n }\n for (const d of p.detached) attach(d.id, d.parent, d.index);\n for (const d of p.detached) invalidateChildDerivedFrom(d.parent);\n },\n });\n\n registerKitOp<{ id: NodeId; from: TPose; to: TPose }>('kit:setPose', {\n apply: (p) => {\n (requireNode(p.id) as { pose: TPose }).pose = p.to;\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { pose: TPose }).pose = p.from;\n invalidateDependents(p.id);\n },\n });\n\n // A derivation is handed its dependencies' nodes, not only their poses, so a\n // connector reading `data` or `layer` goes stale on these two exactly as it\n // does on a move.\n registerKitOp<{ id: NodeId; from: TData; to: TData }>('kit:setData', {\n apply: (p) => {\n (requireNode(p.id) as { data: TData }).data = p.to;\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { data: TData }).data = p.from;\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{ id: NodeId; from: TLayer; to: TLayer }>('kit:setLayer', {\n apply: (p) => {\n requireLayerIndex(p.to);\n (requireNode(p.id) as { layer: TLayer }).layer = p.to;\n invalidateOrder();\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { layer: TLayer }).layer = p.from;\n invalidateOrder();\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{\n id: NodeId;\n from: Node<TData, TLayer, TPose>['dependsOn'];\n to: Node<TData, TLayer, TPose>['dependsOn'];\n }>('kit:setDependsOn', {\n apply: (p) => { retarget(p.id, p.to); },\n revert: (p) => { retarget(p.id, p.from); },\n });\n\n /** The strategies each live `kit:setLayout` payload swaps between. A payload\n * replayed from a persisted history has none, and resolves its keys. */\n const layoutRefs = new WeakMap<object, { from: LayoutStrategy<TPose> | null; to: LayoutStrategy<TPose> | null }>();\n interface SetLayoutPayload { id: NodeId; fromKey?: string; toKey?: string }\n function placeLayout(p: SetLayoutPayload, side: 'from' | 'to'): void {\n const node = requireNode(p.id) as unknown as FnBearingNode;\n const field = fnField('layout');\n const live = layoutRefs.get(p);\n const key = side === 'from' ? p.fromKey : p.toKey;\n if (live === undefined && key !== undefined) {\n delete node.layout;\n restoreFn(field, node, key, 'kit:setLayout', dwarn);\n return;\n }\n const layout = live?.[side] ?? null;\n if (layout === null) delete node.layout;\n else field.write(node, layout);\n }\n registerKitOp<SetLayoutPayload>('kit:setLayout', {\n apply: (p) => { placeLayout(p, 'to'); },\n revert: (p) => { placeLayout(p, 'from'); },\n });\n\n registerKitOp<{\n id: NodeId; fromParent: NodeId | null; fromIndex: number;\n toParent: NodeId | null; toIndex: number;\n }>('kit:move', {\n apply: (p) => {\n detach(p.id);\n attach(p.id, p.toParent, p.toIndex);\n // Both ends: the container it left no longer hugs it, and the one it\n // joined now does.\n invalidateChildDerivedFrom(p.fromParent);\n invalidateDependents(p.id);\n },\n revert: (p) => {\n detach(p.id);\n attach(p.id, p.fromParent, p.fromIndex);\n invalidateChildDerivedFrom(p.toParent);\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{ layer: TLayer; from: boolean; to: boolean }>('kit:setLayerVisible', {\n apply: (p) => { state.layers[requireLayerIndex(p.layer)].visible = p.to; },\n revert: (p) => { state.layers[requireLayerIndex(p.layer)].visible = p.from; },\n });\n\n registerKitOp<{ layer: TLayer; from: boolean; to: boolean }>('kit:setLayerLocked', {\n apply: (p) => {\n state.layers[requireLayerIndex(p.layer)].locked = p.to;\n if (p.to) selection = reachable(selection);\n },\n revert: (p) => { state.layers[requireLayerIndex(p.layer)].locked = p.from; },\n });\n\n registerKitOp<{ layer: TLayer; from?: ParallaxOpts; to?: ParallaxOpts }>('kit:setLayerParallax', {\n apply: (p) => { setParallax(state.layers[requireLayerIndex(p.layer)], p.to); },\n revert: (p) => { setParallax(state.layers[requireLayerIndex(p.layer)], p.from); },\n });\n\n registerKitOp<{ record: UserLayerRecord<TLayer>; index: number }>('kit:addLayer', {\n apply: (p) => {\n state.layers.splice(p.index, 0, { ...p.record });\n rebuildLayerIndex();\n },\n revert: (p) => {\n state.layers.splice(p.index, 1);\n rebuildLayerIndex();\n },\n });\n\n registerKitOp<{ record: LayerRecord<TLayer>; index: number }>('kit:removeLayer', {\n apply: (p) => {\n state.layers.splice(p.index, 1);\n rebuildLayerIndex();\n },\n revert: (p) => {\n state.layers.splice(p.index, 0, { ...p.record } as LayerRecord<TLayer>);\n rebuildLayerIndex();\n },\n });\n\n registerKitOp<{ layer: TLayer; from: string; to: string }>('kit:renameLayer', {\n apply: (p) => {\n (state.layers[requireLayerIndex(p.layer)] as UserLayerRecord<TLayer>).name = p.to;\n },\n revert: (p) => {\n (state.layers[requireLayerIndex(p.layer)] as UserLayerRecord<TLayer>).name = p.from;\n },\n });\n\n registerKitOp<{ layer: TLayer; from: number; to: number }>('kit:moveLayer', {\n apply: (p) => {\n const [rec] = state.layers.splice(p.from, 1);\n state.layers.splice(p.to, 0, rec);\n rebuildLayerIndex();\n },\n revert: (p) => {\n const [rec] = state.layers.splice(p.to, 1);\n state.layers.splice(p.from, 0, rec);\n rebuildLayerIndex();\n },\n });\n\n // ── Op execution (used by both kit mutations and consumer recordOp) ────\n function runOp(kind: string, payload: unknown): void {\n const handler = registered.get(kind);\n if (!handler) throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n handler.apply(payload);\n }\n\n /** Bridge a registered scene op into an engine `Op`: a direction-flipping\n * wrapper over the `RegisteredOp`'s `apply`/`revert` pair. `invert()`\n * flips the direction with the same payload, so undo replays `revert`\n * and redo replays `apply` — no per-op inverse code. `name`/`args` carry\n * the (kind, payload) pair for eviction pruning (and, later,\n * serialization). Handler lookup happens at apply time so re-registered\n * kinds take effect on replay, but existence is checked eagerly to fail\n * fast at the call site. */\n function makeOp(kind: string, payload: unknown, dir: 'fwd' | 'rev' = 'fwd'): Op {\n if (!registered.has(kind)) {\n throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n }\n return {\n name: kind,\n args: payload,\n coalesceKey: coalesceKeyFor(kind, payload),\n apply: () => {\n const handler = registered.get(kind);\n if (!handler) throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n (dir === 'fwd' ? handler.apply : handler.revert)(payload);\n },\n invert: () => makeOp(kind, payload, dir === 'fwd' ? 'rev' : 'fwd'),\n };\n }\n\n /** Rebind an external op to the adapter supplied at the `applyBatch` call\n * site — the scene's engine was constructed without an adapter, so ops\n * it stores and later replays must close over the right one. Forwards\n * the apply return value (no-op detection) and preserves\n * `coalesceKey`/`name`/`args`/`label` for coalescing and eviction. See\n * `bindOpToHistoryAdapter` for RESTORED entries (lazy accessor). */\n function bindOpToAdapter(op: Op, adapter: unknown): Op {\n return {\n name: op.name,\n args: op.args,\n label: op.label,\n coalesceKey: op.coalesceKey,\n apply: () => op.apply(adapter),\n invert: () => bindOpToAdapter(op.invert(), adapter),\n };\n }\n\n /** Best-effort coalesce-grouping token: node ops carry `payload.id`,\n * layer ops `payload.layer`. Payloads with neither get no key and never\n * coalesce (the engine treats a missing key on either side as\n * \"new entry\"). Keys only take effect when the scene opts in via\n * `UseSceneOptions.coalesceWindowMs` (default `0`, which disables\n * coalescing entirely). */\n function coalesceKeyFor(kind: string, payload: unknown): string | undefined {\n if (payload === null || typeof payload !== 'object') return undefined;\n const p = payload as { id?: unknown; layer?: unknown };\n const token =\n typeof p.id === 'string' ? p.id\n : typeof p.layer === 'string' ? p.layer\n : undefined;\n return token === undefined ? undefined : `${kind}:${token}`;\n }\n\n /** Run `fn` with scene-side recording suppressed and per-op notifies\n * batched. Used whenever the engine drives mutations (undo/redo/goto):\n * engine-applied ops may re-enter scene mutation methods, which must\n * apply but not record. The caller fires exactly one `notify()` after. */\n function withRecordingSuppressed<T>(fn: () => T): T {\n const prevSuppress = suppressRecording;\n suppressRecording = true;\n batchDepth++;\n const prevDirty = batchDirty;\n try {\n return fn();\n } finally {\n batchDepth--;\n suppressRecording = prevSuppress;\n batchDirty = prevDirty;\n }\n }\n\n function executeAndLog(kind: string, payload: unknown, label: string): void {\n if (suppressRecording) {\n runOp(kind, payload);\n appliedLog?.push({ kind, payload });\n notify();\n return;\n }\n if (currentBatch) {\n runOp(kind, payload);\n appliedLog?.push({ kind, payload });\n currentBatch.ops.push(makeOp(kind, payload));\n notify();\n return;\n }\n // The engine applies the op itself (inside applyOps) — no separate\n // runOp call, or the mutation would run twice.\n history.applyOps([makeOp(kind, payload)], label);\n notify();\n }\n\n // ── Public Scene object ────────────────────────────────────────────────\n\n // Register consumer-supplied ops up front.\n if (options.ops) {\n for (const [k, h] of Object.entries(options.ops)) {\n registered.set(k, h);\n }\n }\n\n /**\n * Layer-major DFS-preorder ids, and the same sequence as nodes. Four walks\n * for two sequences, which wants explaining, because collapsing them is the\n * obvious cleanup and each collapse was measured to cost something:\n *\n * - ids vs nodes: projecting one from the other is a whole extra pass, worth\n * 20% of `renderOrder()` on a multi-layer scene.\n * - flat vs bucketed: a single layer needs no buckets and can compare the\n * layer id instead of indexing it, which is 1.4x. Behind a branch in one\n * function it also slows the bucketed path by 20% — the two shapes share\n * one optimized body, and whichever ran first wins it.\n *\n * All four emit the same order and `renderOrder.test.ts` holds them to it.\n */\n function renderOrderInternal(): NodeId[] {\n return state.layers.length === 1 ? renderOrderFlat() : renderOrderBucketed();\n }\n\n function renderOrderNodesInternal(): Node<TData, TLayer, TPose>[] {\n return state.layers.length === 1 ? renderOrderNodesFlat() : renderOrderNodesBucketed();\n }\n\n /**\n * Render order survives everything except a structural edit, so both walks\n * are cached against a counter the structural writers bump: `attach` and\n * `detach` (add / remove / reparent / reorder), `kit:setLayer` (which bucket\n * a node lands in), `rebuildLayerIndex` (the layer list itself), and\n * `loadState`. Pose and data edits leave order alone and must NOT invalidate\n * — they fire per frame during a drag, which is exactly when the cache pays.\n *\n * A missed bump is a silent wrong answer: nodes painted in the wrong z-order,\n * or unpickable. `renderOrder.test.ts` walks each structural op and asserts\n * the order moved.\n */\n let structureGeneration = 0;\n let orderCache: {\n gen: number;\n ids?: NodeId[];\n nodes?: Node<TData, TLayer, TPose>[];\n byLayer?: Map<TLayer, Node<TData, TLayer, TPose>[]>;\n } = { gen: 0 };\n\n function invalidateOrder(): void {\n structureGeneration++;\n }\n\n const EMPTY_NODES: readonly Node<TData, TLayer, TPose>[] = [];\n\n function currentOrderCache(): typeof orderCache {\n if (orderCache.gen !== structureGeneration) {\n orderCache = { gen: structureGeneration };\n }\n return orderCache;\n }\n\n function renderOrderFlat(): NodeId[] {\n const only = state.layers[0].id;\n const out: NodeId[] = [];\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n if (node.layer === only) out.push(id);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n return out;\n }\n\n function renderOrderNodesFlat(): Node<TData, TLayer, TPose>[] {\n const only = state.layers[0].id;\n const out: Node<TData, TLayer, TPose>[] = [];\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n if (node.layer === only) out.push(node);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n return out;\n }\n\n /** One DFS of the tree, bucketed by layer: appending in preorder keeps each\n * bucket in preorder, so concatenating them is the layer-major sequence. */\n function renderOrderBucketed(): NodeId[] {\n const buckets: NodeId[][] = state.layers.map(() => []);\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n const bucket = buckets[state.layerIndex.get(node.layer) ?? -1];\n if (bucket) bucket.push(id);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n const out: NodeId[] = [];\n for (const bucket of buckets) {\n for (const id of bucket) out.push(id);\n }\n return out;\n }\n\n function renderOrderNodesBucketed(): Node<TData, TLayer, TPose>[] {\n const buckets: Node<TData, TLayer, TPose>[][] = state.layers.map(() => []);\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n const bucket = buckets[state.layerIndex.get(node.layer) ?? -1];\n if (bucket) bucket.push(node);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n const out: Node<TData, TLayer, TPose>[] = [];\n for (const bucket of buckets) {\n for (const node of bucket) out.push(node);\n }\n return out;\n }\n\n // ── scene.history ──────────────────────────────────────────────────────\n // The `History` the kit's `undo`/`redo` actions resolve their `history` dep\n // to, and the handle a mode machine opens journals against. Handing out\n // `history` (the engine) directly would let an action-driven undo replay ops\n // with scene-side recording still armed and without bumping the version, so\n // every member that mutates routes through the scene's own wrapper\n // (`withRecordingSuppressed` + one `notify()`); reads forward to the engine.\n\n /** Wrapped journal → the engine's own, for `resumeJournal`: the engine keys\n * resumability off journal identity, which a wrapper would not match. */\n const rawJournals = new WeakMap<Journal, Journal>();\n\n /** Same treatment as the façade: a journal drives adapter mutation itself,\n * so its applies/undos re-enter scene mutation methods. */\n function wrapJournal(raw: Journal): Journal {\n const wrapped: Journal = {\n targetId: raw.targetId,\n forkedAtEntryId: raw.forkedAtEntryId,\n applyBatch(ops, label) {\n runArrivalEdit(ops, (all) => {\n atomically(() => withRecordingSuppressed(() => raw.applyBatch(all, label)), () => true);\n notify();\n });\n },\n undo() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.undo()));\n notify();\n },\n redo() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.redo()));\n notify();\n },\n canUndo: () => raw.canUndo(),\n canRedo: () => raw.canRedo(),\n entries: () => raw.entries(),\n seal: () => raw.seal(),\n getVersion: () => raw.getVersion(),\n subscribe: (listener) => raw.subscribe(listener),\n commit(label) {\n // Flushes the session's net ops to the parent stack — no apply, but\n // the parent's undo depth changes and listeners read that.\n raw.commit(label);\n notify();\n },\n cancel() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.cancel()));\n notify();\n },\n suspend: () => raw.suspend(),\n isActive: () => raw.isActive(),\n };\n rawJournals.set(wrapped, raw);\n return wrapped;\n }\n\n const sceneHistory: History = {\n // Mutating: applied ops re-enter the scene's own mutation methods.\n apply(op, label) {\n refuseUntracked('history.apply');\n runArrivalEdit([op], (all) => {\n const run = () => (all.length === 1\n ? history.apply(op, label)\n : history.applyOps(all, label ?? op.label ?? ''));\n atomically(() => withRecordingSuppressed(run), () => true);\n notify();\n });\n },\n applyOps(ops, label) {\n refuseUntracked('history.applyOps');\n runArrivalEdit(ops, (all) => {\n atomically(() => withRecordingSuppressed(() => history.applyOps(all, label)), () => true);\n notify();\n });\n },\n undo: () => { scene.undo(); },\n redo: () => { scene.redo(); },\n goto: (n) => { scene.jumpToHistoryIndex(n); },\n // Stack-only: nothing applies, but what `canUndo()` answers changes.\n clear() {\n history.clear();\n notify();\n },\n recordEntry(ops, label, opts) {\n history.recordEntry(ops, label, opts);\n notify();\n },\n restore: (snapshot) => { scene.restoreHistory(snapshot); },\n // Reads forward to the engine, `version` included: it counts history\n // operations, where the scene's counts every mutation.\n canUndo: () => history.canUndo(),\n canRedo: () => history.canRedo(),\n undoDepth: () => history.undoDepth(),\n redoDepth: () => history.redoDepth(),\n entries: () => history.entries(),\n getVersion: () => history.getVersion(),\n subscribe: (listener) => history.subscribe(listener),\n serialize: () => history.serialize(),\n allForwardOps: () => history.allForwardOps(),\n seal: () => history.seal(),\n currentEntryId: () => history.currentEntryId(),\n beginJournal: (opts) => wrapJournal(history.beginJournal(opts)),\n resumeJournal: (journal) => history.resumeJournal(rawJournals.get(journal) ?? journal),\n };\n\n function applyBatchNow(ops: Op[], label: string, adapter: unknown): void {\n const journal: Journal | null = (activeJournalAccessor ?? (() => null))();\n // Either route drives mutations from a history engine (the journal's\n // inner history, or the scene's own), so scene-side recording is\n // suppressed for the duration: op applies that re-enter scene\n // mutation methods via the adapter must mutate without re-recording.\n // batchDepth coalesces the per-op notify() calls (same as\n // scene.batch); exactly one listener dispatch fires at the end —\n // mirroring the single-notification semantics callers expect.\n const prevSuppress = suppressRecording;\n const prevDirty = batchDirty;\n suppressRecording = true;\n batchDepth++;\n batchDirty = false;\n try {\n atomically(() => {\n if (journal) {\n journal.applyBatch(ops, label);\n } else {\n // Native path: record the external ops themselves as one engine\n // entry — coalescible across applyBatch calls via their own\n // coalesceKeys — rebound to this call's adapter.\n history.applyOps(ops.map((op) => bindOpToAdapter(op, adapter)), label);\n }\n }, () => true);\n } finally {\n batchDepth--;\n suppressRecording = prevSuppress;\n // Re-merge any outer batch's pending dirt so a nested call can't\n // swallow it; at true top level prevDirty is always false.\n batchDirty = batchDirty || prevDirty;\n // Flush inside finally so a throwing op can't strand subscribers\n // after earlier ops in the batch already mutated state (mirrors\n // scene.batch). Depth-guarded: a nested context defers to the\n // outermost flush.\n if (batchDepth === 0 && batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n }\n\n const scene: Scene<TData, TLayer, TPose> = {\n get nodes() { return state.nodes; },\n get roots() { return state.roots; },\n get layers() { return state.layers; },\n registry,\n\n get(id) { return state.nodes.get(id); },\n incarnation(id) {\n const node = state.nodes.get(id);\n if (!node) return undefined;\n let token = incarnations.get(node);\n if (token === undefined) {\n token = nextIncarnation++;\n incarnations.set(node, token);\n }\n return token;\n },\n\n childrenOf(id) {\n const n = state.nodes.get(id);\n return n && n.kind === 'container' ? n.children : [];\n },\n\n ancestorsOf(id) {\n const out: NodeId[] = [];\n let cur = state.nodes.get(id)?.parent ?? null;\n while (cur !== null) {\n out.push(cur);\n cur = state.nodes.get(cur)?.parent ?? null;\n }\n return out;\n },\n\n renderOrder() {\n const c = currentOrderCache();\n return (c.ids ??= renderOrderInternal());\n },\n\n renderOrderNodes() {\n const c = currentOrderCache();\n return (c.nodes ??= renderOrderNodesInternal());\n },\n\n nodesOnLayer(layer) {\n const c = currentOrderCache();\n let byLayer = c.byLayer;\n if (!byLayer) {\n byLayer = new Map();\n for (const node of (c.nodes ??= renderOrderNodesInternal())) {\n let bucket = byLayer.get(node.layer);\n if (!bucket) byLayer.set(node.layer, (bucket = []));\n bucket.push(node);\n }\n c.byLayer = byLayer;\n }\n return byLayer.get(layer) ?? EMPTY_NODES;\n },\n\n add(spec) {\n const id = spec.id ?? generateId();\n if (state.nodes.has(id)) {\n throw new Error(`Scene: id collision on \"${id}\"`);\n }\n requireLayerIndex(spec.layer);\n refuseLockedLayer(spec.layer, 'add to');\n const parent = spec.parent ?? null;\n if (parent !== null) {\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);\n refuseLocked(parent, 'add under');\n }\n if (parent !== null && bareLayoutEdit()) {\n // A bare add under a container is an edit of its own, so it settles\n // its arrival like one — as a batch, which is what makes the\n // arrangement part of the same undo step.\n return scene.batch(`add ${spec.kind}`, () => scene.add(spec));\n }\n const sibs = siblingsOf(parent);\n const index = spec.index ?? sibs.length;\n noteArrival(id, parent, null);\n executeAndLog('kit:add', {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...(spec.pickable !== undefined ? { pickable: spec.pickable } : {}),\n ...fnKeysOf(fnFields, { ...spec, id, kind: spec.kind } as unknown as FnBearingNode, 'opKey'),\n }, `add ${spec.kind}`);\n // A function cannot travel through the serializable op payload. Patch it\n // directly onto the live node after the op applies.\n patchNodeFunctions(spec, id, { cacheForRedo: true });\n return id;\n },\n\n remove(id) {\n scene.removeMany([id]);\n },\n\n removalClosure(rootIds) {\n return removalClosure(rootIds).ids;\n },\n\n removeMany(rootIds) {\n if (rootIds.length === 0) return;\n // Every id resolves against the pre-removal tree, so an id another one\n // cascades away is absorbed rather than being a second, failing removal.\n const { ids, removing } = removalClosure(rootIds);\n for (const nid of ids) refuseLocked(nid, 'remove');\n // requireNode is what rejects an id that is not in the scene, and it runs\n // before anything mutates.\n const snapshot: Node<TData, TLayer, TPose>[] = ids.map((nid) => {\n const n = requireNode(nid);\n return n.kind === 'container' ? { ...n, children: [...n.children] } : { ...n };\n });\n // The rest is reachable through a snapshotted parent's cloned `children`.\n const detached = snapshot\n .filter((n) => n.parent === null || !removing.has(n.parent))\n .map((n) => ({ id: n.id, parent: n.parent, index: siblingsOf(n.parent).indexOf(n.id) }))\n .sort((l, r) => l.index - r.index);\n // Ephemeral, and ids are reusable: an override left behind would\n // reattach itself to whatever is added under this id next.\n for (const nid of ids) overrides.clear(nid);\n const fnKeys = snapshot.flatMap((n) => {\n const keys = fnKeysOf(fnFields, n as unknown as FnBearingNode, 'opKey');\n return Object.keys(keys).length === 0 ? [] : [{ id: n.id, ...keys }];\n });\n const payload: RemoveSnapshot = {\n nodes: snapshot, detached,\n ...(fnKeys.length > 0 ? { fnKeys } : {}),\n };\n if (detached.some((d) => d.parent !== null) && bareLayoutEdit()) {\n scene.batch('remove', () => scene.removeMany(rootIds));\n return;\n }\n for (const d of detached) noteDeparture(d.id, d.parent, null);\n executeAndLog('kit:remove', payload, 'remove');\n },\n\n update(id, patch) {\n const node = requireNode(id);\n refuseLocked(id, 'update');\n executeAndLog('kit:setData', { id, from: node.data, to: patch.data }, 'update');\n },\n\n setPose(id, pose) {\n const node = requireNode(id);\n refuseLocked(id, 'set the pose of');\n if (node.kind === 'container' && resized(layoutFrame, id, node.pose, pose)) {\n if (bareLayoutEdit()) {\n scene.batch('setPose', () => scene.setPose(id, pose));\n return;\n }\n noteChange(id);\n }\n executeAndLog('kit:setPose', { id, from: node.pose, to: pose }, 'setPose');\n },\n\n setLayer(id, layer) {\n requireLayerIndex(layer);\n const node = requireNode(id);\n refuseLocked(id, 'relayer');\n if (node.layer !== layer) refuseLockedLayer(layer, 'move nodes onto');\n if (node.parent !== null) {\n const parentNode = requireNode(node.parent);\n assertSubtreeLayer(id, layer, node.parent, parentNode.layer, 'relayer');\n }\n if (node.layer === layer) return;\n // DFS preorder: collect id + all descendants.\n const subtree: NodeId[] = [];\n const stack: NodeId[] = [id];\n while (stack.length > 0) {\n const curId = stack.pop()!;\n const cur = state.nodes.get(curId);\n if (!cur) continue;\n subtree.push(curId);\n refuseLocked(curId, 'relayer');\n if (cur.kind === 'container') {\n for (let i = cur.children.length - 1; i >= 0; i--) {\n stack.push(cur.children[i]);\n }\n }\n }\n if (subtree.length === 1) {\n // Fast path: single node, no batch needed.\n executeAndLog('kit:setLayer', { id, from: node.layer, to: layer }, 'setLayer');\n } else {\n scene.batch('setLayer', () => {\n for (const sid of subtree) {\n const cur = requireNode(sid);\n if (cur.layer === layer) continue;\n executeAndLog('kit:setLayer', { id: sid, from: cur.layer, to: layer }, 'setLayer');\n }\n });\n }\n },\n\n setDependsOn(id, dependsOn) {\n const node = requireNode(id);\n refuseLocked(id, 'retarget');\n if (sameDependsOn(node.dependsOn, dependsOn)) return;\n executeAndLog(\n 'kit:setDependsOn',\n { id, from: node.dependsOn, to: dependsOn },\n 'setDependsOn',\n );\n },\n\n setLayout(id, layout) {\n const node = requireNode(id);\n if (node.kind !== 'container') throw new Error(`Scene: \"${id}\" is not a container`);\n refuseLocked(id, 'set the layout of');\n const field = fnField('layout');\n let to: LayoutStrategy<TPose> | null;\n if (typeof layout === 'string') {\n to = (field.fnOf(layout) as LayoutStrategy<TPose> | undefined) ?? null;\n if (to === null) throw new Error(`Scene: no layout \"${layout}\" in this scene's registry`);\n } else {\n to = layout;\n }\n const from = node.layout ?? null;\n if (from === to) return;\n if (to !== null) hasLayouts = true;\n if (bareLayoutEdit()) {\n scene.batch('setLayout', () => scene.setLayout(id, to));\n return;\n }\n noteChange(id);\n const fromKey = from === null ? undefined : field.keyOf(from);\n const toKey = to === null ? undefined : field.keyOf(to);\n const payload: SetLayoutPayload = {\n id,\n ...(fromKey !== undefined ? { fromKey } : {}),\n ...(toKey !== undefined ? { toKey } : {}),\n };\n layoutRefs.set(payload, { from, to });\n executeAndLog('kit:setLayout', payload, 'setLayout');\n },\n\n move(id, parent, index) {\n const node = requireNode(id);\n refuseLocked(id, 'move');\n if (parent !== null) {\n refuseLocked(parent, 'move nodes into');\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(id, node.layer, parent, p.layer);\n // Cycle check: parent must not be id or a descendant of id.\n if (parent === id) throw new Error('Scene: cannot parent a node to itself');\n const desc: NodeId[] = [];\n descendants(id, desc);\n if (desc.includes(parent)) {\n throw new Error('Scene: cannot parent a node to its own descendant');\n }\n }\n if ((parent !== null || node.parent !== null) && bareLayoutEdit()) {\n scene.batch('move', () => scene.move(id, parent, index));\n return;\n }\n const fromSibs = siblingsOf(node.parent);\n const fromIndex = fromSibs.indexOf(id);\n const toSibs = parent === node.parent ? fromSibs : siblingsOf(parent);\n const toIndex = index ?? toSibs.length;\n noteArrival(id, parent, node.parent);\n noteDeparture(id, node.parent, parent);\n noteChange(node.parent);\n executeAndLog('kit:move', {\n id, fromParent: node.parent, fromIndex, toParent: parent, toIndex,\n }, 'move');\n },\n\n reorder(id, index) {\n const node = requireNode(id);\n refuseLocked(id, 'reorder');\n if (node.parent !== null && bareLayoutEdit()) {\n scene.batch('reorder', () => scene.reorder(id, index));\n return;\n }\n noteChange(node.parent);\n const sibs = siblingsOf(node.parent);\n const fromIndex = sibs.indexOf(id);\n executeAndLog('kit:move', {\n id, fromParent: node.parent, fromIndex, toParent: node.parent, toIndex: index,\n }, 'reorder');\n },\n\n setLayerVisible(layer, visible) {\n const i = requireLayerIndex(layer);\n executeAndLog('kit:setLayerVisible', { layer, from: state.layers[i].visible, to: visible }, 'setLayerVisible');\n },\n\n setLayerLocked(layer, locked) {\n const i = requireLayerIndex(layer);\n executeAndLog('kit:setLayerLocked', { layer, from: state.layers[i].locked, to: locked }, 'setLayerLocked');\n },\n\n setLayerParallax(layer, parallax) {\n const i = requireLayerIndex(layer);\n executeAndLog(\n 'kit:setLayerParallax',\n { layer, from: state.layers[i].parallax, to: parallax },\n 'setLayerParallax',\n );\n },\n\n isLocked: (id) => isLockedInternal(id),\n\n unlocked: (fn) => withLocksLifted(fn),\n\n addLayer(spec) {\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`Scene: duplicate layer id \"${spec.id}\"`);\n }\n const index = spec.index ?? state.layers.length;\n const clamped = Math.max(0, Math.min(index, state.layers.length));\n const record: UserLayerRecord<TLayer> = {\n kind: 'user',\n id: spec.id,\n name: spec.name,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n };\n executeAndLog('kit:addLayer', { record, index: clamped }, 'addLayer');\n },\n\n removeLayer(layer) {\n const index = requireLayerIndex(layer);\n const rec = state.layers[index];\n if (rec.kind !== 'user') {\n throw new Error(`Scene: cannot remove system layer \"${layer}\"`);\n }\n // A layer operation, like the lock toggle: taking a locked layer away\n // takes its nodes with it.\n withLocksLifted(() => scene.batch('removeLayer', () => {\n const tagged: NodeId[] = [];\n for (const [id, node] of state.nodes) {\n if (node.layer === layer) tagged.push(id);\n }\n scene.removeMany(tagged);\n const finalIndex = requireLayerIndex(layer);\n executeAndLog('kit:removeLayer', { record: rec, index: finalIndex }, 'removeLayer');\n }));\n },\n\n renameLayer(layer, name) {\n const rec = state.layers[requireLayerIndex(layer)];\n if (rec.kind !== 'user') {\n throw new Error(`Scene: cannot rename system layer \"${layer}\"`);\n }\n executeAndLog('kit:renameLayer', { layer, from: rec.name, to: name }, 'renameLayer');\n },\n\n moveLayer(layer, index) {\n const from = requireLayerIndex(layer);\n const to = Math.max(0, Math.min(index, state.layers.length - 1));\n if (from === to) return;\n // Build the proposed order and a temp index map, then verify the\n // child-below-parent invariant holds for every node before mutating.\n const proposed = [...state.layers];\n const [rec] = proposed.splice(from, 1);\n proposed.splice(to, 0, rec);\n const tempIndex = new Map<TLayer, number>();\n for (let i = 0; i < proposed.length; i++) tempIndex.set(proposed[i].id, i);\n for (const node of state.nodes.values()) {\n if (node.parent === null) continue;\n const parent = state.nodes.get(node.parent);\n if (!parent) continue;\n if (tempIndex.get(node.layer)! < tempIndex.get(parent.layer)!) {\n throw new Error(\n `Scene: moveLayer(\"${layer}\", ${index}) — a child may not render below its parent's layer`,\n );\n }\n }\n executeAndLog('kit:moveLayer', { layer, from, to }, 'moveLayer');\n },\n\n registerOp(kind, handler) {\n if (kind.startsWith('kit:')) {\n throw new Error(`Scene: op kind \"${kind}\" is reserved (kit:* prefix)`);\n }\n registered.set(kind, handler as RegisteredOp<unknown>);\n },\n\n recordOp(op) {\n executeAndLog(op.kind, op.payload, op.kind);\n },\n\n setActiveJournalAccessor(fn) {\n activeJournalAccessor = fn;\n },\n\n applyBatch(ops, label, adapter) {\n refuseUntracked('applyBatch');\n runArrivalEdit(ops, (all) => applyBatchNow(all, label, adapter));\n },\n\n setArrivalHandler(handler) {\n arrivalHandler = handler;\n return () => {\n if (arrivalHandler === handler) arrivalHandler = null;\n };\n },\n\n layoutOf(id) {\n return layoutOfInternal(id);\n },\n\n onReflow(listener) {\n reflowListeners.add(listener);\n return () => { reflowListeners.delete(listener); };\n },\n\n overrides,\n\n getSelection: () => selection,\n\n setSelection(ids) {\n selection = reachable([...ids]);\n notify();\n },\n\n history: sceneHistory,\n\n undo() {\n if (!history.canUndo()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.undo()));\n notify();\n return true;\n },\n\n redo() {\n if (!history.canRedo()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.redo()));\n notify();\n return true;\n },\n\n canUndo: () => history.canUndo(),\n canRedo: () => history.canRedo(),\n\n /** Read-only snapshot of every history entry currently reachable from\n * the present state. Order: oldest applied first, then redoable\n * entries in the order they'd be re-applied (top of redo stack last).\n * Each entry's `id` is stable for the entry's lifetime. */\n historyEntries() {\n const { undo, redo } = history.entries();\n const out: { id: string; label: string }[] = [];\n for (const e of undo) out.push({ id: String(e.id), label: e.label });\n // entries().redo is already chronological: the next redo comes first.\n for (const e of redo) out.push({ id: String(e.id), label: e.label });\n return out;\n },\n\n /** Index of the \"current state\". `0` = nothing applied (initial);\n * equals the number of applied (undoable) entries —\n * `historyEntries().length` when fully redone. */\n historyIndex: () => history.undoDepth(),\n\n /** Walk to a target history index by calling undo/redo repeatedly.\n * Caps at the valid range; returns true if the index changed. */\n jumpToHistoryIndex(targetIndex: number) {\n const total = history.undoDepth() + history.redoDepth();\n const target = Math.max(0, Math.min(total, targetIndex));\n if (target === history.undoDepth()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.goto(target)));\n notify();\n return true;\n },\n\n serializeHistory: () => history.serialize(),\n\n restoreHistory(snapshot: SerializedHistory) {\n // restore() only rebuilds the stacks — no op applies, no node-state\n // mutation. The caller guarantees state already matches the head.\n history.restore(snapshot);\n notify();\n },\n\n setHistoryAdapter(fn) {\n historyAdapterAccessor = fn;\n },\n\n batch(label, fn) {\n // Captured at open, not at recordEntry: by the time the batch closes\n // the selection has already moved to wherever the batch put it.\n const outermost = batchDepth === 0;\n if (outermost) currentBatch = { label, ops: [], selectionBefore: selection };\n const ownsArrivals = outermost && openArrivals(true);\n batchDepth++;\n try {\n if (!outermost) return fn();\n try {\n const result = atomically(() => {\n const r = fn();\n if (ownsArrivals) for (const p of settleArrivals()) scene.setPose(asNodeId(p.id), p.to as TPose);\n return r;\n }, () => (currentBatch?.ops.length ?? 0) > 0);\n if (ownsArrivals) emitReflow();\n return result;\n } catch (err) {\n // Reverted already; the half-built entry must not reach history.\n currentBatch = null;\n throw err;\n }\n } finally {\n batchDepth--;\n if (ownsArrivals) {\n arrivals = null;\n reflowDue = null;\n }\n if (batchDepth === 0) {\n if (currentBatch) {\n const finished = currentBatch;\n currentBatch = null;\n // Ops were applied live as they were issued (state stays\n // readable mid-batch); recordEntry pushes without re-applying.\n if (finished.ops.length > 0) {\n history.recordEntry(finished.ops, finished.label, { selectionBefore: finished.selectionBefore });\n }\n }\n // Fire one coalesced notify if any op inside the batch dirtied\n // state. Nested batches contribute to the same flush — only the\n // outermost emits.\n if (batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n }\n },\n\n untracked(fn) {\n const prevSuppress = suppressRecording;\n const versionBefore = version;\n suppressRecording = true;\n untrackedDepth++;\n const ownsArrivals = openArrivals(true);\n batchDepth++;\n try {\n const result = atomically(() => {\n const r = fn();\n if (ownsArrivals) for (const p of settleArrivals()) scene.setPose(asNodeId(p.id), p.to as TPose);\n return r;\n }, () => false);\n if (ownsArrivals) emitReflow();\n return result;\n } finally {\n batchDepth--;\n if (ownsArrivals) {\n arrivals = null;\n reflowDue = null;\n }\n untrackedDepth--;\n suppressRecording = prevSuppress;\n if (version !== versionBefore) history.seal();\n if (batchDepth === 0 && batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n },\n\n toJSON(): SerializedScene<TData, TLayer, TPose> {\n const nodes: SerializedNode<TData, TLayer, TPose>[] = [];\n for (const n of renderOrderNodesInternal()) {\n const id = n.id;\n const out: SerializedNode<TData, TLayer, TPose> = {\n id,\n kind: n.kind,\n layer: n.layer,\n pose: n.pose,\n data: n.data,\n };\n if (n.parent != null) out.parent = n.parent;\n if (n.dependsOn === 'children') out.dependsOn = 'children';\n else if (n.dependsOn && n.dependsOn.length > 0) out.dependsOn = n.dependsOn;\n if (n.pickable === false) out.pickable = false;\n Object.assign(\n out,\n fnKeysOf(fnFields, n as unknown as FnBearingNode, 'jsonKey', (field) => {\n throw new Error(\n `Scene.toJSON: node '${id}' has ${field.spec.field} but no matching registry key. ` +\n `The function must be registered via createScene's registry option to round-trip.`\n );\n }),\n );\n nodes.push(out);\n }\n const systemLayers = state.layers.map((l) => {\n const layer: SerializedLayer<TLayer> = { id: l.id };\n if (l.visible === false) layer.visible = false;\n if (l.locked === true) layer.locked = true;\n if (l.parallax) layer.parallax = l.parallax;\n if (l.kind === 'user') {\n layer.kind = 'user';\n layer.name = l.name;\n }\n return layer;\n });\n return { version: 1, systemLayers, nodes };\n },\n\n loadState(json) {\n // Validate + map up front (throws before we touch live state on a bad\n // version or unknown registry key).\n const specs = specsFromSerialized(json, registry);\n // Reset node + layer state.\n dependents.clear();\n state.nodes.clear();\n state.roots.length = 0;\n state.layers.length = 0;\n state.layerIndex.clear();\n invalidateOrder();\n for (let i = 0; i < json.systemLayers.length; i++) {\n const spec = json.systemLayers[i];\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`Scene.loadState: duplicate system layer id \"${spec.id}\"`);\n }\n state.layers.push(layerFromSerialized(spec));\n state.layerIndex.set(spec.id, i);\n }\n // Clear history + the transient batch and function-field caches.\n history.clear();\n for (const field of fnFields) field.pending.clear();\n currentBatch = null;\n batchDepth = 0;\n batchDirty = false;\n // Rebuild nodes (bypass the log, exactly like construction).\n applyConstructionSpecs(specs);\n notify();\n },\n\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n getVersion: () => version,\n };\n\n /** Insert nodes without writing to the undo log — used by construction\n * (`options.initial`) and by `loadState`. Specs must list parents before\n * children (the order `toJSON()` emits). Throws on id collision, unknown\n * layer, non-container parent, or cross-layer subtree. */\n function applyConstructionSpecs(specs: readonly AddNodeSpec<TData, TLayer, TPose>[]): void {\n for (const spec of specs) {\n // Bypass the log: we want construction to start with empty history.\n const id = spec.id ?? generateId();\n if (state.nodes.has(id)) {\n throw new Error(`Scene: id collision on \"${id}\"`);\n }\n requireLayerIndex(spec.layer);\n const parent = spec.parent ?? null;\n if (parent !== null) {\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);\n }\n const sibs = siblingsOf(parent);\n const index = spec.index ?? sibs.length;\n runOp('kit:add', {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...(spec.pickable !== undefined ? { pickable: spec.pickable } : {}),\n });\n // No `kit:add` reaches history here, so nothing ever replays these and\n // `pruneCacheForDroppedOps` — which only scans `kit:add` — could never\n // drop the entries. A restore after `remove` comes from `kit:remove`'s\n // revert, which clones the whole node and carries every field along.\n patchNodeFunctions(spec, id, { cacheForRedo: false });\n }\n }\n\n // Apply initial nodes (not undoable — they're part of the construction).\n if (options.initial) {\n applyConstructionSpecs(options.initial);\n notify();\n }\n\n // ── Internal / test-only access ───────────────────────────────────────\n // Attach private state accessors directly on the returned object, hidden\n // behind `as unknown` because Scene<> is the public interface.\n // __clipCacheSize / __derivePathCacheSize: used only by test files to assert\n // prune behaviour.\n (scene as unknown as { __clipCacheSize: () => number }).__clipCacheSize =\n () => fnField('clipFromPose').pending.size;\n (scene as unknown as { __derivePathCacheSize: () => number }).__derivePathCacheSize =\n () => fnField('derivePath').pending.size;\n (scene as unknown as { __derivePoseCacheSize: () => number }).__derivePoseCacheSize =\n () => fnField('derivePose').pending.size;\n\n return scene;\n}\n\n/** Map a `SerializedScene` to construction specs. Shared by `sceneFromJSON`\n * (new instance) and `Scene.loadState` (in-place). Validates version and\n * resolves every `NODE_FN_FIELDS` key → function via the registry;\n * throws on an unsupported version or an unknown registry key. */\nfunction specsFromSerialized<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose>,\n registry: SceneRegistry<TPose>,\n): AddNodeSpec<TData, TLayer, TPose>[] {\n if (json.version !== 1) {\n throw new Error(`Scene: unsupported version ${json.version}; only v1 supported`);\n }\n return json.nodes.map((n) => {\n const spec: AddNodeSpec<TData, TLayer, TPose> = {\n id: n.id as NodeId,\n kind: n.kind,\n layer: n.layer,\n pose: n.pose,\n data: n.data,\n };\n if (n.parent !== undefined) spec.parent = n.parent as NodeId;\n if (n.pickable !== undefined) spec.pickable = n.pickable;\n if (n.dependsOn !== undefined) {\n spec.dependsOn = n.dependsOn === 'children'\n ? 'children'\n : (n.dependsOn as readonly NodeId[]);\n }\n const serialized = n as unknown as Record<string, string | undefined>;\n for (const field of NODE_FN_FIELDS) {\n const key = serialized[field.jsonKey];\n if (key === undefined) continue;\n const fn = (registry[field.field] as Record<string, unknown> | undefined)?.[key];\n if (!fn) {\n throw new Error(\n `Scene: unknown ${field.field} key '${key}'. ` +\n `Register a function with this key in the registry option.`,\n );\n }\n (spec as unknown as Record<string, unknown>)[field.field] = fn;\n }\n return spec;\n });\n}\n\n/** The scene's selection in the shape `createHistory` wants, for a consumer\n * building a second History over the same scene (a modality machine, a\n * journal owner) that should restore selection the way the scene's own\n * history does. */\nexport function sceneSelectionStore(scene: {\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n}): HistorySelection {\n return {\n get: () => scene.getSelection(),\n set: (ids) => scene.setSelection(ids as readonly NodeId[]),\n };\n}\n\n/** Reconstruct a Scene from a JSON snapshot produced by `scene.toJSON()`.\n * Function fields (e.g., `clipFromPose`) are resolved by string key via the\n * registry passed in `options`. Throws on unknown version, unknown registry\n * keys, or invalid scene shape (cross-layer subtrees, unknown layer ids).\n * Loaded scenes start with empty history — undo/redo is NOT serialized. */\nexport function sceneFromJSON<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose>,\n options: {\n registry?: SceneRegistry<TPose>;\n historyLimit?: number;\n coalesceWindowMs?: number;\n generateId?: () => NodeId;\n ops?: Readonly<Record<string, RegisteredOp<unknown>>>;\n layoutFrame?: UseSceneOptions<TData, TLayer, TPose>['layoutFrame'];\n } = {},\n): Scene<TData, TLayer, TPose> {\n const registry = options.registry ?? {};\n // Built empty and then loaded, so the snapshot's layer stack is rebuilt by\n // the one reader that knows how — `createScene` mints system layers only.\n const scene = createScene<TData, TLayer, TPose>({\n systemLayers: json.systemLayers.map((l) => ({ id: l.id })),\n registry,\n ...(options.historyLimit !== undefined ? { historyLimit: options.historyLimit } : {}),\n ...(options.coalesceWindowMs !== undefined ? { coalesceWindowMs: options.coalesceWindowMs } : {}),\n ...(options.generateId !== undefined ? { generateId: options.generateId } : {}),\n ...(options.ops !== undefined ? { ops: options.ops } : {}),\n ...(options.layoutFrame !== undefined ? { layoutFrame: options.layoutFrame } : {}),\n });\n scene.loadState(json);\n return scene;\n}\n"],"mappings":";;;;;;;;;;;;;AAiDA,IAAIC,IAAmB,GACjBC,WACJC,EAAS,KAAK,IAAA,CAAoB,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG;AAI5F,SAASC,GAAY,GAAqC,GAAoC;CAC5F,AAAIC,MAAO,KAAA,IAAW,OAAOC,EAAO,WAC/B,EAAO,WAAWD;AACzB;AAEA,SAASE,GACP,GACqB;CACrB,IAAMC,IAAO;EACX,IAAIC,EAAK;EACT,SAASA,EAAK,WAAW;EACzB,QAAQA,EAAK,UAAU;EACvB,GAAIA,EAAK,WAAW,EAAE,UAAUA,EAAK,SAAS,IAAI,CAAC;CACrD;CACA,OAAOA,EAAK,SAAS,SACjB;EAAE,GAAGD;EAAM,MAAM;EAAQ,MAAMC,EAAK,QAAQA,EAAK;CAAG,IACpD;EAAE,GAAGD;EAAM,MAAM;CAAS;AAChC;AAKA,SAAgBE,EACd,GAC6B;CAC7B,IAAI,CAACC,EAAQ,gBAAgBA,EAAQ,aAAa,WAAW,GAC3D,MAAU,MAAM,wDAAwD;CAI1E,IAAMC,IAA0C;EAC9C,uBAAO,IAAI,IAAI;EACf,OAAO,CAAC;EACR,QAAQ,CAAC;EACT,4BAAY,IAAI,IAAI;CACtB,GAKMC,IAAWC,GAAgBH,EAAQ,YAAY,CAAC,CAAC,GAmBjDI,IAAWC,EAA0BH,CAAQ,GAC7CI,KAAW,MACfF,E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;GAC5E,IAAI,CAACnJ,GACH,MAAU,MACR,kBAAkBH,EAAM,MAAM,QAAQsJ,EAAI,6DAE5C;GAEF,EAA6CtJ,EAAM,SAASG;EAC9D;EACA,OAAOjB;CACT,CAAC;AACH;AAMA,SAAgB6P,EAAoB,GAGf;CACnB,OAAO;EACL,WAAW5K,EAAM,aAAa;EAC9B,MAAM,MAAQA,EAAM,aAAa7B,CAAwB;CAC3D;AACF;AAOA,SAAgB0M,EACd,GACA,IAOI,CAAC,GACwB;CAC7B,IAAM1P,IAAWF,EAAQ,YAAY,CAAC,GAGhC+E,IAAQhF,EAAkC;EAC9C,cAAcwP,EAAK,aAAa,KAAK,OAAO,EAAE,IAAIpI,EAAE,GAAG,EAAE;EACzD;EACA,GAAInH,EAAQ,iBAAiB,KAAA,IAAqD,CAAC,IAA1C,EAAE,cAAcA,EAAQ,aAAa;EAC9E,GAAIA,EAAQ,qBAAqB,KAAA,IAA6D,CAAC,IAAlD,EAAE,kBAAkBA,EAAQ,iBAAiB;EAC1F,GAAIA,EAAQ,eAAe,KAAA,IAAiD,CAAC,IAAtC,EAAE,YAAYA,EAAQ,WAAW;EACxE,GAAIA,EAAQ,QAAQ,KAAA,IAAmC,CAAC,IAAxB,EAAE,KAAKA,EAAQ,IAAI;EACnD,GAAIA,EAAQ,gBAAgB,KAAA,IAAmD,CAAC,IAAxC,EAAE,aAAaA,EAAQ,YAAY;CAC7E,CAAC;CAED,OADA+E,EAAM,UAAUwK,CAAI,GACbxK;AACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":["asNodeId","s"],"sources":["../../../src/core/scene/types.ts"],"sourcesContent":["import type { Path } from '@weasel-js/geom';\nimport type { History, SerializedHistory } from '@weasel-js/history';\nimport type { ParallaxOpts } from '../viewport/parallax';\nimport type { ContainerBounds, LayoutStrategy } from '../../layout/types';\nimport type { PoseComposition } from './composeFrame';\n\n/**\n * Axis-aligned rectangle pose with optional rotation. The canonical pose\n * shape used by `composeRectPose` and the `unionBounds` helper. Rotation is\n * in radians, pivoted on the unrotated AABB center; absent === 0. Kit-side\n * code that consumes rotation already reads `pose.rotation ?? 0`\n * (`wrapNodeOutput`, `rotate/handle.ts`, `pathInWorld.ts`), so\n * the slot exists on every default scene whether or not the consumer\n * populates it.\n */\nexport interface RectPose {\n x: number;\n y: number;\n width: number;\n height: number;\n /** Rotation in radians around the unrotated AABB center. Absent === 0. */\n rotation?: number;\n}\n\n/**\n * # SceneNode — the thing in the scene\n *\n * A `SceneNode` is the single canonical unit of a weasel scene. Everything\n * the user sees on the canvas — a shape, a group, an annotation, a tile —\n * is one of these. Containers and leaves are both nodes; the kit has no\n * other concept of \"scene element.\"\n *\n * ## Three orthogonal slots\n *\n * Every node carries three independent slots, plus its tree position:\n *\n * - **`data: TData`** — app-defined payload. The kit never inspects it.\n * Color, label, kind, glyph, sample-rate, whatever the app's domain\n * calls for. Mutated via `Scene.update(id, { data })`.\n *\n * - **`pose: TPose`** — local transform, relative to the node's direct\n * parent (or world, for root nodes). Default `RectPose` is\n * `{ x, y, width, height }`, but `TPose` is fully generic so apps can\n * use rotated rects, paths, ellipses, etc. The kit composes world\n * poses via `composeWorldPose` when rendering / hit-testing / snapping.\n *\n * - **`layer: TLayer`** — a string tag associating the node with a\n * visual `RenderLayer` at draw time. Separate from `LayerRecord` (the\n * per-layer visible/locked metadata held by the `Scene`).\n *\n * Tree position lives on the node itself: every node has a `parent` (or\n * `null` for roots), and `ContainerNode` adds an ordered `children: NodeId[]`.\n *\n * ## Identity is by `NodeId`, not by reference\n *\n * Nodes are addressed by `NodeId` everywhere outside the scene tree:\n * selection is `NodeId[]`, ops reference `NodeId`s, adapter methods accept\n * `string` ids and look up the node on demand. The `Node` object itself is\n * a snapshot of current state — don't hold references to it across scene\n * updates; look up by id when you need the latest.\n *\n * Picking helpers (`pickBest`, `pickEvery`) likewise return ids, not nodes —\n * they're hit-testing primitives that stay ignorant of node payload shape.\n *\n * ## Vocabulary\n *\n * The kit-internal name is `Node`; the public re-export is `SceneNode`\n * (avoids collision with DOM `Node` at call sites). Adapter methods speak\n * the same vocabulary: `getNode`, `getNodes`, `insertNode`, `removeNode`,\n * `cloneNode`, `addNode`. Older code, demos, and comments may still say\n * \"object\" or \"item\" — those are historical aliases for the same concept.\n */\n\n/** Opaque branded id. Treat as opaque outside the kit. */\nimport type { NodeId } from '@weasel-js/routing';\nexport type { NodeId };\n\n/** Brand a string as a NodeId. */\nexport const asNodeId = (s: string): NodeId => s as NodeId;\n\n/**\n * One dependency, as a derivation reads it: the node itself and the pose it is\n * painted at.\n *\n * The node comes along because a connector legitimately reads more than a box\n * — an edge that thickens with its endpoint's weight, or routes only to nodes\n * on a given layer, is answering off `data` and `layer`. The scene already\n * invalidates dependents on `kit:setData` and `kit:setLayer` for exactly that,\n * so handing over only the pose made the invalidation pay for a read nothing\n * could perform.\n */\nexport interface DerivedDep<TPose> {\n node: Node<unknown, string, TPose>;\n /** Its override when it has one, else its own derived pose, else the pose\n * the document stores — `effectivePose`, the same answer the renderer uses. */\n pose: TPose;\n /** The path it derives, or `null` when it derives none. Read it to place\n * something *along* a dependency rather than beside it — a label on a\n * routed edge, a tick on a curve.\n *\n * Resolved on first read and memoized on the dependency, so a route costs\n * the same whether one node reads it or five, and a dependency nobody asks\n * about costs nothing. */\n readonly path: Path | null;\n}\n\n/** Computes a node's path from its dependencies: the type of a node's\n * `derivePath` and of each entry in `SceneRegistry.derivePath`. */\nexport type DerivePathFn<TPose> = (\n node: Node<unknown, string, TPose>,\n deps: readonly (DerivedDep<TPose> | undefined)[],\n) => Path | null;\n\n/** Computes a node's pose from its dependencies: the type of a node's\n * `derivePose` and of each entry in `SceneRegistry.derivePose`. */\nexport type DerivePoseFn<TPose> = (\n node: Node<unknown, string, TPose>,\n deps: readonly (DerivedDep<TPose> | undefined)[],\n) => TPose | null;\n\ninterface NodeBase<TData, TLayer extends string, TPose> {\n id: NodeId;\n layer: TLayer;\n pose: TPose;\n data: TData;\n parent: NodeId | null;\n /** Nodes whose poses this node's geometry is computed from. Fixed at add\n * time. Absent or empty means the node's geometry is authored, which is the\n * normal case.\n *\n * `'children'` means \"my own children, in child order\" — a container that\n * hugs its contents, which a fixed id list cannot express because\n * reparenting would have to maintain it. The two forms differ in lifetime\n * as well as in membership: deleting a node deletes everything that names\n * it in `dependsOn`, but a container outlives the children it derives\n * from — an emptied group is still a group. */\n dependsOn?: readonly NodeId[] | 'children';\n /** Whether the hit-test walk can return this node. Default `true`; `false`\n * makes it transparent to picking, so a click on it lands on whatever is\n * behind — normally its own container.\n *\n * For content a container owns rather than content the user selects on its\n * own: the label inside a box, a body's rows. Without it the innermost hit\n * wins, and dragging a labeled box moves the label out of the box. It does\n * not hide the node from anything else — it still paints, still clips, and\n * a consumer can still select it by id. */\n pickable?: boolean;\n /** Computes this node's path from its dependencies, in `dependsOn` order —\n * each one the node and the pose it is painted at.\n * A dependency that has been removed arrives as `undefined`.\n * Returning `null` means \"nothing to draw right now\". Re-evaluated when a\n * dependency's world pose changes, never authored. Absolute-pose `Scene`\n * makes that the dependency's own pose, and an ancestor's move reaches it as\n * a `setPose` of its own from the container cascade.\n * `node` is deliberately widened: naming `TData`/`TLayer` here puts them in\n * a contravariant position, making `Scene` invariant in both and breaking\n * assignment kit-wide. The cost is that a `derivePath` casts to read `node.data`. */\n derivePath?: DerivePathFn<TPose>;\n /** Computes this node's pose from its dependencies' poses, the same way\n * `derivePath` computes its path — same `dependsOn` list, same widened\n * `node`, same registry-keyed serialization.\n *\n * Where a derived path is resolved at paint time and reaches only the\n * painter, a derived pose is what the node *is* at: it feeds bounds,\n * hit-testing, selection chrome, snapping and layout, and every reader\n * gets it through `effectivePose`. A pose override still wins over it —\n * that is what lets a drag preview a node the document says is elsewhere.\n *\n * Returning `null` means \"I have nothing to derive from right now\", and\n * the node falls back to its authored `pose`. `setPose` on a derived node\n * still writes that authored pose; it is simply not what anything reads. */\n derivePose?: DerivePoseFn<TPose>;\n}\n\n/** A node with no children — a shape, a label, an image. */\nexport interface LeafNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'leaf';\n}\n\n/** A node with an ordered list of children. This is the real group: what\n * Cmd+G creates, what SVG `<g>` round-trips to. A container has its own pose,\n * which its children's poses are relative to, and may optionally clip them. */\nexport interface ContainerNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'container';\n children: NodeId[];\n /** Optional clip-path source. Re-evaluated each render. Returning `null`\n * means \"no clip for this container right now\"; an empty / zero-area path\n * means \"clip everything out\" (children render nowhere). When set, the\n * renderer rasterizes the returned path into the stencil buffer and\n * paints descendants only where it covers. */\n clipFromPose?: (pose: TPose) => Path | null;\n /** How this container arranges its children. Whenever the container's\n * child set or order changes, or its bounds change size, the scene hands\n * the change to the strategy — `depart` for children that left it,\n * `arrive` for children that joined it, `childPoses` otherwise — and records the poses it writes in the same\n * undo entry as the change. A drag reads it too: it is the layout `move`\n * reflows and drops against. */\n layout?: LayoutStrategy<TPose>;\n}\n\n/** A pose a container's layout wrote — reported by {@link Scene.onReflow} —\n * in the node's stored frame. */\nexport interface LayoutMove<TPose> {\n id: NodeId;\n from: TPose;\n to: TPose;\n}\n\n/** How a scene reads a laid-out container's bounds and folds poses to the\n * world frame a {@link LayoutStrategy} works in. */\nexport interface LayoutFrame<TPose> {\n /** The container's bounds, from its world pose. Default: the pose's own\n * `x`/`y`/`width`/`height`; a pose without them is not laid out. */\n bounds?(pose: TPose): ContainerBounds | null;\n /** `pose` resized from bounds `from` to `to`, for a layout that grows its\n * container. Default: `to`'s fields written over the pose. */\n remap?(pose: TPose, from: ContainerBounds, to: ContainerBounds): TPose;\n /** Omit for the absolute-pose model. A scene whose canvas composes poses\n * (`<SceneCanvas poseComposition>`) passes the same strategy here. */\n composition?: PoseComposition<TPose>;\n}\n\n/** A node in the scene tree: either a leaf or a container. Re-exported\n * publicly as `SceneNode`, to avoid colliding with the DOM's `Node`. */\nexport type Node<TData, TLayer extends string, TPose = RectPose> =\n | LeafNode<TData, TLayer, TPose>\n | ContainerNode<TData, TLayer, TPose>;\n\ninterface LayerRecordBase<TLayer extends string> {\n id: TLayer;\n visible: boolean;\n locked: boolean;\n /** Draw this layer as a parallax plane: through a view derived from the\n * camera's (see `deriveParallaxView`), and picked through the same one.\n * Absent means the layer moves with the camera. */\n parallax?: ParallaxOpts;\n}\n\n/** A layer declared when the scene was created. Fixed set, no display name —\n * these are the kit's own render bands, not something a user manages. */\nexport interface SystemLayerRecord<TLayer extends string>\n extends LayerRecordBase<TLayer> {\n kind: 'system';\n}\n\n/** A layer the user created and can rename, reorder or delete. */\nexport interface UserLayerRecord<TLayer extends string>\n extends LayerRecordBase<TLayer> {\n kind: 'user';\n name: string;\n}\n\n/** Per-layer metadata held by the scene: whether it is visible and locked,\n * and where it sits in the render stack. Distinct from a node's `layer` tag,\n * which merely names one of these. */\nexport type LayerRecord<TLayer extends string> =\n | SystemLayerRecord<TLayer>\n | UserLayerRecord<TLayer>;\n\n/** What `Scene.add` needs to mint a node. Everything except the id is\n * required; the id is generated unless one is supplied. */\nexport interface AddNodeSpec<TData, TLayer extends string, TPose = RectPose> {\n kind: 'leaf' | 'container';\n layer: TLayer;\n pose: TPose;\n data: TData;\n parent?: NodeId | null;\n index?: number;\n /** Explicit id wins over the Scene's `generateId` and the kit default. */\n id?: NodeId;\n /** Mirrors `SceneNode.pickable`. Omit for the default, which is pickable. */\n pickable?: boolean;\n /** Only meaningful when `kind === 'container'`. Attach a clip-path function\n * to the node; ignored for leaves. Mirrors `ContainerNode.clipFromPose`. */\n clipFromPose?: (pose: TPose) => Path | null;\n /** Mirrors `SceneNode.dependsOn`. */\n dependsOn?: readonly NodeId[] | 'children';\n /** Mirrors `SceneNode.derivePath`. Taken as a live function; its registry key is\n * looked up from it, never passed in. */\n derivePath?: DerivePathFn<TPose>;\n /** Mirrors `SceneNode.derivePose`, on the same terms as `derivePath`. */\n derivePose?: DerivePoseFn<TPose>;\n /** Mirrors `ContainerNode.layout`; ignored for leaves. */\n layout?: LayoutStrategy<TPose>;\n}\n\n/** A custom scene mutation registered with `Scene.registerOp`: how to apply\n * it and how to undo it. The pair is what makes it participate in history. */\nexport interface RegisteredOp<P> {\n apply: (payload: P) => void;\n revert: (payload: P) => void;\n}\n\n/** One of the layers a scene is created with. */\nexport interface SystemLayerSpec<TLayer extends string> {\n id: TLayer;\n visible?: boolean;\n locked?: boolean;\n /** See `LayerRecord.parallax`. */\n parallax?: ParallaxOpts;\n}\n\n/** Argument to `Scene.addLayer`. Always produces a `UserLayerRecord`\n * (`kind: 'user'`). */\nexport interface AddLayerSpec<TLayer extends string> {\n id: TLayer;\n name: string;\n /** Default `true`. */\n visible?: boolean;\n /** Default `false`. */\n locked?: boolean;\n /** See `LayerRecord.parallax`. */\n parallax?: ParallaxOpts;\n /** Render-stack position. Default: top of stack (highest render index). */\n index?: number;\n}\n\n/** One layer as it appears in a snapshot. A snapshot written before layer\n * kind was serialized carries neither field, and loads as a system layer —\n * which is what every layer in such a snapshot was. */\nexport interface SerializedLayer<TLayer extends string>\n extends SystemLayerSpec<TLayer> {\n kind?: 'system' | 'user';\n /** Present on a user layer, absent on a system one. */\n name?: string;\n}\n\n/** JSON-serializable shape of a Scene's current state. Produced by\n * `scene.toJSON()`; consumed by `sceneFromJSON()`. Function fields\n * (e.g., `clipFromPose`) appear as string keys (`clipFromPoseKey`) and\n * are resolved through `SceneRegistry` at load time. */\nexport interface SerializedScene<TData, TLayer extends string, TPose> {\n version: 1;\n /** The whole layer stack, system and user alike — the name predates user\n * layers and is kept so existing snapshots still parse. */\n systemLayers: readonly SerializedLayer<TLayer>[];\n nodes: readonly SerializedNode<TData, TLayer, TPose>[];\n}\n\n/** JSON-serializable shape of a single node. Mirrors `AddNodeSpec` but\n * with function fields replaced by registry keys. */\nexport interface SerializedNode<TData, TLayer extends string, TPose> {\n id: string;\n kind: 'leaf' | 'container';\n layer: TLayer;\n pose: TPose;\n data: TData;\n /** Parent id; omitted for roots. */\n parent?: string;\n /** Registry key for the container's clip-path factory.\n * Containers only; omitted when the container has no clip. */\n clipFromPoseKey?: string;\n /** Ids this node's geometry derives from, or `'children'`. Omitted when it\n * derives from nothing. */\n dependsOn?: readonly string[] | 'children';\n /** Mirrors `SceneNode.pickable`. Omitted when the node is pickable. */\n pickable?: boolean;\n /** Registry key for the node's `derivePath` function. Omitted when it has none. */\n derivePathKey?: string;\n /** Registry key for the node's `derivePose` function. Omitted when it has none. */\n derivePoseKey?: string;\n /** Registry key for the container's layout strategy. Omitted when it has none. */\n layoutKey?: string;\n}\n\n/** Per-scene registry mapping string keys to live function references.\n * Passed to `createScene({ ..., registry })` and `sceneFromJSON(json, { registry })`.\n * Each function-field type has its own keyed map. */\nexport interface SceneRegistry<TPose> {\n /** Maps registry keys to `clipFromPose` factory functions for container nodes. */\n clipFromPose?: Readonly<Record<string, (pose: TPose) => Path | null>>;\n /** Maps registry keys to `derivePath` functions for nodes with `dependsOn`. */\n derivePath?: Readonly<Record<string, DerivePathFn<TPose>>>;\n /** Maps registry keys to `derivePose` functions for nodes with `dependsOn`. */\n derivePose?: Readonly<Record<string, DerivePoseFn<TPose>>>;\n /** Maps registry keys to container layout strategies. */\n layout?: Readonly<Record<string, LayoutStrategy<TPose>>>;\n // A new function field is a row in `NODE_FN_FIELDS` (core/scene/nodeFnFields.ts)\n // plus its entry here; the field name is the registry key by construction.\n}\n\n/**\n * Decides what one edit's changes to containers do to their children.\n * `arrivals` maps each container to the ids that joined it — by an `add`\n * under it or a `move` into it, whatever op or call made them — in the order\n * they arrived. `changed` names every container whose child set or order\n * changed, or whose pose changed size, arrivals included. Both are read once\n * the edit's other mutations have landed.\n *\n * Return the poses to write, in each node's stored frame; they become part of\n * the same edit, and so of the same undo step. An empty map writes nothing.\n * Return `null` to refuse: the whole edit is reverted (see\n * `SceneArrivalRefused`).\n *\n * Runs only for live edits. Undo, redo and a restored history replay the\n * arrangement that was decided the first time. With none installed, a scene\n * holding declared layouts (`ContainerNode.layout`) runs its own.\n */\nexport type SceneArrivalHandler<TPose> = (\n arrivals: ReadonlyMap<NodeId, readonly NodeId[]>,\n changed: ReadonlySet<NodeId>,\n /** The nodes that left each container in the edit, by the container they\n * left — removed, or moved out. */\n departures: ReadonlyMap<NodeId, readonly NodeId[]>,\n) => ReadonlyMap<NodeId, TPose> | null;\n\n/** Options for `useScene` — the layers the scene has, what it starts out\n * holding, and how its history behaves. */\nexport interface UseSceneOptions<TData, TLayer extends string, TPose = RectPose> {\n systemLayers: readonly SystemLayerSpec<TLayer>[];\n initial?: readonly AddNodeSpec<TData, TLayer, TPose>[];\n ops?: Readonly<Record<string, RegisteredOp<unknown>>>;\n historyLimit?: number;\n /** Window (ms) within which consecutive same-shaped mutations merge into\n * the previous undo entry (matching per-op coalesce keys — e.g. repeated\n * `setPose` on the same node, or repeated `applyBatch` calls whose ops\n * carry matching `coalesceKey` multisets). `0` (default) disables\n * coalescing: every mutation is a discrete undo entry. Undo of a\n * coalesced entry returns to the state before the first merged mutation;\n * redo restores the latest. `scene.batch` entries never coalesce. */\n coalesceWindowMs?: number;\n generateId?: () => NodeId;\n /** Per-scene registry for non-serializable function fields (clipFromPose, etc.).\n * Required only when serializing/deserializing scenes that use function fields. */\n registry?: SceneRegistry<TPose>;\n /** How laid-out containers are measured. See {@link LayoutFrame}. */\n layoutFrame?: LayoutFrame<TPose>;\n /** When supplied, `scene.applyOps(ops, label)` consults this on every call.\n * If it returns a non-null `Journal`, ops are routed to the journal's\n * `applyBatch` instead of recording a new parent-history entry. The journal\n * drives adapter mutation internally (via `op.apply(adapter)`), so the\n * scene state changes as normal; only the history tracking differs.\n *\n * The accessor is called on every `applyOps` invocation so the caller can\n * swap the active journal in and out by updating the closure's reference\n * (e.g., an app's mode machine holds `let activeJournal: Journal | null`\n * and the accessor reads that variable).\n *\n * When the accessor isn't known at scene-construction time (typical for\n * mode machines that depend on `scene.history`), pass nothing here and\n * wire it after construction via `scene.setActiveJournalAccessor(fn)`. */\n getActiveJournal?: () => import('@weasel-js/history').Journal | null;\n /** Re-render the host on every scene mutation. Default `true`. Set `false`\n * when the scene is read by a frame loop rather than by a render — a game\n * loop, a simulation — and nothing in the host's DOM derives from it.\n * Read by `useScene`; `createScene` ignores it. */\n subscribe?: boolean;\n}\n\n/**\n * One node's ephemeral presentation override — what a frame loop wants to say\n * about a node without saying it about the document.\n *\n * Not document content: never recorded in history, never in `toJSON`, and\n * writing one does not bump `Scene.getVersion()`. Hoist one entry per node and\n * mutate it in place on a frame loop; `PoseOverrides.commit()` is what makes a\n * mutation visible.\n */\nexport interface PoseOverride<TPose> {\n /** Replaces the node's document pose everywhere the render and hit-test\n * paths read one, including the clip a container derives from its pose, and\n * winning over a `derivePose`. Resolved by `effectivePose` — reading\n * `node.pose` directly is how those paths came to disagree about where a\n * node is. */\n pose?: TPose;\n /** Multiplied into the node's painted alpha, on top of any `alphaFor`. */\n alpha?: number;\n}\n\n/**\n * The scene's ephemeral per-node overrides — see {@link PoseOverride}.\n *\n * The intended shape of a frame is: `set` each node once, mutate the entries\n * in place per frame, `commit()` once. `commit` is not optional bookkeeping —\n * the painter memo keys on pose *reference*, so a mutation without a commit\n * paints the previous frame with no error.\n *\n * To promote a frame to document state (dropping a drag, baking an animation),\n * write it once through `Scene.setPose` and `clear` the override.\n */\nexport interface PoseOverrides<TPose> {\n /** Store `entry` for `id` **by reference**; the caller keeps mutating it. */\n set(id: NodeId, entry: PoseOverride<TPose>): void;\n get(id: NodeId): PoseOverride<TPose> | undefined;\n has(id: NodeId): boolean;\n /** The overridden ids, as a snapshot array. */\n ids(): readonly NodeId[];\n clear(id: NodeId): void;\n clearAll(): void;\n /** Publish this frame's in-place mutations: invalidate the painter memo for\n * every overridden node, then notify subscribers. */\n commit(): void;\n /** Notified after every write. The canvas uses this to repaint without a\n * scene version bump. */\n subscribe(fn: () => void): () => void;\n /** Monotonic write counter. A snapshot for observers that poll. */\n getGeneration(): number;\n}\n\n/**\n * The kit-owned scene tree: nodes, layers, and the undo history over both.\n *\n * A scene is logical, not visual — it says what exists and where, and nothing\n * about how it is painted. Every mutating method is undoable, and reads are\n * snapshots rather than live views. Nodes are addressed by `NodeId`; hold ids\n * across mutations, not node objects.\n *\n * Three type parameters keep it domain-agnostic: `TData` is the app's payload,\n * which the kit never inspects; `TPose` is the transform shape, `RectPose` by\n * default; `TLayer` is the union of layer names.\n */\nexport interface Scene<TData, TLayer extends string, TPose = RectPose> {\n // Reads\n readonly nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>;\n readonly roots: readonly NodeId[];\n readonly layers: readonly LayerRecord<TLayer>[];\n /** The registry this scene resolves node functions against — the consumer's\n * entries over the kit's. */\n readonly registry: SceneRegistry<TPose>;\n get(id: NodeId): Node<TData, TLayer, TPose> | undefined;\n /** A token for the node `id` names right now, for telling one node from a\n * later one that reuses its id. It holds for as long as the node stays in\n * the scene, whatever edits it takes, and is different every time the id\n * enters the scene — by `add`, by an undo or redo that brings it back, or\n * by `loadState`. `undefined` when `id` is not in the scene. Compare tokens\n * for equality only; their order means nothing. */\n incarnation(id: NodeId): number | undefined;\n childrenOf(id: NodeId): readonly NodeId[];\n ancestorsOf(id: NodeId): readonly NodeId[];\n renderOrder(): Iterable<NodeId>;\n /** The same layer-major sequence as {@link Scene.renderOrder}, as the nodes\n * themselves. Prefer this wherever the ids are only going to be resolved\n * back to nodes: the traversal already holds them, and re-looking each one\n * up was ~40% of the area hit-test's per-node cost. Cached until a\n * structural edit, so repeat calls hand back the same array — a snapshot,\n * not a live view, and not yours to mutate. */\n renderOrderNodes(): readonly Node<TData, TLayer, TPose>[];\n /** The nodes on one layer, in render order. Cached alongside\n * {@link Scene.renderOrderNodes} until a structural edit, so a caller that\n * only cares about one layer pays the tree walk once rather than once per\n * call. A snapshot, not a live view, and not yours to mutate. An unknown\n * layer id yields an empty array. */\n nodesOnLayer(layer: TLayer): readonly Node<TData, TLayer, TPose>[];\n\n // Mutations (all auto-undoable)\n add(spec: AddNodeSpec<TData, TLayer, TPose>): NodeId;\n /** Delete `id`, its **entire subtree**, and **everything that derives from**\n * any of those nodes — a node listing one of them in `dependsOn` goes too,\n * along with its own subtree, transitively. A dependent can live anywhere in\n * the tree, so this deletes nodes the caller never named and may unlink\n * several disjoint subtrees at once. Recorded as one undoable step; `undo()`\n * restores every one of them where it was, child order intact. */\n remove(id: NodeId): void;\n /** {@link remove} over several roots at once, as a **single** undoable step.\n * Ids resolve against the tree as it stands at the call, so an id that\n * another one would cascade away is absorbed rather than removed twice —\n * which is what makes it safe to pass a whole selection. Throws if any id is\n * not in the scene; an empty list does nothing and records no step. */\n removeMany(ids: readonly NodeId[]): void;\n /** Every node {@link removeMany} would take if given `ids`: each id, its\n * subtree, everything deriving from any of those, and those nodes' subtrees\n * in turn. The authoritative answer — the cascade relations live here, and\n * a caller reconstructing them from `dependsOn` and `children` drifts the\n * moment a third one is added. Ids not in the scene come back unchanged.\n *\n * A set, not a restore order: a dependent can be reached before the parent\n * it sits under, which is also in the closure. */\n removalClosure(ids: readonly NodeId[]): readonly NodeId[];\n update(id: NodeId, patch: { data: TData }): void;\n setPose(id: NodeId, pose: TPose): void;\n /** Retag `id` to `layer`. On a **container this cascades**: every descendant\n * is moved to the same layer, recorded as a **single** undo step.\n *\n * Invariants:\n * - **Layer floor** — a child may not render below its parent, so retagging\n * to a layer *below* the node's parent throws. Retagging to the parent's\n * layer or any higher one is allowed; a node with no parent is\n * unconstrained.\n * - **No-op elision** — setting the layer a node already has does nothing\n * and pushes **no** history entry. */\n setLayer(id: NodeId, layer: TLayer): void;\n /** Point `id` at a different set of dependencies — retargeting an edge's end\n * onto another node, or switching a container between an id list and\n * `'children'`. Recorded as one undoable step.\n *\n * Order is significant: a derivation reads its dependencies positionally,\n * so `[b, a]` is not `[a, b]`. Ids need not be in the scene — a declared\n * dependency that appears later invalidates the node when it does, the same\n * as one declared at `add`. Passing `undefined` drops the declaration, after\n * which nothing cascades the node away.\n *\n * **No-op elision** — declaring what the node already declares does nothing\n * and pushes no history entry. */\n setDependsOn(id: NodeId, dependsOn: readonly NodeId[] | 'children' | undefined): void;\n /** Give container `id` a different layout — a strategy, its key in\n * `SceneRegistry.layout`, or `null` for none — and re-arrange its children\n * under it, as one undoable step. Throws for a leaf, or a key the registry\n * does not hold. A registered layout is recorded by its key, so a\n * serialized history restores it; an unregistered one lives only as long\n * as the session.\n *\n * **No-op elision** — setting the layout a container already has does\n * nothing and pushes no history entry. */\n setLayout(id: NodeId, layout: LayoutStrategy<TPose> | string | null): void;\n /** Reparent `id` under `parent` (or to a root when `parent` is `null`) at\n * `index` within the new sibling list, appending when `index` is omitted.\n * Siblings are reindexed. Recorded as one undoable step.\n *\n * Rejected (throws) when:\n * - `parent` exists but is a **leaf**, not a container;\n * - the move would form a **cycle** — `parent` is `id` itself or one of\n * `id`'s own descendants;\n * - it would drop `id` **below its new parent's layer** (child may not\n * render below its parent).\n *\n * `move(id, null)` — detaching to a root — is always allowed regardless of\n * layer, since a root has no parent to render beneath. */\n move(id: NodeId, parent: NodeId | null, index?: number): void;\n /** Shift `id` to `index` within its **current** parent's child list. Unlike\n * {@link move}, the parent never changes — only sibling order. */\n reorder(id: NodeId, index: number): void;\n setLayerVisible(layer: TLayer, visible: boolean): void;\n /** Lock or unlock a layer. A locked layer still paints, but its nodes are\n * out of reach: picking and area selection pass over them, the selection\n * drops them, and every node mutation on them throws. Locking is never\n * blocked by the lock, and neither are the other layer operations. */\n setLayerLocked(layer: TLayer, locked: boolean): void;\n /** Set or clear (`undefined`) a layer's parallax — see\n * `LayerRecord.parallax`. Undoable; an animation tweening it writes inside\n * {@link Scene.untracked} so no frame becomes an undo step. */\n setLayerParallax(layer: TLayer, parallax: ParallaxOpts | undefined): void;\n /** Whether `id` sits on a locked layer or under a container that does.\n * A container's lock covers its whole subtree, whatever layers the\n * descendants are tagged to. An id not in the scene is not locked. */\n isLocked(id: NodeId): boolean;\n /** Run `fn` with the lock guard lifted, for a programmatic edit that has to\n * reach a locked node. Undo and redo never need it. */\n unlocked<T>(fn: () => T): T;\n addLayer(spec: AddLayerSpec<TLayer>): void;\n /** Drop a user layer and every node tagged to it, as one undoable step.\n * Removal cascades, so this also deletes nodes **on other layers** that\n * derive from a node on this one. */\n removeLayer(layer: TLayer): void;\n renameLayer(layer: TLayer, name: string): void;\n moveLayer(layer: TLayer, index: number): void;\n\n // Custom op seam\n registerOp<P>(kind: string, handler: RegisteredOp<P>): void;\n recordOp<P>(op: { kind: string; payload: P }): void;\n\n /** Install (or clear) the active-journal accessor after scene construction.\n * Useful when the journal source (typically a mode machine) is built\n * with `scene.history` as a dependency — a chicken-and-egg situation\n * where the accessor can't be passed in via `UseSceneOptions`.\n *\n * Pass `null` to detach. Overrides any `getActiveJournal` set in\n * `UseSceneOptions`. */\n setActiveJournalAccessor(\n fn: (() => import('@weasel-js/history').Journal | null) | null,\n ): void;\n\n /** Install what the scene does when nodes join a container, replacing any\n * handler installed before; `null` removes it. Returns a function that\n * removes this handler, and does nothing once another has replaced it.\n * See {@link SceneArrivalHandler}. */\n setArrivalHandler(handler: SceneArrivalHandler<TPose> | null): () => void;\n\n /** Apply a batch of ops with journal-aware routing.\n *\n * - **Without active journal** (or no `getActiveJournal` in options):\n * the ops themselves are recorded as one undo entry on the scene's own\n * history, rebound to `adapter` — undo replays each op's `invert()`\n * against that same adapter. Consecutive `applyBatch` entries can\n * coalesce via matching op `coalesceKey`s when the scene opts into\n * `coalesceWindowMs`.\n * - **With active journal**: routes ops to `journal.applyBatch(ops, label)`.\n * The scene's history recording is suppressed for the duration so the\n * journal's inner history — not the scene's undo stack — tracks the batch.\n * Mutations still happen on `adapter` / scene state.\n *\n * `adapter` must be the same adapter the ops expect (typically a\n * `SceneCanvasAdapter`). Pass `this` from `sceneToAdapter` or a compatible\n * adapter. */\n applyBatch(ops: import('core/ops/types').Op[], label: string, adapter: unknown): void;\n\n // Selection\n\n /** The transient set of active ids — \"operate on these N as a unit\".\n * Shared by every view over this scene unless a view supplies its own\n * (see `CanvasView.selection`). Not document content: it never appears\n * in `toJSON`. It does ride on history entries, so undo and redo put\n * back the selection an edit was made under; changing it is never an\n * undo step of its own. */\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n\n // Ephemeral presentation state\n\n /** Per-node pose / alpha overrides the render and hit-test paths read\n * through. Like {@link Scene.getSelection} this is not document content:\n * writes are never recorded, never serialized, and do not bump\n * {@link Scene.getVersion}. See {@link PoseOverrides}. */\n readonly overrides: PoseOverrides<TPose>;\n\n // History\n /** The scene's undo/redo engine, in the shape `@weasel-js/history` defines —\n * what the kit's `undo` / `redo` actions resolve their `history` dep to, and\n * what a mode machine opens journals against. Mutating members route through\n * the scene's own wrappers, so an undo driven through this bumps\n * {@link Scene.getVersion} and notifies subscribers exactly as\n * {@link Scene.undo} does; `getVersion` / `subscribe` on it report the\n * engine's history version, not the scene's. */\n readonly history: History;\n undo(): boolean;\n redo(): boolean;\n canUndo(): boolean;\n canRedo(): boolean;\n batch<T>(label: string, fn: () => T): T;\n /** The layout container `id` declares, or `null` for a leaf or a\n * container that declares none. */\n layoutOf(id: NodeId): LayoutStrategy<TPose> | null;\n /** Called with the poses each live edit's layout pass wrote, after the\n * edit lands — never for an undo or redo, which restore poses rather than\n * arrange them. What a reflow animation glides from. */\n onReflow(listener: (moves: readonly LayoutMove<TPose>[]) => void): () => void;\n /** Run `fn` with every mutation applied but none recorded — for writes\n * that are not edits, such as a simulation stepping poses each frame.\n * Undo and redo move between recorded states and never restore an\n * untracked write; the next recorded change starts from whatever the\n * untracked writes left, so undoing it lands there. A `batch` inside\n * records nothing; inside a `batch`, these writes stay out of its entry.\n * Notifies once, reverts `fn`'s writes if it throws, and throws on\n * `applyBatch` and `history.apply` / `applyOps`, which exist to record. */\n untracked<T>(fn: () => T): T;\n /** Read-only snapshot of every history entry currently reachable from\n * the present state. Oldest applied first, then redoable entries in\n * the order they'd be re-applied. Each entry id is stable. */\n historyEntries(): readonly { id: string; label: string }[];\n /** Index of the \"current state\". Equals the count of applied entries;\n * `0` means \"nothing applied\" (initial). */\n historyIndex(): number;\n /** Jump to the given history index by calling undo/redo repeatedly.\n * Clamps to [0, total]. Returns true if any movement occurred. */\n jumpToHistoryIndex(index: number): boolean;\n\n // History persistence\n /** Snapshot the undo/redo history in a JSON-serializable form (the\n * engine's `SerializedHistory`). Entries containing any nameless op are\n * dropped (hand-rolled anonymous ops passed to `applyBatch`); kit and\n * consumer-registered ops always carry names. Payload JSON-safety\n * (e.g. typed arrays inside poses) is the caller's concern. Do not call\n * mid-`batch` — the open batch's ops are not yet recorded. */\n serializeHistory(): SerializedHistory;\n /** Replace the undo/redo history from a `serializeHistory()` snapshot.\n * Call on a scene whose node/layer state already matches the snapshot's\n * head state (i.e. right after `loadState` from the paired scene\n * snapshot); node state is NOT mutated. Ops re-registered via\n * `registerOp` before this call round-trip; unknown kinds become no-op\n * placeholders; external ops rebuild via the global op-factory registry\n * and replay against the `setHistoryAdapter` accessor. Restored entries\n * never coalesce with new ones. Notifies once. Do not call mid-`batch`:\n * the stacks are replaced underneath the open batch, whose eventual\n * flush would graft onto (and evict against) the restored stacks. */\n restoreHistory(snapshot: SerializedHistory): void;\n /** Install (or clear with `null`) the accessor for the adapter that\n * RESTORED external ops (recorded via `applyBatch`, rebuilt from a\n * `restoreHistory` snapshot) apply against on undo/redo. Resolved lazily\n * at each apply, so wiring order relative to `restoreHistory` doesn't\n * matter. Live `applyBatch` entries are unaffected (they bind their\n * call-site adapter). If unset when a restored op applies, the op is a\n * debug-warned no-op. */\n setHistoryAdapter(fn: (() => unknown) | null): void;\n\n // Serialization\n /** Snapshot the current scene state to a JSON-serializable shape.\n * History (undo/redo stacks) is NOT captured. Function fields like\n * `ContainerNode.clipFromPose` are translated to string keys via the\n * scene's registry; throws if any function field has no matching key. */\n toJSON(): SerializedScene<TData, TLayer, TPose>;\n /** Replace this scene's entire node + layer state in place from a snapshot\n * produced by `toJSON()`. Unlike `sceneFromJSON`, the existing Scene\n * instance is preserved — holders such as `<SceneCanvas>` keep their\n * reference. History (undo/redo) is cleared, matching `sceneFromJSON`.\n * Bumps `getVersion()` and notifies subscribers exactly once.\n *\n * Throws on an unsupported version or unknown registry/layer ids; on a\n * malformed snapshot the scene is left empty or partially populated (callers should treat a\n * `loadState` throw as fatal and reload). Snapshots from `toJSON()` are\n * always well-formed. */\n loadState(json: SerializedScene<TData, TLayer, TPose>): void;\n\n // Subscription (used by useScene; also for non-React observers)\n subscribe(listener: () => void): () => void;\n /** Monotonically increasing version. Snapshot for `useSyncExternalStore`. */\n getVersion(): number;\n}\n"],"mappings":";AA8EA,IAAaA,KAAY,MAAsBC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { asNodeId as e } from "./types.js";
|
|
2
|
+
import { createScene as t } from "./scene.js";
|
|
3
|
+
import { useRef as n, useSyncExternalStore as r } from "react";
|
|
4
|
+
//#region src/core/scene/useScene.ts
|
|
5
|
+
var i = () => () => {}, a = "default";
|
|
6
|
+
function o(e) {
|
|
7
|
+
return !!e && typeof e == "object" && "items" in e && !("systemLayers" in e);
|
|
8
|
+
}
|
|
9
|
+
function s(n) {
|
|
10
|
+
return o(n) ? t({
|
|
11
|
+
systemLayers: [{ id: a }],
|
|
12
|
+
historyLimit: n.historyLimit,
|
|
13
|
+
generateId: n.generateId,
|
|
14
|
+
initial: n.items.map((t) => ({
|
|
15
|
+
kind: "leaf",
|
|
16
|
+
layer: a,
|
|
17
|
+
pose: t,
|
|
18
|
+
data: t,
|
|
19
|
+
id: e(t.id)
|
|
20
|
+
}))
|
|
21
|
+
}) : t(n);
|
|
22
|
+
}
|
|
23
|
+
function c(e) {
|
|
24
|
+
let t = n(null);
|
|
25
|
+
t.current === null && (t.current = s(e));
|
|
26
|
+
let a = t.current, o = e?.subscribe !== !1;
|
|
27
|
+
return r(o ? a.subscribe : i, a.getVersion, a.getVersion), a;
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
export { c as useScene };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=useScene.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useScene.js","names":["NEVER_SUBSCRIBE","DEFAULT_LAYER","isTrivialOptions","options","buildScene","createScene","item","asNodeId","useScene","sceneRef","useRef","scene","subscribed","useSyncExternalStore"],"sources":["../../../src/core/scene/useScene.ts"],"sourcesContent":["import { useRef, useSyncExternalStore } from 'react';\nimport { createScene } from './scene';\nimport type { NodeId, Scene, UseSceneOptions } from './types';\nimport { asNodeId } from './types';\n\n/** Trivial-form options: a flat list of items, no layers, no parenting. The\n * full `useScene` form is reachable any time by adding `systemLayers`.\n *\n * `historyLimit` and `generateId` are accepted because they're orthogonal to\n * the \"what's in the scene\" question. `ops` is intentionally omitted — if\n * you need custom ops, your app state already lives outside the \"flat list\n * of rects\" frame and you should reach for the full `UseSceneOptions`. */\nexport interface UseSceneTrivialOptions<TItem extends { id: string }> {\n items: readonly TItem[];\n historyLimit?: number;\n generateId?: () => NodeId;\n /** Re-render the host on every scene mutation. Default `true`. See\n * {@link UseSceneOptions.subscribe}. */\n subscribe?: boolean;\n}\n\n/** A subscribe function that never notifies. `useSyncExternalStore` still runs\n * (hooks are unconditional) but the host is never re-rendered by the store. */\nconst NEVER_SUBSCRIBE = () => () => {};\n\nconst DEFAULT_LAYER = 'default' as const;\ntype DefaultLayer = typeof DEFAULT_LAYER;\n\nfunction isTrivialOptions<TItem extends { id: string }>(\n options: unknown,\n): options is UseSceneTrivialOptions<TItem> {\n return (\n !!options\n && typeof options === 'object'\n && 'items' in (options as Record<string, unknown>)\n && !('systemLayers' in (options as Record<string, unknown>))\n );\n}\n\nfunction buildScene(options: unknown): Scene<unknown, string, unknown> {\n if (!isTrivialOptions(options)) {\n return createScene(options as UseSceneOptions<unknown, string, unknown>) as Scene<unknown, string, unknown>;\n }\n return createScene<unknown, DefaultLayer, unknown>({\n systemLayers: [{ id: DEFAULT_LAYER }],\n historyLimit: options.historyLimit,\n generateId: options.generateId,\n initial: options.items.map((item) => ({\n kind: 'leaf',\n layer: DEFAULT_LAYER,\n pose: item,\n data: item,\n id: asNodeId(item.id),\n })),\n }) as Scene<unknown, string, unknown>;\n}\n\n/** React hook returning a kit-owned `Scene`. The Scene is constructed once\n * per host component and tracked via `useSyncExternalStore`, so React re-\n * renders on every Scene mutation (including undo/redo) unless\n * `subscribe: false` opts out.\n *\n * Two call shapes:\n * - **Trivial**: `useScene({ items })` — one auto-registered system layer\n * named `'default'`, each item added as a leaf with `pose === data === item`.\n * Cheapest path for \"a flat list of rects.\"\n * - **Full**: `useScene({ systemLayers, initial?, ops?, ... })` — explicit\n * layers, parenting, and custom op registration. */\nexport function useScene<TItem extends { id: string }>(\n options: UseSceneTrivialOptions<TItem>,\n): Scene<TItem, DefaultLayer, TItem>;\n/** The full call shape: explicit layers, initial nodes, custom ops, and\n * history configuration. */\nexport function useScene<TData, TLayer extends string, TPose = import('../../features/groups/composePose').RectPose>(\n options: UseSceneOptions<TData, TLayer, TPose>,\n): Scene<TData, TLayer, TPose>;\n/** Create and subscribe to a scene. */\nexport function useScene(options: unknown): unknown {\n const sceneRef = useRef<Scene<unknown, string, unknown> | null>(null);\n if (sceneRef.current === null) sceneRef.current = buildScene(options);\n const scene = sceneRef.current;\n const subscribed = (options as { subscribe?: boolean } | null)?.subscribe !== false;\n useSyncExternalStore(\n subscribed ? scene.subscribe : NEVER_SUBSCRIBE,\n scene.getVersion,\n scene.getVersion,\n );\n return scene;\n}\n"],"mappings":";;;;AAuBA,IAAMA,gBAA8B,CAAC,GAE/BC,IAAgB;AAGtB,SAASC,EACP,GAC0C;CAC1C,OACE,CAAC,CAACC,KACC,OAAOA,KAAY,YACnB,WAAYA,KACZ,EAAE,kBAAmBA;AAE5B;AAEA,SAASC,EAAW,GAAmD;CAIrE,OAHKF,EAAiBC,CAAO,IAGtBE,EAA4C;EACjD,cAAc,CAAC,EAAE,IAAIJ,EAAc,CAAC;EACpC,cAAcE,EAAQ;EACtB,YAAYA,EAAQ;EACpB,SAASA,EAAQ,MAAM,KAAK,OAAU;GACpC,MAAM;GACN,OAAOF;GACP,MAAMK;GACN,MAAMA;GACN,IAAIC,EAASD,EAAK,EAAE;EACtB,EAAE;CACJ,CAAC,IAbQD,EAAYF,CAAoD;AAc3E;AAsBA,SAAgBK,EAAS,GAA2B;CAClD,IAAMC,IAAWC,EAA+C,IAAI;CACpE,AAAID,EAAS,YAAY,SAAM,EAAS,UAAUL,EAAWD,CAAO;CACpE,IAAMQ,IAAQF,EAAS,SACjBG,IAAcT,GAA4C,cAAc;CAM9E,OALAU,EACED,IAAaD,EAAM,YAAYX,GAC/BW,EAAM,YACNA,EAAM,UACR,GACOA;AACT"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { unionAABB as e } from "../geometry/unionBounds.js";
|
|
2
|
+
//#region src/core/selection/chromeState.ts
|
|
3
|
+
var t = {
|
|
4
|
+
selection: [],
|
|
5
|
+
multiActive: !1,
|
|
6
|
+
boundsOf: () => null,
|
|
7
|
+
unionBounds: null,
|
|
8
|
+
modifiers: {
|
|
9
|
+
alt: !1,
|
|
10
|
+
shift: !1,
|
|
11
|
+
meta: !1,
|
|
12
|
+
ctrl: !1
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
function n(t) {
|
|
16
|
+
let { selection: n, multiActive: r, effectiveBoundsOf: i, modifiers: a, canRotate: o } = t;
|
|
17
|
+
return {
|
|
18
|
+
selection: n,
|
|
19
|
+
multiActive: r,
|
|
20
|
+
boundsOf: i,
|
|
21
|
+
modifiers: a,
|
|
22
|
+
canRotate: o ?? (() => !0),
|
|
23
|
+
get unionBounds() {
|
|
24
|
+
return r ? e(n.map((e) => i(e))) : null;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { t as EMPTY_CHROME_STATE, n as buildChromeState };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=chromeState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chromeState.js","names":["EMPTY_CHROME_STATE","buildChromeState","args","effectiveBoundsOf","canRotate","multiActive","unionAABB","selection","id"],"sources":["../../../src/core/selection/chromeState.ts"],"sourcesContent":["import type { NodeId } from '../scene/types';\nimport type { ModifierState } from '../modifierState';\nimport type { Bounds } from '../viewport/fitViewToBounds';\nimport { unionAABB } from 'core/geometry/unionBounds';\n\nexport type { Bounds };\n\n/** Nothing selected, nothing resolvable — what a caller reads before a\n * surface has attached, or where chrome state has no owner. */\nexport const EMPTY_CHROME_STATE: ChromeState = {\n selection: [],\n multiActive: false,\n boundsOf: () => null,\n unionBounds: null,\n modifiers: { alt: false, shift: false, meta: false, ctrl: false },\n};\n\n/**\n * Read-only state that affordances consult on every render and hit-test\n * call. Built via `buildChromeState` and held across renders, so affordances\n * must not cache anything they read from it.\n */\nexport interface ChromeState {\n /** Currently selected ids. Live; reflects useSelection's React state. */\n readonly selection: readonly NodeId[];\n /** True when the canvas is in multi-mode AND >= 2 ids are selected. */\n readonly multiActive: boolean;\n /** Bounds for any selection member id. Honors active-tool overlay state\n * (move/resize/rotate ghosts → ghost bounds; otherwise → committed\n * pose bounds). Returns null for unknown ids or ids whose bounds aren't\n * computable. */\n boundsOf(id: string): Bounds | null;\n /** Multi-union AABB when `multiActive`. Recomputed from `boundsOf` over\n * every selected id on each read, expanding rotated members to the extent\n * of their ink; null otherwise. */\n readonly unionBounds: Bounds | null;\n /** Active modifier state at the moment of the call. */\n readonly modifiers: ModifierState;\n /** True iff the node's pose-descriptor declares it can carry a rotation.\n * Affordances consult this to decide whether to expose rotate cursors /\n * drag-bands. Defaults to `true` when the descriptor doesn't declare\n * (back-compat) or when the id is unknown — the rotation gesture will\n * no-op visually for poses without AABB fields, but the affordance\n * doesn't lie about the cursor. Optional on the interface so unit-test\n * call sites that construct `ChromeState` by hand keep compiling;\n * affordances should treat an absent predicate as \"true\". */\n canRotate?(id: string): boolean;\n}\n\nexport interface BuildChromeStateArgs {\n selection: readonly NodeId[];\n multiActive: boolean;\n effectiveBoundsOf: (id: string) => Bounds | null;\n modifiers: ModifierState;\n /** Optional rotation-support predicate. When omitted, `canRotate` returns\n * `true` for every id — preserves pre-existing affordance behavior for\n * unit-test call sites that don't wire pose-descriptor capability. */\n canRotate?: (id: string) => boolean;\n}\n\nexport function buildChromeState(args: BuildChromeStateArgs): ChromeState {\n const { selection, multiActive, effectiveBoundsOf, modifiers, canRotate } = args;\n return {\n selection,\n multiActive,\n boundsOf: effectiveBoundsOf,\n modifiers,\n canRotate: canRotate ?? (() => true),\n // Not cached: the state is memoized across renders, and poses move under\n // it (a committed move, a live preview) without any of its inputs changing.\n get unionBounds() {\n if (!multiActive) return null;\n return unionAABB(selection.map((id) => effectiveBoundsOf(id)));\n },\n };\n}\n"],"mappings":";;AASA,IAAaA,IAAkC;CAC7C,WAAW,CAAC;CACZ,aAAa;CACb,gBAAgB;CAChB,aAAa;CACb,WAAW;EAAE,KAAK;EAAO,OAAO;EAAO,MAAM;EAAO,MAAM;CAAM;AAClE;AA6CA,SAAgBC,EAAiB,GAAyC;CACxE,IAAM,EAAE,cAAW,gBAAa,sBAAmB,cAAW,iBAAcC;CAC5E,OAAO;EACL;EACA;EACA,UAAUC;EACV;EACA,WAAWC,YAAoB;EAG/B,IAAI,cAAc;GAEhB,OADKC,IACEC,EAAUC,EAAU,KAAK,MAAOJ,EAAkBK,CAAE,CAAC,CAAC,IADpC;EAE3B;CACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"selectionTarget.js","names":["MULTI_RESIZE_TARGET_ID"],"sources":["../../../src/core/selection/selectionTarget.ts"],"sourcesContent":["/** Synthetic id a canvas uses to address the\n * union-AABB target when 2+ real ids are selected. The selection-overlay\n * layer and the affordance hit-tester both resolve it to `ChromeState`'s\n * `unionBounds`; consumers wiring their own selection-overlay layer can\n * reference the same constant.\n *\n * Lives in `core/selection` (next to `ChromeState`) because it's a\n * selection-derived concept, not a tool concept — `affordances/`,\n * `features/selection/`, and `tools/` all consume it, so it must sit at\n * the bottom of the layering (`core` → `affordances` → `tools` →\n * `features`). */\nexport const MULTI_RESIZE_TARGET_ID = '__weasel:multi-selection';\n"],"mappings":";AAWA,IAAaA,IAAyB"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { dlog as e } from "../../debug/flag.js";
|
|
2
|
+
import { useLayoutEffect as t, useMemo as n, useRef as r, useState as i, useSyncExternalStore as a } from "react";
|
|
3
|
+
import { useLatest as o } from "@weasel-js/react";
|
|
4
|
+
//#region src/core/selection/useSelection.ts
|
|
5
|
+
function s(e) {
|
|
6
|
+
let t = e, n = /* @__PURE__ */ new Set();
|
|
7
|
+
return {
|
|
8
|
+
getSelection: () => t,
|
|
9
|
+
setSelection: (e) => {
|
|
10
|
+
t = e;
|
|
11
|
+
for (let e of n) e();
|
|
12
|
+
},
|
|
13
|
+
subscribe: (e) => (n.add(e), () => {
|
|
14
|
+
n.delete(e);
|
|
15
|
+
})
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function c(c = {}) {
|
|
19
|
+
let { mode: l = "single", extend: u = "shift", initial: d = [], lock: f = !1, scene: p } = c, [m] = i(() => s([...d])), h = p ?? m, g = r(d);
|
|
20
|
+
a(h.subscribe, () => h.getSelection());
|
|
21
|
+
let _ = r(!1);
|
|
22
|
+
t(() => {
|
|
23
|
+
p && !_.current && (_.current = !0, g.current.length > 0 && p.getSelection().length === 0 && p.setSelection([...g.current]));
|
|
24
|
+
}, [p]);
|
|
25
|
+
let v = o({
|
|
26
|
+
mode: l,
|
|
27
|
+
extend: u,
|
|
28
|
+
lock: f
|
|
29
|
+
});
|
|
30
|
+
return n(() => {
|
|
31
|
+
let t = () => h.getSelection(), n = (n) => {
|
|
32
|
+
v.current.lock || (e("selection", "set", {
|
|
33
|
+
from: t().length,
|
|
34
|
+
to: n.length,
|
|
35
|
+
ids: n
|
|
36
|
+
}), h.setSelection(n));
|
|
37
|
+
}, r = (e) => t().filter((t) => t !== e);
|
|
38
|
+
return {
|
|
39
|
+
get current() {
|
|
40
|
+
return t();
|
|
41
|
+
},
|
|
42
|
+
get: t,
|
|
43
|
+
set: n,
|
|
44
|
+
add(e) {
|
|
45
|
+
v.current.mode === "single" ? n([e]) : t().includes(e) || n([...t(), e]);
|
|
46
|
+
},
|
|
47
|
+
remove(e) {
|
|
48
|
+
t().includes(e) && n(r(e));
|
|
49
|
+
},
|
|
50
|
+
toggle(e) {
|
|
51
|
+
t().includes(e) ? n(r(e)) : n(v.current.mode === "single" ? [e] : [...t(), e]);
|
|
52
|
+
},
|
|
53
|
+
clear() {
|
|
54
|
+
n([]);
|
|
55
|
+
},
|
|
56
|
+
contains: (e) => t().includes(e),
|
|
57
|
+
applyClick(e, i) {
|
|
58
|
+
let { mode: a, extend: o } = v.current;
|
|
59
|
+
a === "multi" && i[o] ? n(t().includes(e) ? r(e) : [...t(), e]) : n([e]);
|
|
60
|
+
},
|
|
61
|
+
adapterMethods: {
|
|
62
|
+
getSelection: () => t(),
|
|
63
|
+
setSelection: (e) => n(e)
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}, [h, v]);
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
export { c as useSelection };
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=useSelection.js.map
|