Skip to content

Commit fd4d411

Browse files
vanceingallsclaude
andauthored
refactor(audio): the review's cleanup list, and the design record behind the rack (#3176)
* fix(core): remove the build-audio-fx-runtime.ts stray resurrected by a main merge An earlier merge with main brought this deleted file back (git's merge/delete handling on an unchanged-on-one-side file); package.json already points at build-inline-artifact.ts, so it sat unreachable and duplicating that file's config, both of which fallow flagged. * fix(studio): pull TimelineLanes under the 600-line cap TimelineLanes.tsx hit 620 lines. Extracted the three per-clip pointer gestures (resize-start, pointer-down move-arm, click/razor-split) into createClipGestureHandlers — one factory call per rendered clip instead of ~120 lines of inline handler bodies in the render loop. 529 lines now. * fix(studio): split the extracted pointerdown handler under the CRAP threshold Moving the ~120-line gesture logic into timelineClipGestureHandlers.ts concentrated it into two functions fallow flagged (onPointerDown at CRAP 63.6, onResizeStart at 31.6). Split the decision logic (which gesture a pointerdown implies) into a pure resolvePointerDownAction, then split its own intent-blocking check into isIntentBlocked. onResizeStart's guard moved into canStartResize. Every function now scores under 30. * fix(studio): drop the unused DomEditSelection import in PropertyPanelFlat CI caught it on PR #3026 (wa-12-panel-params); a later refactor in the stack removed the last use of the type here without removing the import. * fix(studio): close the typecheck and fallow gaps wa-18b-reschedule opened useAutomationLanes.ts's write() assumed gesture-scoped coalescing and a preview-only commit that useDomEditAttributeCommits.ts never grew — backported that option support from its own later commit so the two sides of the API agree. The paste path and its tests were missing the box selection's v0/v1 bounds a sibling commit added to AutomationSelection. The FX panel's carve controls still edited the six mechanism numbers (maxCutDb, bands, intelligibilityBias) after carveProfile() collapsed authoring to one Strength knob, so those fields no longer existed on HfCarveSettings; UI now edits strength, and analyseCarveBands is called with carveProfile(strength). Also closes fallow's complexity, dead-code and duplication findings on this PR's diff: extracted automationLaneDragMath.ts (pure group/point-move math) and useAutomationRangeDrag.ts (the marquee-select gesture) out of useAutomationLaneGestures.ts, pulled a couple of render-loop ternaries and a resolver into named functions, dropped an export nothing outside its file used, and shared a step-simplifier between audioCarve's two envelope builders. The edge-stretch vs. box-select priority test in TimelineAutomationLane.test was still pinning the pre-box-select rule (edge wins over a point sitting on it) that a sibling commit deliberately reversed — a point inside the box is now selected content, so grabbing it drags the group instead. Updated the test to the shipped rule instead of the old one. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(core): cap the via conic's weight so an edge-clamped via point can't NaN A via point pulled out past the segment (viaX: 5, viaY: -3) clamps to (0.999, 0.001) — exactly on the steady region's edge, where edge - viaX is 0. viaConic divided by that zero to get an infinite weight, and shapeVia turned Infinity into NaN a few steps later (Infinity - Infinity in the quadratic coefficient). NaN reaching setValueCurveAtTime silences the automated parameter for the rest of the render. Capped the weight at 1e6 instead of leaving it unbounded — past that point the arc already reads as touching the via point, so nothing visible is lost. Also hardened shapeVia's existing denominator guard (`<= 0`) to `!(> 0)`, since NaN fails the original comparison and fell through it. Review by Miga (PR #3208). * fix(studio-server): fingerprint the proactive waveform cache key too The route already keys the waveform cache on the asset's size and mtime as well as its path, so a rebuilt-in-place file gets fresh peaks instead of stale ones. generateWaveformCache — the proactive path that runs on upload — still called buildWaveformCacheKey with the path alone, so it wrote to a different key than the route reads from (making the pre-generated cache never found) and kept the exact collision bug this fingerprint exists to fix on its own path. Review by Miga (PR #3211). * style(docs): run oxfmt on the /hyperframes-audio skill docs Table column widths had drifted out of alignment with oxfmt's own rules, failing format:check and blocking the Preflight gate every downstream branch inherits. Whitespace only, no content change. * fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration \b treats `_` as a word character, so \bbed\b never matched bed_01, music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap — an underscore-separated bed classified as "unknown" and could end up offered as its own carve source. Replaced the short hints with a boundary that actually excludes letters and digits on both sides. clipsOverlap computed end = start + duration without guarding sign, so a negative duration put end before start — an interval that does not describe anything, and one specific case showed it silently dropping a real overlap (a shorter, earlier broken end rejected a clip that genuinely contained the point). Duration clamps to zero instead: a clip cannot un-play time, and a zero-length clip at its start is the sane reading of "duration nobody wrote down as positive." Review by Miga (PR #3212). * fix(studio): widen PropertyPanel's resetModules render timeout again The 20s margin (already once widened for the same reason) is timing out in CI's full-monorepo Test run — the resetModules()+fresh-import render this test needs is uncached and competes with every other package's test suite for the same worker pool, and the same test passes in well under 2s standalone. Went to 45s rather than re-tuning to whatever number happens to clear the current CI load, since that number moves every time CI gains a package. * fix(studio): stop the single-candidate auto-apply carve firing twice Two auto-apply effects both fire when sourceOptions.length === 1: the multi-candidate effect only guards length === 0, so a single candidate passes it too, and the single-candidate effect passes its own guard right after — both compute the same sources list and both call setCarve, so the common case (one narrator, one bed) triggered two decodes, two FFT runs, and two concurrent attribute writes for one decision. The multi-candidate effect now defers to its sibling for exactly one candidate, which already has its own detailed handling for that case. Review by Miga (PR #3213). * feat(core): carve against every voice over a bed, always (#3212) * feat(core): carve against every voice over a bed, always dynamically A bed usually runs under a whole sequence — a narrator, an interview answer, a second presenter — and carving against one of them left the others fighting it. `source` becomes `sources`, and `mixCarveSources` sums every voice onto the BED's clock before anything is measured. That is what keeps one analysis sufficient: the chain is fixed, so there is no per-voice filter to switch between, and bands drawn from all the speech there is with envelopes that rise wherever any of it happens answer the actual question — where and when is speech masking this bed. Summed rather than averaged: two people talking at once mask more than either alone. Audio before the bed starts is dropped rather than folded in at zero, since it plays over nothing and shifting it would put a cut where there is no voice. `dynamic` is gone. A fixed depth thins the bed through every pause, and once both have been heard there is no reason to want it, so every carve follows the speech. Two helpers the panel and the headless script now share instead of each carrying a copy — two definitions of "what does this name suggest" drift, and then the two disagree about which track is the voice: - `classifyAudioName` reads a track's kind from its id and filename together. `unknown` is deliberately common: treating an unrecognised name as "not a voice" would hide the one track somebody needs to pick. - `clipsOverlap` keeps out a voice that never plays while the bed does. An unwritten duration counts as unbounded, not zero — refusing a clip whose length the composition leaves to the media would drop the commonest case there is. Files written before this still load: a single `source` reads as a one-voice list, a stored `dynamic` is ignored, and an absent attribute means the defaults whole. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration \b treats `_` as a word character, so \bbed\b never matched bed_01, music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap — an underscore-separated bed classified as "unknown" and could end up offered as its own carve source. Replaced the short hints with a boundary that actually excludes letters and digits on both sides. clipsOverlap computed end = start + duration without guarding sign, so a negative duration put end before start — an interval that does not describe anything, and one specific case showed it silently dropping a real overlap (a shorter, earlier broken end rejected a clip that genuinely contained the point). Duration clamps to zero instead: a clip cannot un-play time, and a zero-length clip at its start is the sane reading of "duration nobody wrote down as positive." Review by Miga (PR #3212). --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(studio): port the carve UI off the removed source/dynamic fields #3212 (accidentally squash-merged into this branch instead of main) changed HfCarveSettings from a single `source` + `dynamic` toggle to a `sources` list with dynamic mode removed outright — the multi-voice UI consumer that goes with that shape lands in the very next PR, so this branch was left with a type that no longer matched its own code. Minimal port, not the multi-voice redesign that PR does properly: the "Listen to" picker and analyse() treat sources[0] as the one voice this UI still understands, and every dynamic-mode branch (the automated envelope lanes, the toggle, the checkbox) is gone along with the field — a carve is now always the static value the analysis computes, matching what the type change made permanent. Test suite trimmed the same way: the automation-lane and toggle tests covered behavior that no longer exists. * docs(plans): fix pre-existing oxfmt formatting drift in audio-fx-presets Blocks the regression workflow's required preflight gate. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent f6cf3b2 commit fd4d411

13 files changed

Lines changed: 648 additions & 32 deletions

packages/core/src/audio/audioFxGraph.test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,39 @@ describe("buildFxChain", () => {
216216
expect(c.created.find((x) => x.kind === "biquad")!.frequency.value).toBe(2000);
217217
});
218218

219+
it("lines new values up against the built nodes, skipping a bypassed one", () => {
220+
// A bypassed node is not in the graph, so the update has to walk the
221+
// ENABLED nodes to stay aligned with what was built. Walking `next.nodes`
222+
// instead shifts everything after the bypass by one and pushes each node's
223+
// parameters into its neighbour — and the shape is unchanged either way,
224+
// so nothing forces a rebuild that would hide it.
225+
const c = ctx();
226+
const withBypass = (frequency: number): HfAudioFxChain => ({
227+
version: 1,
228+
nodes: [
229+
{
230+
type: "highpass",
231+
enabled: true,
232+
params: { ...defaultAudioFxParams("highpass"), frequency: 100 },
233+
},
234+
{ type: "peaking", enabled: false, params: defaultAudioFxParams("peaking") },
235+
{
236+
type: "lowpass",
237+
enabled: true,
238+
params: { ...defaultAudioFxParams("lowpass"), frequency },
239+
},
240+
],
241+
});
242+
const h = buildFxChain(asCtx(c), withBypass(8000));
243+
const biquads = c.created.filter((n) => n.kind === "biquad");
244+
expect(biquads).toHaveLength(2);
245+
246+
expect(h.update(withBypass(3000))).toBe(true);
247+
// The lowpass took the new cutoff; the highpass was left where it was.
248+
expect(biquads[0]!.frequency.value).toBe(100);
249+
expect(biquads[1]!.frequency.value).toBe(3000);
250+
});
251+
219252
it("reports that a rebuild is needed when the chain shape changes", () => {
220253
const c = ctx();
221254
const h = buildFxChain(asCtx(c), chain("peaking"));

packages/core/src/audio/audioFxGraph.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
*/
1010

1111
import {
12+
enabledAudioFxNodes,
1213
getAudioFxDef,
1314
normalizeAudioFxParams,
1415
type HfAudioFxChain,
@@ -484,8 +485,7 @@ export interface FxChainHandle {
484485
* into the running nodes; when it changes, the caller rebuilds.
485486
*/
486487
function shapeOf(chain: HfAudioFxChain): string {
487-
return chain.nodes
488-
.filter((node) => node.enabled !== false)
488+
return enabledAudioFxNodes(chain)
489489
.map((node) => {
490490
const p = normalizeAudioFxParams(node.type, node.params);
491491
const poles = p.poles !== undefined ? `:${p.poles}` : "";
@@ -510,25 +510,23 @@ export function buildFxChain(ctx: BaseAudioContext, chain: HfAudioFxChain): FxCh
510510
const handles: { id?: string; type: string; handle: FxNodeHandle }[] = [];
511511

512512
let tail: AudioNode = input;
513-
for (const node of chain.nodes) {
514-
if (node.enabled === false) continue;
513+
for (const node of enabledAudioFxNodes(chain)) {
515514
const handle = buildFxNode(ctx, node.type, node.params ?? {});
516515
tail.connect(handle.input);
517516
tail = handle.output;
518517
handles.push({ ...(node.id ? { id: node.id } : {}), type: node.type, handle });
519518
}
520519
tail.connect(output);
521520

522-
let shape = shapeOf(chain);
521+
const shape = shapeOf(chain);
523522

524523
return {
525524
input,
526525
output,
527526
nodes: handles,
528527
update(next) {
529528
if (shapeOf(next) !== shape) return false;
530-
const active = next.nodes.filter((node) => node.enabled !== false);
531-
active.forEach((node, i) => {
529+
enabledAudioFxNodes(next).forEach((node, i) => {
532530
const held = handles[i];
533531
if (!held) return;
534532
held.handle.update(normalizeAudioFxParams(node.type, node.params));
@@ -541,7 +539,9 @@ export function buildFxChain(ctx: BaseAudioContext, chain: HfAudioFxChain): FxCh
541539
if (node.id === undefined) delete held.id;
542540
else held.id = node.id;
543541
});
544-
shape = shapeOf(next);
542+
// `shape` is not reassigned: the early return above already established
543+
// that `shapeOf(next)` equals it, so recomputing was a whole normalise +
544+
// join per observer tick to write back the string that was already there.
545545
return true;
546546
},
547547
dispose() {

packages/core/src/audioAutomation.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import {
33
applyCurve,
44
shapeProgress,
55
fxAutomationTarget,
6+
HF_AUDIO_AUTOMATION_ATTR,
7+
HF_AUDIO_AUTOMATION_DATA_KEY,
68
isConstantLane,
79
parseAutomation,
810
parseAutomationTarget,
@@ -30,6 +32,14 @@ const lane = (points: HfAutomationLane["points"], target = "volume"): HfAutomati
3032
points,
3133
});
3234

35+
describe("the automation attribute's two spellings", () => {
36+
it("names the same attribute either way", () => {
37+
// Same split as the FX chain: written as an attribute, read as a dataset
38+
// key. Derived, so a rename cannot half-land.
39+
expect(HF_AUDIO_AUTOMATION_ATTR).toBe(`data-${HF_AUDIO_AUTOMATION_DATA_KEY}`);
40+
});
41+
});
42+
3343
describe("targets", () => {
3444
it("reads volume and fx targets, and rejects anything else", () => {
3545
expect(parseAutomationTarget("volume")).toEqual({ kind: "volume" });

packages/core/src/audioAutomation.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,13 @@
1111
* curve, three consumers, or the picture and the sound disagree.
1212
*/
1313

14-
import { getAudioFxDef, type HfAudioFxChain, type HfAudioFxNumberParam } from "./audioFx.js";
14+
import { getAudioFxDef, type HfAudioFxChain } from "./audioFx.js";
1515

1616
export const HF_AUDIO_AUTOMATION_ATTR = "data-automation";
1717

18+
/** The same attribute as a `dataset` / `dataAttributes` key. See `HF_AUDIO_FX_DATA_KEY`. */
19+
export const HF_AUDIO_AUTOMATION_DATA_KEY = HF_AUDIO_AUTOMATION_ATTR.slice("data-".length);
20+
1821
/** Automation files are versioned; a reader must refuse a version it doesn't know. */
1922
export const HF_AUDIO_AUTOMATION_VERSION = 1;
2023

@@ -138,15 +141,14 @@ export function resolveAutomationRange(
138141
const def = getAudioFxDef(node.type);
139142
const param = def?.params.find((p) => p.key === parsed.param);
140143
if (!param || param.kind !== "number") return null;
141-
const p = param as HfAudioFxNumberParam;
142144
return {
143-
min: p.min,
144-
max: p.max,
145-
step: p.step,
146-
unit: p.unit,
147-
label: `${def?.label ?? node.type} · ${p.label}`,
148-
scale: p.scale === "log" && p.min > 0 ? "log" : "linear",
149-
default: p.default,
145+
min: param.min,
146+
max: param.max,
147+
step: param.step,
148+
unit: param.unit,
149+
label: `${def?.label ?? node.type} · ${param.label}`,
150+
scale: param.scale === "log" && param.min > 0 ? "log" : "linear",
151+
default: param.default,
150152
};
151153
}
152154

packages/core/src/audioFx.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ import {
55
enabledAudioFxNodes,
66
getAudioFxDef,
77
HF_AUDIO_FX,
8+
HF_AUDIO_FX_ATTR,
89
HF_AUDIO_FX_CHAIN_VERSION,
10+
HF_AUDIO_FX_DATA_KEY,
911
HF_AUDIO_FX_IDS,
1012
normalizeAudioFxParams,
1113
parseAudioFxChain,
@@ -47,6 +49,15 @@ describe("effect registry", () => {
4749
});
4850
});
4951

52+
describe("the chain attribute's two spellings", () => {
53+
it("names the same attribute either way", () => {
54+
// The studio WRITES through the attribute and READS through the dataset
55+
// key, so the read side used to carry its own `"fx-chain"` literal and a
56+
// rename would only half-land. Derived now; this is what keeps it derived.
57+
expect(HF_AUDIO_FX_ATTR).toBe(`data-${HF_AUDIO_FX_DATA_KEY}`);
58+
});
59+
});
60+
5061
describe("normalizeAudioFxParams", () => {
5162
it("fills missing keys with defaults", () => {
5263
expect(normalizeAudioFxParams("peaking", {})).toEqual(defaultAudioFxParams("peaking"));

packages/core/src/audioFx.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,16 @@
1616

1717
export const HF_AUDIO_FX_ATTR = "data-fx-chain";
1818

19+
/**
20+
* The same attribute as a `dataset` / `dataAttributes` key — the `data-` prefix
21+
* is not part of that spelling.
22+
*
23+
* Derived rather than restated: the studio writes through
24+
* `HF_AUDIO_FX_ATTR` and reads through the key, so a hardcoded `"fx-chain"`
25+
* on the read side is a rename waiting to half-land.
26+
*/
27+
export const HF_AUDIO_FX_DATA_KEY = HF_AUDIO_FX_ATTR.slice("data-".length);
28+
1929
/** Chain files are versioned; a reader must refuse a version it doesn't know. */
2030
export const HF_AUDIO_FX_CHAIN_VERSION = 1;
2131

packages/studio/src/components/editor/audioFxSummary.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
* grouping exists to prevent — that they are seven things to manage.
88
*/
99

10-
import { parseAudioFxChain } from "@hyperframes/core/audio-fx";
10+
import { HF_AUDIO_FX_DATA_KEY, parseAudioFxChain } from "@hyperframes/core/audio-fx";
1111
import type { DomEditSelection } from "./domEditingTypes";
1212

1313
export function audioFxSummary(element: DomEditSelection): string {
14-
const raw = element.dataAttributes?.["fx-chain"];
14+
const raw = element.dataAttributes?.[HF_AUDIO_FX_DATA_KEY];
1515
const carveAttr = element.dataAttributes?.["fx-carve"];
1616
let handBuilt = 0;
1717
let carveNodes = 0;

packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { useEffect, useState } from "react";
1111
import {
1212
defaultAudioFxParams,
1313
HF_AUDIO_FX_ATTR,
14+
HF_AUDIO_FX_DATA_KEY,
1415
mintAudioFxNodeId,
1516
parseAudioFxChain,
1617
serializeAudioFxChain,
@@ -41,6 +42,7 @@ import {
4142
automatedTargetsOf,
4243
automationAttrValue,
4344
HF_AUDIO_AUTOMATION_ATTR,
45+
HF_AUDIO_AUTOMATION_DATA_KEY,
4446
readPanelAutomation,
4547
resolveAutomationRange,
4648
withoutLane,
@@ -109,7 +111,7 @@ export function AudioFxGroup({
109111
onSetAttributeLive: (attr: string, value: string | null) => void | Promise<void>;
110112
}) {
111113
const chain = ((): HfAudioFxChain => {
112-
const raw = element.dataAttributes?.["fx-chain"];
114+
const raw = element.dataAttributes?.[HF_AUDIO_FX_DATA_KEY];
113115
if (!raw) return { version: 1, nodes: [] };
114116
try {
115117
return parseAudioFxChain(raw);
@@ -120,7 +122,10 @@ export function AudioFxGroup({
120122
}
121123
})();
122124

123-
const automation = readPanelAutomation(element.dataAttributes?.["automation"], chain);
125+
const automation = readPanelAutomation(
126+
element.dataAttributes?.[HF_AUDIO_AUTOMATION_DATA_KEY],
127+
chain,
128+
);
124129
const automatedTargets = automatedTargetsOf(automation);
125130

126131
/**
@@ -485,11 +490,24 @@ export function AudioFxGroup({
485490
const analyse = async (active: HfCarveSettings | null = carve): Promise<void> => {
486491
if (!active?.sources.length) return;
487492
const doc = element.element?.ownerDocument;
493+
if (!doc) return;
488494
// Every named voice that is actually there with something to decode. A source
489495
// naming a deleted track is skipped rather than failing the whole analysis.
490-
const voices = active.sources
491-
.map((id) => doc?.getElementById(id) as HTMLAudioElement | null)
492-
.filter((el): el is HTMLAudioElement => Boolean(el?.getAttribute("src")));
496+
//
497+
// Read out to plain values here rather than carrying elements around: it is
498+
// what lets the src and the start be non-null by construction downstream
499+
// instead of by assertion.
500+
const voices: { src: string; start: string | null }[] = [];
501+
for (const id of active.sources) {
502+
const el = doc.getElementById(id);
503+
// By tag name, not `instanceof HTMLAudioElement`: these elements belong to
504+
// the composition's iframe document, so the constructor they were made
505+
// from is not this realm's and the instanceof is false for every one.
506+
if (el?.tagName !== "AUDIO") continue;
507+
const src = el.getAttribute("src");
508+
if (!src) continue;
509+
voices.push({ src, start: el.getAttribute("data-start") });
510+
}
493511
if (voices.length === 0) return;
494512
setAnalysing(true);
495513
try {
@@ -502,7 +520,7 @@ export function AudioFxGroup({
502520
.webkitOfflineAudioContext;
503521
if (!Ctor) return;
504522
const decode = async (relative: string): Promise<AudioBuffer> => {
505-
const res = await fetch(new URL(relative, doc!.baseURI).href);
523+
const res = await fetch(new URL(relative, doc.baseURI).href);
506524
return new Ctor(1, 1, DECODE_SAMPLE_RATE).decodeAudioData(await res.arrayBuffer());
507525
};
508526
const bedStart = clipStart(element.dataAttributes?.["start"]);
@@ -512,9 +530,9 @@ export function AudioFxGroup({
512530
// is also what lets the bands and the envelopes stay a single set: the chain is
513531
// fixed, so there is no per-voice filter to switch between.
514532
const decoded = await Promise.all(
515-
voices.map(async (el) => ({
516-
samples: (await decode(el.getAttribute("src")!)).getChannelData(0),
517-
offsetSeconds: clipStart(el.getAttribute("data-start")) - bedStart,
533+
voices.map(async (voice) => ({
534+
samples: (await decode(voice.src)).getChannelData(0),
535+
offsetSeconds: clipStart(voice.start) - bedStart,
518536
})),
519537
);
520538
const voiceMix = mixCarveSources(decoded, DECODE_SAMPLE_RATE);

packages/studio/src/components/editor/propertyPanelAutomation.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import {
1010
HF_AUDIO_AUTOMATION_ATTR,
11+
HF_AUDIO_AUTOMATION_DATA_KEY,
1112
parseAutomation,
1213
resolveAutomation,
1314
resolveAutomationRange,
@@ -77,4 +78,4 @@ export function automationAttrValue(automation: HfAutomation): string {
7778
return automation.lanes.length > 0 ? serializeAutomation(automation) : "";
7879
}
7980

80-
export { HF_AUDIO_AUTOMATION_ATTR, resolveAutomationRange };
81+
export { HF_AUDIO_AUTOMATION_ATTR, HF_AUDIO_AUTOMATION_DATA_KEY, resolveAutomationRange };

packages/studio/src/components/editor/propertyPanelFxSection.test.tsx

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,55 @@ describe("FxSection chain", () => {
165165
expect(next.nodes.map((n) => n.type)).toEqual(["reverb", "peaking"]);
166166
});
167167

168+
it("keeps a half-typed value with its own effect across a reorder", () => {
169+
// Rows used to be keyed `${type}-${index}`, so two effects of the same type
170+
// kept their keys through a reorder and React reused each row where it
171+
// stood. The controls hold real state — a number field mid-edit is held as
172+
// text — so the buffer stayed at the position and landed on whichever
173+
// effect moved into it.
174+
const peaking = (id: string, frequency: number) => ({
175+
type: "peaking",
176+
id,
177+
enabled: true,
178+
params: { ...defaultAudioFxParams("peaking"), frequency },
179+
});
180+
const a = peaking("pa", 400);
181+
const b = peaking("pb", 1600);
182+
const chainOfNodes = (...nodes: unknown[]): HfAudioFxChain =>
183+
({ version: 1, nodes }) as HfAudioFxChain;
184+
185+
const host = document.createElement("div");
186+
document.body.append(host);
187+
const root = createRoot(host);
188+
const render = (chain: HfAudioFxChain) =>
189+
act(() => {
190+
root.render(
191+
<FxSection
192+
chain={chain}
193+
onChainChange={vi.fn()}
194+
onChainPreview={vi.fn()}
195+
carve={null}
196+
onCarveChange={vi.fn()}
197+
sourceOptions={[]}
198+
/>,
199+
);
200+
});
201+
202+
render(chainOfNodes(a, b));
203+
// Only the first card is open, which is the one being edited.
204+
const openFrequency = (): HTMLInputElement =>
205+
host.querySelector<HTMLInputElement>(".hf-fx-node .hf-fx-number")!;
206+
207+
expect(openFrequency().value).toBe("400");
208+
typeInto(openFrequency(), "123");
209+
expect(openFrequency().value).toBe("123");
210+
211+
// The author moves that effect down; the other one takes the open slot.
212+
render(chainOfNodes(b, a));
213+
214+
expect(openFrequency().value).toBe("1600");
215+
});
216+
168217
it("cannot move the ends past themselves", () => {
169218
const { host } = mount({ chain: chainOf("peaking", "reverb") });
170219
const ups = host.querySelectorAll('.hf-fx-move[title="Move up"]');

0 commit comments

Comments
 (0)