@weasel-js/core 1.12.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +199 -0
- package/dist/animation/poseTarget.js +46 -15
- package/dist/animation/poseTarget.js.map +1 -1
- package/dist/animation/poseTransition.js +3 -3
- package/dist/animation/poseTransition.js.map +1 -1
- package/dist/animation/reflow.js +3 -6
- package/dist/animation/reflow.js.map +1 -1
- package/dist/animation/rig/bindRig.js +2 -2
- package/dist/animation/rig/bindRig.js.map +1 -1
- package/dist/animation/rig/skinBinding.js +2 -2
- package/dist/animation/rig/skinBinding.js.map +1 -1
- package/dist/barrel/canvas.js +5 -3
- package/dist/barrel/chrome.js +3 -1
- package/dist/barrel/paths.js +3 -2
- package/dist/barrel/routing.js +2 -2
- package/dist/barrel/scene.js +6 -1
- package/dist/barrel/text.js +2 -2
- package/dist/canvas/NodeShape.js +1 -0
- package/dist/canvas/NodeShape.js.map +1 -1
- package/dist/canvas/SceneCanvas/SceneCanvasInput.js +2 -0
- package/dist/canvas/SceneCanvas/SceneCanvasInput.js.map +1 -1
- package/dist/canvas/SceneCanvas/canvasPassThrough.js +1 -1
- package/dist/canvas/SceneCanvas/canvasPassThrough.js.map +1 -1
- package/dist/canvas/SceneCanvas/defaultNodeRouting.js +2 -2
- package/dist/canvas/SceneCanvas/defaultNodeRouting.js.map +1 -1
- package/dist/canvas/SceneCanvas/scenePointQuery.js +20 -2
- package/dist/canvas/SceneCanvas/scenePointQuery.js.map +1 -1
- package/dist/canvas/SceneCanvas/useCanvasTools.js +3 -0
- package/dist/canvas/SceneCanvas/useCanvasTools.js.map +1 -1
- package/dist/canvas/SceneCanvas/useContributionRoles.js +2 -0
- package/dist/canvas/SceneCanvas/useContributionRoles.js.map +1 -1
- package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js +25 -19
- package/dist/canvas/SceneCanvas/usePreviewGhostLayer.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js +7 -0
- package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneCanvasTools.js +1 -0
- package/dist/canvas/SceneCanvas/useSceneCanvasTools.js.map +1 -1
- package/dist/canvas/SceneCanvas/useScenePicking.js +31 -6
- package/dist/canvas/SceneCanvas/useScenePicking.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneSelectTool.js +4 -5
- package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneStandardActions.js +5 -3
- package/dist/canvas/SceneCanvas/useSceneStandardActions.js.map +1 -1
- package/dist/canvas/SceneCanvas.js +19 -2
- package/dist/canvas/SceneCanvas.js.map +1 -1
- package/dist/canvas/accentColor.js +26 -3
- package/dist/canvas/accentColor.js.map +1 -1
- package/dist/canvas/buildSceneLayer.js +1 -1
- package/dist/canvas/buildSceneLayer.js.map +1 -1
- package/dist/canvas/buildSceneTree.js +14 -20
- package/dist/canvas/buildSceneTree.js.map +1 -1
- package/dist/canvas/canvasRenderer.js +6 -2
- package/dist/canvas/canvasRenderer.js.map +1 -1
- package/dist/canvas/copiesAbove.js +1 -1
- package/dist/canvas/copiesAbove.js.map +1 -1
- package/dist/canvas/defaultDrawOne.js +10 -7
- package/dist/canvas/defaultDrawOne.js.map +1 -1
- package/dist/canvas/deps/areaSelect.js +5 -2
- package/dist/canvas/deps/areaSelect.js.map +1 -1
- package/dist/canvas/deps/booleans.js +1 -1
- package/dist/canvas/deps/booleans.js.map +1 -1
- package/dist/canvas/deps/enteredGroup.js +81 -0
- package/dist/canvas/deps/enteredGroup.js.map +1 -0
- package/dist/canvas/deps/hitTestArea.js +27 -15
- package/dist/canvas/deps/hitTestArea.js.map +1 -1
- package/dist/canvas/deps/insert.js +4 -36
- package/dist/canvas/deps/insert.js.map +1 -1
- package/dist/canvas/deps/insertSite.js +39 -0
- package/dist/canvas/deps/insertSite.js.map +1 -0
- package/dist/canvas/deps/lassoSelect.js +6 -3
- package/dist/canvas/deps/lassoSelect.js.map +1 -1
- package/dist/canvas/deps/pathLeaf.js +1 -1
- package/dist/canvas/deps/pathLeaf.js.map +1 -1
- package/dist/canvas/deps/slice.js +2 -1
- package/dist/canvas/deps/slice.js.map +1 -1
- package/dist/canvas/derivedPath.js +14 -6
- package/dist/canvas/derivedPath.js.map +1 -1
- package/dist/canvas/doubleClickTarget.js +9 -11
- package/dist/canvas/doubleClickTarget.js.map +1 -1
- package/dist/canvas/drawnBounds.js +16 -7
- package/dist/canvas/drawnBounds.js.map +1 -1
- package/dist/canvas/inheritedPaints.js +22 -11
- package/dist/canvas/inheritedPaints.js.map +1 -1
- package/dist/canvas/nodeShapes/nodePaint.js +1 -7
- package/dist/canvas/nodeShapes/nodePaint.js.map +1 -1
- package/dist/canvas/nodeShapes/pathPainter.js +2 -3
- package/dist/canvas/nodeShapes/pathPainter.js.map +1 -1
- package/dist/canvas/nodeShapes/rectFallbackPainter.js +1 -1
- package/dist/canvas/nodeShapes/rectFallbackPainter.js.map +1 -1
- package/dist/canvas/nodeShapes/shapePainter.js +2 -3
- package/dist/canvas/nodeShapes/shapePainter.js.map +1 -1
- package/dist/canvas/ownClip.js +24 -0
- package/dist/canvas/ownClip.js.map +1 -0
- package/dist/canvas/paintCull.js.map +1 -1
- package/dist/canvas/pickIndex/nodeBroadBox.js +86 -0
- package/dist/canvas/pickIndex/nodeBroadBox.js.map +1 -0
- package/dist/canvas/pickIndex/scenePickIndex.js +208 -0
- package/dist/canvas/pickIndex/scenePickIndex.js.map +1 -0
- package/dist/canvas/pickWalk.js +14 -90
- package/dist/canvas/pickWalk.js.map +1 -1
- package/dist/canvas/poseCascade.js +1 -1
- package/dist/canvas/poseCascade.js.map +1 -1
- package/dist/canvas/publishPreviews.js +97 -0
- package/dist/canvas/publishPreviews.js.map +1 -0
- package/dist/canvas/sceneAdapter.js +7 -5
- package/dist/canvas/sceneAdapter.js.map +1 -1
- package/dist/canvas/sceneClipboard.js +17 -10
- package/dist/canvas/sceneClipboard.js.map +1 -1
- package/dist/canvas/scenePickReads.js +37 -0
- package/dist/canvas/scenePickReads.js.map +1 -0
- package/dist/canvas/scenePickSource.js +74 -0
- package/dist/canvas/scenePickSource.js.map +1 -0
- package/dist/canvas/sceneSlotWiring.js +9 -4
- package/dist/canvas/sceneSlotWiring.js.map +1 -1
- package/dist/canvas/sceneViewRender.js +13 -8
- package/dist/canvas/sceneViewRender.js.map +1 -1
- package/dist/canvas/shownNodes.js +15 -0
- package/dist/canvas/shownNodes.js.map +1 -0
- package/dist/canvas/useCanvasPaint.js +3 -1
- package/dist/canvas/useCanvasPaint.js.map +1 -1
- package/dist/canvas/useSceneAdapter.js +5 -3
- package/dist/canvas/useSceneAdapter.js.map +1 -1
- package/dist/clipboard.d.ts +2 -2
- package/dist/{clone-C3e0OTuF.d.ts → clone-qb2e1F5p.d.ts} +2 -2
- package/dist/clone.d.ts +3 -3
- package/dist/core/isPlainObject.js +2 -2
- package/dist/core/layers/layerGroup.js.map +1 -1
- package/dist/core/layers/render.js.map +1 -1
- package/dist/core/scene/NodeRouting.js.map +1 -1
- package/dist/core/scene/arrivalWindow.js +1 -1
- package/dist/core/scene/arrivalWindow.js.map +1 -1
- package/dist/core/scene/clipNothing.js +2 -5
- package/dist/core/scene/clipNothing.js.map +1 -1
- package/dist/core/scene/declaredFieldSetters.js +44 -0
- package/dist/core/scene/declaredFieldSetters.js.map +1 -0
- package/dist/core/scene/depMemo.js +3 -0
- package/dist/core/scene/depMemo.js.map +1 -1
- package/dist/core/scene/dependents.js +3 -1
- package/dist/core/scene/dependents.js.map +1 -1
- package/dist/core/scene/documentOf.js +43 -0
- package/dist/core/scene/documentOf.js.map +1 -0
- package/dist/core/scene/effectivePose.js +37 -13
- package/dist/core/scene/effectivePose.js.map +1 -1
- package/dist/core/scene/fieldEdits.js +17 -14
- package/dist/core/scene/fieldEdits.js.map +1 -1
- package/dist/core/scene/historyForm.js +4 -4
- package/dist/core/scene/historyForm.js.map +1 -1
- package/dist/core/scene/inheritedPaint.js +27 -5
- package/dist/core/scene/inheritedPaint.js.map +1 -1
- package/dist/core/scene/kitOps.js +3 -23
- package/dist/core/scene/kitOps.js.map +1 -1
- package/dist/core/scene/layoutPass.js +1 -2
- package/dist/core/scene/layoutPass.js.map +1 -1
- package/dist/core/scene/nodeAsShown.js +72 -0
- package/dist/core/scene/nodeAsShown.js.map +1 -0
- package/dist/core/scene/nodeFnFields.js +2 -10
- package/dist/core/scene/nodeFnFields.js.map +1 -1
- package/dist/core/scene/nodeMemo.js +6 -1
- package/dist/core/scene/nodeMemo.js.map +1 -1
- package/dist/core/scene/nodeStore.js +2 -4
- package/dist/core/scene/nodeStore.js.map +1 -1
- package/dist/core/scene/pathEffects/derive.js +3 -2
- package/dist/core/scene/pathEffects/derive.js.map +1 -1
- package/dist/core/scene/pathEffects/foundHidden.js +35 -0
- package/dist/core/scene/pathEffects/foundHidden.js.map +1 -0
- package/dist/core/scene/plyStacks.js +89 -0
- package/dist/core/scene/plyStacks.js.map +1 -0
- package/dist/core/scene/poseHold.js +42 -24
- package/dist/core/scene/poseHold.js.map +1 -1
- package/dist/core/scene/poseOverrides.js +35 -38
- package/dist/core/scene/poseOverrides.js.map +1 -1
- package/dist/core/scene/posePlies.js +59 -0
- package/dist/core/scene/posePlies.js.map +1 -0
- package/dist/core/scene/reconcileSpecs.js +6 -15
- package/dist/core/scene/reconcileSpecs.js.map +1 -1
- package/dist/core/scene/renderOrder.js +10 -4
- package/dist/core/scene/renderOrder.js.map +1 -1
- package/dist/core/scene/sameValue.js +17 -0
- package/dist/core/scene/sameValue.js.map +1 -0
- package/dist/core/scene/scene.js +3 -3
- package/dist/core/scene/scene.js.map +1 -1
- package/dist/core/scene/sceneEdits.js +8 -0
- package/dist/core/scene/sceneEdits.js.map +1 -1
- package/dist/core/scene/sceneState.js +1 -2
- package/dist/core/scene/sceneState.js.map +1 -1
- package/dist/core/scene/serialization.js +45 -9
- package/dist/core/scene/serialization.js.map +1 -1
- package/dist/core/scene/staleReplay.js +5 -2
- package/dist/core/scene/staleReplay.js.map +1 -1
- package/dist/core/scene/statedFields.js +4 -2
- package/dist/core/scene/statedFields.js.map +1 -1
- package/dist/core/scene/treeEdits.js +2 -4
- package/dist/core/scene/treeEdits.js.map +1 -1
- package/dist/core/scene/treeOrder.js +3 -1
- package/dist/core/scene/treeOrder.js.map +1 -1
- package/dist/core/scene/treeReads.js +1 -2
- package/dist/core/scene/treeReads.js.map +1 -1
- package/dist/core/scene/treeShape.js +13 -0
- package/dist/core/scene/treeShape.js.map +1 -0
- package/dist/core/scene/types.js.map +1 -1
- package/dist/core/scene/useScene.js +1 -1
- package/dist/core/scene/useScene.js.map +1 -1
- package/dist/{cornerHandles-p8fDIAKt.d.ts → cornerHandles-CNCb7aTY.d.ts} +1 -1
- package/dist/{depSchema-mG19aEdD.d.ts → depSchema-CpIQzKWQ.d.ts} +38 -59
- package/dist/devtools/handlers.js +1 -1
- package/dist/devtools/handlers.js.map +1 -1
- package/dist/devtools/protocol.js.map +1 -1
- package/dist/devtools-protocol.d.ts +4 -3
- package/dist/devtools.d.ts +3 -2
- package/dist/features/measure/measureHit.js +5 -3
- package/dist/features/measure/measureHit.js.map +1 -1
- package/dist/features/measure/measurement.js +1 -1
- package/dist/features/measure/measurement.js.map +1 -1
- package/dist/features/modes/modeLayers.js +14 -7
- package/dist/features/modes/modeLayers.js.map +1 -1
- package/dist/features/modes/modeTriggers.js +3 -3
- package/dist/features/modes/modeTriggers.js.map +1 -1
- package/dist/features/pathEffects/effectSources.js +25 -16
- package/dist/features/pathEffects/effectSources.js.map +1 -1
- package/dist/features/pathEffects/readSource.js +1 -1
- package/dist/features/pathEffects/readSource.js.map +1 -1
- package/dist/features/pathEffects/useEffectSourcesLayer.js +15 -19
- package/dist/features/pathEffects/useEffectSourcesLayer.js.map +1 -1
- package/dist/features/paths/editablePath.js +1 -1
- package/dist/features/paths/editablePath.js.map +1 -1
- package/dist/features/paths/pathSnap/sceneIndex.js +1 -1
- package/dist/features/paths/pathSnap/sceneIndex.js.map +1 -1
- package/dist/features/selection/enteredGroupFrame.js +65 -0
- package/dist/features/selection/enteredGroupFrame.js.map +1 -0
- package/dist/features/selection/enteredGroupScope.js +44 -0
- package/dist/features/selection/enteredGroupScope.js.map +1 -0
- package/dist/features/text/sceneTextDrafts.js +26 -27
- package/dist/features/text/sceneTextDrafts.js.map +1 -1
- package/dist/features/text/textHitAt.js +4 -2
- package/dist/features/text/textHitAt.js.map +1 -1
- package/dist/features/text/useSceneTextEdit.js +3 -3
- package/dist/features/text/useSceneTextEdit.js.map +1 -1
- package/dist/features/viewports/viewportLayer.js +2 -1
- package/dist/features/viewports/viewportLayer.js.map +1 -1
- package/dist/index.d.ts +230 -77
- package/dist/index.js +16 -6
- package/dist/interactions/actions/admitsChild.js +11 -0
- package/dist/interactions/actions/admitsChild.js.map +1 -0
- package/dist/interactions/actions/defaults/contextMenu.js +16 -3
- package/dist/interactions/actions/defaults/contextMenu.js.map +1 -1
- package/dist/interactions/actions/defaults/createPaintAction.js +4 -1
- package/dist/interactions/actions/defaults/createPaintAction.js.map +1 -1
- package/dist/interactions/actions/defaults/enterGroup.js +88 -0
- package/dist/interactions/actions/defaults/enterGroup.js.map +1 -0
- package/dist/interactions/actions/defaults/enterPathEdit.js +1 -1
- package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -1
- package/dist/interactions/actions/defaults/enterTextEdit.js +1 -1
- package/dist/interactions/actions/defaults/enterTextEdit.js.map +1 -1
- package/dist/interactions/actions/defaults/group.js +7 -7
- package/dist/interactions/actions/defaults/group.js.map +1 -1
- package/dist/interactions/actions/defaults/selectAll.js +7 -3
- package/dist/interactions/actions/defaults/selectAll.js.map +1 -1
- package/dist/interactions/actions/defaults/selectDeep.js +35 -0
- package/dist/interactions/actions/defaults/selectDeep.js.map +1 -0
- package/dist/interactions/actions/drawnBoxes.js +2 -1
- package/dist/interactions/actions/drawnBoxes.js.map +1 -1
- package/dist/interactions/actions/insert/action.js +1 -0
- package/dist/interactions/actions/insert/action.js.map +1 -1
- package/dist/interactions/actions/insert/parent.js +7 -5
- package/dist/interactions/actions/insert/parent.js.map +1 -1
- package/dist/interactions/actions/insert/placeAction.js +3 -2
- package/dist/interactions/actions/insert/placeAction.js.map +1 -1
- package/dist/interactions/actions/insert/session.js +2 -2
- package/dist/interactions/actions/insert/session.js.map +1 -1
- package/dist/interactions/actions/move/commit/reparent.js +1 -1
- package/dist/interactions/actions/move/commit/reparent.js.map +1 -1
- package/dist/interactions/actions/move/gestureAdapter.js +6 -7
- package/dist/interactions/actions/move/gestureAdapter.js.map +1 -1
- package/dist/interactions/actions/move/layout/exits.js +1 -1
- package/dist/interactions/actions/move/layout/exits.js.map +1 -1
- package/dist/interactions/actions/move/session.js +4 -4
- package/dist/interactions/actions/move/session.js.map +1 -1
- package/dist/interactions/actions/pathCommands/pathNodes.js +14 -5
- package/dist/interactions/actions/pathCommands/pathNodes.js.map +1 -1
- package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js +14 -2
- package/dist/interactions/gestures/thresholdDrag/thresholdDrag.js.map +1 -1
- package/dist/{math-B56zxVs5.d.ts → math-C_elShP_.d.ts} +2 -5
- package/dist/math.d.ts +1 -1
- package/dist/move.d.ts +4 -4
- package/dist/{options-DBxEryYq.d.ts → options-ClEm3SEl.d.ts} +1 -1
- package/dist/resize.d.ts +4 -4
- package/dist/test-seams.d.ts +6 -6
- package/dist/tools/builtin/pressTarget.js +22 -0
- package/dist/tools/builtin/pressTarget.js.map +1 -0
- package/dist/tools/builtin/select/adapterPointQuery.js +3 -3
- package/dist/tools/builtin/select/adapterPointQuery.js.map +1 -1
- package/dist/tools/builtin/select/collapseDeferred.js +40 -0
- package/dist/tools/builtin/select/collapseDeferred.js.map +1 -0
- package/dist/tools/builtin/select/groupEntry.js +82 -0
- package/dist/tools/builtin/select/groupEntry.js.map +1 -0
- package/dist/tools/builtin/select/pressDecision.js +1 -1
- package/dist/tools/builtin/select/pressDecision.js.map +1 -1
- package/dist/tools/builtin/select/useSelectTool.js +61 -45
- package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
- package/dist/{types-7puAuVD2.d.ts → types-49uYJN3j.d.ts} +1 -1
- package/dist/{types-CniVctmk.d.ts → types-BEdRIhNc.d.ts} +272 -109
- package/dist/{types-oFeQ5VjV.d.ts → types-p2alu-R1.d.ts} +1 -1
- package/dist/version.js +1 -1
- package/package.json +25 -25
|
@@ -8,7 +8,8 @@ import { treePreorder } from "./treeOrder.js";
|
|
|
8
8
|
*/
|
|
9
9
|
/** Whether `value` is a snapshot `specsFromSerialized` reads, as against a live scene. */
|
|
10
10
|
function isSerializedScene(value) {
|
|
11
|
-
|
|
11
|
+
const version = typeof value === "object" && value != null ? value.version : void 0;
|
|
12
|
+
return (version === 1 || version === 2) && Array.isArray(value.nodes);
|
|
12
13
|
}
|
|
13
14
|
/** One layer record from its snapshot form. A snapshot with no `kind` predates
|
|
14
15
|
* user layers, so everything in it was a system layer. */
|
|
@@ -49,14 +50,15 @@ function serializeScene(state, fnFields, doc) {
|
|
|
49
50
|
if (n.pickable === false) out.pickable = false;
|
|
50
51
|
if (n.hidden === true) out.hidden = true;
|
|
51
52
|
if (n.locked === true) out.locked = true;
|
|
52
|
-
if (n.
|
|
53
|
+
if (n.units !== void 0) out.units = n.units;
|
|
54
|
+
if (n.clip !== void 0) out.clip = n.clip;
|
|
53
55
|
Object.assign(out, fnKeysOf(fnFields, n, "jsonKey", (field) => {
|
|
54
56
|
throw new Error(`Scene.toJSON: node '${id}' has ${field.spec.field} but no matching registry key. The function must be registered via createScene's registry option to round-trip.`);
|
|
55
57
|
}));
|
|
56
58
|
nodes.push(out);
|
|
57
59
|
}
|
|
58
60
|
return {
|
|
59
|
-
version:
|
|
61
|
+
version: 2,
|
|
60
62
|
systemLayers: state.layers.map((l) => {
|
|
61
63
|
const layer = { id: l.id };
|
|
62
64
|
if (l.visible === false) layer.visible = false;
|
|
@@ -76,13 +78,23 @@ function serializeScene(state, fnFields, doc) {
|
|
|
76
78
|
/** Map a `SerializedScene` to construction specs. Shared by `sceneFromJSON`
|
|
77
79
|
* (new instance) and `Scene.loadState` (in-place). Validates version and
|
|
78
80
|
* resolves every `NODE_FN_FIELDS` key → function via the registry;
|
|
79
|
-
* throws on an unsupported version
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
81
|
+
* throws on an unsupported version, and on an unknown registry key unless
|
|
82
|
+
* `opts.unknownKeys` is `'skip'`. */
|
|
83
|
+
function specsFromSerialized(json, registry, opts = {}) {
|
|
84
|
+
let entries;
|
|
85
|
+
if (json.version === 1) entries = json.nodes.map((n) => ({
|
|
86
|
+
n,
|
|
87
|
+
kind: nodeKindOf(1, n, opts.classifyV1)
|
|
88
|
+
}));
|
|
89
|
+
else if (json.version === 2) entries = json.nodes.map((n) => ({
|
|
90
|
+
n,
|
|
91
|
+
kind: nodeKindOf(2, n)
|
|
92
|
+
}));
|
|
93
|
+
else throw new Error(`Scene: unsupported version ${String(Reflect.get(json, "version"))}; versions 1 and 2 are supported`);
|
|
94
|
+
return entries.map(({ n, kind }) => {
|
|
83
95
|
const spec = {
|
|
84
96
|
id: n.id,
|
|
85
|
-
kind
|
|
97
|
+
kind,
|
|
86
98
|
layer: n.layer,
|
|
87
99
|
pose: n.pose,
|
|
88
100
|
data: n.data
|
|
@@ -92,19 +104,43 @@ function specsFromSerialized(json, registry) {
|
|
|
92
104
|
if (n.hidden === true) spec.hidden = true;
|
|
93
105
|
if (n.locked === true) spec.locked = true;
|
|
94
106
|
if (n.units !== void 0) spec.units = n.units;
|
|
107
|
+
if (n.clip !== void 0) spec.clip = n.clip;
|
|
95
108
|
if (n.dependsOn !== void 0) spec.dependsOn = n.dependsOn === "children" ? "children" : n.dependsOn;
|
|
96
109
|
const serialized = n;
|
|
97
110
|
for (const field of NODE_FN_FIELDS) {
|
|
98
111
|
const key = serialized[field.jsonKey];
|
|
99
112
|
if (key === void 0) continue;
|
|
100
113
|
const fn = registry[field.field]?.[key];
|
|
114
|
+
if (!fn && opts.unknownKeys === "skip") {
|
|
115
|
+
opts.onSkip?.({
|
|
116
|
+
id: spec.id,
|
|
117
|
+
field: field.field,
|
|
118
|
+
key
|
|
119
|
+
});
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
101
122
|
if (!fn) throw new Error(`Scene: unknown ${field.field} key '${key}'. Register a function with this key in the registry option.`);
|
|
102
123
|
spec[field.field] = fn;
|
|
103
124
|
}
|
|
125
|
+
if (clipsAsV1(json.version, spec)) spec.clip = "outline";
|
|
104
126
|
return spec;
|
|
105
127
|
});
|
|
106
128
|
}
|
|
129
|
+
/** Version 1 clipped a container with no clip function to its outline, which
|
|
130
|
+
* is what `clip: 'outline'` draws on a group. One a classifier makes a mark
|
|
131
|
+
* gets no clip, since which painter claims it is not known here; one whose
|
|
132
|
+
* clip key was skipped loads as it would have without it. */
|
|
133
|
+
function clipsAsV1(version, spec) {
|
|
134
|
+
return version === 1 && spec.kind === "group" && spec.clipFromPose === void 0;
|
|
135
|
+
}
|
|
136
|
+
/** The kind a saved node loads as: its own on version 2; on version 1 a `leaf` is a
|
|
137
|
+
* mark and a `container` goes to `classify`, or is a group without one. */
|
|
138
|
+
function nodeKindOf(version, n, classify) {
|
|
139
|
+
if (version === 2) return n.kind;
|
|
140
|
+
if (n.kind === "leaf") return "mark";
|
|
141
|
+
return classify ? classify(n) : "group";
|
|
142
|
+
}
|
|
107
143
|
|
|
108
144
|
//#endregion
|
|
109
|
-
export { isSerializedScene, layerFromSerialized, serializeScene, specsFromSerialized };
|
|
145
|
+
export { isSerializedScene, layerFromSerialized, nodeKindOf, serializeScene, specsFromSerialized };
|
|
110
146
|
//# sourceMappingURL=serialization.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serialization.js","names":[],"sources":["../../../src/core/scene/serialization.ts"],"sourcesContent":["/**\n * A scene to and from its JSON snapshot: the walk that writes one, and the\n * two readers that turn one back into layer records and node specs.\n */\nimport {\n NODE_FN_FIELDS, fnKeysOf, type FnBearingNode, type NodeFnField,\n} from './nodeFnFields';\nimport type { SerializedDoc } from './docValues';\nimport { treePreorder } from './treeOrder';\nimport type {\n AddNodeSpec, LayerRecord, Node, NodeId, SceneRegistry, SerializedLayer, SerializedNode, SerializedScene,\n} from './types';\n\n/** Whether `value` is a snapshot `specsFromSerialized` reads, as against a live scene. */\nexport function isSerializedScene<TData, TLayer extends string, TPose>(\n value: unknown,\n): value is SerializedScene<TData, TLayer, TPose> {\n return typeof value === 'object' && value != null\n && (value as { version?: unknown }).version === 1\n && Array.isArray((value as { nodes?: unknown }).nodes);\n}\n\n/** What a snapshot is written from. */\nexport interface SerializableState<TData, TLayer extends string, TPose> {\n nodes: Map<NodeId, Node<TData, TLayer, TPose>>;\n roots: NodeId[];\n layers: LayerRecord<TLayer>[];\n}\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. */\nexport function 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 ...(spec.annotation ? { annotation: true } : {}),\n };\n return spec.kind === 'user'\n ? { ...base, kind: 'user', name: spec.name ?? spec.id }\n : { ...base, kind: 'system' };\n}\n\n/** The snapshot of `state`: layers in order, nodes in tree preorder, and the\n * document values when there are any. Throws\n * when a node carries a function the registry has no key for. */\nexport function serializeScene<TData, TLayer extends string, TPose>(\n state: SerializableState<TData, TLayer, TPose>,\n fnFields: readonly NodeFnField[],\n doc?: SerializedDoc,\n): SerializedScene<TData, TLayer, TPose> {\n const nodes: SerializedNode<TData, TLayer, TPose>[] = [];\n for (const n of treePreorder(state.roots, state.nodes)) {\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 if (n.hidden === true) out.hidden = true;\n if (n.locked === true) out.locked = true;\n if (n.kind === 'container' && n.units !== undefined) out.units = n.units;\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.annotation) layer.annotation = true;\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, ...(doc ? { doc } : {}) };\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. */\nexport function specsFromSerialized<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose>,\n registry: SceneRegistry<TPose, TData, TLayer>,\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.hidden === true) spec.hidden = true;\n if (n.locked === true) spec.locked = true;\n if (n.units !== undefined) spec.units = n.units;\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"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"serialization.js","names":[],"sources":["../../../src/core/scene/serialization.ts"],"sourcesContent":["/**\n * A scene to and from its JSON snapshot: the walk that writes one, and the\n * two readers that turn one back into layer records and node specs.\n */\nimport {\n NODE_FN_FIELDS, fnKeysOf, type FnBearingNode, type NodeFnField,\n} from './nodeFnFields';\nimport type { SerializedDoc } from './docValues';\nimport { treePreorder } from './treeOrder';\nimport type {\n AddNodeSpec, LayerRecord, Node, NodeId, SceneRegistry, SerializedLayer, SerializedNode, SerializedNodeV1,\n SerializedScene, SerializedSceneV1,\n} from './types';\n\n/** Whether `value` is a snapshot `specsFromSerialized` reads, as against a live scene. */\nexport function isSerializedScene<TData, TLayer extends string, TPose>(\n value: unknown,\n): value is SerializedScene<TData, TLayer, TPose> | SerializedSceneV1<TData, TLayer, TPose> {\n const version = typeof value === 'object' && value != null\n ? (value as { version?: unknown }).version : undefined;\n return (version === 1 || version === 2)\n && Array.isArray((value as { nodes?: unknown }).nodes);\n}\n\n/** What a snapshot is written from. */\nexport interface SerializableState<TData, TLayer extends string, TPose> {\n nodes: Map<NodeId, Node<TData, TLayer, TPose>>;\n roots: NodeId[];\n layers: LayerRecord<TLayer>[];\n}\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. */\nexport function 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 ...(spec.annotation ? { annotation: true } : {}),\n };\n return spec.kind === 'user'\n ? { ...base, kind: 'user', name: spec.name ?? spec.id }\n : { ...base, kind: 'system' };\n}\n\n/** The snapshot of `state`: layers in order, nodes in tree preorder, and the\n * document values when there are any. Throws\n * when a node carries a function the registry has no key for. */\nexport function serializeScene<TData, TLayer extends string, TPose>(\n state: SerializableState<TData, TLayer, TPose>,\n fnFields: readonly NodeFnField[],\n doc?: SerializedDoc,\n): SerializedScene<TData, TLayer, TPose> {\n const nodes: SerializedNode<TData, TLayer, TPose>[] = [];\n for (const n of treePreorder(state.roots, state.nodes)) {\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 if (n.hidden === true) out.hidden = true;\n if (n.locked === true) out.locked = true;\n if (n.units !== undefined) out.units = n.units;\n if (n.clip !== undefined) out.clip = n.clip;\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.annotation) layer.annotation = true;\n if (l.kind === 'user') {\n layer.kind = 'user';\n layer.name = l.name;\n }\n return layer;\n });\n return { version: 2, systemLayers, nodes, ...(doc ? { doc } : {}) };\n}\n\n/** Decides what a version 1 `container` becomes; `leaf` is always a mark. */\nexport type V1Classifier<TData, TLayer extends string, TPose> =\n (node: SerializedNodeV1<TData, TLayer, TPose>) => 'mark' | 'group';\n\n/** Options for {@link specsFromSerialized}. */\nexport interface SpecsFromSerializedOptions<TData, TLayer extends string, TPose> {\n /** What a version 1 `container` loads as; see {@link V1Classifier}. */\n classifyV1?: V1Classifier<TData, TLayer, TPose>;\n /** `'skip'` loads a node whose registry key is unknown without that\n * function, for a save that outlived the code that registered it.\n * Default `'throw'`. */\n unknownKeys?: 'throw' | 'skip';\n /** Hears each key `unknownKeys: 'skip'` leaves out, as it is left out. */\n onSkip?: (skipped: SkippedKey) => void;\n}\n\n/** A registry key a load left out: the node, the function field it named,\n * and the key. */\nexport interface SkippedKey {\n id: NodeId;\n field: keyof SceneRegistry<unknown>;\n key: string;\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, and on an unknown registry key unless\n * `opts.unknownKeys` is `'skip'`. */\nexport function specsFromSerialized<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose> | SerializedSceneV1<TData, TLayer, TPose>,\n registry: SceneRegistry<TPose, TData, TLayer>,\n opts: SpecsFromSerializedOptions<TData, TLayer, TPose> = {},\n): AddNodeSpec<TData, TLayer, TPose>[] {\n type Entry = { n: Omit<SerializedNode<TData, TLayer, TPose>, 'kind'>; kind: 'mark' | 'group' };\n let entries: Entry[];\n if (json.version === 1) {\n entries = json.nodes.map((n) => ({ n, kind: nodeKindOf(1, n, opts.classifyV1) }));\n } else if (json.version === 2) {\n entries = json.nodes.map((n) => ({ n, kind: nodeKindOf(2, n) }));\n } else {\n throw new Error(`Scene: unsupported version ${String(Reflect.get(json, 'version'))}; versions 1 and 2 are supported`);\n }\n return entries.map(({ n, kind }) => {\n const spec: AddNodeSpec<TData, TLayer, TPose> = {\n id: n.id as NodeId,\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.hidden === true) spec.hidden = true;\n if (n.locked === true) spec.locked = true;\n if (n.units !== undefined) spec.units = n.units;\n if (n.clip !== undefined) spec.clip = n.clip;\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 && opts.unknownKeys === 'skip') {\n opts.onSkip?.({ id: spec.id!, field: field.field, key });\n continue;\n }\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 if (clipsAsV1(json.version, spec)) spec.clip = 'outline';\n return spec;\n });\n}\n\n/** Version 1 clipped a container with no clip function to its outline, which\n * is what `clip: 'outline'` draws on a group. One a classifier makes a mark\n * gets no clip, since which painter claims it is not known here; one whose\n * clip key was skipped loads as it would have without it. */\nfunction clipsAsV1(version: 1 | 2, spec: { kind: string; clipFromPose?: unknown }): boolean {\n return version === 1 && spec.kind === 'group' && spec.clipFromPose === undefined;\n}\n\n/** The kind a saved node loads as: its own on version 2; on version 1 a `leaf` is a\n * mark and a `container` goes to `classify`, or is a group without one. */\nexport function nodeKindOf<TData, TLayer extends string, TPose>(\n version: 1 | 2,\n n: SerializedNode<TData, TLayer, TPose> | SerializedNodeV1<TData, TLayer, TPose>,\n classify?: V1Classifier<TData, TLayer, TPose>,\n): 'mark' | 'group' {\n if (version === 2) return (n as SerializedNode<TData, TLayer, TPose>).kind;\n if (n.kind === 'leaf') return 'mark';\n return classify ? classify(n as SerializedNodeV1<TData, TLayer, TPose>) : 'group';\n}\n"],"mappings":"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"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { hasChildren } from "./treeShape.js";
|
|
2
|
+
|
|
1
3
|
//#region src/core/scene/staleReplay.ts
|
|
2
4
|
/** A scene edit named a node the scene does not hold, or one it already does. */
|
|
3
5
|
var SceneMembershipError = class extends Error {};
|
|
@@ -8,7 +10,7 @@ function createStaleReplay(nodes) {
|
|
|
8
10
|
const holds = (id) => id === null || nodes.has(id);
|
|
9
11
|
const childless = (id, within) => {
|
|
10
12
|
const node = nodes.get(id);
|
|
11
|
-
return node
|
|
13
|
+
return node === void 0 || !hasChildren(node) || node.children.every((c) => within?.has(c) === true);
|
|
12
14
|
};
|
|
13
15
|
function stale(kind, payload, forward) {
|
|
14
16
|
switch (kind) {
|
|
@@ -31,7 +33,8 @@ function createStaleReplay(nodes) {
|
|
|
31
33
|
case "kit:setLayer":
|
|
32
34
|
case "kit:setDependsOn":
|
|
33
35
|
case "kit:setLayout":
|
|
34
|
-
case "kit:setUnits":
|
|
36
|
+
case "kit:setUnits":
|
|
37
|
+
case "kit:setClip": return !nodes.has(payload.id);
|
|
35
38
|
default: return false;
|
|
36
39
|
}
|
|
37
40
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"staleReplay.js","names":[],"sources":["../../../src/core/scene/staleReplay.ts"],"sourcesContent":["/**\n * What a replay does with an op whose node is not where its entry left it.\n *\n * An untracked edit changes the tree without the history stack hearing of it,\n * so an entry can name a node that edit removed, or add one it already put\n * back. Replaying such an op is skipped rather than refused: a refusal leaves\n * the entry on top of its stack, and every entry beneath it out of reach. The\n * inverse of a skipped op is skipped too, so undo then redo changes nothing.\n */\nimport type { RemoveSnapshot } from './kitOps';\nimport type { Node, NodeId } from './types';\n\n/** A scene edit named a node the scene does not hold, or one it already does. */\nexport class SceneMembershipError extends Error {}\n\nexport interface StaleReplay {\n /** Run a step that replays recorded ops. */\n during<T>(step: () => T): T;\n /** Whether replaying this kit op would address a node that is gone, or\n * restore one that is already there. Always false outside `during`. */\n skips(kind: string, payload: unknown, forward: boolean): boolean;\n}\n\nexport function createStaleReplay<TData, TLayer extends string, TPose>(\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>,\n): StaleReplay {\n let replaying = 0;\n /** Kit payloads whose last replay was skipped, by the direction it ran in. */\n const skipped = new WeakMap<object, boolean>();\n const holds = (id: NodeId | null): boolean => id === null || nodes.has(id);\n const childless = (id: NodeId, within?: ReadonlySet<NodeId>): boolean => {\n const node = nodes.get(id);\n return node
|
|
1
|
+
{"version":3,"file":"staleReplay.js","names":[],"sources":["../../../src/core/scene/staleReplay.ts"],"sourcesContent":["/**\n * What a replay does with an op whose node is not where its entry left it.\n *\n * An untracked edit changes the tree without the history stack hearing of it,\n * so an entry can name a node that edit removed, or add one it already put\n * back. Replaying such an op is skipped rather than refused: a refusal leaves\n * the entry on top of its stack, and every entry beneath it out of reach. The\n * inverse of a skipped op is skipped too, so undo then redo changes nothing.\n */\nimport type { RemoveSnapshot } from './kitOps';\nimport { hasChildren } from './treeShape';\nimport type { Node, NodeId } from './types';\n\n/** A scene edit named a node the scene does not hold, or one it already does. */\nexport class SceneMembershipError extends Error {}\n\nexport interface StaleReplay {\n /** Run a step that replays recorded ops. */\n during<T>(step: () => T): T;\n /** Whether replaying this kit op would address a node that is gone, or\n * restore one that is already there. Always false outside `during`. */\n skips(kind: string, payload: unknown, forward: boolean): boolean;\n}\n\nexport function createStaleReplay<TData, TLayer extends string, TPose>(\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>,\n): StaleReplay {\n let replaying = 0;\n /** Kit payloads whose last replay was skipped, by the direction it ran in. */\n const skipped = new WeakMap<object, boolean>();\n const holds = (id: NodeId | null): boolean => id === null || nodes.has(id);\n const childless = (id: NodeId, within?: ReadonlySet<NodeId>): boolean => {\n const node = nodes.get(id);\n return node === undefined || !hasChildren(node) || node.children.every((c) => within?.has(c) === true);\n };\n\n function stale(kind: string, payload: unknown, forward: boolean): boolean {\n switch (kind) {\n case 'kit:add': {\n const p = payload as { id: NodeId; parent: NodeId | null };\n return forward ? nodes.has(p.id) || !holds(p.parent) : !nodes.has(p.id) || !childless(p.id);\n }\n case 'kit:remove': {\n const p = payload as RemoveSnapshot<TData, TLayer, TPose>;\n if (!forward) return p.nodes.some((n) => nodes.has(n.id)) || !p.detached.every((d) => holds(d.parent));\n const taken = new Set(p.nodes.map((n) => n.id));\n return !p.nodes.every((n) => nodes.has(n.id) && childless(n.id, taken));\n }\n case 'kit:move': {\n const p = payload as { id: NodeId; fromParent: NodeId | null; toParent: NodeId | null };\n return !nodes.has(p.id) || !holds(forward ? p.toParent : p.fromParent);\n }\n case 'kit:setPose':\n case 'kit:setData':\n case 'kit:setLayer':\n case 'kit:setDependsOn':\n case 'kit:setLayout':\n case 'kit:setUnits':\n case 'kit:setClip':\n return !nodes.has((payload as { id: NodeId }).id);\n default:\n return false;\n }\n }\n\n function skips(kind: string, payload: unknown, forward: boolean): boolean {\n if (replaying === 0 || typeof payload !== 'object' || payload === null) return false;\n if (skipped.get(payload) === !forward) return skipped.delete(payload);\n if (!stale(kind, payload, forward)) return false;\n skipped.set(payload, forward);\n return true;\n }\n\n return {\n during(step) {\n replaying++;\n try {\n return step();\n } finally {\n replaying--;\n }\n },\n skips,\n };\n}\n"],"mappings":";;;;AAcA,IAAa,uBAAb,cAA0C,MAAM,CAAC;AAUjD,SAAgB,kBACd,OACa;CACb,IAAI,YAAY;;CAEhB,MAAM,0BAAU,IAAI,QAAyB;CAC7C,MAAM,SAAS,OAA+B,OAAO,QAAQ,MAAM,IAAI,EAAE;CACzE,MAAM,aAAa,IAAY,WAA0C;EACvE,MAAM,OAAO,MAAM,IAAI,EAAE;EACzB,OAAO,SAAS,UAAa,CAAC,YAAY,IAAI,KAAK,KAAK,SAAS,OAAO,MAAM,QAAQ,IAAI,CAAC,MAAM,IAAI;CACvG;CAEA,SAAS,MAAM,MAAc,SAAkB,SAA2B;EACxE,QAAQ,MAAR;GACE,KAAK,WAAW;IACd,MAAM,IAAI;IACV,OAAO,UAAU,MAAM,IAAI,EAAE,EAAE,KAAK,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC,MAAM,IAAI,EAAE,EAAE,KAAK,CAAC,UAAU,EAAE,EAAE;GAC5F;GACA,KAAK,cAAc;IACjB,MAAM,IAAI;IACV,IAAI,CAAC,SAAS,OAAO,EAAE,MAAM,MAAM,MAAM,MAAM,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,SAAS,OAAO,MAAM,MAAM,EAAE,MAAM,CAAC;IACrG,MAAM,QAAQ,IAAI,IAAI,EAAE,MAAM,KAAK,MAAM,EAAE,EAAE,CAAC;IAC9C,OAAO,CAAC,EAAE,MAAM,OAAO,MAAM,MAAM,IAAI,EAAE,EAAE,KAAK,UAAU,EAAE,IAAI,KAAK,CAAC;GACxE;GACA,KAAK,YAAY;IACf,MAAM,IAAI;IACV,OAAO,CAAC,MAAM,IAAI,EAAE,EAAE,KAAK,CAAC,MAAM,UAAU,EAAE,WAAW,EAAE,UAAU;GACvE;GACA,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK,eACH,OAAO,CAAC,MAAM,IAAK,QAA2B,EAAE;GAClD,SACE,OAAO;EACX;CACF;CAEA,SAAS,MAAM,MAAc,SAAkB,SAA2B;EACxE,IAAI,cAAc,KAAK,OAAO,YAAY,YAAY,YAAY,MAAM,OAAO;EAC/E,IAAI,QAAQ,IAAI,OAAO,MAAM,CAAC,SAAS,OAAO,QAAQ,OAAO,OAAO;EACpE,IAAI,CAAC,MAAM,MAAM,SAAS,OAAO,GAAG,OAAO;EAC3C,QAAQ,IAAI,SAAS,OAAO;EAC5B,OAAO;CACT;CAEA,OAAO;EACL,OAAO,MAAM;GACX;GACA,IAAI;IACF,OAAO,KAAK;GACd,UAAU;IACR;GACF;EACF;EACA;CACF;AACF"}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
//#region src/core/scene/statedFields.ts
|
|
2
2
|
/** The plain optional fields of a node or spec as a spread for `scene.add`:
|
|
3
3
|
* each present only when stated, so an unstated one keeps the scene's
|
|
4
|
-
* default
|
|
4
|
+
* default, and a flag states only `true`. What a copy of a node carries over
|
|
5
|
+
* besides its kind, layer, pose, data and functions. */
|
|
5
6
|
var statedFields = (n) => ({
|
|
6
7
|
...n.pickable !== void 0 ? { pickable: n.pickable } : {},
|
|
7
8
|
...n.hidden === true ? { hidden: true } : {},
|
|
8
9
|
...n.locked === true ? { locked: true } : {},
|
|
9
|
-
...n.
|
|
10
|
+
...n.units !== void 0 ? { units: n.units } : {},
|
|
11
|
+
...n.clip !== void 0 ? { clip: n.clip } : {}
|
|
10
12
|
});
|
|
11
13
|
|
|
12
14
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"statedFields.js","names":[],"sources":["../../../src/core/scene/statedFields.ts"],"sourcesContent":["import type { UnitScope } from '@weasel-js/quantity';\
|
|
1
|
+
{"version":3,"file":"statedFields.js","names":[],"sources":["../../../src/core/scene/statedFields.ts"],"sourcesContent":["import type { UnitScope } from '@weasel-js/quantity';\nimport type { NodeClip } from './types';\n\n/** The plain optional fields a node or an `AddNodeSpec` may state. */\nexport interface StatedNodeFields {\n pickable?: boolean;\n hidden?: boolean;\n locked?: boolean;\n units?: UnitScope;\n clip?: NodeClip;\n}\n\n/** The plain optional fields of a node or spec as a spread for `scene.add`:\n * each present only when stated, so an unstated one keeps the scene's\n * default, and a flag states only `true`. What a copy of a node carries over\n * besides its kind, layer, pose, data and functions. */\nexport const statedFields = (n: StatedNodeFields & { kind?: string }): StatedNodeFields => ({\n ...(n.pickable !== undefined ? { pickable: n.pickable } : {}),\n ...(n.hidden === true ? { hidden: true } : {}),\n ...(n.locked === true ? { locked: true } : {}),\n ...(n.units !== undefined ? { units: n.units } : {}),\n ...(n.clip !== undefined ? { clip: n.clip } : {}),\n});\n"],"mappings":";;;;;AAgBA,IAAa,gBAAgB,OAA+D;CAC1F,GAAI,EAAE,aAAa,SAAY,EAAE,UAAU,EAAE,SAAS,IAAI,CAAC;CAC3D,GAAI,EAAE,WAAW,OAAO,EAAE,QAAQ,KAAK,IAAI,CAAC;CAC5C,GAAI,EAAE,WAAW,OAAO,EAAE,QAAQ,KAAK,IAAI,CAAC;CAC5C,GAAI,EAAE,UAAU,SAAY,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;CAClD,GAAI,EAAE,SAAS,SAAY,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;AACjD"}
|
|
@@ -8,7 +8,7 @@ import { SceneMembershipError } from "./staleReplay.js";
|
|
|
8
8
|
function removeSnapshot(ids, removing, store, fnFields) {
|
|
9
9
|
const nodes = ids.map((nid) => {
|
|
10
10
|
const n = store.requireNode(nid);
|
|
11
|
-
return n.
|
|
11
|
+
return n.children ? {
|
|
12
12
|
...n,
|
|
13
13
|
children: [...n.children]
|
|
14
14
|
} : { ...n };
|
|
@@ -40,7 +40,7 @@ function createTreeEdits(env) {
|
|
|
40
40
|
const { noteArrival, noteDeparture, noteChange } = env.arrivals;
|
|
41
41
|
/** Check that `spec` can be placed, and answer with the `kit:add` payload
|
|
42
42
|
* that places it. Throws on an id collision, an unknown or locked layer,
|
|
43
|
-
* a parent
|
|
43
|
+
* a locked parent, and a layer below the
|
|
44
44
|
* parent's. */
|
|
45
45
|
function addPayload(spec) {
|
|
46
46
|
const id = spec.id ?? env.generateId();
|
|
@@ -50,7 +50,6 @@ function createTreeEdits(env) {
|
|
|
50
50
|
const parent = spec.parent ?? null;
|
|
51
51
|
if (parent !== null) {
|
|
52
52
|
const p = requireNode(parent);
|
|
53
|
-
if (p.kind !== "container") throw new Error(`Scene: parent "${parent}" is not a container`);
|
|
54
53
|
assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);
|
|
55
54
|
refuse(parent, "add under");
|
|
56
55
|
}
|
|
@@ -111,7 +110,6 @@ function createTreeEdits(env) {
|
|
|
111
110
|
if (parent !== null) {
|
|
112
111
|
refuse(parent, "move nodes into");
|
|
113
112
|
const p = requireNode(parent);
|
|
114
|
-
if (p.kind !== "container") throw new Error(`Scene: parent "${parent}" is not a container`);
|
|
115
113
|
assertSubtreeLayer(id, node.layer, parent, p.layer);
|
|
116
114
|
if (parent === id) throw new Error("Scene: cannot parent a node to itself");
|
|
117
115
|
const desc = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"treeEdits.js","names":[],"sources":["../../../src/core/scene/treeEdits.ts"],"sourcesContent":["/**\n * The scene's edits to its tree: adding and removing nodes, reparenting, and\n * reordering siblings. Each checks its arguments, then records one kit op.\n */\nimport type { ArrivalWindow } from './arrivalWindow';\nimport type { RemoveSnapshot } from './kitOps';\nimport type { createLayerStack } from './layerStack';\nimport type { LockGuard } from './lockGuard';\nimport { fnKeysOf, type FnBearingNode, type NodeFnField } from './nodeFnFields';\nimport type { createNodeStore } from './nodeStore';\nimport type { Recorder } from './recorder';\nimport { SceneMembershipError } from './staleReplay';\nimport { statedFields } from './statedFields';\nimport type { AddNodeSpec, Node, NodeId, Scene } from './types';\n\nexport interface TreeEditsEnv<TData, TLayer extends string, TPose> {\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>;\n generateId(): NodeId;\n store: Pick<\n ReturnType<typeof createNodeStore<TData, TLayer, TPose>>,\n 'requireNode' | 'siblingsOf' | 'descendants' | 'removalClosure' | 'patchNodeFunctions'\n >;\n locks: Pick<LockGuard<TLayer>, 'refuse' | 'refuseLayer' | 'lifted'>;\n layers: Pick<ReturnType<typeof createLayerStack<TLayer>>, 'requireLayerIndex' | 'assertSubtreeLayer'>;\n fnFields: readonly NodeFnField[];\n /** Run a registered op without recording it. */\n runOp(kind: string, payload: unknown): void;\n recorder: Pick<Recorder, 'record' | 'edit'>;\n arrivals: Pick<ArrivalWindow<TPose>, 'noteArrival' | 'noteDeparture' | 'noteChange'>;\n}\n\nexport interface TreeEdits<TData, TLayer extends string, TPose>\n extends Pick<Scene<TData, TLayer, TPose>, 'add' | 'remove' | 'removalClosure' | 'removeMany' | 'move' | 'reorder'> {\n /** Place nodes as the document a scene starts from, or is loaded with:\n * nothing is recorded, and no lock refuses. Specs list parents before\n * children, the order `toJSON()` emits. */\n construct(specs: readonly AddNodeSpec<TData, TLayer, TPose>[]): void;\n}\n\n/** What `kit:remove` carries for the nodes `ids`, read before any of them\n * goes. Throws on an id that is not in the scene. */\nfunction removeSnapshot<TData, TLayer extends string, TPose>(\n ids: readonly NodeId[],\n removing: ReadonlySet<NodeId>,\n store: Pick<TreeEditsEnv<TData, TLayer, TPose>['store'], 'requireNode' | 'siblingsOf'>,\n fnFields: readonly NodeFnField[],\n): RemoveSnapshot<TData, TLayer, TPose> {\n const nodes: Node<TData, TLayer, TPose>[] = ids.map((nid) => {\n const n = store.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 = nodes\n .filter((n) => n.parent === null || !removing.has(n.parent))\n .map((n) => ({ id: n.id, parent: n.parent, index: store.siblingsOf(n.parent).indexOf(n.id) }))\n .sort((l, r) => l.index - r.index);\n const fnKeys = nodes.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 return { nodes, detached, ...(fnKeys.length > 0 ? { fnKeys } : {}) };\n}\n\nexport function createTreeEdits<TData, TLayer extends string, TPose>(\n env: TreeEditsEnv<TData, TLayer, TPose>,\n): TreeEdits<TData, TLayer, TPose> {\n const { nodes, fnFields } = env;\n const { requireNode, siblingsOf, descendants, removalClosure, patchNodeFunctions } = env.store;\n const { refuse, refuseLayer } = env.locks;\n const { requireLayerIndex, assertSubtreeLayer } = env.layers;\n const { record, edit } = env.recorder;\n const { noteArrival, noteDeparture, noteChange } = env.arrivals;\n\n /** Check that `spec` can be placed, and answer with the `kit:add` payload\n * that places it. Throws on an id collision, an unknown or locked layer,\n * a parent that is not a container or is locked, and a layer below the\n * parent's. */\n function addPayload(spec: AddNodeSpec<TData, TLayer, TPose>) {\n const id = spec.id ?? env.generateId();\n if (nodes.has(id)) throw new SceneMembershipError(`Scene: id collision on \"${id}\"`);\n requireLayerIndex(spec.layer);\n refuseLayer(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 refuse(parent, 'add under');\n }\n return {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index: spec.index ?? siblingsOf(parent).length,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...statedFields(spec),\n ...fnKeysOf(fnFields, { ...spec, id, kind: spec.kind } as unknown as FnBearingNode, 'opKey'),\n };\n }\n\n function removeMany(rootIds: readonly NodeId[]): void {\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) refuse(nid, 'remove');\n const payload = removeSnapshot(ids, removing, env.store, fnFields);\n const { detached } = payload;\n edit('remove', detached.some((d) => d.parent !== null), () => {\n for (const d of detached) noteDeparture(d.id, d.parent, null);\n record('kit:remove', payload, 'remove');\n });\n }\n\n return {\n construct(specs) {\n env.locks.lifted(() => {\n for (const spec of specs) {\n const payload = addPayload(spec);\n env.runOp('kit:add', payload);\n patchNodeFunctions(spec, payload.id, null);\n }\n });\n },\n\n add(spec) {\n const payload = addPayload(spec);\n const label = `add ${spec.kind}`;\n return edit(label, payload.parent !== null, () => {\n noteArrival(payload.id, payload.parent, null);\n record('kit:add', payload, label);\n patchNodeFunctions(spec, payload.id, payload);\n return payload.id;\n });\n },\n\n remove: (id) => removeMany([id]),\n\n removalClosure: (rootIds) => removalClosure(rootIds).ids,\n\n removeMany,\n\n move(id, parent, index) {\n const node = requireNode(id);\n refuse(id, 'move');\n if (parent !== null) {\n refuse(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 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 const fromParent = node.parent;\n edit('move', parent !== null || fromParent !== null, () => {\n const fromIndex = siblingsOf(fromParent).indexOf(id);\n const toIndex = index ?? siblingsOf(parent).length;\n noteArrival(id, parent, fromParent);\n noteDeparture(id, fromParent, parent);\n noteChange(fromParent);\n record('kit:move', { id, fromParent, fromIndex, toParent: parent, toIndex }, 'move');\n });\n },\n\n reorder(id, index) {\n const node = requireNode(id);\n refuse(id, 'reorder');\n const parent = node.parent;\n edit('reorder', parent !== null, () => {\n noteChange(parent);\n const fromIndex = siblingsOf(parent).indexOf(id);\n record('kit:move', { id, fromParent: parent, fromIndex, toParent: parent, toIndex: index }, 'reorder');\n });\n },\n };\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"treeEdits.js","names":[],"sources":["../../../src/core/scene/treeEdits.ts"],"sourcesContent":["/**\n * The scene's edits to its tree: adding and removing nodes, reparenting, and\n * reordering siblings. Each checks its arguments, then records one kit op.\n */\nimport type { ArrivalWindow } from './arrivalWindow';\nimport type { RemoveSnapshot } from './kitOps';\nimport type { createLayerStack } from './layerStack';\nimport type { LockGuard } from './lockGuard';\nimport { fnKeysOf, type FnBearingNode, type NodeFnField } from './nodeFnFields';\nimport type { createNodeStore } from './nodeStore';\nimport type { Recorder } from './recorder';\nimport { SceneMembershipError } from './staleReplay';\nimport { statedFields } from './statedFields';\nimport type { AddNodeSpec, Node, NodeId, Scene } from './types';\n\nexport interface TreeEditsEnv<TData, TLayer extends string, TPose> {\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>;\n generateId(): NodeId;\n store: Pick<\n ReturnType<typeof createNodeStore<TData, TLayer, TPose>>,\n 'requireNode' | 'siblingsOf' | 'descendants' | 'removalClosure' | 'patchNodeFunctions'\n >;\n locks: Pick<LockGuard<TLayer>, 'refuse' | 'refuseLayer' | 'lifted'>;\n layers: Pick<ReturnType<typeof createLayerStack<TLayer>>, 'requireLayerIndex' | 'assertSubtreeLayer'>;\n fnFields: readonly NodeFnField[];\n /** Run a registered op without recording it. */\n runOp(kind: string, payload: unknown): void;\n recorder: Pick<Recorder, 'record' | 'edit'>;\n arrivals: Pick<ArrivalWindow<TPose>, 'noteArrival' | 'noteDeparture' | 'noteChange'>;\n}\n\nexport interface TreeEdits<TData, TLayer extends string, TPose>\n extends Pick<Scene<TData, TLayer, TPose>, 'add' | 'remove' | 'removalClosure' | 'removeMany' | 'move' | 'reorder'> {\n /** Place nodes as the document a scene starts from, or is loaded with:\n * nothing is recorded, and no lock refuses. Specs list parents before\n * children, the order `toJSON()` emits. */\n construct(specs: readonly AddNodeSpec<TData, TLayer, TPose>[]): void;\n}\n\n/** What `kit:remove` carries for the nodes `ids`, read before any of them\n * goes. Throws on an id that is not in the scene. */\nfunction removeSnapshot<TData, TLayer extends string, TPose>(\n ids: readonly NodeId[],\n removing: ReadonlySet<NodeId>,\n store: Pick<TreeEditsEnv<TData, TLayer, TPose>['store'], 'requireNode' | 'siblingsOf'>,\n fnFields: readonly NodeFnField[],\n): RemoveSnapshot<TData, TLayer, TPose> {\n const nodes: Node<TData, TLayer, TPose>[] = ids.map((nid) => {\n const n = store.requireNode(nid);\n return n.children ? { ...n, children: [...n.children] } : { ...n };\n });\n // The rest is reachable through a snapshotted parent's cloned `children`.\n const detached = nodes\n .filter((n) => n.parent === null || !removing.has(n.parent))\n .map((n) => ({ id: n.id, parent: n.parent, index: store.siblingsOf(n.parent).indexOf(n.id) }))\n .sort((l, r) => l.index - r.index);\n const fnKeys = nodes.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 return { nodes, detached, ...(fnKeys.length > 0 ? { fnKeys } : {}) };\n}\n\nexport function createTreeEdits<TData, TLayer extends string, TPose>(\n env: TreeEditsEnv<TData, TLayer, TPose>,\n): TreeEdits<TData, TLayer, TPose> {\n const { nodes, fnFields } = env;\n const { requireNode, siblingsOf, descendants, removalClosure, patchNodeFunctions } = env.store;\n const { refuse, refuseLayer } = env.locks;\n const { requireLayerIndex, assertSubtreeLayer } = env.layers;\n const { record, edit } = env.recorder;\n const { noteArrival, noteDeparture, noteChange } = env.arrivals;\n\n /** Check that `spec` can be placed, and answer with the `kit:add` payload\n * that places it. Throws on an id collision, an unknown or locked layer,\n * a locked parent, and a layer below the\n * parent's. */\n function addPayload(spec: AddNodeSpec<TData, TLayer, TPose>) {\n const id = spec.id ?? env.generateId();\n if (nodes.has(id)) throw new SceneMembershipError(`Scene: id collision on \"${id}\"`);\n requireLayerIndex(spec.layer);\n refuseLayer(spec.layer, 'add to');\n const parent = spec.parent ?? null;\n if (parent !== null) {\n const p = requireNode(parent);\n assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);\n refuse(parent, 'add under');\n }\n return {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index: spec.index ?? siblingsOf(parent).length,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...statedFields(spec),\n ...fnKeysOf(fnFields, { ...spec, id, kind: spec.kind } as unknown as FnBearingNode, 'opKey'),\n };\n }\n\n function removeMany(rootIds: readonly NodeId[]): void {\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) refuse(nid, 'remove');\n const payload = removeSnapshot(ids, removing, env.store, fnFields);\n const { detached } = payload;\n edit('remove', detached.some((d) => d.parent !== null), () => {\n for (const d of detached) noteDeparture(d.id, d.parent, null);\n record('kit:remove', payload, 'remove');\n });\n }\n\n return {\n construct(specs) {\n env.locks.lifted(() => {\n for (const spec of specs) {\n const payload = addPayload(spec);\n env.runOp('kit:add', payload);\n patchNodeFunctions(spec, payload.id, null);\n }\n });\n },\n\n add(spec) {\n const payload = addPayload(spec);\n const label = `add ${spec.kind}`;\n return edit(label, payload.parent !== null, () => {\n noteArrival(payload.id, payload.parent, null);\n record('kit:add', payload, label);\n patchNodeFunctions(spec, payload.id, payload);\n return payload.id;\n });\n },\n\n remove: (id) => removeMany([id]),\n\n removalClosure: (rootIds) => removalClosure(rootIds).ids,\n\n removeMany,\n\n move(id, parent, index) {\n const node = requireNode(id);\n refuse(id, 'move');\n if (parent !== null) {\n refuse(parent, 'move nodes into');\n const p = requireNode(parent);\n assertSubtreeLayer(id, node.layer, parent, p.layer);\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 const fromParent = node.parent;\n edit('move', parent !== null || fromParent !== null, () => {\n const fromIndex = siblingsOf(fromParent).indexOf(id);\n const toIndex = index ?? siblingsOf(parent).length;\n noteArrival(id, parent, fromParent);\n noteDeparture(id, fromParent, parent);\n noteChange(fromParent);\n record('kit:move', { id, fromParent, fromIndex, toParent: parent, toIndex }, 'move');\n });\n },\n\n reorder(id, index) {\n const node = requireNode(id);\n refuse(id, 'reorder');\n const parent = node.parent;\n edit('reorder', parent !== null, () => {\n noteChange(parent);\n const fromIndex = siblingsOf(parent).indexOf(id);\n record('kit:move', { id, fromParent: parent, fromIndex, toParent: parent, toIndex: index }, 'reorder');\n });\n },\n };\n}\n"],"mappings":"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"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { hasChildren } from "./treeShape.js";
|
|
2
|
+
|
|
1
3
|
//#region src/core/scene/treeOrder.ts
|
|
2
4
|
/** Every node reachable from `roots`, in tree preorder: a parent before its
|
|
3
5
|
* children, siblings in sibling order, whatever layer each sits on. */
|
|
@@ -8,7 +10,7 @@ function treePreorder(roots, nodes) {
|
|
|
8
10
|
const node = nodes.get(stack.pop());
|
|
9
11
|
if (!node) continue;
|
|
10
12
|
out.push(node);
|
|
11
|
-
if (node
|
|
13
|
+
if (hasChildren(node)) for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i]);
|
|
12
14
|
}
|
|
13
15
|
return out;
|
|
14
16
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"treeOrder.js","names":[],"sources":["../../../src/core/scene/treeOrder.ts"],"sourcesContent":["import type { Node, NodeId } from './types';\n\n/** Every node reachable from `roots`, in tree preorder: a parent before its\n * children, siblings in sibling order, whatever layer each sits on. */\nexport function treePreorder<TData, TLayer extends string, TPose>(\n roots: readonly NodeId[],\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>,\n): Node<TData, TLayer, TPose>[] {\n const out: Node<TData, TLayer, TPose>[] = [];\n const stack: NodeId[] = [...roots].reverse();\n while (stack.length > 0) {\n const node = nodes.get(stack.pop()!);\n if (!node) continue;\n out.push(node);\n if (node
|
|
1
|
+
{"version":3,"file":"treeOrder.js","names":[],"sources":["../../../src/core/scene/treeOrder.ts"],"sourcesContent":["import type { Node, NodeId } from './types';\nimport { hasChildren } from './treeShape';\n\n/** Every node reachable from `roots`, in tree preorder: a parent before its\n * children, siblings in sibling order, whatever layer each sits on. */\nexport function treePreorder<TData, TLayer extends string, TPose>(\n roots: readonly NodeId[],\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>,\n): Node<TData, TLayer, TPose>[] {\n const out: Node<TData, TLayer, TPose>[] = [];\n const stack: NodeId[] = [...roots].reverse();\n while (stack.length > 0) {\n const node = nodes.get(stack.pop()!);\n if (!node) continue;\n out.push(node);\n if (hasChildren(node)) {\n for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i]);\n }\n }\n return out;\n}\n"],"mappings":";;;;;AAKA,SAAgB,aACd,OACA,OAC8B;CAC9B,MAAM,MAAoC,CAAC;CAC3C,MAAM,QAAkB,CAAC,GAAG,KAAK,CAAC,CAAC,QAAQ;CAC3C,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,OAAO,MAAM,IAAI,MAAM,IAAI,CAAE;EACnC,IAAI,CAAC,MAAM;EACX,IAAI,KAAK,IAAI;EACb,IAAI,YAAY,IAAI,GAClB,KAAK,IAAI,IAAI,KAAK,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK,MAAM,KAAK,KAAK,SAAS,EAAE;CAEnF;CACA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"treeReads.js","names":[],"sources":["../../../src/core/scene/treeReads.ts"],"sourcesContent":["/** The scene's reads of one node and its place in the tree. */\nimport type { Node, NodeId, Scene } from './types';\n\nexport function createTreeReads<TData, TLayer extends string, TPose>(\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>,\n): Pick<Scene<TData, TLayer, TPose>, 'get' | 'incarnation' | 'childrenOf' | 'ancestorsOf'> {\n // Keyed by node object: every entry into `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\n return {\n get: (id) => nodes.get(id),\n\n incarnation(id) {\n const node = 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 = nodes.get(id);\n return n
|
|
1
|
+
{"version":3,"file":"treeReads.js","names":[],"sources":["../../../src/core/scene/treeReads.ts"],"sourcesContent":["/** The scene's reads of one node and its place in the tree. */\nimport type { Node, NodeId, Scene } from './types';\n\nexport function createTreeReads<TData, TLayer extends string, TPose>(\n nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>,\n): Pick<Scene<TData, TLayer, TPose>, 'get' | 'incarnation' | 'childrenOf' | 'ancestorsOf'> {\n // Keyed by node object: every entry into `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\n return {\n get: (id) => nodes.get(id),\n\n incarnation(id) {\n const node = 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 = nodes.get(id);\n return n?.children ?? [];\n },\n\n ancestorsOf(id) {\n const out: NodeId[] = [];\n let cur = nodes.get(id)?.parent ?? null;\n while (cur !== null) {\n out.push(cur);\n cur = nodes.get(cur)?.parent ?? null;\n }\n return out;\n },\n };\n}\n"],"mappings":";AAGA,SAAgB,gBACd,OACyF;CAGzF,MAAM,+BAAe,IAAI,QAAwB;CACjD,IAAI,kBAAkB;CAEtB,OAAO;EACL,MAAM,OAAO,MAAM,IAAI,EAAE;EAEzB,YAAY,IAAI;GACd,MAAM,OAAO,MAAM,IAAI,EAAE;GACzB,IAAI,CAAC,MAAM,OAAO;GAClB,IAAI,QAAQ,aAAa,IAAI,IAAI;GACjC,IAAI,UAAU,QAAW;IACvB,QAAQ;IACR,aAAa,IAAI,MAAM,KAAK;GAC9B;GACA,OAAO;EACT;EAEA,WAAW,IAAI;GAEb,OADU,MAAM,IAAI,EACb,CAAA,EAAG,YAAY,CAAC;EACzB;EAEA,YAAY,IAAI;GACd,MAAM,MAAgB,CAAC;GACvB,IAAI,MAAM,MAAM,IAAI,EAAE,CAAC,EAAE,UAAU;GACnC,OAAO,QAAQ,MAAM;IACnB,IAAI,KAAK,GAAG;IACZ,MAAM,MAAM,IAAI,GAAG,CAAC,EAAE,UAAU;GAClC;GACA,OAAO;EACT;CACF;AACF"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region src/core/scene/treeShape.ts
|
|
2
|
+
/** True for a node with no children: absent and empty are the same thing. */
|
|
3
|
+
function isLeaf(node) {
|
|
4
|
+
return node.children === void 0 || node.children.length === 0;
|
|
5
|
+
}
|
|
6
|
+
/** True for a node with at least one child; narrows `children` to present. */
|
|
7
|
+
function hasChildren(node) {
|
|
8
|
+
return node.children !== void 0 && node.children.length > 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//#endregion
|
|
12
|
+
export { hasChildren, isLeaf };
|
|
13
|
+
//# sourceMappingURL=treeShape.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"treeShape.js","names":[],"sources":["../../../src/core/scene/treeShape.ts"],"sourcesContent":["import type { NodeId } from '@weasel-js/routing';\n\n/** True for a node with no children: absent and empty are the same thing. */\nexport function isLeaf(node: { children?: readonly NodeId[] }): boolean {\n return node.children === undefined || node.children.length === 0;\n}\n\n/** True for a node with at least one child; narrows `children` to present. */\nexport function hasChildren<T extends { children?: readonly NodeId[] }>(\n node: T,\n): node is T & { children: NodeId[] } {\n return node.children !== undefined && node.children.length > 0;\n}\n"],"mappings":";;AAGA,SAAgB,OAAO,MAAiD;CACtE,OAAO,KAAK,aAAa,UAAa,KAAK,SAAS,WAAW;AACjE;;AAGA,SAAgB,YACd,MACoC;CACpC,OAAO,KAAK,aAAa,UAAa,KAAK,SAAS,SAAS;AAC/D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../src/core/scene/types.ts"],"sourcesContent":["import type { History, SerializedHistory } from '@weasel-js/history';\nimport type { SerializedSceneHistory } from './historyForm';\nimport type { ParallaxOpts } from '../viewport/parallax';\nimport type { UnitScope } from '@weasel-js/quantity';\nimport type { LayoutStrategy } from '../../layout/types';\nimport type { AddLayerSpec, LayerRecord, SystemLayerRecord, SystemLayerSpec, UserLayerRecord } from './layerTypes';\nimport type { LayoutFrame, LayoutMove } from './layoutTypes';\nimport type { PoseComposition } from './composeFrame';\nimport type { PoseRemoval, PoseWrite, PoseWriteOrigin, RemovedNode, ScenePoseReports } from './poseWrites';\nimport type { PoseHold, PoseOverride, PoseOverrides } from './poseOverrideTypes';\nimport type { SceneChanges } from './sceneChanges';\nimport type { SerializedLayer, SerializedNode, SerializedScene } from './serializedTypes';\nimport type { UseSceneOptions } from './useSceneOptions';\nimport type { SceneDocValues } from './docValues';\nimport type { SceneEditPasses } from './editPass';\nimport type { RectPose } from '../geometry/rectPose';\nexport type { RectPose, UseSceneOptions };\nexport type { AddLayerSpec, LayerRecord, SystemLayerRecord, SystemLayerSpec, UserLayerRecord };\nexport type { PoseRemoval, PoseWrite, PoseWriteOrigin, RemovedNode, ScenePoseReports };\nexport type { LayoutFrame, LayoutMove, PoseHold, PoseOverride, PoseOverrides, SerializedLayer, SerializedNode, SerializedScene };\n\n/**\n * # SceneNode — the thing in the scene\n *\n * Everything the user sees on the canvas — a shape, a group, an annotation,\n * a tile — is a node. Containers and leaves are both nodes; the kit has no\n * other concept of \"scene element.\"\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 * - **`pose: TPose`** — local transform, relative to the node's direct\n * parent (or world, for root nodes).\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 * Nodes are addressed by `NodeId` everywhere outside the scene tree. Don't\n * hold references to a `Node` object across scene updates; look up by id\n * when you need the latest.\n *\n * The kit-internal name is `Node`; the public re-export is `SceneNode`\n * (avoids collision with DOM `Node` at call sites).\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\nimport type { DerivedDep, Bivariant, DerivePathFn, DerivePoseFn, ClipFromPoseFn, CopiesFromPoseFn } from './nodeFnTypes';\nexport type { DerivedDep, Bivariant, DerivePathFn, DerivePoseFn, ClipFromPoseFn, CopiesFromPoseFn };\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. It does not hide the node\n * from anything else — it still paints, still clips, and a consumer can\n * still select it by id. */\n pickable?: boolean;\n /** Not drawn, with its whole subtree: picking, area selection, select-all,\n * snapping and the selection pass over it, and an SVG export writes it with\n * `display=\"none\"`. Absent means shown; `Scene.isHidden` folds in its\n * ancestors' flags and its layer's visibility. */\n hidden?: boolean;\n /** Out of reach, with its whole subtree: still drawn, but picking and area\n * selection pass over it, the selection drops it, and every edit to it\n * throws, as on a locked layer. Absent means unlocked; `Scene.isLocked`\n * folds in its ancestors' and its layer's. */\n locked?: 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. */\n derivePath?: DerivePathFn<TPose, TData, TLayer>;\n /** Computes this node's pose from its dependencies' poses, the same way\n * `derivePath` computes its path — same `dependsOn` list, same\n * 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 *\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, TData, TLayer>;\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). */\n clipFromPose?: ClipFromPoseFn<TPose>;\n /** Draws the whole subtree again under each affine it returns, on top of\n * the original, which still draws once as authored. The copies are paint,\n * not nodes: nothing stores them, so they follow every edit to the\n * children, and a pick that lands on one answers with the child it copies.\n * A copy is a copy of the clipped content — the clip travels with it.\n * Re-evaluated each render; `null` or `[]` draws no copies. */\n copiesFromPose?: CopiesFromPoseFn<TPose, TData, TLayer>;\n /** How this container arranges its children. Whenever the container's\n * child set or order changes, its bounds change size, or a child's pose is\n * written, the scene hands 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 /** The units its children are shown, typed and snapped in (their poses stay\n * in world units), and what one base unit is worth in the enclosing scope's.\n * It covers the children, not the container; `sceneUnitScopes` reads the chain. */\n units?: UnitScope;\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\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 /** Mirrors `SceneNode.hidden`. */\n hidden?: boolean;\n /** Mirrors `SceneNode.locked`. */\n locked?: boolean;\n /** Only meaningful when `kind === 'container'`. Attach a clip-path function\n * to the node; ignored for leaves. Mirrors `ContainerNode.clipFromPose`. */\n clipFromPose?: ClipFromPoseFn<TPose>;\n /** Mirrors `ContainerNode.copiesFromPose`; ignored for leaves. */\n copiesFromPose?: CopiesFromPoseFn<TPose, TData, TLayer>;\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, TData, TLayer>;\n /** Mirrors `SceneNode.derivePose`, on the same terms as `derivePath`. */\n derivePose?: DerivePoseFn<TPose, TData, TLayer>;\n /** Mirrors `ContainerNode.layout`; ignored for leaves. */\n layout?: LayoutStrategy<TPose>;\n /** Mirrors `ContainerNode.units`; ignored for leaves. */\n units?: UnitScope;\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 /** Opts this kind into coalescing under `UseSceneOptions.coalesceWindowMs`:\n * two entries of this kind that return the same key inside the window\n * merge, and undoing the merged entry calls `revert` with the first\n * payload only. Declare it only when `revert` restores an absolute state\n * (a stored \"from\" value), never for a relative payload such as a delta.\n * Omitted, or returning `undefined`, the op is always its own entry. */\n coalesceKey?: (payload: P) => string | undefined;\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, TData = unknown, TLayer extends string = string> {\n /** Maps registry keys to `clipFromPose` factory functions for container nodes. */\n clipFromPose?: Readonly<Record<string, ClipFromPoseFn<TPose>>>;\n /** Maps registry keys to `copiesFromPose` functions for container nodes. */\n copiesFromPose?: Readonly<Record<string, CopiesFromPoseFn<TPose, TData, TLayer>>>;\n /** Maps registry keys to `derivePath` functions for nodes with `dependsOn`. */\n derivePath?: Readonly<Record<string, DerivePathFn<TPose, TData, TLayer>>>;\n /** Maps registry keys to `derivePose` functions for nodes with `dependsOn`. */\n derivePose?: Readonly<Record<string, DerivePoseFn<TPose, TData, TLayer>>>;\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, whose pose changed size, or one of whose children was posed,\n * arrivals included. Both are read once 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/**\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 extends ScenePoseReports<TPose, Node<TData, TLayer, TPose>>, SceneChanges, SceneDocValues, SceneEditPasses {\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, TData, TLayer>;\n /** See {@link UseSceneOptions.composition}. */\n readonly composition: PoseComposition<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. Cached until a structural edit, so repeat calls hand back\n * the same array — a snapshot, 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. A snapshot, not\n * a live view, and not yours to mutate. An unknown layer id yields an\n * empty array. */\n nodesOnLayer(layer: TLayer): readonly Node<TData, TLayer, TPose>[];\n\n /** A fresh id from this scene's `generateId`, or the kit default: the id\n * `add` would give a spec with none. For code that has to name a node\n * before it exists, such as one building an insert op. */\n mintId(): NodeId;\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. 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 /** Show or hide a layer. Hiding drops its nodes from the selection. */\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` is locked: it or an ancestor carries `locked`, or sits on a\n * locked layer. A 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 /** Whether `id` is not drawn: its own layer is hidden, or it or an ancestor\n * carries `hidden`. A hidden layer hides only the nodes tagged to it. An\n * id not in the scene is not hidden. */\n isHidden(id: NodeId): boolean;\n /** Hide or show node `id` and its subtree — see `SceneNode.hidden`. One\n * undo step; hiding drops the subtree from the selection. Never blocked by\n * a lock, and setting what the node already has records nothing. */\n setHidden(id: NodeId, hidden: boolean): void;\n /** Lock or unlock node `id` and its subtree — see `SceneNode.locked`. One\n * undo step; locking drops the subtree from the selection. Never blocked\n * by a lock, and setting what the node already has records nothing. */\n setLocked(id: NodeId, locked: boolean): void;\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 with `null`) the active-journal accessor after scene\n * construction, for a journal source built with `scene.history` as a\n * dependency. Overrides any `getActiveJournal` set in `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 against `adapter` as one undo entry.\n *\n * The entry holds the scene writes the ops made, as a direct call records\n * them, and beside them any op that wrote no scene state, bound to\n * `adapter`. Undo restores those writes; it does not call an op's\n * `invert()` or the adapter again. **What an op states is not recorded**:\n * one applied over a document that already holds its result, as after an\n * `untracked` preview, records a write from that pose to itself, and undo\n * goes nowhere. Put the document back first.\n *\n * The entry lands in the open `batch` when there is one, else on the\n * active journal, else on the scene's own history, where it can coalesce\n * under `coalesceWindowMs` with one whose ops' keys match.\n *\n * Returns false when the arrival handler refused the batch: it is reverted\n * and unrecorded. Inside `batch` it is true; that batch may still refuse. */\n applyBatch(ops: import('core/ops/types').Op[], label: string, adapter: unknown): boolean;\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. Removing a node deselects it. */\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 * 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, options?: import('./recorder').SceneBatchOptions): 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 /** Declare the unit scope of container `id`, or clear it with `null`. */\n setUnits(id: NodeId, units: UnitScope | null): 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, clamped to [0, total]. Returns true\n * 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`, marked with the scene's recorded form).\n * An entry holds the scene's own ops, whichever way the edit was made.\n * An op handed to `applyBatch` that wrote no scene state is held as\n * itself, and an entry with a nameless one is dropped. Payload\n * JSON-safety (e.g. typed arrays inside poses) is the caller's concern.\n * Do not call mid-`batch` — the open batch's ops are not yet recorded. */\n serializeHistory(): SerializedSceneHistory;\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. A snapshot that is not in\n * the current recorded form (see `SCENE_HISTORY_FORM`) is dropped:\n * the history is left as it was. 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 apply against on undo/redo: the ops handed to\n * `applyBatch` that wrote no scene state, such as a selection change,\n * rebuilt from a `restoreHistory` snapshot. Resolved lazily at each\n * apply, so wiring order relative to `restoreHistory` doesn't matter.\n * Live `applyBatch` entries are unaffected (they bind their call-site\n * adapter). If unset when a restored op applies, the op is a debug-warned\n * 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. Selected\n * ids the snapshot does not hold leave the selection, and every pose\n * override is cleared.\n *\n * Throws inside any other edit — `batch`, `untracked`, `applyBatch`, an\n * undo — which would revert to a state this replaces. 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}\n"],"mappings":";;AAkDA,IAAa,YAAY,MAAsB"}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../src/core/scene/types.ts"],"sourcesContent":["import type { History, SerializedHistory } from '@weasel-js/history';\nimport type { SerializedSceneHistory } from './historyForm';\nimport type { ParallaxOpts } from '../viewport/parallax';\nimport type { UnitScope } from '@weasel-js/quantity';\nimport type { LayoutStrategy } from '../../layout/types';\nimport type { AddLayerSpec, LayerRecord, SystemLayerRecord, SystemLayerSpec, UserLayerRecord } from './layerTypes';\nimport type { LayoutFrame, LayoutMove } from './layoutTypes';\nimport type { PoseComposition } from './composeFrame';\nimport type { PoseRemoval, PoseWrite, PoseWriteOrigin, RemovedNode, ScenePoseReports } from './poseWrites';\nimport type { PoseHold, PoseOverride, PoseOverrides, ShownOverride } from './poseOverrideTypes';\nimport type { SceneChanges } from './sceneChanges';\nimport type {\n SerializedLayer, SerializedNode, SerializedNodeV1, SerializedScene, SerializedSceneV1,\n} from './serializedTypes';\nimport type { UseSceneOptions } from './useSceneOptions';\nimport type { SceneDocValues } from './docValues';\nimport type { SceneDeclaredFieldSetters } from './declaredFieldSetters';\nimport type { SceneEditPasses } from './editPass';\nimport type { SceneArrivalHandler } from './arrivalTypes';\nimport type { RegisteredOp } from './registeredOp';\nimport type { SpecsFromSerializedOptions } from './serialization';\nimport type { RectPose } from '../geometry/rectPose';\nexport type { RectPose, RegisteredOp, SceneArrivalHandler, UseSceneOptions };\nexport type { AddLayerSpec, LayerRecord, SystemLayerRecord, SystemLayerSpec, UserLayerRecord };\nexport type { PoseRemoval, PoseWrite, PoseWriteOrigin, RemovedNode, ScenePoseReports };\nexport type { LayoutFrame, LayoutMove, PoseHold, PoseOverride, PoseOverrides, ShownOverride, SerializedLayer, SerializedNode, SerializedNodeV1, SerializedScene, SerializedSceneV1 };\n\n/**\n * # SceneNode — the thing in the scene\n *\n * Everything the user sees on the canvas — a shape, a group, an annotation,\n * a tile — is a node. Marks and groups are both nodes; the kit has no\n * other concept of \"scene element.\"\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 * - **`pose: TPose`** — local transform, relative to the node's direct\n * parent (or world, for root nodes).\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 * Nodes are addressed by `NodeId` everywhere outside the scene tree. Don't\n * hold references to a `Node` object across scene updates; look up by id\n * when you need the latest.\n *\n * The kit-internal name is `Node`; the public re-export is `SceneNode`\n * (avoids collision with DOM `Node` at call sites).\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\nimport type { DerivedDep, Bivariant, DerivePathFn, DerivePoseFn, ClipFromPoseFn, CopiesFromPoseFn } from './nodeFnTypes';\nexport type { DerivedDep, Bivariant, DerivePathFn, DerivePoseFn, ClipFromPoseFn, CopiesFromPoseFn };\n\n/** A clip a node declares by name rather than by function: see `SceneNode.clip`. */\nexport type NodeClip = 'outline';\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. It does not hide the node\n * from anything else — it still paints, still clips, and a consumer can\n * still select it by id. */\n pickable?: boolean;\n /** Not drawn, with its whole subtree: picking, area selection, select-all,\n * snapping and the selection pass over it, and an SVG export writes it with\n * `display=\"none\"`. Absent means shown; `Scene.isHidden` folds in its\n * ancestors' flags and its layer's visibility. */\n hidden?: boolean;\n /** Out of reach, with its whole subtree: still drawn, but picking and area\n * selection pass over it, the selection drops it, and every edit to it\n * throws, as on a locked layer. Absent means unlocked; `Scene.isLocked`\n * folds in its ancestors' and its layer's. */\n locked?: 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. */\n derivePath?: DerivePathFn<TPose, TData, TLayer>;\n /** Computes this node's pose from its dependencies' poses, the same way\n * `derivePath` computes its path — same `dependsOn` list, same\n * 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 *\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, TData, TLayer>;\n /** Ordered child ids. Absent until the node gets its first child. */\n children?: NodeId[];\n /** Optional clip-path source. Re-evaluated each render. Returning `null`\n * means \"no clip for this node right now\"; an empty / zero-area path\n * means \"clip everything out\" (children render nowhere). Wins over `clip`. */\n clipFromPose?: ClipFromPoseFn<TPose>;\n /** `'outline'` clips the children to this node's own outline: a mark's\n * painter silhouette, or for a group the silhouette of its `data.path`.\n * Absent, and with no `clipFromPose`, the children are not clipped. */\n clip?: NodeClip;\n /** Draws the whole subtree again under each affine it returns, on top of\n * the original, which still draws once as authored. The copies are paint,\n * not nodes: nothing stores them, so they follow every edit to the\n * children, and a pick that lands on one answers with the child it copies.\n * A copy is a copy of the clipped content — the clip travels with it.\n * Re-evaluated each render; `null` or `[]` draws no copies. */\n copiesFromPose?: CopiesFromPoseFn<TPose, TData, TLayer>;\n /** How this node arranges its children. Whenever the node's\n * child set or order changes, its bounds change size, or a child's pose is\n * written, the scene hands 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 /** The units its children are shown, typed and snapped in (their poses stay\n * in world units), and what one base unit is worth in the enclosing scope's.\n * It covers the children, not the node; `sceneUnitScopes` reads the chain. */\n units?: UnitScope;\n}\n\n/** A node that is drawn and picked as one thing — a shape, a label, an image.\n * It may still hold children, which are what it is made of. */\nexport interface MarkNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'mark';\n}\n\n/** A node the user gathers things into: what Cmd+G creates, what SVG `<g>`\n * round-trips to. An emptied group is still a group. */\nexport interface GroupNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'group';\n}\n\n/** A node in the scene tree: either a mark or a group. Re-exported\n * publicly as `SceneNode`, to avoid colliding with the DOM's `Node`. */\nexport type Node<TData, TLayer extends string, TPose = RectPose> =\n | MarkNode<TData, TLayer, TPose>\n | GroupNode<TData, TLayer, TPose>;\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: 'mark' | 'group';\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 /** Mirrors `SceneNode.hidden`. */\n hidden?: boolean;\n /** Mirrors `SceneNode.locked`. */\n locked?: boolean;\n /** Attach a clip-path function to the node; mirrors `SceneNode.clipFromPose`. */\n clipFromPose?: ClipFromPoseFn<TPose>;\n /** Mirrors `SceneNode.clip`. */\n clip?: NodeClip;\n /** Mirrors `SceneNode.copiesFromPose`. */\n copiesFromPose?: CopiesFromPoseFn<TPose, TData, TLayer>;\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, TData, TLayer>;\n /** Mirrors `SceneNode.derivePose`, on the same terms as `derivePath`. */\n derivePose?: DerivePoseFn<TPose, TData, TLayer>;\n /** Mirrors `SceneNode.layout`. */\n layout?: LayoutStrategy<TPose>;\n /** Mirrors `SceneNode.units`. */\n units?: UnitScope;\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, TData = unknown, TLayer extends string = string> {\n /** Maps registry keys to `clipFromPose` factory functions for nodes. */\n clipFromPose?: Readonly<Record<string, ClipFromPoseFn<TPose>>>;\n /** Maps registry keys to `copiesFromPose` functions for nodes. */\n copiesFromPose?: Readonly<Record<string, CopiesFromPoseFn<TPose, TData, TLayer>>>;\n /** Maps registry keys to `derivePath` functions for nodes with `dependsOn`. */\n derivePath?: Readonly<Record<string, DerivePathFn<TPose, TData, TLayer>>>;\n /** Maps registry keys to `derivePose` functions for nodes with `dependsOn`. */\n derivePose?: Readonly<Record<string, DerivePoseFn<TPose, TData, TLayer>>>;\n /** Maps registry keys to 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 * 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 extends ScenePoseReports<TPose, Node<TData, TLayer, TPose>>, SceneChanges, SceneDocValues, SceneEditPasses, SceneDeclaredFieldSetters {\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, TData, TLayer>;\n /** See {@link UseSceneOptions.composition}. */\n readonly composition: PoseComposition<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. Cached until a structural edit, so repeat calls hand back\n * the same array — a snapshot, 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. A snapshot, not\n * a live view, and not yours to mutate. An unknown layer id yields an\n * empty array. */\n nodesOnLayer(layer: TLayer): readonly Node<TData, TLayer, TPose>[];\n\n /** A fresh id from this scene's `generateId`, or the kit default: the id\n * `add` would give a spec with none. For code that has to name a node\n * before it exists, such as one building an insert op. */\n mintId(): NodeId;\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. 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 mark, 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 * - 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 /** Show or hide a layer. Hiding drops its nodes from the selection. */\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` is locked: it or an ancestor carries `locked`, or sits on a\n * locked layer. A 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 /** Whether `id` is not drawn: its own layer is hidden, or it or an ancestor\n * carries `hidden`. A hidden layer hides only the nodes tagged to it. An\n * id not in the scene is not hidden. */\n isHidden(id: NodeId): boolean;\n /** Hide or show node `id` and its subtree — see `SceneNode.hidden`. One\n * undo step; hiding drops the subtree from the selection. Never blocked by\n * a lock, and setting what the node already has records nothing. */\n setHidden(id: NodeId, hidden: boolean): void;\n /** Lock or unlock node `id` and its subtree — see `SceneNode.locked`. One\n * undo step; locking drops the subtree from the selection. Never blocked\n * by a lock, and setting what the node already has records nothing. */\n setLocked(id: NodeId, locked: boolean): void;\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 with `null`) the active-journal accessor after scene\n * construction, for a journal source built with `scene.history` as a\n * dependency. Overrides any `getActiveJournal` set in `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 against `adapter` as one undo entry.\n *\n * The entry holds the scene writes the ops made, as a direct call records\n * them, and beside them any op that wrote no scene state, bound to\n * `adapter`. Undo restores those writes; it does not call an op's\n * `invert()` or the adapter again. **What an op states is not recorded**:\n * one applied over a document that already holds its result, as after an\n * `untracked` preview, records a write from that pose to itself, and undo\n * goes nowhere. Put the document back first.\n *\n * The entry lands in the open `batch` when there is one, else on the\n * active journal, else on the scene's own history, where it can coalesce\n * under `coalesceWindowMs` with one whose ops' keys match.\n *\n * Returns false when the arrival handler refused the batch: it is reverted\n * and unrecorded. Inside `batch` it is true; that batch may still refuse. */\n applyBatch(ops: import('core/ops/types').Op[], label: string, adapter: unknown): boolean;\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. Removing a node deselects it. */\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n\n // Ephemeral presentation state\n\n /** Per-node pose / alpha / path / data 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, TData>;\n\n // History\n /** The scene's undo/redo engine, in the shape `@weasel-js/history` defines.\n * 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, options?: import('./recorder').SceneBatchOptions): T;\n /** The layout group `id` declares, or `null` for a mark or a group with none. */\n layoutOf(id: NodeId): LayoutStrategy<TPose> | null;\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, clamped to [0, total]. Returns true\n * 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`, marked with the scene's recorded form).\n * An entry holds the scene's own ops, whichever way the edit was made.\n * An op handed to `applyBatch` that wrote no scene state is held as\n * itself, and an entry with a nameless one is dropped. Payload\n * JSON-safety (e.g. typed arrays inside poses) is the caller's concern.\n * Do not call mid-`batch` — the open batch's ops are not yet recorded. */\n serializeHistory(): SerializedSceneHistory;\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. A snapshot that is not in\n * the current recorded form (see `SCENE_HISTORY_FORM`) is dropped:\n * the history is left as it was. 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 apply against on undo/redo: the ops handed to\n * `applyBatch` that wrote no scene state, such as a selection change,\n * rebuilt from a `restoreHistory` snapshot. Resolved lazily at each\n * apply, so wiring order relative to `restoreHistory` doesn't matter.\n * Live `applyBatch` entries are unaffected (they bind their call-site\n * adapter). If unset when a restored op applies, the op is a debug-warned\n * 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 * `GroupNode.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. Selected\n * ids the snapshot does not hold leave the selection, and every pose\n * override is cleared.\n *\n * Throws inside any other edit — `batch`, `untracked`, `applyBatch`, an\n * undo — which would revert to a state this replaces. 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. `opts` reads the snapshot as `specsFromSerialized` does. */\n loadState(\n json: SerializedScene<TData, TLayer, TPose> | SerializedSceneV1<TData, TLayer, TPose>,\n opts?: SpecsFromSerializedOptions<TData, TLayer, TPose>,\n ): void;\n\n}\n"],"mappings":";;AAwDA,IAAa,YAAY,MAAsB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useScene.js","names":[],"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>);\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: '
|
|
1
|
+
{"version":3,"file":"useScene.js","names":[],"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>);\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: 'mark',\n layer: DEFAULT_LAYER,\n pose: item,\n data: item,\n id: asNodeId(item.id),\n })),\n });\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('./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,IAAM,8BAA8B,CAAC;AAErC,IAAM,gBAAgB;AAGtB,SAAS,iBACP,SAC0C;CAC1C,OACE,CAAC,CAAC,WACC,OAAO,YAAY,YACnB,WAAY,WACZ,EAAE,kBAAmB;AAE5B;AAEA,SAAS,WAAW,SAAmD;CACrE,IAAI,CAAC,iBAAiB,OAAO,GAC3B,OAAO,YAAY,OAAoD;CAEzE,OAAO,YAA4C;EACjD,cAAc,CAAC,EAAE,IAAI,cAAc,CAAC;EACpC,cAAc,QAAQ;EACtB,YAAY,QAAQ;EACpB,SAAS,QAAQ,MAAM,KAAK,UAAU;GACpC,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;GACN,IAAI,SAAS,KAAK,EAAE;EACtB,EAAE;CACJ,CAAC;AACH;;AAsBA,SAAgB,SAAS,SAA2B;CAClD,MAAM,WAAW,OAA+C,IAAI;CACpE,IAAI,SAAS,YAAY,MAAM,SAAS,UAAU,WAAW,OAAO;CACpE,MAAM,QAAQ,SAAS;CACvB,MAAM,aAAc,SAA4C,cAAc;CAC9E,qBACE,aAAa,MAAM,YAAY,iBAC/B,MAAM,YACN,MAAM,UACR;CACA,OAAO;AACT"}
|