Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): the geometry and plumbing behind automation lanes (#3023)
Vance Ingalls3cfacf440d4d
diff --git a/.fallowrc.jsonc b/.fallowrc.jsoncindex a6bc9d1b8d..40523d40b5 100644--- a/.fallowrc.jsonc+++ b/.fallowrc.jsonc@@ -160,6 +160,22 @@"file": "packages/core/src/audio/audioFxGraph.ts","exports": ["ensureAudioFxWorklets"],},+ // automationLaneGeometry is the bottom of the audio-automation stack: its+ // consumer is the lane component one PR upstack, so a per-PR audit diffing+ // against the merge base sees these as unused. Consumed for real once the+ // stack merges; safe to drop this entry then.+ {+ "file": "packages/studio/src/player/components/automationLaneGeometry.ts",+ "exports": [+ "POINT_MERGE_SEC",+ "GRAB_PX",+ "DRAW_SAMPLES",+ "PAD_X",+ "formatValue",+ "laneFor",+ "withLane",+ ],+ },// drawElementService is the bottom of the fast-capture Graphite stack// (#1917): its consumers (frameCapture in #1919) land two PRs upstack, so// a per-PR audit diffing against the merge base sees these exports as@@ -684,6 +700,12 @@// complexity pre-dates the computed-timeline work. Exempted at file level// rather than refactored as scope creep."ignore": [+ // audio-fx-runtime-entry.ts: the browser-side IIFE entry for the offline FX+ // render. It runs only inside the headless page the engine drives, so unit+ // coverage cannot reach it and its CRAP score is coverage-driven rather+ // than complexity-driven (5 cyclomatic). Its behaviour is covered by the+ // engine's real-browser render tests.+ "packages/core/stubs/audio-fx-runtime-entry.ts",// useGestureRecording.ts: readBasePosition/connectGsapRuntime/tick are// inherited gesture-runtime control flow. This stack only changes// recordSample to coalesce display-rate events onto authored frames;diff --git a/packages/studio/src/player/components/TimelinePropertyLanes.tsx b/packages/studio/src/player/components/TimelinePropertyLanes.tsxindex 31dd97962d..7366d32135 100644--- a/packages/studio/src/player/components/TimelinePropertyLanes.tsx+++ b/packages/studio/src/player/components/TimelinePropertyLanes.tsx@@ -1,4 +1,4 @@-import { useMemo, type MouseEvent as ReactMouseEvent, type RefObject } from "react";+import { useMemo, type MouseEvent as ReactMouseEvent, type ReactNode, type RefObject } from "react";import {classifyPropertyGroup,type GsapAnimation,@@ -35,6 +35,12 @@ export interface TimelinePropertyLanesProps {onContextMenuKeyframe?: (e: ReactMouseEvent, target: TimelineKeyframeTarget) => void;onMoveKeyframe?: (target: TimelineKeyframeTarget, toClipPercentage: number) => Promise<boolean>;suppressClickRef?: RefObject<boolean>;+ /**+ * Rendered after the keyframe lanes, inside this wrapper. An audio clip's+ * automation lane lives here so it shares the same disclosure — and so the+ * header caret's `aria-controls` covers it too.+ */+ footer?: ReactNode;}/**@@ -196,6 +202,7 @@ export function TimelinePropertyLanes({onContextMenuKeyframe,onMoveKeyframe,suppressClickRef,+ footer,}: TimelinePropertyLanesProps) {// Memoized: TimelineDiamondLane is React.memo'd, and rebuilding the lanes (and// a fresh keyframesData literal per lane) on every render would re-render every@@ -263,6 +270,7 @@ export function TimelinePropertyLanes({/></div>))}+ {footer}</div>);}diff --git a/packages/studio/src/player/components/automationLaneData.test.ts b/packages/studio/src/player/components/automationLaneData.test.tsnew file mode 100644index 0000000000..948c926167--- /dev/null+++ b/packages/studio/src/player/components/automationLaneData.test.ts@@ -0,0 +1,66 @@+// @vitest-environment happy-dom+import { describe, expect, it } from "vitest";+import { elementAutomation, elementFxChain } from "./automationLaneData";+import type { TimelineElement } from "../store/timelineElement";++const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({+ id: "bgm",+ key: "bgm",+ tag: "audio",+ start: 0,+ duration: 10,+ track: 10,+ ...over,+});++const CHAIN = JSON.stringify({+ version: 1,+ nodes: [{ type: "lowpass", id: "n1", params: { frequency: 400, q: 0.9, poles: "2" } }],+});+const LANE = JSON.stringify({+ version: 1,+ lanes: [{ target: "fx.n1.frequency", points: [{ t: 0, v: 400 }] }],+});++describe("automationLaneData", () => {+ it("returns the same object for the same attributes", () => {+ // The lane compares its drag draft against this identity; a fresh object per+ // playhead tick would drop the drag.+ const a = elementAutomation(el({ automation: LANE, fxChain: CHAIN }));+ const b = elementAutomation(el({ automation: LANE, fxChain: CHAIN }));+ expect(a).toBe(b);+ expect(elementFxChain(el({ fxChain: CHAIN }))).toBe(elementFxChain(el({ fxChain: CHAIN })));+ });++ it("re-parses when the chain changes even though the automation text did not", () => {+ const withChain = elementAutomation(el({ automation: LANE, fxChain: CHAIN }));+ const withoutChain = elementAutomation(el({ automation: LANE }));+ expect(withChain.lanes.map((l) => l.target)).toEqual(["fx.n1.frequency"]);+ // No chain to resolve against, so the fx lane is dropped rather than drawn.+ expect(withoutChain.lanes).toEqual([]);+ });++ it("keeps a hot entry alive when other elements push the cache past its limit", () => {+ // Eviction used to clear the whole map, which changed every lane's identity+ // at once and released any drag in progress.+ const hot = el({ automation: LANE, fxChain: CHAIN });+ const first = elementAutomation(hot);+ for (let i = 0; i < 40; i += 1) {+ elementAutomation(+ el({+ automation: JSON.stringify({+ version: 1,+ lanes: [{ target: "volume", points: [{ t: i, v: 0.5 }] }],+ }),+ }),+ );+ elementAutomation(hot);+ }+ expect(elementAutomation(hot)).toBe(first);+ });++ it("reads an unreadable attribute as nothing rather than throwing", () => {+ expect(elementAutomation(el({ automation: "{nope" })).lanes).toEqual([]);+ expect(elementFxChain(el({ fxChain: "{nope" }))).toBeNull();+ });+});diff --git a/packages/studio/src/player/components/automationLaneData.ts b/packages/studio/src/player/components/automationLaneData.tsnew file mode 100644index 0000000000..375f891dcd--- /dev/null+++ b/packages/studio/src/player/components/automationLaneData.ts@@ -0,0 +1,93 @@+/**+ * Reading an element's automation, shared by the lane UI and the row layout.+ *+ * The attributes are carried on TimelineElement verbatim rather than parsed at+ * the manifest boundary: the lane reads and writes them, and round-tripping+ * through the attribute is what keeps the lane, the property panel and the+ * running audio graph on one source of truth.+ *+ * Both parse the same two attributes: the layout needs the lane count to+ * reserve height, the lanes need the lanes themselves. Parsing is cached by the+ * attribute text so the identity only changes when the text does — the lane's+ * drag draft compares against that identity, and a fresh object on every+ * playhead tick would throw away the drag in progress.+ */++import {+ parseAutomation,+ resolveAutomation,+ type HfAutomation,+ type HfAutomationLane,+} from "@hyperframes/core/audio-automation";+import { parseAudioFxChain, type HfAudioFxChain } from "@hyperframes/core/audio-fx";+import type { TimelineElement } from "../store/playerStore";++const EMPTY: HfAutomation = { version: 1, lanes: [] };++const chainCache = new Map<string, HfAudioFxChain | null>();+const automationCache = new Map<string, HfAutomation>();+const CACHE_LIMIT = 64;++/**+ * Parse once per distinct attribute text, keeping the same object until the text+ * changes — the lane compares its drag draft against that identity.+ *+ * Eviction drops the oldest entry rather than clearing the map: clearing would+ * change the identity of every lane's automation at once, and any lane mid-drag+ * would release its draft and jump back to the stored value.+ */+function cached<T>(store: Map<string, T>, key: string, build: () => T): T {+ const hit = store.get(key);+ if (hit !== undefined) {+ // Re-insert so the entry counts as recently used.+ store.delete(key);+ store.set(key, hit);+ return hit;+ }+ const value = build();+ if (store.size >= CACHE_LIMIT) {+ const oldest = store.keys().next();+ if (!oldest.done) store.delete(oldest.value);+ }+ store.set(key, value);+ return value;+}++/** The element's FX chain, or null when it has none or it is unreadable. */+export function elementFxChain(element: TimelineElement): HfAudioFxChain | null {+ const raw = element.fxChain;+ if (!raw) return null;+ return cached(chainCache, raw, () => {+ try {+ return parseAudioFxChain(raw);+ } catch {+ return null;+ }+ });+}++/**+ * The element's automation, bound to its chain the same way preview and the+ * render bind it: a lane whose effect has been deleted is dropped rather than+ * drawn on the wrong axis.+ */+export function elementAutomation(element: TimelineElement): HfAutomation {+ const raw = element.automation;+ if (!raw) return EMPTY;+ const chain = elementFxChain(element);+ // Both texts key the entry: the resolved lanes depend on the chain too. Joined+ // through a separator no attribute can contain.+ return cached(automationCache, `${raw}\u0000${element.fxChain ?? ""}`, () => {+ try {+ return resolveAutomation(parseAutomation(raw), chain ?? undefined);+ } catch {+ // Unreadable automation draws no lanes rather than breaking the row.+ return EMPTY;+ }+ });+}++/** Lanes in the order they are drawn, one row each. */+export function elementAutomationLanes(element: TimelineElement): HfAutomationLane[] {+ return elementAutomation(element).lanes;+}diff --git a/packages/studio/src/player/components/automationLaneGeometry.test.ts b/packages/studio/src/player/components/automationLaneGeometry.test.tsnew file mode 100644index 0000000000..8bf266bb27--- /dev/null+++ b/packages/studio/src/player/components/automationLaneGeometry.test.ts@@ -0,0 +1,68 @@+// @vitest-environment happy-dom+import { describe, expect, it } from "vitest";+import { automationTargets, fromUnit, toUnit } from "./automationLaneGeometry";+import { resolveAutomationRange, VOLUME_RANGE } from "@hyperframes/core/audio-automation";+import type { HfAudioFxChain } from "@hyperframes/core/audio-fx";++const chain: HfAudioFxChain = {+ version: 1,+ nodes: [+ { type: "lowpass", id: "n1", enabled: true, params: {} },+ // No id: the panel has not touched it, so nothing can address it.+ { type: "peaking", enabled: true, params: {} },+ // Worklet-backed: no AudioParams to schedule.+ { type: "compressor", id: "n3", enabled: true, params: {} },+ ],+};++describe("automationTargets", () => {+ it("offers volume plus every addressable automatable knob", () => {+ const targets = automationTargets(chain).map((t) => t.target);+ expect(targets[0]).toBe("volume");+ expect(targets).toContain("fx.n1.frequency");+ expect(targets).toContain("fx.n1.q");+ });++ it("skips a node with no id — a lane could not address it stably", () => {+ expect(automationTargets(chain).some((t) => t.target.includes("peaking"))).toBe(false);+ });++ it("skips a worklet effect, which exposes no AudioParams", () => {+ expect(automationTargets(chain).some((t) => t.target.startsWith("fx.n3."))).toBe(false);+ });++ it("offers just the fader for a track with no chain", () => {+ expect(automationTargets(null).map((t) => t.target)).toEqual(["volume"]);+ });++ it("labels an fx target with its effect and knob", () => {+ const found = automationTargets(chain).find((t) => t.target === "fx.n1.frequency");+ expect(found?.label).toMatch(/Cutoff/);+ expect(found?.range.scale).toBe("log");+ });+});++describe("value ↔ lane position", () => {+ it("maps a linear range straight onto the lane", () => {+ expect(toUnit(VOLUME_RANGE, 0)).toBe(0);+ expect(toUnit(VOLUME_RANGE, 1)).toBe(1);+ expect(toUnit(VOLUME_RANGE, 0.25)).toBeCloseTo(0.25, 10);+ });++ it("maps a log-read knob on its own scale, so its middle is geometric", () => {+ const range = resolveAutomationRange("fx.n1.frequency", chain)!;+ const mid = fromUnit(range, 0.5);+ expect(mid).toBeCloseTo(Math.sqrt(range.min * range.max), 4);+ // Round trip: a value put in comes back out.+ expect(fromUnit(range, toUnit(range, 900))).toBeCloseTo(900, 6);+ });++ it("clamps a pointer that has left the lane", () => {+ expect(fromUnit(VOLUME_RANGE, -3)).toBe(0);+ expect(fromUnit(VOLUME_RANGE, 4)).toBe(1);+ });++ it("reads a zero-width range as the bottom rather than dividing by zero", () => {+ expect(toUnit({ ...VOLUME_RANGE, min: 1, max: 1 }, 1)).toBe(0);+ });+});diff --git a/packages/studio/src/player/components/automationLaneGeometry.ts b/packages/studio/src/player/components/automationLaneGeometry.tsnew file mode 100644index 0000000000..dae7151cd3--- /dev/null+++ b/packages/studio/src/player/components/automationLaneGeometry.ts@@ -0,0 +1,118 @@+/**+ * The maths behind an automation lane: which parameters it can offer, how a+ * value maps to a position in the lane, and how a lane is edited.+ *+ * Pure — no React, no DOM. Split from the lane component so the geometry can be+ * tested on its own, and so the component is left with the parts that genuinely+ * need a pointer and a render.+ */++import {+ fxAutomationTarget,+ resolveAutomationRange,+ VOLUME_RANGE,+ VOLUME_TARGET,+ type AutomationRange,+ type HfAutomation,+ type HfAutomationLane,+} from "@hyperframes/core/audio-automation";+import { getAudioFxDef, type HfAudioFxChain } from "@hyperframes/core/audio-fx";++/** Points nearer than this in clip seconds are the same point, not two. */+export const POINT_MERGE_SEC = 0.02;+/** Hit radius for grabbing a point, in px. */+export const GRAB_PX = 7;+/** Samples used to draw a segment the eye should see as curved. */+export const DRAW_SAMPLES = 64;+/**+ * Slack on each side of the envelope, so a point sitting exactly at the clip's+ * start or end is drawn whole instead of half outside the lane. Wide enough for+ * the grab circle plus its stroke.+ */+export const PAD_X = GRAB_PX + 2;++export interface AutomationTargetOption {+ target: string;+ label: string;+ range: AutomationRange;+}++/**+ * Everything this clip could automate: its fader, then each automatable knob of+ * each effect in its chain. Effects with no chain node id are skipped — a lane+ * has nothing stable to address them by (the panel mints ids as it adds nodes).+ */+export function automationTargets(chain: HfAudioFxChain | null): AutomationTargetOption[] {+ const out: AutomationTargetOption[] = [+ { target: VOLUME_TARGET, label: "Volume", range: VOLUME_RANGE },+ ];+ for (const node of chain?.nodes ?? []) {+ out.push(...nodeTargets(node, chain));+ }+ return out;+}++/** One effect's automatable knobs. Empty for a node no lane could address. */+function nodeTargets(+ node: HfAudioFxChain["nodes"][number],+ chain: HfAudioFxChain | null,+): AutomationTargetOption[] {+ const nodeId = node.id;+ const def = nodeId ? getAudioFxDef(node.type) : undefined;+ if (!nodeId || !def) return [];+ const out: AutomationTargetOption[] = [];+ for (const param of def.params) {+ if (param.kind !== "number" || !param.automatable) continue;+ const target = fxAutomationTarget(nodeId, param.key);+ const range = resolveAutomationRange(target, chain ?? undefined);+ if (range) out.push({ target, label: range.label, range });+ }+ return out;+}++/** Value → 0..1 up the lane, honouring a log-read knob's own scale. */+export function toUnit(range: AutomationRange, value: number): number {+ const { min, max } = range;+ if (max <= min) return 0;+ if (range.scale === "log" && min > 0 && value > 0) {+ return (Math.log(value) - Math.log(min)) / (Math.log(max) - Math.log(min));+ }+ return (value - min) / (max - min);+}++export function fromUnit(range: AutomationRange, unit: number): number {+ const t = Math.min(1, Math.max(0, unit));+ const { min, max } = range;+ if (range.scale === "log" && min > 0) {+ return Math.exp(Math.log(min) + t * (Math.log(max) - Math.log(min)));+ }+ return min + t * (max - min);+}++export function formatValue(range: AutomationRange, value: number): string {+ const decimals = range.step >= 1 ? 0 : range.step >= 0.1 ? 1 : 2;+ const shown =+ range.unit === "" && range.max === 1 ? `${Math.round(value * 100)}%` : value.toFixed(decimals);+ return range.unit ? `${shown} ${range.unit}` : shown;+}++export function laneFor(automation: HfAutomation, target: string): HfAutomationLane {+ return automation.lanes.find((l) => l.target === target) ?? { target, points: [] };+}++/**+ * Replace one lane in place, dropping it when it has no points left.+ *+ * Order is preserved deliberately. A lane with no explicitly chosen parameter+ * shows whichever comes first, so moving the edited one to the end would switch+ * the lane out from under the pointer on the first edit.+ */+export function withLane(automation: HfAutomation, lane: HfAutomationLane): HfAutomation {+ const empty = lane.points.length === 0;+ const exists = automation.lanes.some((l) => l.target === lane.target);+ const lanes = automation.lanes+ .map((l) => (l.target === lane.target ? lane : l))+ .filter((l) => l.points.length > 0);+ if (!exists && !empty) lanes.push(lane);+ return { version: 1, lanes };+}diff --git a/packages/studio/src/player/components/automationLaneHeight.ts b/packages/studio/src/player/components/automationLaneHeight.tsnew file mode 100644index 0000000000..3ad43c4282--- /dev/null+++ b/packages/studio/src/player/components/automationLaneHeight.ts@@ -0,0 +1,11 @@+/**+ * Height of one audio automation lane.+ *+ * Its own module because both the row layout and the lane itself need it, and+ * putting it in either would have the layout importing a component or the+ * component's constant living somewhere it is not used.+ *+ * Taller than a keyframe lane because it carries a value axis rather than a row+ * of diamonds: a fader envelope drawn 28px high cannot be aimed.+ */+export const AUTOMATION_LANE_H = 48;diff --git a/packages/studio/src/player/components/timelineLayout.ts b/packages/studio/src/player/components/timelineLayout.tsindex 853f812566..682f0f50f1 100644--- a/packages/studio/src/player/components/timelineLayout.ts+++ b/packages/studio/src/player/components/timelineLayout.ts@@ -1,3 +1,4 @@+import { AUTOMATION_LANE_H } from "./automationLaneHeight";import type { ZoomMode } from "../store/playerStore";import type { TimelineTimeRange } from "../lib/timelineClipIndex";@@ -86,6 +87,8 @@ export const TRACKS_LEFT_PAD = 48;export interface TimelineTrackHeightClip {clipId: string;laneCount: number;+ /** Audio automation lanes shown when expanded, reserved at their own height. */+ automationLaneCount?: number;}type TimelineTrackHeightInput = readonly (readonly TimelineTrackHeightClip[])[];@@ -101,12 +104,15 @@ export function trackHeights(): number[] {return tracks.map((clips) => {let laneCount = 0;- if (expandedClipIds) {- for (const clip of clips) {- if (expandedClipIds.has(clip.clipId)) laneCount = Math.max(laneCount, clip.laneCount);- }+ let automationLanes = 0;+ for (const clip of clips) {+ if (!expandedClipIds?.has(clip.clipId)) continue;+ laneCount = Math.max(laneCount, clip.laneCount);+ automationLanes = Math.max(automationLanes, clip.automationLaneCount ?? 0);}- return TRACK_H + Math.max(0, Math.trunc(laneCount)) * LANE_H;+ return (+ TRACK_H + Math.max(0, Math.trunc(laneCount)) * LANE_H + automationLanes * AUTOMATION_LANE_H+ );});}diff --git a/packages/studio/src/player/components/useAutomationLanes.test.tsx b/packages/studio/src/player/components/useAutomationLanes.test.tsxnew file mode 100644index 0000000000..2003035ea2--- /dev/null+++ b/packages/studio/src/player/components/useAutomationLanes.test.tsx@@ -0,0 +1,109 @@+// @vitest-environment happy-dom+import { act } from "react";+import { describe, expect, it } from "vitest";+import { createRoot } from "react-dom/client";+import { useAutomationLanes, type AutomationLaneBinding } from "./useAutomationLanes";+import type { TimelineElement } from "../store/playerStore";++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++/** Bind one element through the hook and hand back what the lane would get. */+function bindOnce(element: TimelineElement): AutomationLaneBinding {+ let captured: AutomationLaneBinding | null = null;+ function Probe() {+ captured = useAutomationLanes().bind(element, true);+ return null;+ }+ const host = document.createElement("div");+ document.body.append(host);+ act(() => {+ createRoot(host).render(<Probe />);+ });+ if (!captured) throw new Error("bind never ran");+ return captured;+}++const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({+ id: "music",+ key: "music",+ tag: "audio",+ start: 0,+ duration: 12,+ track: 10,+ ...over,+});++const CHAIN = JSON.stringify({+ version: 1,+ nodes: [{ type: "lowpass", id: "n2", params: { frequency: 400, q: 0.9, poles: "2" } }],+});++describe("useAutomationLanes", () => {+ it("drops a lane whose effect is no longer in the chain", () => {+ // n1 was deleted from the chain but its lane survived in the attribute.+ // Drawn as-is it landed on the volume axis, with points off the lane and+ // a selector that had no option for it.+ const automation = JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "fx.n1.speed",+ points: [+ { t: 0, v: 0.4 },+ { t: 12, v: 6 },+ ],+ },+ { target: "volume", points: [{ t: 0, v: 0.55 }] },+ ],+ });+ const bound = bindOnce(el({ automation, fxChain: CHAIN }));+ expect(bound.automation.lanes.map((l) => l.target)).toEqual(["volume"]);+ });++ it("keeps a lane whose effect is still there", () => {+ const automation = JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "fx.n2.frequency",+ points: [+ { t: 0, v: 400 },+ { t: 4, v: 8000 },+ ],+ },+ ],+ });+ const bound = bindOnce(el({ automation, fxChain: CHAIN }));+ expect(bound.lanes.map((l) => l.target)).toEqual(["fx.n2.frequency"]);+ });++ it("gives one lane per automated parameter, in draw order", () => {+ const automation = JSON.stringify({+ version: 1,+ lanes: [+ { target: "volume", points: [{ t: 0, v: 0.5 }] },+ { target: "fx.n2.frequency", points: [{ t: 0, v: 400 }] },+ { target: "fx.n2.q", points: [{ t: 0, v: 1 }] },+ ],+ });+ const bound = bindOnce(el({ automation, fxChain: CHAIN }));+ expect(bound.lanes.map((l) => l.target)).toEqual(["volume", "fx.n2.frequency", "fx.n2.q"]);+ });++ it("reads an element with neither attribute as an empty volume lane", () => {+ const bound = bindOnce(el());+ expect(bound.lanes).toEqual([]);+ expect(bound.chain).toBeNull();+ });++ it("is read-only without an edit session, whatever the selection", () => {+ // No DomEditProvider in this tree — the bare player case.+ expect(bindOnce(el({ automation: undefined })).readOnly).toBe(true);+ });++ it("survives an unreadable attribute instead of breaking the row", () => {+ const bound = bindOnce(el({ automation: "{not json", fxChain: "{also not}" }));+ expect(bound.automation.lanes).toEqual([]);+ expect(bound.chain).toBeNull();+ });+});diff --git a/packages/studio/src/player/components/useAutomationLanes.ts b/packages/studio/src/player/components/useAutomationLanes.tsnew file mode 100644index 0000000000..0e23ce8336--- /dev/null+++ b/packages/studio/src/player/components/useAutomationLanes.ts@@ -0,0 +1,85 @@+/**+ * Writes for the timeline's audio automation lanes.+ *+ * Kept out of TimelineLanes so that component does not grow another concern.+ * Reading lives in `automationLaneData`, shared with the row layout, which needs+ * the lane count to reserve height.+ *+ * Edits go to the *selected* element, because that is what the attribute commit+ * path targets. An unselected clip still draws its envelopes — they are just+ * read only, which is also what stops a stray drag from editing the wrong track.+ */++import { useCallback, useMemo } from "react";+import {+ HF_AUDIO_AUTOMATION_ATTR,+ serializeAutomation,+ type HfAutomation,+ type HfAutomationLane,+} from "@hyperframes/core/audio-automation";+import type { HfAudioFxChain } from "@hyperframes/core/audio-fx";+import { useDomEditActionsContextOptional } from "../../contexts/DomEditContext";+import type { TimelineElement } from "../store/playerStore";+import { elementAutomation, elementFxChain } from "./automationLaneData";++export interface AutomationLaneBinding {+ automation: HfAutomation;+ /** One entry per lane, in draw order — each gets its own row. */+ lanes: HfAutomationLane[];+ chain: HfAudioFxChain | null;+ /** Continuous write while dragging; does not persist. */+ onPreview(next: HfAutomation): void;+ /** Gesture-end write; this is the one that persists and lands in undo. */+ onCommit(next: HfAutomation): void;+ /**+ * Select this clip, which is what makes its lanes editable. A lane calls this+ * instead of writing when it is read-only — pressing the lane is the only+ * route in, since lanes sit below the clip bar where the timeline's own+ * selection handler never sees them.+ */+ onSelect(): void;+ readOnly: boolean;+}++export interface UseAutomationLanesResult {+ bind(element: TimelineElement, isSelected: boolean): AutomationLaneBinding;+}++export function useAutomationLanes(): UseAutomationLanesResult {+ // Optional: the player also runs outside Studio, where there is no edit+ // session. There the lanes render read-only, which is the right fallback.+ const domEdit = useDomEditActionsContextOptional();++ const bind = useCallback(+ (element: TimelineElement, isSelected: boolean): AutomationLaneBinding => {+ const chain = elementFxChain(element);+ const automation = elementAutomation(element);++ const write = (next: HfAutomation, persist: boolean): void => {+ if (!domEdit || !isSelected) return;+ const value = next.lanes.length > 0 ? serializeAutomation(next) : "";+ if (persist) void domEdit.handleDomAttributeCommit(HF_AUDIO_AUTOMATION_ATTR, value);+ // Dragging a point writes live: no preview refresh, so the composition+ // does not reload and restart playback on every pixel.+ else void domEdit.handleDomAttributeLiveCommit(HF_AUDIO_AUTOMATION_ATTR, value || null);+ };++ return {+ automation,+ lanes: automation.lanes,+ chain,+ onPreview: (next) => write(next, false),+ onCommit: (next) => write(next, true),+ // Deliberately not awaited before an edit: the commit handlers close+ // over the selection as it was when they were built, so writing in the+ // same tick would land on whichever element was selected before.+ // Selecting is its own gesture; the lane goes live after it.+ onSelect: () => void domEdit?.handleTimelineElementSelect(element),+ readOnly: !domEdit || !isSelected,+ };+ },+ [domEdit],+ );++ return useMemo(() => ({ bind }), [bind]);+}diff --git a/packages/studio/src/player/components/useTimelineTrackLayout.ts b/packages/studio/src/player/components/useTimelineTrackLayout.tsindex 0455293994..bfa1170ea9 100644--- a/packages/studio/src/player/components/useTimelineTrackLayout.ts+++ b/packages/studio/src/player/components/useTimelineTrackLayout.ts@@ -1,6 +1,8 @@import { useMemo, useRef } from "react";import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import { animationLaneGroups } from "./TimelinePropertyLanes";+import { isAudioTimelineElement } from "../../utils/timelineInspector";+import { elementAutomationLanes } from "./automationLaneData";import { usePlayerStore, type TimelineElement } from "../store/playerStore";import type { DraggedClipState } from "./timelineClipDragTypes";import { useTimelineTrackDerivations } from "./useTimelineTrackDerivations";@@ -85,7 +87,15 @@ function useTimelineRowHeights();if (!active) return [];const clipId = active.key ?? active.id;- return [{ clipId, laneCount: laneCounts.get(clipId) ?? 0 }];+ return [+ {+ clipId,+ laneCount: laneCounts.get(clipId) ?? 0,+ automationLaneCount: isAudioTimelineElement(active)+ ? elementAutomationLanes(active).length+ : 0,+ },+ ];});const rowHeights = trackHeights(heightTracks, expandedClipIds);return {diff --git a/packages/studio/src/player/hooks/useExpandedTimelineElements.ts b/packages/studio/src/player/hooks/useExpandedTimelineElements.tsindex 8cceebcf0a..64b903db33 100644--- a/packages/studio/src/player/hooks/useExpandedTimelineElements.ts+++ b/packages/studio/src/player/hooks/useExpandedTimelineElements.ts@@ -152,6 +152,13 @@ function hostElementState(flat: TimelineElement | undefined): Partial<TimelineElhidden: flat.hidden,timelineLocked: flat.timelineLocked,timelineRole: flat.timelineRole,+ // Same reason as the three above: these are read off the host element, which+ // an expanded child is built without. Missing them, an audio child inside a+ // sub-composition reserved no automation height and drew no lanes, while the+ // property panel — reading the live DOM selection rather than this row —+ // still showed the chain and its toggles.+ fxChain: flat.fxChain,+ automation: flat.automation,};}diff --git a/packages/studio/src/player/lib/timelineDOM.test.ts b/packages/studio/src/player/lib/timelineDOM.test.tsindex 08ad532baa..78a0bc7ec6 100644--- a/packages/studio/src/player/lib/timelineDOM.test.ts+++ b/packages/studio/src/player/lib/timelineDOM.test.ts@@ -296,3 +296,36 @@ describe("mergeTimelineElementsPreservingDowngrades — genuine removal vs trans).toEqual(["a", "c"]);});});++describe("audio FX attributes on parsed elements", () => {+ const CHAIN = '{"version":1,"nodes":[{"type":"lowpass","id":"n1","params":{}}]}';+ const LANE = '{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1}]}]}';++ it("carries data-fx-chain and data-automation off the element", () => {+ // The timeline row is what reserves automation height and draws the lanes;+ // parsed straight from the DOM it used to arrive without either attribute,+ // so the panel showed a chain the timeline could not.+ const doc = new DOMParser().parseFromString(+ `<div data-composition-id="main" data-start="0" data-duration="10">+ <audio id="bgm" data-start="0" data-duration="10" data-fx-chain='${CHAIN}'+ data-automation='${LANE}'></audio>+ </div>`,+ "text/html",+ );+ const [bgm] = parseTimelineFromDOM(doc, 10).filter((e) => e.domId === "bgm");+ expect(bgm?.fxChain).toBe(CHAIN);+ expect(bgm?.automation).toBe(LANE);+ });++ it("leaves them unset on a track that carries neither", () => {+ const doc = new DOMParser().parseFromString(+ `<div data-composition-id="main" data-start="0" data-duration="10">+ <audio id="bgm" data-start="0" data-duration="10"></audio>+ </div>`,+ "text/html",+ );+ const [bgm] = parseTimelineFromDOM(doc, 10).filter((e) => e.domId === "bgm");+ expect(bgm?.fxChain).toBeUndefined();+ expect(bgm?.automation).toBeUndefined();+ });+});diff --git a/packages/studio/src/player/lib/timelineDOM.ts b/packages/studio/src/player/lib/timelineDOM.tsindex a8730caa4b..e109822ce9 100644--- a/packages/studio/src/player/lib/timelineDOM.ts+++ b/packages/studio/src/player/lib/timelineDOM.ts@@ -138,6 +138,10 @@ export function createTimelineElementFromManifestClip(params: {if (hostEl.hasAttribute("data-hidden")) entry.hidden = true;const timelineRole = hostEl.getAttribute("data-timeline-role");if (timelineRole) entry.timelineRole = timelineRole;+ const fxChain = hostEl.getAttribute("data-fx-chain");+ if (fxChain) entry.fxChain = fxChain;+ const automation = hostEl.getAttribute("data-automation");+ if (automation) entry.automation = automation;entry.zIndex = readTimelineElementZIndex(hostEl);}if (clip.assetUrl) entry.src = clip.assetUrl;@@ -334,6 +338,14 @@ export function parseTimelineFromDOM(doc: Document, rootDuration: number): Timelif (resolvedSrc) entry.src = resolvedSrc;}+ // Read from the element, like the manifest path does: without these an audio+ // clip parsed straight from the DOM reserved no automation height and drew no+ // lanes, while the property panel still showed its chain.+ const domFxChain = el.getAttribute("data-fx-chain");+ if (domFxChain) entry.fxChain = domFxChain;+ const domAutomation = el.getAttribute("data-automation");+ if (domAutomation) entry.automation = domAutomation;+if (el.hasAttribute("data-timeline-locked")) {entry.timelineLocked = true;}diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.tsindex f373b3b8a4..020f24aec5 100644--- a/packages/studio/src/player/store/playerStore.ts+++ b/packages/studio/src/player/store/playerStore.ts@@ -16,70 +16,9 @@ import { createThumbnailSlice, type ThumbnailSlice } from "./thumbnailSlice";export type { KeyframeCacheEntry } from "./keyframeSlice";export { liveTime } from "./liveTime";-export interface TimelineElement {- id: string;- label?: string;- key?: string;- kind?: ClipManifestClip["kind"];- tag: string;- start: number;- duration: number;- track: number;- /**- * The data-track-index as written in the source file. Set at the manifest- * translation boundary (createTimelineElementFromManifestClip) from the- * runtime clip's verbatim track, and preserved through display-lane remaps- * (normalizeToZones packs sparse authored tracks onto contiguous display- * lanes; expanded sub-comp children get synthetic display rows). Lane edits- * must persist THIS space — writing a display-lane number into a sparse file- * re-targets the wrong track. For an expanded child the value is in its OWN- * source file's coordinate space, not the host timeline's.- */- authoredTrack?: number;- /** Resolved z-index for stacking-aware timeline ordering. */- zIndex?: number;- /** True when the effective z-index was authored inline or through CSS, not auto. */- hasExplicitZIndex?: boolean;- /** Canonical CSS stacking context this element's z-index participates in. */- stackingContextId?: string | null;- /** Nearest parent composition context, matching RuntimeTimelineClip. */- parentCompositionId?: string | null;- /** Composition ancestry from root to nearest parent, matching RuntimeTimelineClip. */- compositionAncestors?: string[];- domId?: string;- /** Stable `data-hf-id` attribute value — used as primary patch target when present */- hfId?: string;- /** Best-effort selector used when patching source HTML back from timeline edits */- selector?: string;- /** Zero-based occurrence index for non-unique selectors */- selectorIndex?: number;- /** Source composition file that owns this element, when known */- sourceFile?: string;- src?: string;- playbackStart?: number;- playbackStartAttr?: "media-start" | "playback-start";- playbackRate?: number;- sourceDuration?: number;- volume?: number;- /** Path from data-composition-src — identifies sub-composition elements */- compositionSrc?: string;- /** Whether this row came from authored clip timing or Studio's full-duration layer fallback. */- timingSource?: "authored" | "implicit";- /** Set by data-timeline-locked on the host element — disables move and trim in Studio. */- timelineLocked?: boolean;- /** Set by data-hidden on the host element — hides the clip in preview and render. */- hidden?: boolean;- /** Value of data-timeline-role attribute — used to identify music vs. voiceover. */- timelineRole?: string;- /**- * Set by useExpandedTimelineElements on an inline-expanded sub-composition- * child: the absolute master-timeline start of the sub-comp host the child- * lives in. Presence marks the element as expanded; edits subtract it to get- * the child's local (sourceFile-relative) time. Works at any nesting depth.- */- expandedParentStart?: number;- expandedHostKey?: string;-}+import type { TimelineElement } from "./timelineElement";++export type { TimelineElement };export type ZoomMode = "fit" | "manual";type TimelineTool = "select" | "razor";diff --git a/packages/studio/src/player/store/timelineElement.ts b/packages/studio/src/player/store/timelineElement.tsnew file mode 100644index 0000000000..104e969890--- /dev/null+++ b/packages/studio/src/player/store/timelineElement.ts@@ -0,0 +1,78 @@+/**+ * One row in the timeline: a clip as Studio needs it, translated from the+ * runtime's manifest at createTimelineElementFromManifestClip.+ *+ * Split out of playerStore, which had reached the 600-line studio ceiling and+ * could not carry another field. Re-exported from there, so every existing+ * importer is unaffected.+ */++import type { ClipManifestClip } from "../lib/playbackTypes";++export interface TimelineElement {+ id: string;+ label?: string;+ key?: string;+ kind?: ClipManifestClip["kind"];+ tag: string;+ start: number;+ duration: number;+ track: number;+ /**+ * The data-track-index as written in the source file. Set at the manifest+ * translation boundary (createTimelineElementFromManifestClip) from the+ * runtime clip's verbatim track, and preserved through display-lane remaps+ * (normalizeToZones packs sparse authored tracks onto contiguous display+ * lanes; expanded sub-comp children get synthetic display rows). Lane edits+ * must persist THIS space — writing a display-lane number into a sparse file+ * re-targets the wrong track. For an expanded child the value is in its OWN+ * source file's coordinate space, not the host timeline's.+ */+ authoredTrack?: number;+ /** Resolved z-index for stacking-aware timeline ordering. */+ zIndex?: number;+ /** True when the effective z-index was authored inline or through CSS, not auto. */+ hasExplicitZIndex?: boolean;+ /** Canonical CSS stacking context this element's z-index participates in. */+ stackingContextId?: string | null;+ /** Nearest parent composition context, matching RuntimeTimelineClip. */+ parentCompositionId?: string | null;+ /** Composition ancestry from root to nearest parent, matching RuntimeTimelineClip. */+ compositionAncestors?: string[];+ domId?: string;+ /** Stable `data-hf-id` attribute value — used as primary patch target when present */+ hfId?: string;+ /** Best-effort selector used when patching source HTML back from timeline edits */+ selector?: string;+ /** Zero-based occurrence index for non-unique selectors */+ selectorIndex?: number;+ /** Source composition file that owns this element, when known */+ sourceFile?: string;+ src?: string;+ playbackStart?: number;+ playbackStartAttr?: "media-start" | "playback-start";+ playbackRate?: number;+ sourceDuration?: number;+ volume?: number;+ /** Verbatim `data-fx-chain` / `data-automation`; see automationLaneData. */+ fxChain?: string;+ automation?: string;+ /** Path from data-composition-src — identifies sub-composition elements */+ compositionSrc?: string;+ /** Whether this row came from authored clip timing or Studio's full-duration layer fallback. */+ timingSource?: "authored" | "implicit";+ /** Set by data-timeline-locked on the host element — disables move and trim in Studio. */+ timelineLocked?: boolean;+ /** Set by data-hidden on the host element — hides the clip in preview and render. */+ hidden?: boolean;+ /** Value of data-timeline-role attribute — used to identify music vs. voiceover. */+ timelineRole?: string;+ /**+ * Set by useExpandedTimelineElements on an inline-expanded sub-composition+ * child: the absolute master-timeline start of the sub-comp host the child+ * lives in. Presence marks the element as expanded; edits subtract it to get+ * the child's local (sourceFile-relative) time. Works at any nesting depth.+ */+ expandedParentStart?: number;+ expandedHostKey?: string;+}