The VS Code of video editing, built for agents.
TypeScript
Refactor AppearanceSettings and update keyframe handling
konstantin-paulus38bc44805bd3
diff --git a/apps/web/src/components/sidebar-right/inspector/appearance.tsx b/apps/web/src/components/sidebar-right/inspector/appearance.tsxindex 149e02aa..ab88f341 100644--- a/apps/web/src/components/sidebar-right/inspector/appearance.tsx+++ b/apps/web/src/components/sidebar-right/inspector/appearance.tsx@@ -24,24 +24,26 @@ import { PanelSection } from "@/components/ui/panel-section";import { Show, createMemo, createSignal } from "solid-js";import { Icon } from "@/components/ui/icon";import { SegmentedIconTabs } from "@/components/ui/segmented-icon-tabs";-import { useEntityState, useEntityTag, BlendMode, isRect, addComponent, removeComponent, setComponent, isAudio, removeKeyframeTrack } from "@/components/engine";-import { useEngine } from "@/context/engine";import { Keyframe } from "@/components/ui/keyframe";-import { hasComponent } from 'bitecs';-import { BLEND_MODE_ORDER, BLEND_MODE_SEPARATORS } from "./blend-mode-menu";--type AppearanceSettingsProps = {- selection: Set<number>;-};--function capitalize(str: string) {- return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();-}+import { useHas, useTrait, useWorld } from "@diffusionstudio/koota-solid";+import {+ BlendMode,+ BlendModeType,+ Computed,+ CornerRadius,+ Hidden,+ MixedCornerRadius,+ isAudio,+ isRect,+} from "@diffusionstudio/runtime";+import { useDerived, useEditor } from "@/engine/hooks";+import { removeKeyframeTrack, syncKeyframe } from "@/engine/keyframes";+import { BLEND_MODE_ORDER, BLEND_MODE_SEPARATORS, blendModeName, displayBlendMode } from "./blend-modes";-function displayBlendMode(mode: string) {- if (mode === String(BlendMode.SOURCE_OVER)) return "Normal";+import type { Entity } from "koota";- return capitalize(mode.replace("_", " "));+type AppearanceSettingsProps = {+ selection: Entity[];};function round(v: number) {@@ -63,40 +65,58 @@ const RADIUS_MODE_ITEMS = [},] as const;-export function AppearanceSettings(props: AppearanceSettingsProps) {- const { world } = useEngine();- const c = world.components;- const eid = () => props.selection.values().next().value!;+type Corner = 'cornerRadiusTopLeft' | 'cornerRadiusTopRight' | 'cornerRadiusBottomRight' | 'cornerRadiusBottomLeft';- const opacity = useEntityState(c.Computed.opacity, eid, 1);- const blendMode = useEntityState(c.Appearance.blendMode, eid, 0);- const hidden = useEntityTag(c.Hidden, eid);+const CORNERS: Corner[] = ['cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomRight', 'cornerRadiusBottomLeft'];- const vertexRadius = useEntityState(c.Computed.cornerRadius, eid, 0);- const mixedTL = useEntityState(c.Computed.cornerRadiusTopLeft, eid, 0);- const mixedTR = useEntityState(c.Computed.cornerRadiusTopRight, eid, 0);- const mixedBR = useEntityState(c.Computed.cornerRadiusBottomRight, eid, 0);- const mixedBL = useEntityState(c.Computed.cornerRadiusBottomLeft, eid, 0);+/**+ * Opacity, blending, visibility and corner radii. All of them are props+ * (`opacity`, `blendMode`, `hidden`, `cornerRadius` and the four per-corner+ * radii) written through the editor; the shown values are Computed, which+ * the motion system writes, hence `useDerived`. A radius the panel leaves+ * at its default is unset rather than written as 0, and a mode switch+ * drops the other mode's props and tracks: uniform is `cornerRadius`,+ * separate is the four corners with `cornerRadius` gone.+ */+export function AppearanceSettings(props: AppearanceSettingsProps) {+ const world = useWorld();+ const editor = useEditor();+ const entity = () => props.selection[0]!;- const hasMixed = hasComponent(world, eid(), c.MixedCornerRadius);+ const opacity = useDerived(() => entity().get(Computed)?.opacity ?? 1);+ const blendModeTrait = useTrait(entity, BlendMode);+ const blendMode = () => blendModeTrait()?.value ?? BlendModeType.SOURCE_OVER;+ const hidden = useHas(entity, Hidden);++ const vertexRadius = useDerived(() => entity().get(Computed)?.cornerRadius ?? 0);+ const mixedTL = useDerived(() => entity().get(Computed)?.cornerRadiusTopLeft ?? 0);+ const mixedTR = useDerived(() => entity().get(Computed)?.cornerRadiusTopRight ?? 0);+ const mixedBR = useDerived(() => entity().get(Computed)?.cornerRadiusBottomRight ?? 0);+ const mixedBL = useDerived(() => entity().get(Computed)?.cornerRadiusBottomLeft ?? 0);const [selectedBlendMode, setSelectedBlendMode] = createSignal(blendMode());- const [radiusMode, setRadiusMode] = createSignal<RadiusMode>(hasMixed ? 'separate' : 'uniform');+ const [radiusMode, setRadiusMode] = createSignal<RadiusMode>(entity().has(MixedCornerRadius) ? 'separate' : 'uniform');const handleOpacityChange = (v: number) => {- setComponent(world, eid(), c.Appearance, { opacity: Math.round(v) / 100 });+ const value = Math.round(v) / 100;+ editor.editProperty(entity(), 'opacity', value === 1 ? false : value);+ syncKeyframe(world, editor, entity(), 'opacity', value);};- const handleBlendModePointerEnter = (mode: number) => (c.Appearance.blendMode[eid()] = mode);+ const previewBlendMode = (mode: BlendModeType) => {+ if (mode === BlendModeType.SOURCE_OVER) {+ entity().remove(BlendMode);+ return;+ }+ entity().add(BlendMode);+ entity().set(BlendMode, { value: mode });+ };- const handleBlendModeSelect = (mode: number | null) => {- if (mode === null) return;+ const handleBlendModeSelect = (mode: BlendModeType | null) => {+ if (mode === null || mode === selectedBlendMode()) return;setSelectedBlendMode(mode);-- if (mode === blendMode()) return;-- setComponent(world, eid(), c.Appearance, { blendMode: mode });+ editor.editProperty(entity(), 'blendMode', mode === BlendModeType.SOURCE_OVER ? false : blendModeName(mode));};const handleBlendModeOpenChange = (isOpen: boolean) => {@@ -104,17 +124,13 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {// Reset blend mode if it has not been changed.if (selectedBlendMode() !== blendMode()) {- handleBlendModePointerEnter(selectedBlendMode());+ previewBlendMode(selectedBlendMode());}};const handleVisibilityChange = () => {- if (!hasComponent(world, eid(), c.Hidden)) {- addComponent(world, eid(), c.Hidden);- } else {- removeComponent(world, eid(), c.Hidden);- }- }+ editor.editProperty(entity(), 'hidden', !hidden());+ };// Radius helpersconst isRadiusDefault = createMemo(() => {@@ -125,41 +141,40 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {});const handleUniformRadiusChange = (v: number) => {- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.topLeft');- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.topRight');- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.bottomRight');- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.bottomLeft');- removeComponent(world, eid(), c.MixedCornerRadius);- setComponent(world, eid(), c.CornerRadius, v);+ for (const corner of CORNERS) {+ removeKeyframeTrack(world, editor, entity(), corner);+ }+ if (entity().has(MixedCornerRadius)) {+ for (const corner of CORNERS) {+ editor.editProperty(entity(), corner, false);+ }+ }+ editor.editProperty(entity(), 'cornerRadius', v === 0 ? false : v);+ syncKeyframe(world, editor, entity(), 'cornerRadius', v);setRadiusMode('uniform');};- const handleSeparateRadiusChange = (corner: 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft', v: number) => {- removeKeyframeTrack(world, eid(), 'vertexRadius');- setComponent(world, eid(), c.MixedCornerRadius, { [corner]: v });+ const handleSeparateRadiusChange = (corner: Corner, v: number) => {+ removeKeyframeTrack(world, editor, entity(), 'cornerRadius');+ editor.editProperty(entity(), corner, v);+ syncKeyframe(world, editor, entity(), corner, v);};const handleRadiusModeChange = (value: RadiusMode) => {setRadiusMode(value);if (value === 'separate') {+ // Read before the uniform radius goes, which resets it.const r = vertexRadius();- removeKeyframeTrack(world, eid(), 'vertexRadius');- removeComponent(world, eid(), c.CornerRadius);- setComponent(world, eid(), c.MixedCornerRadius, {- topLeft: r,- topRight: r,- bottomRight: r,- bottomLeft: r,- });+ removeKeyframeTrack(world, editor, entity(), 'cornerRadius');+ if (entity().has(CornerRadius)) {+ editor.editProperty(entity(), 'cornerRadius', false);+ }+ for (const corner of CORNERS) {+ editor.editProperty(entity(), corner, r);+ }} else {- const avg = mixedTL();- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.topLeft');- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.topRight');- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.bottomRight');- removeKeyframeTrack(world, eid(), 'mixedVertexRadius.bottomLeft');- removeComponent(world, eid(), c.MixedCornerRadius);- setComponent(world, eid(), c.CornerRadius, avg);+ handleUniformRadiusChange(mixedTL());}};@@ -189,7 +204,7 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {value={Math.round(opacity() * 100)}onChange={handleOpacityChange}format={(v) => `${v}%`}- keyframe={<Keyframe target={eid()} property="opacity" />}+ keyframe={<Keyframe target={entity()} property="opacity" />}/></div></ControlRow>@@ -208,9 +223,9 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {</Show><SelectItemitem={itemProps.item}- onPointerEnter={() => handleBlendModePointerEnter(itemProps.item.rawValue)}+ onPointerEnter={() => previewBlendMode(itemProps.item.rawValue)}>- {displayBlendMode(BlendMode[itemProps.item.rawValue])}+ {displayBlendMode(itemProps.item.rawValue)}</SelectItem></>)}@@ -219,7 +234,7 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {icon={<Icon name="blending-mode-default" class="size-5" />}valueClass="text-xxs flex-1">- {displayBlendMode(BlendMode[selectedBlendMode()])}+ {displayBlendMode(selectedBlendMode())}</SelectIconTrigger><SelectPortal><SelectContent class="w-44 overscroll-contain" />@@ -228,7 +243,7 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {</div></ControlRow>- <Show when={isRect(world, eid()) && !isAudio(world, eid())}>+ <Show when={isRect(entity()) && !isAudio(entity())}><ContextMenu><ContextMenuTrigger<typeof ControlRow>as={ControlRow}@@ -244,7 +259,7 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {icon={<Icon name="corner-radius-all" />}sliderEnabledlimitEvents- keyframe={<Keyframe target={eid()} property="vertexRadius" />}+ keyframe={<Keyframe target={entity()} property="cornerRadius" />}/><SegmentedIconTabsvalue={() => radiusMode()}@@ -270,10 +285,10 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {autoSelectstep={1}min={0}- onNumber={(v) => handleSeparateRadiusChange('topLeft', v)}+ onNumber={(v) => handleSeparateRadiusChange('cornerRadiusTopLeft', v)}sliderEnabledlimitEvents- keyframe={<Keyframe target={eid()} property="mixedVertexRadius.topLeft" />}+ keyframe={<Keyframe target={entity()} property="cornerRadiusTopLeft" />}/><ControlledTextFieldicon={<Icon name="corner-radius-top-right" />}@@ -281,10 +296,10 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {autoSelectstep={1}min={0}- onNumber={(v) => handleSeparateRadiusChange('topRight', v)}+ onNumber={(v) => handleSeparateRadiusChange('cornerRadiusTopRight', v)}sliderEnabledlimitEvents- keyframe={<Keyframe target={eid()} property="mixedVertexRadius.topRight" />}+ keyframe={<Keyframe target={entity()} property="cornerRadiusTopRight" />}/><ControlledTextFieldicon={<Icon name="corner-radius-bottom-left" />}@@ -292,10 +307,10 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {autoSelectstep={1}min={0}- onNumber={(v) => handleSeparateRadiusChange('bottomLeft', v)}+ onNumber={(v) => handleSeparateRadiusChange('cornerRadiusBottomLeft', v)}sliderEnabledlimitEvents- keyframe={<Keyframe target={eid()} property="mixedVertexRadius.bottomLeft" />}+ keyframe={<Keyframe target={entity()} property="cornerRadiusBottomLeft" />}/><ControlledTextFieldicon={<Icon name="corner-radius-bottom-right" />}@@ -303,10 +318,10 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {autoSelectstep={1}min={0}- onNumber={(v) => handleSeparateRadiusChange('bottomRight', v)}+ onNumber={(v) => handleSeparateRadiusChange('cornerRadiusBottomRight', v)}sliderEnabledlimitEvents- keyframe={<Keyframe target={eid()} property="mixedVertexRadius.bottomRight" />}+ keyframe={<Keyframe target={entity()} property="cornerRadiusBottomRight" />}/></ControlRow></Show>diff --git a/apps/web/src/components/sidebar-right/inspector/audio.tsx b/apps/web/src/components/sidebar-right/inspector/audio.tsxindex ed24459f..6404160e 100644--- a/apps/web/src/components/sidebar-right/inspector/audio.tsx+++ b/apps/web/src/components/sidebar-right/inspector/audio.tsx@@ -7,7 +7,7 @@ import { ControlRow } from "@/components/ui/control-group";import { Icon } from "@/components/ui/icon";import { PanelSection } from "@/components/ui/panel-section";import { ControlledTextField } from "@/components/ui/text-field";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { useVolumeMeter, type ChannelLevels } from "@/hooks/use-volume-meter";import { cx } from "@/lib/cva";diff --git a/apps/web/src/components/sidebar-right/inspector/blend-modes.ts b/apps/web/src/components/sidebar-right/inspector/blend-modes.tsnew file mode 100644index 00000000..aa4c9cde--- /dev/null+++ b/apps/web/src/components/sidebar-right/inspector/blend-modes.ts@@ -0,0 +1,53 @@+/* 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/. */++import { BlendModeType } from "@diffusionstudio/runtime";+import { BLEND_MODES } from "@diffusionstudio/reconciler";++import type { BlendMode } from "@diffusionstudio/jsx";++// Ordered to match Figma's blend mode menu groupings.+export const BLEND_MODE_ORDER: BlendModeType[] = [+ BlendModeType.SOURCE_OVER,+ BlendModeType.DARKEN,+ BlendModeType.MULTIPLY,+ BlendModeType.COLOR_BURN,+ BlendModeType.LIGHTEN,+ BlendModeType.SCREEN,+ BlendModeType.COLOR_DODGE,+ BlendModeType.OVERLAY,+ BlendModeType.SOFT_LIGHT,+ BlendModeType.HARD_LIGHT,+ BlendModeType.DIFFERENCE,+ BlendModeType.EXCLUSION,+ BlendModeType.HUE,+ BlendModeType.SATURATION,+ BlendModeType.COLOR,+ BlendModeType.LUMINOSITY,+];++// Modes that begin a new group (separator goes before them).+export const BLEND_MODE_SEPARATORS = new Set<BlendModeType>([+ BlendModeType.DARKEN,+ BlendModeType.LIGHTEN,+ BlendModeType.OVERLAY,+ BlendModeType.DIFFERENCE,+ BlendModeType.HUE,+]);++const NAMES = new Map<BlendModeType, BlendMode>(+ Object.entries(BLEND_MODES).map(([name, mode]) => [mode, name as BlendMode]),+);++/** The mode as the JSX spells it (`blendMode="colorDodge"`). */+export function blendModeName(mode: BlendModeType): BlendMode {+ return NAMES.get(mode) ?? "sourceOver";+}++/** The mode as the menu labels it: "Normal", "Color dodge", ... */+export function displayBlendMode(mode: BlendModeType): string {+ if (mode === BlendModeType.SOURCE_OVER) return "Normal";+ const name = BlendModeType[mode].replace("_", " ");+ return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();+}diff --git a/apps/web/src/components/sidebar-right/inspector/effects-inspector.tsx b/apps/web/src/components/sidebar-right/inspector/effects-inspector.tsxindex bd81dd4b..4c88151a 100644--- a/apps/web/src/components/sidebar-right/inspector/effects-inspector.tsx+++ b/apps/web/src/components/sidebar-right/inspector/effects-inspector.tsx@@ -14,7 +14,7 @@ import {} from "@/components/ui/floating-inspector";import { Icon } from "@/components/ui/icon";import { IncrementDecrementControl } from "@/components/ui/increment-decrement-control";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { SliderInput } from "@/components/ui/slider-input";import { ControlledTextField } from "@/components/ui/text-field";import { useEngine } from "@/context/engine";diff --git a/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsx b/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsxindex 71307772..e0fec2f4 100644--- a/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsx+++ b/apps/web/src/components/sidebar-right/inspector/gradient-picker.tsx@@ -24,7 +24,7 @@ import {SelectValue,} from "@/components/ui/select";import { ControlledTextField } from "@/components/ui/text-field";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { OpacitySwatch } from "@/components/ui/opacity-swatch";import {FloatingInspector,diff --git a/apps/web/src/components/sidebar-right/inspector/inspector.tsx b/apps/web/src/components/sidebar-right/inspector/inspector.tsxindex 044325cf..db740345 100644--- a/apps/web/src/components/sidebar-right/inspector/inspector.tsx+++ b/apps/web/src/components/sidebar-right/inspector/inspector.tsx@@ -23,11 +23,11 @@ import { BackgroundSettings } from "./background";import { SceneTemplatePanel } from "./scene-template";import { AssetInfoPanel } from "./asset-info";import { TimeSettings } from "./time";+import { AppearanceSettings } from "./appearance";// import { Alignment } from "./alignment";// import { ExportPanel } from "./export";// import { TransformSettings } from "./transform";// import { LayoutPanel } from "./layout";-// import { AppearanceSettings } from "./appearance";// import { CaptionSettings } from "./caption-settings";// import { TextPanel } from "./text";// import { FillsSettings } from "./fills";@@ -137,9 +137,9 @@ export function Inspector() {<LayoutPanel selection={nodes()} /></Show> */}- {/* <Show when={includesTarget("shape", "text", "scene", "caption", "group", "audio", "mask")}>+ <Show when={includesTarget("shape", "text", "scene", "caption", "group", "audio", "mask")}><AppearanceSettings selection={nodes()} />- </Show> */}+ </Show>{/* <Show when={includesTarget("caption")}><CaptionSettings selection={nodes()} />diff --git a/apps/web/src/components/sidebar-right/inspector/layout.tsx b/apps/web/src/components/sidebar-right/inspector/layout.tsxindex 1f07741c..a0d53206 100644--- a/apps/web/src/components/sidebar-right/inspector/layout.tsx+++ b/apps/web/src/components/sidebar-right/inspector/layout.tsx@@ -8,7 +8,7 @@ import { ControlledTextField } from "@/components/ui/text-field";import { Icon } from "@/components/ui/icon";import { PanelSection } from "@/components/ui/panel-section";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { useEntityState, useEntityTag, isScene, addComponent, removeComponent, setComponent, resizeEntity } from "@/components/engine";import {Checkbox,diff --git a/apps/web/src/components/sidebar-right/inspector/shadow-inspector.tsx b/apps/web/src/components/sidebar-right/inspector/shadow-inspector.tsxindex 591b400e..f2135e3f 100644--- a/apps/web/src/components/sidebar-right/inspector/shadow-inspector.tsx+++ b/apps/web/src/components/sidebar-right/inspector/shadow-inspector.tsx@@ -20,7 +20,7 @@ import { ControlledTextField } from "@/components/ui/text-field";import { IncrementDecrementControl } from "@/components/ui/increment-decrement-control";import { useEntityState, setComponent } from "@/components/engine";import { useEngine } from "@/context/engine";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";type ShadowInspectorProps = {diff --git a/apps/web/src/components/sidebar-right/inspector/strokes.tsx b/apps/web/src/components/sidebar-right/inspector/strokes.tsxindex 539fd107..b07fbac2 100644--- a/apps/web/src/components/sidebar-right/inspector/strokes.tsx+++ b/apps/web/src/components/sidebar-right/inspector/strokes.tsx@@ -10,7 +10,7 @@ import { Icon } from "@/components/ui/icon";import { PanelSection } from "@/components/ui/panel-section";import { ControlledTextField } from "@/components/ui/text-field";import { SegmentedIconTabs } from "@/components/ui/segmented-icon-tabs";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { useEngine } from "@/context/engine";import { StrokeJoin, useEntityState, createEntity, deleteEntity, getSiblingEntities, addComponent, appendChild, setComponent } from "@/components/engine";import { FillRow } from "./fill-row";diff --git a/apps/web/src/components/sidebar-right/inspector/transform/offset-row.tsx b/apps/web/src/components/sidebar-right/inspector/transform/offset-row.tsxindex f2ad14ac..dd2d30ea 100644--- a/apps/web/src/components/sidebar-right/inspector/transform/offset-row.tsx+++ b/apps/web/src/components/sidebar-right/inspector/transform/offset-row.tsx@@ -14,7 +14,7 @@ import {} from "@/components/ui/context-menu";import { useEngine } from "@/context/engine";import { useEntityState, addComponent, setComponent } from "@/components/engine";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";export type OffsetRowProps = {diff --git a/apps/web/src/components/sidebar-right/inspector/transform/rotate-row.tsx b/apps/web/src/components/sidebar-right/inspector/transform/rotate-row.tsxindex fd35cce8..30027b2e 100644--- a/apps/web/src/components/sidebar-right/inspector/transform/rotate-row.tsx+++ b/apps/web/src/components/sidebar-right/inspector/transform/rotate-row.tsx@@ -15,7 +15,7 @@ import {} from '@/components/ui/context-menu';import { useEngine } from '@/context/engine';import { useEntityState, setComponent } from '@/components/engine';-import { Keyframe } from '@/components/ui/keyframe';+import { Keyframe } from '@/components/ui/keyframe-bitecs';type RotateRowProps = {diff --git a/apps/web/src/components/sidebar-right/inspector/transform/scale-row.tsx b/apps/web/src/components/sidebar-right/inspector/transform/scale-row.tsxindex a1037d13..784921d3 100644--- a/apps/web/src/components/sidebar-right/inspector/transform/scale-row.tsx+++ b/apps/web/src/components/sidebar-right/inspector/transform/scale-row.tsx@@ -14,7 +14,7 @@ import {} from "@/components/ui/context-menu";import { useEngine } from "@/context/engine";import { useEntityState, setComponent, useEntityTag, removeComponent, removeKeyframeTrack } from "@/components/engine";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { SegmentedIconTabs } from "@/components/ui/segmented-icon-tabs";import { hasComponent } from "bitecs";diff --git a/apps/web/src/components/sidebar-right/inspector/transform/skew-row.tsx b/apps/web/src/components/sidebar-right/inspector/transform/skew-row.tsxindex 848aa184..3e2958ca 100644--- a/apps/web/src/components/sidebar-right/inspector/transform/skew-row.tsx+++ b/apps/web/src/components/sidebar-right/inspector/transform/skew-row.tsx@@ -14,7 +14,7 @@ import {} from "@/components/ui/context-menu";import { useEngine } from "@/context/engine";import { useEntityState, setComponent } from "@/components/engine";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";export type SkewRowProps = {diff --git a/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsx b/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsxindex 7385be67..64e3b56d 100644--- a/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsx+++ b/apps/web/src/components/sidebar-right/inspector/transform/transform-settings.tsx@@ -25,7 +25,7 @@ import { useEngine } from "@/context/engine";import { useEntityState, getParentEntity, setComponent } from "@/components/engine";import { createStoredSignal } from "@/lib/store";import { store } from "@/init";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { hasComponent } from "bitecs";diff --git a/apps/web/src/components/timeline/layers/keyframe.tsx b/apps/web/src/components/timeline/layers/keyframe.tsxindex 174f7037..4f3897e5 100644--- a/apps/web/src/components/timeline/layers/keyframe.tsx+++ b/apps/web/src/components/timeline/layers/keyframe.tsx@@ -6,7 +6,7 @@ import { createMemo, Show } from 'solid-js';import { Button } from '@/components/ui/button';import { Icon } from '@/components/ui/icon';import { Tooltip, TooltipContent, TooltipPortal, TooltipTrigger } from '@/components/ui/tooltip';-import { Keyframe } from '@/components/ui/keyframe';+import { Keyframe } from '@/components/ui/keyframe-bitecs';import { useEngine } from '@/context/engine';import { useECS } from '@/context/ecs';import { KEYFRAME_TRACK_HEIGHT } from '@/components/engine/timeline/config';diff --git a/apps/web/src/components/ui/color-opacity-picker.tsx b/apps/web/src/components/ui/color-opacity-picker.tsxindex 93afc5f8..77d29e33 100644--- a/apps/web/src/components/ui/color-opacity-picker.tsx+++ b/apps/web/src/components/ui/color-opacity-picker.tsx@@ -4,7 +4,7 @@import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icon";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { checkerboardStyle } from "@/components/ui/opacity-swatch";import {diff --git a/apps/web/src/components/ui/fill-item.tsx b/apps/web/src/components/ui/fill-item.tsxindex 65c66986..47136e7b 100644--- a/apps/web/src/components/ui/fill-item.tsx+++ b/apps/web/src/components/ui/fill-item.tsx@@ -5,7 +5,7 @@import { createEffect, createMemo, createSignal, onCleanup, Show } from "solid-js";import { AssetThumbnail } from "@/components/ui/asset-thumbnail";import { Icon } from "@/components/ui/icon";-import { Keyframe } from "@/components/ui/keyframe";+import { Keyframe } from "@/components/ui/keyframe-bitecs";import { OpacitySwatch } from "@/components/ui/opacity-swatch";import { useEngine } from "@/context/engine";import { mergeColorWithOpacity } from "@/utils";diff --git a/apps/web/src/components/ui/keyframe-bitecs.tsx b/apps/web/src/components/ui/keyframe-bitecs.tsxnew file mode 100644index 00000000..949767a1--- /dev/null+++ b/apps/web/src/components/ui/keyframe-bitecs.tsx@@ -0,0 +1,74 @@+/* 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/. */++import { useEngine } from "@/context/engine";+import { findKeyframeTargetNode } from "@/components/engine/api";+import { cx } from "@/lib/cva";+import { createMemo, Show } from "solid-js";+import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";+import { getParentEntity, toggleKeyframeTrack, useEntityState, type PropertyPath } from "../engine";++type KeyframeProps = {+ target: number;+ property: PropertyPath;+ disabled?: boolean;+ class?: string;+};++export function Keyframe(props: KeyframeProps) {+ const { world } = useEngine();+ const c = world.components;++ const nodeEid = createMemo(() => findKeyframeTargetNode(world, props.target));+ const isAvailable = createMemo(() => getParentEntity(world, props.target) !== null && nodeEid() !== null);++ const tracks = useEntityState(c.Cache.keyframeTracks, nodeEid, []);+ const localFrame = useEntityState(c.Computed.localTime, nodeEid, 0);++ const matchedTrack = createMemo(() => {+ for (const tid of tracks()) {+ if (c.KeyframeTrack.property[tid] !== props.property) continue;+ if (c.KeyframeTrack.target[tid] !== props.target) continue;+ return tid;+ }+ return null;+ });++ const hasTrack = createMemo(() => matchedTrack() !== null);++ const keyframes = useEntityState(c.Cache.keyframes, matchedTrack, []);++ const isActive = createMemo(() => {+ return keyframes().some(kf => Math.round(c.Keyframe.time[kf]) === localFrame());+ });++ const toggleKeyframe = () => toggleKeyframeTrack(world, props.target, props.property);++ return (+ <Show when={isAvailable()}>+ <Tooltip openDelay={600} disabled={props.disabled}>+ <TooltipTrigger+ as="button"+ type="button"+ class={cx("flex items-center size-6 justify-center transition-colors group disabled:cursor-not-allowed disabled:opacity-50", props.class)}+ onClick={toggleKeyframe}+ disabled={props.disabled}+ >+ <div+ class={cx(+ "size-1.5 rotate-45 border transition-colors",+ isActive()+ ? "bg-primary"+ : "bg-transparent group-hover:border-foreground",+ hasTrack()+ ? "border-primary"+ : "border-muted-foreground"+ )}+ />+ </TooltipTrigger>+ <TooltipContent>{isActive() ? "Remove keyframe" : "Add keyframe"}</TooltipContent>+ </Tooltip>+ </Show>+ )+}diff --git a/apps/web/src/components/ui/keyframe.tsx b/apps/web/src/components/ui/keyframe.tsxindex 949767a1..e343e303 100644--- a/apps/web/src/components/ui/keyframe.tsx+++ b/apps/web/src/components/ui/keyframe.tsx@@ -2,72 +2,70 @@* 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/. */-import { useEngine } from "@/context/engine";-import { findKeyframeTargetNode } from "@/components/engine/api";+import { Show } from "solid-js";+import { useHas, useWorld } from "@diffusionstudio/koota-solid";+import { Cache, Source } from "@diffusionstudio/runtime";import { cx } from "@/lib/cva";-import { createMemo, Show } from "solid-js";+import { useDerived, useEditor } from "@/engine/hooks";+import { findKeyframeAt, findKeyframeTrack, keyframeFrame, toggleKeyframe } from "@/engine/keyframes";import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";-import { getParentEntity, toggleKeyframeTrack, useEntityState, type PropertyPath } from "../engine";++import type { AnimatableProperty } from "@diffusionstudio/jsx";+import type { Entity } from "koota";type KeyframeProps = {- target: number;- property: PropertyPath;+ target: Entity;+ property: AnimatableProperty;disabled?: boolean;class?: string;};export function Keyframe(props: KeyframeProps) {- const { world } = useEngine();- const c = world.components;-- const nodeEid = createMemo(() => findKeyframeTargetNode(world, props.target));- const isAvailable = createMemo(() => getParentEntity(world, props.target) !== null && nodeEid() !== null);-- const tracks = useEntityState(c.Cache.keyframeTracks, nodeEid, []);- const localFrame = useEntityState(c.Computed.localTime, nodeEid, 0);-- const matchedTrack = createMemo(() => {- for (const tid of tracks()) {- if (c.KeyframeTrack.property[tid] !== props.property) continue;- if (c.KeyframeTrack.target[tid] !== props.target) continue;- return tid;- }- return null;- });-- const hasTrack = createMemo(() => matchedTrack() !== null);+ const world = useWorld();+ const editor = useEditor();- const keyframes = useEntityState(c.Cache.keyframes, matchedTrack, []);+ const hasSource = useHas(() => props.target, Source);- const isActive = createMemo(() => {- return keyframes().some(kf => Math.round(c.Keyframe.time[kf]) === localFrame());- });+ const state = useDerived(+ () => {+ const frame = keyframeFrame(props.target);+ if (frame === null) return { available: false, hasTrack: false, isActive: false };+ const track = findKeyframeTrack(world, props.target, props.property);+ const keyframes = track?.get(Cache)?.keyframes.length ?? 0;+ return {+ available: true,+ hasTrack: track !== null && keyframes > 0,+ isActive: track !== null && findKeyframeAt(track, frame) !== null,+ };+ },+ (a, b) => a.available === b.available && a.hasTrack === b.hasTrack && a.isActive === b.isActive,+ );- const toggleKeyframe = () => toggleKeyframeTrack(world, props.target, props.property);+ const toggle = () => toggleKeyframe(world, editor, props.target, props.property);return (- <Show when={isAvailable()}>+ <Show when={hasSource() && state().available}><Tooltip openDelay={600} disabled={props.disabled}><TooltipTriggeras="button"type="button"class={cx("flex items-center size-6 justify-center transition-colors group disabled:cursor-not-allowed disabled:opacity-50", props.class)}- onClick={toggleKeyframe}+ onClick={toggle}disabled={props.disabled}><divclass={cx("size-1.5 rotate-45 border transition-colors",- isActive()+ state().isActive? "bg-primary": "bg-transparent group-hover:border-foreground",- hasTrack()+ state().hasTrack? "border-primary": "border-muted-foreground")}/></TooltipTrigger>- <TooltipContent>{isActive() ? "Remove keyframe" : "Add keyframe"}</TooltipContent>+ <TooltipContent>{state().isActive ? "Remove keyframe" : "Add keyframe"}</TooltipContent></Tooltip></Show>)diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.tsindex 1dbc959f..d38587d0 100644--- a/apps/web/src/engine/index.ts+++ b/apps/web/src/engine/index.ts@@ -13,3 +13,4 @@ export * from './input';export * from './hud';export * from './library';export * from './asset-actions';+export * from './keyframes';diff --git a/apps/web/src/engine/keyframes.tsx b/apps/web/src/engine/keyframes.tsxnew file mode 100644index 00000000..8040ef99--- /dev/null+++ b/apps/web/src/engine/keyframes.tsx@@ -0,0 +1,143 @@+/* 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/. */++/**+ * Keyframes as edits. In the source a keyframed prop is a `<keyframeTrack+ * property>` under the element whose prop it drives, holding `<keyframe time+ * value easing>` children; so adding a keyframe inserts an element, changing+ * one writes its `value`, and removing the last one removes the track. These+ * are the runtime's `toggleKeyframeTrack`/`syncKeyframeTrack`/+ * `removeKeyframeTrack` in that vocabulary, routed through the editor so the+ * file hears about them. Properties are named as the JSX names them+ * (`AnimatableProperty`), the way a track in the file is.+ */++import { Keyframe as KeyframeElement, KeyframeTrack as KeyframeTrackElement, trackPropertyPath } from "@diffusionstudio/reconciler";+import {+ Cache,+ ChildOf,+ Keyframe,+ KeyframeTrack,+ FrameRate,+ colorToHex,+ findKeyframeTargetNode,+ framesToSeconds,+ getNodeLocalFrame,+ getPropertyPaths,+} from "@diffusionstudio/runtime";++import type { AnimatableProperty } from "@diffusionstudio/jsx";+import type { Entity, World } from "koota";+import type { DocumentEditor } from "./editor";++/** The track driving `target`'s `property`, if any. */+export function findKeyframeTrack(world: World, target: Entity, property: AnimatableProperty): Entity | null {+ const path = trackPropertyPath(target, property);+ if (!path) return null;+ for (const track of world.query(KeyframeTrack, ChildOf(target))) {+ if (track.get(KeyframeTrack)!.property === path) return track;+ }+ return null;+}++/** The keyframe of `track` at local `frame`, if any. */+export function findKeyframeAt(track: Entity, frame: number): Entity | null {+ const keyframes = track.get(Cache)?.keyframes ?? [];+ return keyframes.find((keyframe) => Math.round(keyframe.get(Keyframe)!.time) === frame) ?? null;+}++/** The local frame `target`'s keyframes are authored at: its node's, in the node's source time. */+export function keyframeFrame(target: Entity): number | null {+ const node = findKeyframeTargetNode(target);+ return node === null ? null : getNodeLocalFrame(node);+}++/**+ * The value of `target`'s `property` as shown right now: the computed one,+ * which is what a keyframe added here should hold. Colors come back as the+ * CSS hex a color track's keyframe is spelled with.+ */+function currentValue(world: World, target: Entity, property: AnimatableProperty): number | string | null {+ const path = trackPropertyPath(target, property);+ if (!path) return null;+ const value = getPropertyPaths(world)[path]?.computed[target.id()];+ if (typeof value !== "number") return null;+ return property === "color" ? colorToHex(value) : value;+}++/** A keyframe's `time` as the file spells it: seconds of this project's frame rate. */+function keyframeTime(world: World, frame: number): number {+ return framesToSeconds(frame, world.get(FrameRate)?.value ?? 30);+}++/**+ * Writes a keyframe for `target`'s `property` at the current local frame+ * holding `value` (the shown value when omitted): the keyframe already there+ * takes the value, else one is inserted, into the track or into a new track.+ * Returns the keyframe, or null when the target is not keyframable (no node+ * above it, no source to write under, a property it does not have).+ */+export function writeKeyframe(world: World, editor: DocumentEditor, target: Entity, property: AnimatableProperty, value?: number | string): Entity | null {+ const frame = keyframeFrame(target);+ if (frame === null) return null;+ const held = value ?? currentValue(world, target, property);+ if (held === null) return null;++ const track = findKeyframeTrack(world, target, property);+ const existing = track && findKeyframeAt(track, frame);+ if (existing) {+ editor.editProperty(existing, "value", held);+ return existing;+ }++ const time = keyframeTime(world, frame);+ if (track) {+ const [keyframe] = editor.insertElement(track, () => <KeyframeElement time={time} value={held} />);+ return keyframe ?? null;+ }++ const [created] = editor.insertElement(target, () => (+ <KeyframeTrackElement property={property}>+ <KeyframeElement time={time} value={held} />+ </KeyframeTrackElement>+ ));+ return created ? findKeyframeAt(created, frame) : null;+}++/**+ * Adds a keyframe for `target`'s `property` at the current local frame, or+ * removes the one already there; the track goes with its last keyframe.+ */+export function toggleKeyframe(world: World, editor: DocumentEditor, target: Entity, property: AnimatableProperty): void {+ const frame = keyframeFrame(target);+ if (frame === null) return;++ const track = findKeyframeTrack(world, target, property);+ const existing = track && findKeyframeAt(track, frame);+ if (!existing) {+ writeKeyframe(world, editor, target, property);+ return;+ }++ const last = (track.get(Cache)?.keyframes.length ?? 0) <= 1;+ editor.remove(last ? track : existing);+}++/**+ * Keeps a keyframed prop's track in step with an edit of its value: the+ * keyframe at the current frame takes `value`, or one is added holding it.+ * Nothing happens without a track; editing surfaces call this after+ * writing the prop, since the motion system would otherwise overwrite the+ * edit on the next tick.+ */+export function syncKeyframe(world: World, editor: DocumentEditor, target: Entity, property: AnimatableProperty, value: number | string): void {+ if (findKeyframeTrack(world, target, property) === null) return;+ writeKeyframe(world, editor, target, property, value);+}++/** Removes the track driving `target`'s `property`, keyframes included. */+export function removeKeyframeTrack(world: World, editor: DocumentEditor, target: Entity, property: AnimatableProperty): void {+ const track = findKeyframeTrack(world, target, property);+ if (track) editor.remove(track);+}diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.tsindex 86f07daa..702ce4b0 100644--- a/packages/jsx/src/types.ts+++ b/packages/jsx/src/types.ts@@ -95,6 +95,10 @@ export type AnimatableProperty =| "scaleY"| "opacity"| "cornerRadius"+ | "cornerRadiusTopLeft"+ | "cornerRadiusTopRight"+ | "cornerRadiusBottomRight"+ | "cornerRadiusBottomLeft"| "volume"| "color"| "offset"@@ -207,6 +211,14 @@ type TransformProps = PositionProps & OffsetProps & SizeProps & {opacity?: number;/** Uniform corner radius, px. */cornerRadius?: number;+ /**+ * Per-corner radius, px. A corner without one takes `cornerRadius`, so+ * `cornerRadius={20} cornerRadiusTopLeft={0}` rounds three corners.+ */+ cornerRadiusTopLeft?: number;+ cornerRadiusTopRight?: number;+ cornerRadiusBottomRight?: number;+ cornerRadiusBottomLeft?: number;};/** How an element composites, and whether it does at all. */diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.tsindex 770b01f8..36a1a0e9 100644--- a/packages/reconciler/src/document.ts+++ b/packages/reconciler/src/document.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { Active, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, BlendMode, BlendModeType, Blur, Chars, ClipsContent, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Effect, EffectType, End, FontStyle, FrameRate, Loop, Geometry, GeometryType, Library, getEntityTree, getParentEntity, getParentNode, Hidden, IsMask, isText, ItemIndex, Keyframe, KeyframeTrack, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, Playback, PlaybackRate, Position, removeChild, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getAssetFile, getEntityChildren, getLibrary, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceIn, SourceOut, setCameraMatrix, Start, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SurfaceHost, SurfaceHostHandle, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, Transition, TransitionType, UniformScale, Volume } from '@diffusionstudio/runtime';+import { Active, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, BlendMode, BlendModeType, Blur, Chars, ClipsContent, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Effect, EffectType, End, FontStyle, FrameRate, Loop, Geometry, GeometryType, Library, getEntityTree, getParentEntity, getParentNode, Hidden, IsMask, isText, ItemIndex, Keyframe, KeyframeTrack, MixedCornerRadius, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, Playback, PlaybackRate, Position, removeChild, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getAssetFile, getEntityChildren, getLibrary, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceIn, SourceOut, setCameraMatrix, Start, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SurfaceHost, SurfaceHostHandle, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, Transition, TransitionType, UniformScale, Volume } from '@diffusionstudio/runtime';import { isPropValue, LOOP_ATTR, parseTime, SOURCE_ATTR } from '@diffusionstudio/jsx';import type { CameraMatrix, PropertyPath } from '@diffusionstudio/runtime';@@ -172,7 +172,7 @@ const TRANSITION_TYPES: Record<string, TransitionType> = {};/** The canvas composite operations, spelled camelCase like the other enums. */-const BLEND_MODES: Record<string, BlendModeType> = {+export const BLEND_MODES: Record<string, BlendModeType> = {sourceOver: BlendModeType.SOURCE_OVER,multiply: BlendModeType.MULTIPLY,screen: BlendModeType.SCREEN,@@ -208,6 +208,10 @@ const TRACK_PROPERTIES: Record<string, PropertyPath> = {scaleY: 'scale.y',opacity: 'opacity',cornerRadius: 'vertexRadius',+ cornerRadiusTopLeft: 'mixedVertexRadius.topLeft',+ cornerRadiusTopRight: 'mixedVertexRadius.topRight',+ cornerRadiusBottomRight: 'mixedVertexRadius.bottomRight',+ cornerRadiusBottomLeft: 'mixedVertexRadius.bottomLeft',volume: 'volume',color: 'color',offset: 'stop.offset',@@ -215,6 +219,20 @@ const TRACK_PROPERTIES: Record<string, PropertyPath> = {value: 'effect.value',};+/**+ * The runtime property path a `<keyframeTrack property>` under `holder`+ * drives, or undefined for a name no track can take. `width` depends on the+ * holder: a stroke's is its line width.+ */+export function trackPropertyPath(holder: Entity | null, property: string): PropertyPath | undefined {+ const path = TRACK_PROPERTIES[property];+ if (path === 'width' && holder?.has(Stroke)) return 'stroke.width';+ return path;+}++/** The `<rect>` props of the per-corner radii, in the trait's (CSS) order. */+const CORNER_PROPS = ['cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomRight', 'cornerRadiusBottomLeft'] as const;+/*** Named easings as the descriptors the runtime (and the editor's* interpolation inspector) speak; the descriptor forms pass through with@@ -331,8 +349,13 @@ function syncSurfaceSize(world: World, holder: Entity): void {}}+/**+ * A numeric prop's value, or undefined for none. A boolean is none, not 0+ * or 1: `false` is how an editor unsets a prop (the writer spells it as the+ * attribute's absence), and a number prop has no true.+ */function toNumber(value: unknown) {- if (value === undefined || value === null) {+ if (value === undefined || value === null || typeof value === 'boolean') {return undefined;}@@ -674,11 +697,19 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {const radius = toNumber(value);if (radius === undefined) {entity.remove(CornerRadius);- return;+ } else {+ entity.add(CornerRadius);+ entity.set(CornerRadius, { value: radius });}-- entity.add(CornerRadius);- entity.set(CornerRadius, { value: radius });+ // The corners without a radius of their own take this one.+ this.syncCornerRadii(entity);+ return;+ }+ case 'cornerRadiusTopLeft':+ case 'cornerRadiusTopRight':+ case 'cornerRadiusBottomRight':+ case 'cornerRadiusBottomLeft': {+ this.syncCornerRadii(entity);return;}case 'blendMode': {@@ -1022,11 +1053,30 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {* Solid sets props before the track has a parent.*/private resolveTrackProperty(track: Entity, property: unknown): void {- let path = typeof property === 'string' ? TRACK_PROPERTIES[property] : undefined;- if (path === 'width' && getParentEntity(track)?.has(Stroke)) path = 'stroke.width';+ const path = typeof property === 'string' ? trackPropertyPath(getParentEntity(track), property) : undefined;track.set(KeyframeTrack, { property: path ?? '' });}+ /**+ * Derives `MixedCornerRadius` from the five radius props as authored: it+ * is present while any corner has a radius of its own, and a corner+ * without one takes `cornerRadius`. Recomputed whole on every one of the+ * five, so the order Solid sets them in does not matter.+ */+ private syncCornerRadii(entity: Entity): void {+ const props = entity.get(Authored)?.props ?? {};+ const corners = CORNER_PROPS.map((name) => toNumber(props[name]));+ if (corners.every((corner) => corner === undefined)) {+ entity.remove(MixedCornerRadius);+ return;+ }++ const uniform = toNumber(props.cornerRadius) ?? 0;+ const [topLeft, topRight, bottomRight, bottomLeft] = corners.map((corner) => corner ?? uniform);+ entity.add(MixedCornerRadius);+ entity.set(MixedCornerRadius, { topLeft, topRight, bottomRight, bottomLeft });+ }+/*** Entity handles are minted per lookup, so every comparison here is between* entities: two handles for the same node are never the same object. Textdiff --git a/packages/runtime/MIGRATION.md b/packages/runtime/MIGRATION.mdindex c978f40d..f636e67e 100644--- a/packages/runtime/MIGRATION.md+++ b/packages/runtime/MIGRATION.md@@ -84,7 +84,7 @@ One trait per value rather than one trait with four fields, because a clip rarel- 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.- 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 and Paint/AssetId onChange run the timing recomputes; Start/End/SourceIn/SourceOut/PlaybackRate add/change/remove propagate them through the subtree; Keyframe/ItemIndex onChange resort caches; ChildOf onRemove rebuilds caches (+ `reactToChildDetached`, skipped when the parent is already destroyed). Authored→Computed mirrors register on add and change; trait removal does not reset Computed (same as bitecs).+- Observer-driven behavior faithful to bitecs: Sequential onAdd group-ifies and strips spatial traits; Group/Scene/Audio onAdd and Paint/AssetId onChange run the timing recomputes; Start/End/SourceIn/SourceOut/PlaybackRate add/change/remove propagate them through the subtree; Keyframe/ItemIndex onChange resort caches; ChildOf onRemove rebuilds caches (+ `reactToChildDetached`, skipped when the parent is already destroyed). Authored→Computed mirrors register on add, change and remove (removal re-derives from the traits left, so an unset prop falls back to its default; see the AppearanceSettings slice).- 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.- Still app-side from `api/observers.ts`: persistence scheduling, timeline index rebuilds, `syncInteractiveState`, Selected waveform show/hide, ClipHeight/Expanded, ExportSettings defaults, drag-origin traits.@@ -167,6 +167,10 @@ apps/web now depends on `@diffusionstudio/runtime` and `@diffusionstudio/koota-s**TimeSettings is on the koota world**, and with it the first pieces every timing surface will share. Reads: the resolved bounds are `Computed.start/end`, which the systems write without events, so `useTrait` cannot follow them; `useDerived(read, equals?)` (`engine/hooks/use-derived.ts`) samples `read` once per engine tick against `Engine.frame`, a plain Solid signal the loop bumps after `runSystems` (one signal for every caller, no koota subscription per hook), and notifies only when the sample changes. Use it for any Computed read in UI (Transform/Layout will). Writes stay `editor.editProperty`; `DocumentEditor` keeps to primitives, and what a property means is the panel's business. `time.tsx` has the helpers: `editTime(world, editor, entity, 'start'|'end'|'sourceIn'|'sourceOut', frames | null)` converts project frames to the seconds the file spells (`framesToSeconds`; the desktop writer rounds to 2 decimals, exact up to 100 fps), `null` unsets (`false` is the PropValue the writer removes an attribute for, and the document drops the trait for it), and a `start`/`sourceIn` of 0 is unset too since absence reads as 0; `trimIn/trimOut(world, editor, entity, sceneFrame)` are the runtime's `trimEntityIn/Out` as edits (pin End when absent, then Start + SourceIn computed before either is written, since the Start write moves the origin; SourceOut follows only when authored). When the timeline needs the same, lift them into a shared module then. The panel: Length and In/Out go through `trimOut`/`trimIn`; Speed is `playbackRate` (1 unsets; the start stays put on its own because the rate only scales the source window around it, so the bitecs Delay fixup is gone); "Trim content" on a scene/group is `hasEnd` (a container authoring an End spans it instead of fitting its children), toggled on via `trimIn(entity, Computed.start)`, which writes Start = SourceIn = the first child's offset so the children stay where they are, and off via `editTime('end', null)`; the sequence Frame Rate row is `setSequenceFrameRate` in `engine/asset-actions.ts` (`library.update` in place, then `reactToAssetChange` for every AssetId holder; no End clamp, caps resolve at read time). Runtime fix that came with it: `pinEndToCurrentBounds` pins `Computed.end - origin` instead of `Start + duration`, which was wrong for a container fitting children that start after 0. Not carried over: the bitecs `resolveSequentialOverlaps` call after each timing edit (the runtime's version writes traits without reporting; it needs an editor-side port before the app can call it), and `history.transaction` labels (no undo layer).+ **AppearanceSettings is on the koota world, and with it keyframes as edits.** Opacity, blending, visibility and corner radii are the props `opacity`, `blendMode` (`sourceOver` is unset, spelled `false` like every default), `hidden`, `cornerRadius` and four new `<rect>` props `cornerRadiusTopLeft`/`TopRight`/`BottomRight`/`BottomLeft` (`@diffusionstudio/jsx`, also in `AnimatableProperty`; `TRACK_PROPERTIES` maps them to the `mixedVertexRadius.*` paths). The document derives `MixedCornerRadius` from the five radius props as authored (`syncCornerRadii`, recomputed whole on each so Solid's prop order does not matter): present while any corner has a radius of its own, a corner without one taking `cornerRadius`, gone when none has, which is the render system's "mixed wins while present" with a fallback. The panel's uniform/separate switch drops the other mode's props and tracks. Hovering a blend mode previews through the trait alone (`entity.set(BlendMode)`, restored on close), only a pick is an edit. Reads are Computed via `useDerived` (the shown, possibly animated, value), `useTrait(BlendMode)`, `useHas(Hidden)`. Two changes underneath: (1) `toNumber` in the document treats a boolean as no value instead of 0/1, so `editProperty(entity, 'opacity', false)` unsets the prop (the writer already spelled `false` as the attribute's absence; before, it would have written opacity 0 to the canvas). (2) **Trait removal now resets Computed**: the mirror observers in `world/observers.ts` run `resetAnimatedValues(world, entity, trait)` onRemove (all but `Size`), and `resetAnimatedValues` reads a trait's store only while the entity has it (else the default), with an `ignore` param because koota fires onRemove before clearing the trait and leaves store slots as they were. Before this an unset `opacity` held its last value on the canvas until remount, which no reactive prop or editor unset could live with; "does not reset, same as bitecs" held only while traits were never removed.++ **Keyframes as edits** live in `apps/web/src/engine/keyframes.tsx`, the runtime's `toggleKeyframeTrack`/`syncKeyframeTrack`/`removeKeyframeTrack` in the JSX's vocabulary: properties are `AnimatableProperty` names (what `<keyframeTrack property>` takes; the reconciler exports `trackPropertyPath(holder, name)` to resolve them, and `BLEND_MODES`), and every change goes through the editor. `writeKeyframe(world, editor, target, property, value?)` edits the `value` of the keyframe at the node's current local frame or inserts `<Keyframe time value />` (time as seconds, like the timing props) into the track, or the whole `<KeyframeTrack property><Keyframe/></KeyframeTrack>` when there is none; `value` defaults to the shown (Computed) value, colors as hex. `toggleKeyframe` adds or removes the keyframe at the current frame, removing the track with its last keyframe (`editor.remove`). `syncKeyframe(world, editor, target, property, value)` is what an editing surface calls after writing a prop that has a track, since the motion system would overwrite the edit on the next tick (the observers slice dropped auto-sync on purpose); the appearance panel does so for opacity and the radii. `removeKeyframeTrack` removes the track element. `components/ui/keyframe.tsx` is the koota `Keyframe` diamond (`target: Entity`, `property: AnimatableProperty`; track/active state sampled per tick with `useDerived`, shown only for an element with a `Source`); the bitecs one moved to `components/ui/keyframe-bitecs.tsx` and the unmigrated panels import it from there until they move. Not built: the timeline's keyframe layer and InterpolationSettings (keyframe `easing` edits) are still on the bitecs world.+**Left stale on purpose** (deferred to a docs/examples pass): all eight `examples/*.tsx` still open with `<rect scene="...">` and no `<stage>`, so `tsc -p examples --noEmit` fails on them; `reference/jsx/{scene,roots}.md` still describes the pre-`<stage>` model where a mount grafts roots into an existing document; and `reference/jsx/{audio-sync,video,audio,elements}.md` still document `key` as the `syncTo` target. Deliberately not half-migrated: `reference/jsx` is stale as a whole, and patching the `key` rows alone would hide that.## Remaining work (suggested order)diff --git a/packages/runtime/src/systems/motion.ts b/packages/runtime/src/systems/motion.tsindex 47b773b7..cf982adf 100644--- a/packages/runtime/src/systems/motion.ts+++ b/packages/runtime/src/systems/motion.ts@@ -17,44 +17,52 @@ import { AnimationType, AnimationPhase } from '../constants';import { revealChars, revealWords, scrambleChars } from '../utils/text-motion';import { getSourceWindow } from '../utils/time';-import type { Entity, World } from 'koota';+import type { Entity, Trait, TraitRecord, World } from 'koota';/*** Reset an entity's Computed values back to its authored trait values.- * Motion (animations + keyframes) then layers on top each frame.+ * Motion (animations + keyframes) then layers on top each frame. A trait+ * the entity does not carry counts as its default: koota leaves store slots+ * as they were when a trait is removed, so the slot alone cannot say.+ * `ignore` treats one more trait as absent, for onRemove handlers (koota+ * fires them before the trait is cleared).*/-export function resetAnimatedValues(world: World, entity: Entity | null) {+export function resetAnimatedValues(world: World, entity: Entity | null, ignore?: Trait) {if (entity === null) return;const computed = store(world, Computed);const eid = entity.id();+ const read = <T extends Trait, K extends keyof TraitRecord<T>>(trait: T, field: K, fallback: TraitRecord<T>[K]): TraitRecord<T>[K] => {+ if (trait === ignore || !entity.has(trait)) return fallback;+ return (store(world, trait) as Record<K, TraitRecord<T>[K][]>)[field][eid] ?? fallback;+ };- computed.positionX[eid] = store(world, Position).x[eid] ?? 0;- computed.positionY[eid] = store(world, Position).y[eid] ?? 0;- computed.offsetX[eid] = store(world, Offset).x[eid] ?? 0;- computed.offsetY[eid] = store(world, Offset).y[eid] ?? 0;- computed.rotation[eid] = store(world, Rotation).value[eid] ?? 0;- computed.skewX[eid] = store(world, Skew).x[eid] ?? 0;- computed.skewY[eid] = store(world, Skew).y[eid] ?? 0;- computed.opacity[eid] = store(world, Opacity).value[eid] ?? 1;- computed.color[eid] = store(world, Color).value[eid] ?? 0;- computed.blur[eid] = store(world, Blur).value[eid] ?? 0;- computed.volume[eid] = store(world, Volume).value[eid] ?? 0;- computed.strokeWidth[eid] = store(world, StrokeStyle).width[eid] ?? 1;- computed.cornerRadius[eid] = store(world, CornerRadius).value[eid] ?? 0;- computed.cornerRadiusTopLeft[eid] = store(world, MixedCornerRadius).topLeft[eid] ?? 0;- computed.cornerRadiusTopRight[eid] = store(world, MixedCornerRadius).topRight[eid] ?? 0;- computed.cornerRadiusBottomRight[eid] = store(world, MixedCornerRadius).bottomRight[eid] ?? 0;- computed.cornerRadiusBottomLeft[eid] = store(world, MixedCornerRadius).bottomLeft[eid] ?? 0;- computed.stopOffset[eid] = store(world, ColorStop).offset[eid] ?? 0;- computed.chars[eid] = store(world, Chars).value[eid] ?? '';-- if (entity.has(UniformScale)) {- computed.scaleX[eid] = store(world, UniformScale).value[eid] ?? 1;- computed.scaleY[eid] = store(world, UniformScale).value[eid] ?? 1;+ computed.positionX[eid] = read(Position, 'x', 0);+ computed.positionY[eid] = read(Position, 'y', 0);+ computed.offsetX[eid] = read(Offset, 'x', 0);+ computed.offsetY[eid] = read(Offset, 'y', 0);+ computed.rotation[eid] = read(Rotation, 'value', 0);+ computed.skewX[eid] = read(Skew, 'x', 0);+ computed.skewY[eid] = read(Skew, 'y', 0);+ computed.opacity[eid] = read(Opacity, 'value', 1);+ computed.color[eid] = read(Color, 'value', 0);+ computed.blur[eid] = read(Blur, 'value', 0);+ computed.volume[eid] = read(Volume, 'value', 0);+ computed.strokeWidth[eid] = read(StrokeStyle, 'width', 1);+ computed.cornerRadius[eid] = read(CornerRadius, 'value', 0);+ computed.cornerRadiusTopLeft[eid] = read(MixedCornerRadius, 'topLeft', 0);+ computed.cornerRadiusTopRight[eid] = read(MixedCornerRadius, 'topRight', 0);+ computed.cornerRadiusBottomRight[eid] = read(MixedCornerRadius, 'bottomRight', 0);+ computed.cornerRadiusBottomLeft[eid] = read(MixedCornerRadius, 'bottomLeft', 0);+ computed.stopOffset[eid] = read(ColorStop, 'offset', 0);+ computed.chars[eid] = read(Chars, 'value', '');++ if (entity.has(UniformScale) && ignore !== UniformScale) {+ computed.scaleX[eid] = read(UniformScale, 'value', 1);+ computed.scaleY[eid] = read(UniformScale, 'value', 1);} else {- computed.scaleX[eid] = store(world, Scale).x[eid] ?? 1;- computed.scaleY[eid] = store(world, Scale).y[eid] ?? 1;+ computed.scaleX[eid] = read(Scale, 'x', 1);+ computed.scaleY[eid] = read(Scale, 'y', 1);}}diff --git a/packages/runtime/src/world/observers.ts b/packages/runtime/src/world/observers.tsindex 78e5e63d..048c58e7 100644--- a/packages/runtime/src/world/observers.ts+++ b/packages/runtime/src/world/observers.ts@@ -36,6 +36,7 @@ import {bubbleTimeRangeUp,} from '../actions/timing';import { propagateSize, resolveConstraintOffsets } from '../actions/resize';+import { resetAnimatedValues } from '../systems/motion';import type { Entity, Trait, World } from 'koota';@@ -170,11 +171,14 @@ export function observeWorld(world: World): () => void {// 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).+ // arrive in Computed. Removal re-derives from what is left (the trait+ // being removed counts as gone), so an unset prop falls back to its+ // default on the canvas rather than holding the last value.- const mirror = (trait: Trait, apply: (entity: Entity) => void) => {+ const mirror = (trait: Trait, apply: (entity: Entity) => void, onRemove = true) => {subs.push(world.onAdd(trait, apply));subs.push(world.onChange(trait, apply));+ if (onRemove) subs.push(world.onRemove(trait, (entity) => resetAnimatedValues(world, entity, trait)));};mirror(Position, (entity) => {@@ -262,7 +266,7 @@ export function observeWorld(world: World): () => void {// is a plain set now, so the propagation rides on the event instead.mirror(Size, (entity) => {propagateSize(world, entity);- });+ }, false);return () => {for (const unsubscribe of subs) unsubscribe();diff --git a/reference/jsx/elements.md b/reference/jsx/elements.mdindex ae8a294c..6419dcf6 100644--- a/reference/jsx/elements.md+++ b/reference/jsx/elements.md@@ -44,6 +44,7 @@ All visual elements accept:| `rotation` | `number` | `0` | Rotation in degrees. || `opacity` | `number` | `1` | `0`-`1`. || `cornerRadius` | `number` | `0` | Uniform corner radius, px. |+| `cornerRadiusTopLeft`, `cornerRadiusTopRight`, `cornerRadiusBottomRight`, `cornerRadiusBottomLeft` | `number` | `cornerRadius` | Per-corner radius, px; a corner without one takes `cornerRadius`, so `cornerRadius={20} cornerRadiusTopLeft={0}` rounds three corners. || `start`, `end`, `sourceIn`, `sourceOut` | `Time` | see [timing.md](./timing.md) | Temporal placement. || `transition` | `TransitionSpec \| null` | none | Transition into the next clip; direct children of `<sequence>` only (see [transitions.md](./transitions.md)). |diff --git a/reference/jsx/keyframes.md b/reference/jsx/keyframes.mdindex 963519fb..45cf9a94 100644--- a/reference/jsx/keyframes.md+++ b/reference/jsx/keyframes.md@@ -20,7 +20,7 @@ A `<keyframeTrack>` animates one prop of the element holding it over the node's| `<keyframeTrack>` | `property` (**required**) | The prop of the holding element it drives, by name. One track per prop. || `<keyframe>` | `time` (**required**), `value` (**required**), `easing` | One keyframe: node-local time in any [time format](./timing.md#time-formats), the value at that time (a number, or any CSS color on a `color` track), and the easing into the next keyframe. |-Animatable props (`property`): `x`, `y`, `offsetX`, `offsetY`, `width`, `height`, `rotation`, `opacity`, `cornerRadius`, `volume`, `color`, `offset`, `blur`, `value`. Whose prop is the track's holder's: a track under a [paint or color stop](./paints.md) animates the paint (`color`, `opacity`, `offset`), under a `<stroke>` the stroke (`width` is the line width), under a `<shadow>` the shadow (`blur`, `offsetX`, `offsetY`), under an `<effect>` its `value`. For preset in/out effects (fade, slides, text reveals, ...) use [`<animation>`](./animations.md) instead.+Animatable props (`property`): `x`, `y`, `offsetX`, `offsetY`, `width`, `height`, `rotation`, `scale`, `scaleX`, `scaleY`, `opacity`, `cornerRadius`, `cornerRadiusTopLeft`, `cornerRadiusTopRight`, `cornerRadiusBottomRight`, `cornerRadiusBottomLeft`, `volume`, `color`, `offset`, `blur`, `value`. Whose prop is the track's holder's: a track under a [paint or color stop](./paints.md) animates the paint (`color`, `opacity`, `offset`), under a `<stroke>` the stroke (`width` is the line width), under a `<shadow>` the shadow (`blur`, `offsetX`, `offsetY`), under an `<effect>` its `value`. For preset in/out effects (fade, slides, text reveals, ...) use [`<animation>`](./animations.md) instead.## Semantics