Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor runtime package to implement observer pattern for cache and entity management

konstantin-paulusefa22538fb8a
diff --git a/packages/runtime/MIGRATION.md b/packages/runtime/MIGRATION.md
index 4b3092de..43ea1351 100644
--- a/packages/runtime/MIGRATION.md
+++ b/packages/runtime/MIGRATION.md
@@ -31,6 +31,7 @@ Working doc for migrating the editor engine from bitecs (in `apps/web/src/compon
| Actions: resize, keyframe, overlap | `src/actions/{resize,keyframe,overlap}.ts` | Constraint seeding = ConstraintCache trait presence (was undefined store slots). Overlap uses cloneSubtree + computeTrimStart/End |
| Actions: group, frame, clipboard | `src/actions/{group,frame,clipboard}.ts` | frame.ts also hosts `switchActiveScene` (was api/base.ts): sets the ActiveScene world trait, nothing else |
| Actions: assets, folders (model) | `src/actions/{assets,folders}.ts` | allocateId/raiseIdCounter, appendAssets/upsertAsset/removeAssets, getAssetFile/Blob, insertAssetInTimeline; folder tree ops return changed records for app persistence |
+| Observers (runtime half) | `src/world/observers.ts` | koota subscriptions wiring cache upkeep, Computed mirrors, and time-range reactions; auto-registered by `createRuntimeWorld` (returns a disposer). See semantic notes |
| Seeds (types only, rest follows) | `src/utils/text.ts` (Token/Line/TokenOptions), `src/capture/format.ts` (ContainerFormat) | The remaining engine files merge into these on their slice |
Verification style used so far: `npx tsc --noEmit` in the package, plus throwaway `smoke-test.tmp.ts` in the package root run with `npm exec --yes tsx@latest -- smoke-test.tmp.ts`, deleted afterwards (no test infra in the package yet). koota caps live worlds at 16; call `world.destroy()` in test loops.
@@ -54,7 +55,12 @@ Every world spawns one entity tagged `DocumentRoot` (`createRuntimeWorld`). All
- Deleted is a runtime-only tombstone tag (undo support), never serialized.
- Actions are plain world-first functions (matching queries/systems), not koota `createActions`: they return entities/records and call each other freely, which the bound-record pattern only obscures. No history layer: bitecs `world.history.push/transaction` wrappers are gone; actions write directly and the app groups undo steps by observing koota events. Selection-scoped actions (group, frame, reorderSelection, clipboard) still key off the runtime-defined `Selected` trait.
- appendChild/removeChild dropped their bitecs side calls: `persistEntity`, `syncInteractiveState`, `rebuildTimelineIndex` (app-side via observers/signals) and `disconnectAudioBus` (media slice; decoder/bus disposal hooks return with it). `unpersistEntity` and the dispose* helpers from `api/utils.ts` were likewise not ported yet.
-- `clampTrimToAssetDuration` now goes through `entity.set(Trim)` (fires change events) but only when actually clamping; bitecs wrote the store silently. `reactToChildDetached` is exported for the observers slice to hook Deleted onAdd.
+- Observers: the runtime half of `api/observers.ts` became koota subscriptions in `world/observers.ts` (`observeWorld`, auto-registered by `createRuntimeWorld`). appendChild/removeChild are assert + re-target only; cache/size/constraint/time-range fixups ride the ChildOf add/remove events, so `cloneFromRecords`/restore prime Cache, Computed, and time ranges through the same path as actions. `rebuildCaches`/`aggregateKeyframeTracks` take an `exclude` param because koota fires relation remove events while the departing child is still in the old parent's queries.
+- Observer-driven behavior faithful to bitecs: Sequential onAdd group-ifies and strips spatial traits; Group/Scene/Audio onAdd, Paint/AssetId/Delay/PlaybackRate/Trim onChange, and Trim onRemove run the timing recomputes; Keyframe/ItemIndex onChange resort caches; Deleted onAdd/onRemove rebuild caches (+ `reactToChildDetached`); Trim onAdd defaults `end` to the current Computed.duration (the bitecs setComponent fallback). Authored→Computed mirrors register on add and change; trait removal does not reset Computed (same as bitecs).
+- Not faithful on purpose: keyframe auto-sync on authored edits did not move into observers. koota change events don't say which field changed, and syncing every field of a trait would mint spurious keyframes on untouched properties. Editing surfaces call `syncKeyframeTrack` for the property they changed (resizeEntity already does for width/height).
+- Size propagation is a Size observer now (`propagateSize` on add/change): bitecs restored sizes through `resizeEntity`, koota deserialization is a plain set. `resizeEntity` no longer calls propagateSize itself.
+- `clampTrimToAssetDuration` now goes through `entity.set(Trim)` (fires change events) but only when actually clamping; bitecs wrote the store silently. The Trim onChange handler re-enters once through the clamp and no-ops on the second pass.
+- Still app-side from `api/observers.ts`: persistence scheduling, timeline index rebuilds, `syncInteractiveState`, Selected waveform show/hide, ClipHeight/Expanded, ExportSettings defaults, drag-origin traits. Media slice: dispose hooks on Deleted/Culled onAdd.
- `switchActiveScene` only sets the ActiveScene world trait; timeline buffer clearing and index rebuild stay app-side. `frameSelection` calls it once (bitecs called it redundantly inside and outside the transaction).
- `insertAssetInTimeline` returns the created entity or null when no scene is active (no toast). Folder ops are sync and return the changed records (`deleteFolder` returns removed folder/asset ids) so the app can persist; `moveAssetsToFolder` updates records in place instead of re-fronting them like `saveAsset` did. Panel navigation state (current folder) stays app-side.
- Decoder/host handle traits (`src/traits/media.ts`) are AoS traits typed as opaque `object` until the decoders move in; `entity.get(VideoDecoder)` returns the instance directly.
@@ -69,18 +75,18 @@ Every world spawns one entity tagged `DocumentRoot` (`createRuntimeWorld`). All
- Max 16 live worlds. Entity numbers encode worldId+generation; stores are indexed by `entity.id()`.
- Entities read back from store arrays / trait fields keep their methods (they are numbers; koota patches the prototype).
- `entity.set(trait, data)` throws if the trait is missing; `entity.add` is idempotent and never resets existing values; `set` with a partial object merges over current values. Hence the add-then-set pattern everywhere in serialize and actions. On an exclusive relation, `add(ChildOf(newParent))` re-targets in place.
+- Events: `world.onAdd/onChange/onRemove(trait | ChildOf('*'), cb)` exist; relation callbacks get `(entity, target)`. Exclusive re-target fires remove(old) then add(new); a redundant same-pair add fires nothing; remove events fire while the departing child is still in the old target's queries (hence rebuildCaches' `exclude` param). onAdd fires after initial values are applied (`spawn(Trait({...}))` included) and handlers may set traits on the entity. onChange fires even when the written value is unchanged. Destroy cascades and `world.destroy()` fire remove events with still-usable entities.
## Remaining work (suggested order)
-1. **Observers / cache upkeep**: the bitecs `api/observers.ts` logic that fills `Cache` (children, fills, shadows, strokes, effects, textRanges, masks, keyframeTracks, keyframes, animations) from ChildOf + tags. Decide: koota `onAdd/onRemove(ChildOf('*'))` subscriptions (runtime-owned) vs recompute passes. Systems and timeline-index already consume `Cache`; actions rebuild it imperatively via `actions/cache.ts` (as bitecs did), and `reactToChildDetached` awaits its Deleted onAdd hook. Also decide where Deleted-tombstone pruning and `unpersistEntity` land.
-2. **Media** (`src/media/`): move `engine/decoders/*` wholesale (video, audio, image, sequence, caption/, html, shader, surface, frame-cache, keyframe-index, time-stretcher, audio-peaks) plus `services/audio-bus.ts`. Then tighten the handle trait types in `src/traits/media.ts` to the concrete classes and delete the `Handle = object` placeholder. Reinstate the dispose hooks the actions slice dropped: `disconnectAudioBus` in appendChild/removeChild, decoder disposal in `reactToAssetChange`'s Caption branch, and the dispose* subtree walkers from `api/utils.ts`.
-3. **Playback system**: `systems/playback.ts` (computes `Computed.localTime/start/end/duration/visibility`, drives decoders, pushes into `FramePromises`, uses AudioEngine + Mounts). Depends on media.
-4. **Capture** (`src/capture/`): `engine/encode/*` (encoder, image-encoder, buffer, format, utils). Uses Mode, FramePromises, RenderSurface.
-5. **Render system**: `systems/render.ts` is runtime-capable (OffscreenCanvas) and needed for headless capture; it consumes text layout (`utils/text.ts` full port: layout/measure/render join the Token seed).
-6. **Fonts**: `engine/font/{utils,fixtures}.ts` (check DOM usage: document.fonts needs an injection seam or stays app-side).
-7. **Remaining utils**: captions, transition, contact-sheet, audio-sync, transcode (audit each for DOM/app deps; DOM-touching ones stay app-side).
-8. **App rewrite** (`apps/web`): engine shell wires canvas/AudioContext/DPR into world traits, app-side world traits (input, HUD, selection tool, history, store, timelineIndex signal), history/persistence via koota events (including wrapping the folder/asset model ops with Dexie writes and re-implementing `syncInteractiveState` over `ChildOf(document)` queries: `Not(ChildOf('*'))` throws in koota), UI to `packages/koota-solid` hooks, timeline UI consumes new `TimelineNode.entity`. Delete `engine/components`, `engine/api` progressively.
-9. **CLI**: point node capture at the runtime package.
+1. **Media** (`src/media/`): move `engine/decoders/*` wholesale (video, audio, image, sequence, caption/, html, shader, surface, frame-cache, keyframe-index, time-stretcher, audio-peaks) plus `services/audio-bus.ts`. Then tighten the handle trait types in `src/traits/media.ts` to the concrete classes and delete the `Handle = object` placeholder. Reinstate the dispose hooks earlier slices dropped, as observers in `world/observers.ts`: Deleted onAdd → dispose decoders/hosts/bus, Culled onAdd → dispose decoders, ChildOf events → `disconnectAudioBus`, `reactToAssetChange`'s Caption branch → drop the caption decoder.
+2. **Playback system**: `systems/playback.ts` (computes `Computed.localTime/start/end/duration/visibility`, drives decoders, pushes into `FramePromises`, uses AudioEngine + Mounts). Depends on media.
+3. **Capture** (`src/capture/`): `engine/encode/*` (encoder, image-encoder, buffer, format, utils). Uses Mode, FramePromises, RenderSurface.
+4. **Render system**: `systems/render.ts` is runtime-capable (OffscreenCanvas) and needed for headless capture; it consumes text layout (`utils/text.ts` full port: layout/measure/render join the Token seed).
+5. **Fonts**: `engine/font/{utils,fixtures}.ts` (check DOM usage: document.fonts needs an injection seam or stays app-side).
+6. **Remaining utils**: captions, transition, contact-sheet, audio-sync, transcode (audit each for DOM/app deps; DOM-touching ones stay app-side).
+7. **App rewrite** (`apps/web`): engine shell wires canvas/AudioContext/DPR into world traits, app-side world traits (input, HUD, selection tool, history, store, timelineIndex signal), history/persistence via koota events (including wrapping the folder/asset model ops with Dexie writes, re-implementing `syncInteractiveState` over `ChildOf(document)` queries: `Not(ChildOf('*'))` throws in koota, and re-adding the editing-surface `syncKeyframeTrack` calls the observers slice dropped), Deleted-tombstone pruning + `unpersistEntity`, UI to `packages/koota-solid` hooks, timeline UI consumes new `TimelineNode.entity`. Delete `engine/components`, `engine/api` progressively.
+8. **CLI**: point node capture at the runtime package.
## Layout reminders
diff --git a/packages/runtime/src/actions/cache.ts b/packages/runtime/src/actions/cache.ts
index 4fdcaba2..ef4def45 100644
--- a/packages/runtime/src/actions/cache.ts
+++ b/packages/runtime/src/actions/cache.ts
@@ -24,64 +24,69 @@ import type { Entity, World } from 'koota';
/**
* Refresh the parent's Cache lists that the attached/detached entity
* participates in. Call after a ChildOf change with the affected parent.
+ * `exclude` drops one entity from the fresh lists: koota fires relation
+ * remove events while the departing child is still present in the old
+ * parent's queries.
*/
-export function rebuildCaches(world: World, entity: Entity, parent: Entity | null) {
+export function rebuildCaches(world: World, entity: Entity, parent: Entity | null, exclude: Entity | null = null) {
if (parent === null || isDocument(parent)) return;
if (!parent.has(Cache)) parent.add(Cache);
const cache = store(world, Cache);
const pid = parent.id();
+ const collect = (...params: Parameters<World['query']>) =>
+ [...world.query(...params)].filter(e => e !== exclude);
if (entity.has(Geometry) || entity.has(Group) || entity.has(AdjustmentLayer)) {
- cache.children[pid] = [...world.query(
+ cache.children[pid] = collect(
Or(Geometry, Group, AdjustmentLayer), ChildOf(parent), Not(IsMask), Not(Deleted),
- )].sort(sortByItemIndex);
+ ).sort(sortByItemIndex);
}
if (entity.has(IsMask)) {
- cache.masks[pid] = [...world.query(Geometry, IsMask, ChildOf(parent), Not(Deleted))]
+ cache.masks[pid] = collect(Geometry, IsMask, ChildOf(parent), Not(Deleted))
.sort(sortByItemIndex);
}
if (entity.has(KeyframeTrack)) {
const node = findClosestParentGeometry(parent);
- aggregateKeyframeTracks(world, node);
+ aggregateKeyframeTracks(world, node, exclude);
resetAnimatedValues(world, node);
}
if (entity.has(Keyframe)) {
- cache.keyframes[pid] = [...world.query(Keyframe, ChildOf(parent), Not(Deleted))]
+ cache.keyframes[pid] = collect(Keyframe, ChildOf(parent), Not(Deleted))
.sort(sortByFrame);
}
if (entity.has(Animation)) {
- cache.animations[pid] = [...world.query(Animation, ChildOf(parent), Not(Deleted))]
+ cache.animations[pid] = collect(Animation, ChildOf(parent), Not(Deleted))
.sort(sortByItemIndex);
resetAnimatedValues(world, parent);
}
if (entity.has(Paint)) {
- cache.fills[pid] = [...world.query(Paint, ChildOf(parent), Not(Deleted))]
+ cache.fills[pid] = collect(Paint, ChildOf(parent), Not(Deleted))
.sort(sortByItemIndex);
}
if (entity.has(Stroke)) {
- cache.strokes[pid] = [...world.query(Stroke, ChildOf(parent), Not(Deleted))]
+ cache.strokes[pid] = collect(Stroke, ChildOf(parent), Not(Deleted))
.sort(sortByItemIndex);
}
if (entity.has(Effect)) {
- cache.effects[pid] = [...world.query(Effect, ChildOf(parent), Not(Shadow), Not(Deleted))]
+ cache.effects[pid] = collect(Effect, ChildOf(parent), Not(Shadow), Not(Deleted))
.sort(sortByItemIndex);
}
if (entity.has(Shadow)) {
- cache.shadows[pid] = [...world.query(Shadow, ChildOf(parent), Not(Effect), Not(Deleted))]
+ cache.shadows[pid] = collect(Shadow, ChildOf(parent), Not(Effect), Not(Deleted))
.sort(sortByItemIndex);
}
if (entity.has(TextRange)) {
- cache.textRanges[pid] = [...world.query(TextRange, ChildOf(parent), Not(Deleted))]
+ cache.textRanges[pid] = collect(TextRange, ChildOf(parent), Not(Deleted))
.sort(sortByItemIndex);
}
}
@@ -104,7 +109,7 @@ export function findClosestParentGeometry(entity: Entity): Entity | null {
* `target` field on each track so consumers iterating the cache can look up
* the animated entity without walking ChildOf.
*/
-export function aggregateKeyframeTracks(world: World, node: Entity | null): void {
+export function aggregateKeyframeTracks(world: World, node: Entity | null, exclude: Entity | null = null): void {
if (node === null) return;
if (!node.has(Cache)) node.add(Cache);
@@ -113,6 +118,7 @@ export function aggregateKeyframeTracks(world: World, node: Entity | null): void
const walk = (entity: Entity) => {
for (const child of world.query(ChildOf(entity), Not(Deleted))) {
+ if (child === exclude) continue;
if (child.has(KeyframeTrack)) {
keyframeTrack.target[child.id()] = getParentNode(child);
tracks.push(child);
diff --git a/packages/runtime/src/actions/hierarchy.ts b/packages/runtime/src/actions/hierarchy.ts
index a0dad585..32576b82 100644
--- a/packages/runtime/src/actions/hierarchy.ts
+++ b/packages/runtime/src/actions/hierarchy.ts
@@ -5,6 +5,8 @@
// Parenting and ordering actions (was api/hierarchy.ts). ChildOf is exclusive,
// so re-parenting is a single add; "no parent" does not exist under the
// document root model: detached entities go back to being document children.
+// Cache/size/constraint/time-range fixups ride on the ChildOf events (see
+// world/observers.ts), so these functions only validate and re-target.
import { Not, Or } from 'koota';
@@ -14,9 +16,6 @@ import {
import { getDocument, getEntityTree, getParentNode } from '../queries/hierarchy';
import { assert } from '../utils/assert';
import { sortByItemIndex } from '../utils/sort';
-import { rebuildCaches } from './cache';
-import { propagateSize, resolveConstraintOffsets } from './resize';
-import { reactToChildAttached } from './timing';
import type { Entity, World } from 'koota';
@@ -28,10 +27,6 @@ export function appendChild(world: World, entity: Entity, parent: Entity): void
assert(!getEntityTree(world, entity).includes(parent), 'Cannot parent entity into its own subtree');
entity.add(ChildOf(parent));
- rebuildCaches(world, entity, parent);
- propagateSize(world, entity);
- resolveConstraintOffsets(world, entity);
- reactToChildAttached(world, entity);
}
export function removeChild(world: World, entity: Entity, parent: Entity): void {
@@ -39,7 +34,6 @@ export function removeChild(world: World, entity: Entity, parent: Entity): void
// Back to top-level: re-target to the document (never drop ChildOf).
entity.add(ChildOf(getDocument(world)));
- rebuildCaches(world, entity, parent);
}
/**
diff --git a/packages/runtime/src/actions/resize.ts b/packages/runtime/src/actions/resize.ts
index b0355867..f2540202 100644
--- a/packages/runtime/src/actions/resize.ts
+++ b/packages/runtime/src/actions/resize.ts
@@ -50,7 +50,7 @@ export function resizeEntity(world: World, entity: Entity, params: ResizeParams)
...(width !== undefined && { width: Math.round(width) }),
...(height !== undefined && { height: Math.round(height) }),
});
- propagateSize(world, entity);
+ // The Size observer propagates Computed sizes; constraints resolve here.
resolveConstraintOffsets(world, entity);
if (width !== undefined) {
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 5b41e0a1..0c7d0123 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -1,6 +1,7 @@
export * from './constants';
export * from './traits';
export * from './world/create-world';
+export * from './world/observers';
export * from './world/serialize';
export * from './world/store';
export * from './queries';
diff --git a/packages/runtime/src/world/create-world.ts b/packages/runtime/src/world/create-world.ts
index 19813797..01373fdb 100644
--- a/packages/runtime/src/world/create-world.ts
+++ b/packages/runtime/src/world/create-world.ts
@@ -4,6 +4,7 @@
import { createWorld } from 'koota';
+import { observeWorld } from './observers';
import {
DocumentRoot,
Project,
@@ -51,6 +52,9 @@ export function createRuntimeWorld(projectId: string) {
// The document root all rendered entities hang off (see DocumentRoot).
world.spawn(DocumentRoot);
+ // Cache upkeep, Computed mirrors, and time-range reactions.
+ observeWorld(world);
+
return world;
}
diff --git a/packages/runtime/src/world/observers.ts b/packages/runtime/src/world/observers.ts
new file mode 100644
index 00000000..361cfaa2
--- /dev/null
+++ b/packages/runtime/src/world/observers.ts
@@ -0,0 +1,236 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Runtime-owned invariants as koota event subscriptions (was the runtime half
+// of api/observers.ts): cache upkeep on ChildOf changes, authored-to-Computed
+// mirrors, and time-range reactions. Registered by createRuntimeWorld, so
+// deserialization and clones prime Cache/Computed through the same path as
+// actions. App-side duties of the bitecs observers (persistence, timeline
+// index, interactive state, selection styling, drag origins) and media
+// disposal hooks are layered on by their owners.
+//
+// Keyframe auto-sync on authored edits deliberately did not move here: koota
+// change events don't say which field changed, and syncing every field of a
+// trait would mint spurious keyframes on untouched properties. Editing
+// surfaces call syncKeyframeTrack for the property they changed (resizeEntity
+// already does for width/height).
+
+import { store } from './store';
+import {
+ ChildOf, Deleted, Sequential, Group, Scene, Audio, Paint, AssetId,
+ Delay, PlaybackRate, Trim, Keyframe, ItemIndex,
+ Position, Offset, Rotation, Scale, UniformScale, Skew, Anchor, Flip,
+ Appearance, Color, Blur, Volume, Effect, CornerRadius, MixedCornerRadius,
+ ColorStop, StrokeStyle, Size, Computed,
+} from '../traits';
+import { getParentEntity } from '../queries/hierarchy';
+import { rebuildCaches } from '../actions/cache';
+import {
+ reactToChildAttached, reactToChildDetached, reactToAssetChange,
+ reactToPaintChange, recomputeEntityTimeRange, propagateTimeRangeDown,
+ bubbleTimeRangeUp, clampTrimToAssetDuration,
+} from '../actions/timing';
+import { propagateSize, resolveConstraintOffsets } from '../actions/resize';
+
+import type { Entity, Trait, World } from 'koota';
+
+/**
+ * Wire the runtime invariants into a world. Returns a disposer (worlds are
+ * normally destroyed outright, but tests recycling the 16-world budget can
+ * unhook explicitly).
+ */
+export function observeWorld(world: World): () => void {
+ const subs: (() => void)[] = [];
+
+ // ── Structure ─────────────────────────────────────────────
+
+ subs.push(world.onAdd(ChildOf('*'), (child, parent) => {
+ rebuildCaches(world, child, parent);
+ propagateSize(world, child);
+ resolveConstraintOffsets(world, child);
+ reactToChildAttached(world, child);
+ }));
+
+ // On re-target (and destroy) the remove event fires while the child is
+ // still present in the old parent's queries, so it is excluded by hand.
+ subs.push(world.onRemove(ChildOf('*'), (child, parent) => {
+ rebuildCaches(world, child, parent, child);
+ }));
+
+ subs.push(world.onAdd(Deleted, (entity) => {
+ // The Not(Deleted) cache queries already skip the tombstone.
+ rebuildCaches(world, entity, getParentEntity(entity));
+ reactToChildDetached(world, entity);
+ }));
+
+ subs.push(world.onRemove(Deleted, (entity) => {
+ rebuildCaches(world, entity, getParentEntity(entity));
+ }));
+
+ // Keyframes re-sort by frame, siblings re-sort by index.
+ subs.push(world.onChange(Keyframe, (entity) => {
+ rebuildCaches(world, entity, getParentEntity(entity));
+ }));
+
+ subs.push(world.onChange(ItemIndex, (entity) => {
+ rebuildCaches(world, entity, getParentEntity(entity));
+ }));
+
+ // ── Model invariants ──────────────────────────────────────
+
+ // A sequence is a group without spatial identity of its own.
+ subs.push(world.onAdd(Sequential, (entity) => {
+ entity.add(Group);
+ entity.remove(Position, Offset, Rotation, Scale, Skew, Anchor, Flip);
+ }));
+
+ // First Trim on an entity defaults its end to the current duration (the
+ // bitecs setComponent fallback), so a partial { start } set stays valid.
+ subs.push(world.onAdd(Trim, (entity) => {
+ if (entity.get(Trim)!.end === 0) {
+ entity.set(Trim, { end: store(world, Computed).duration[entity.id()] ?? 0 });
+ }
+ }));
+
+ // ── Time ranges ───────────────────────────────────────────
+
+ const recomputeAndBubble = (entity: Entity) => {
+ recomputeEntityTimeRange(world, entity);
+ bubbleTimeRangeUp(world, entity);
+ };
+
+ subs.push(world.onAdd(Group, recomputeAndBubble));
+ subs.push(world.onAdd(Scene, recomputeAndBubble));
+ subs.push(world.onAdd(Audio, recomputeAndBubble));
+
+ subs.push(world.onChange(Paint, (entity) => {
+ reactToPaintChange(world, entity);
+ }));
+
+ subs.push(world.onChange(AssetId, (entity) => {
+ reactToAssetChange(world, entity);
+ }));
+
+ const propagateAndBubble = (entity: Entity) => {
+ propagateTimeRangeDown(world, entity);
+ bubbleTimeRangeUp(world, entity);
+ };
+
+ subs.push(world.onChange(Delay, propagateAndBubble));
+ subs.push(world.onChange(PlaybackRate, propagateAndBubble));
+
+ subs.push(world.onChange(Trim, (entity) => {
+ // Clamping re-enters this handler once via set; the second pass no-ops.
+ clampTrimToAssetDuration(world, entity);
+ recomputeAndBubble(entity);
+ }));
+
+ subs.push(world.onRemove(Trim, recomputeAndBubble));
+
+ // ── Authored → Computed mirrors ───────────────────────────
+ // Base values for entities the motion system skips (no animation data);
+ // animated entities re-derive them every frame via resetAnimatedValues.
+ // Registered on add and change so both spawn-with-value and add-then-set
+ // arrive in Computed. Trait removal does not reset (same as bitecs).
+
+ const mirror = (trait: Trait, apply: (entity: Entity) => void) => {
+ subs.push(world.onAdd(trait, apply));
+ subs.push(world.onChange(trait, apply));
+ };
+
+ mirror(Position, (entity) => {
+ const computed = store(world, Computed);
+ const { x, y } = entity.get(Position)!;
+ computed.positionX[entity.id()] = x;
+ computed.positionY[entity.id()] = y;
+ });
+
+ mirror(Offset, (entity) => {
+ const computed = store(world, Computed);
+ const { x, y } = entity.get(Offset)!;
+ computed.offsetX[entity.id()] = x;
+ computed.offsetY[entity.id()] = y;
+ });
+
+ mirror(Rotation, (entity) => {
+ store(world, Computed).rotation[entity.id()] = entity.get(Rotation)!.value;
+ });
+
+ mirror(Scale, (entity) => {
+ const computed = store(world, Computed);
+ const { x, y } = entity.get(Scale)!;
+ computed.scaleX[entity.id()] = x;
+ computed.scaleY[entity.id()] = y;
+ });
+
+ mirror(UniformScale, (entity) => {
+ const computed = store(world, Computed);
+ const { value } = entity.get(UniformScale)!;
+ computed.scaleX[entity.id()] = value;
+ computed.scaleY[entity.id()] = value;
+ });
+
+ mirror(Skew, (entity) => {
+ const computed = store(world, Computed);
+ const { x, y } = entity.get(Skew)!;
+ computed.skewX[entity.id()] = x;
+ computed.skewY[entity.id()] = y;
+ });
+
+ mirror(Appearance, (entity) => {
+ store(world, Computed).opacity[entity.id()] = entity.get(Appearance)!.opacity;
+ });
+
+ mirror(Color, (entity) => {
+ store(world, Computed).color[entity.id()] = entity.get(Color)!.value;
+ });
+
+ mirror(Blur, (entity) => {
+ store(world, Computed).blur[entity.id()] = entity.get(Blur)!.value;
+ });
+
+ mirror(Volume, (entity) => {
+ store(world, Computed).volume[entity.id()] = entity.get(Volume)!.value;
+ });
+
+ mirror(Effect, (entity) => {
+ store(world, Computed).value[entity.id()] = entity.get(Effect)!.value;
+ });
+
+ mirror(CornerRadius, (entity) => {
+ store(world, Computed).cornerRadius[entity.id()] = entity.get(CornerRadius)!.value;
+ });
+
+ mirror(MixedCornerRadius, (entity) => {
+ const computed = store(world, Computed);
+ const radius = entity.get(MixedCornerRadius)!;
+ computed.cornerRadiusTopLeft[entity.id()] = radius.topLeft;
+ computed.cornerRadiusTopRight[entity.id()] = radius.topRight;
+ computed.cornerRadiusBottomRight[entity.id()] = radius.bottomRight;
+ computed.cornerRadiusBottomLeft[entity.id()] = radius.bottomLeft;
+ });
+
+ mirror(ColorStop, (entity) => {
+ const computed = store(world, Computed);
+ const stop = entity.get(ColorStop)!;
+ computed.stopOffset[entity.id()] = stop.offset;
+ computed.stopColor[entity.id()] = stop.color;
+ computed.stopOpacity[entity.id()] = stop.opacity;
+ });
+
+ mirror(StrokeStyle, (entity) => {
+ store(world, Computed).strokeWidth[entity.id()] = entity.get(StrokeStyle)!.width;
+ });
+
+ // Size flows into Computed via propagation (descendants owning a Size
+ // re-derive too). bitecs restored sizes through resizeEntity; deserialize
+ // is a plain set now, so the propagation rides on the event instead.
+ mirror(Size, (entity) => {
+ propagateSize(world, entity);
+ });
+
+ return () => {
+ for (const unsubscribe of subs) unsubscribe();
+ };
+}
diff --git a/packages/runtime/src/world/serialize.ts b/packages/runtime/src/world/serialize.ts
index 51e77c0f..2710206f 100644
--- a/packages/runtime/src/world/serialize.ts
+++ b/packages/runtime/src/world/serialize.ts
@@ -16,7 +16,7 @@ import {
Volume, Muted,
KeyframeTrack, Keyframe, Animation, DocumentRoot,
} from '../traits';
-import { getDocument } from '../queries/hierarchy';
+import { createEntity } from '../actions/entities';
import type { Entity, World } from 'koota';
@@ -637,11 +637,9 @@ export function cloneFromRecords(world: World, records: EntityRecord[]) {
const eidMap = new Map<number, Entity>();
for (const record of records) {
- eidMap.set(record.eid, world.spawn());
+ eidMap.set(record.eid, createEntity(world));
}
- const document = getDocument(world);
-
for (const record of records) {
const entity = eidMap.get(record.eid)!;
const copy = { ...record };
@@ -649,9 +647,6 @@ export function cloneFromRecords(world: World, records: EntityRecord[]) {
try {
if (copy.ChildOf !== undefined) {
copy.ChildOf = eidMap.get(copy.ChildOf) ?? copy.ChildOf;
- } else {
- // Parentless record = top-level entity; hang it off the document.
- copy.ChildOf = document;
}
deserializeEntity(entity, copy);