fix(core): make audio automation survive being rescheduled (#3208)

* refactor(studio): split the FX node row out of FxSection

Clears the health findings the FX stack left behind: the chain-node render
callback was a 70-line closure over half of FxSection's state, and the two
reorder arrows were the same button written twice.

Also drops two exports with no consumers, and registers the audio FX runtime
stub as an entry point — it is bundled by file path, so nothing imports it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(studio): lift the audio FX group out of PropertyPanelFlat

`PropertyPanelFlat.tsx` was 672 lines against the repo's 600-line cap, so
the required File size check was red — the sole reason #3014 and #3022 are
blocked. Both reviews say the same thing: "mechanical fix, not a design
problem. Code itself is LGTM."

Moves `AudioFxGroup` and `audioFxSummary` into
`propertyPanelAudioFxGroup.tsx`, which is where a later branch puts them
anyway — done here so the file is under the cap from the point it first
crosses it, rather than ten branches later.

533 lines now. The four audio imports it no longer needs go with it.

Not fixed here: three `FxSection carve` tests fail on this branch with
"Cannot read properties of undefined (reading 'toFixed')". Confirmed
pre-existing by stashing this change and re-running — that is the separate
`Test` failure the review also flags.

* feat(core): automation envelope model for audio tracks

Adds the data model behind Ableton-style automation lanes: breakpoint
envelopes over track volume or one knob of one effect in the track's FX
chain, stored on the element as `data-automation`.

Times are clip-local, so an envelope travels with the clip when it moves —
the clip-envelope model rather than arrangement automation.

`sampleAutomationLane` is the single interpolator. The lane drawing, the
preview scheduler and the render bake all call it, so the picture and the
sound cannot disagree about the curve. Log-scaled parameters interpolate in
log space, matching what their own knob already promises.

FX nodes gain a stable `id`, minted by count rather than randomly so the
document is the same on every machine. Lanes address nodes by id, so
reordering a chain never re-points a lane at a different effect, and a lane
whose effect was deleted is dropped rather than left to reattach.

Also warns when a track carries both a volume lane and a GSAP volume tween,
since only the lane is heard and the tween silently does nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): expose the AudioParams behind automatable FX knobs

Marks the knobs an automation lane can drive and has each graph builder hand
back the AudioParam behind them, so a scheduler can write to a running effect
without knowing what the effect is.

A knob is not always one AudioParam. A wet/dry mix is two gains moving in
opposition, and a knob in milliseconds drives a delay time in seconds, so
each target carries the mapping out of the knob's own declared unit.

What stays unautomatable is stated where it is decided: a WaveShaper curve, a
convolution impulse and a one-pole filter's coefficients are all rebuilt
wholesale rather than scheduled, and the four worklet effects take values by
postMessage rather than through AudioParams.

The registry flag is written by hand, so a test builds every effect and
checks the exposure both ways — nothing flagged is missing, nothing exposed
is unflagged. A flag that lied would offer a lane that silently did nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): play automation envelopes in preview

Schedules each lane onto the AudioParams behind its knob using native ramps
and value curves. Nothing evaluates the envelope per frame: it is handed to
the audio thread once, so it stays sample-accurate however busy the main
thread is, and the offline render will schedule it the same way.

Timing comes from the transport, so an envelope survives seeking into the
middle of a clip, a clip that has not started yet, and a playback rate that
compresses clip seconds into context seconds.

A straight line is only scheduled as a ramp when nothing bends it — no
curvature, a linear parameter scale, and no unit mapping. Log-scaled
parameters and mapped ones are sampled instead, since a delay knob in
milliseconds and a wet/dry pair moving in opposition are not linear in the
parameter they drive.

Lanes with nowhere to write are skipped rather than reported: a one-pole
filter exposes no frequency param, and the worklet effects expose none at
all. Editing an envelope mid-playback re-aims it at the live playhead rather
than restarting the track.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(engine): bake automation envelopes into the render

The offline render schedules FX lanes with the same scheduler preview uses,
inside the OfflineAudioContext that already runs the same graph builders. The
input WAV is the clip's own audio from its first sample, so clip-local time
is offline time and the envelope needs no offset.

Volume lanes take the existing PCM bake rather than a second mechanism: the
lane is converted to keyframes, so a straight fade stays two of them and only
a bent segment is sampled — the baker interpolates linearly and would
otherwise quietly straighten the curve. A volume lane supersedes keyframes
probed from the timeline, which `lint` already warns about.

A browser test sweeps a lowpass from below a 2 kHz tone to well above it and
measures both ends. Parsing the envelope is not the same as scheduling it,
and only running the real thing tells the two apart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): make the volume lane audible in preview

The envelope was scheduled onto the transport's gain AudioParam, but the
runtime rewrites that gain every tick from `data-volume` and the GSAP-seeked
value — so it was erased within a frame. Volume automation was correct in the
render and inaudible while previewing.

The lane now feeds the per-tick path where the probed volume keyframes already
sit, checked ahead of them so the two cannot fight, and the transport no
longer schedules volume at all: one mechanism instead of two racing.

The cost is honest — in preview the level steps per tick rather than per
sample, exactly as the existing keyframe path does. The render still bakes it
into the PCM sample-accurately, and FX parameters are still scheduled on their
own AudioParams, since nothing rewrites those.

Parsed lanes are cached by attribute text: the runtime asks once per tick per
track, and parsing there would run the JSON parser 60 times a second for a
value that only changes on an edit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): apply chain edits to the running graph

A structural edit — an effect added, removed, bypassed, or a filter's pole
count switched — was dropped. `buildFxChain`'s update reports false when the
change is not merely new values, and the attribute observer ignored that, so
the edit only took hold when the persisting write reloaded the composition.
That reload restarted every playing track, which is what was heard as the
audio chopping.

The graph is now swapped in place: the old effects are detached, the new ones
built and connected between the same source and gain, and any lanes
re-scheduled onto the new nodes. The source node is never touched, so playback
does not restart.

A track with no chain is watched too, rather than wired through and forgotten,
so adding its first effect is heard the same way. That means the function
always returns a disposer instead of null for the empty case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(studio): the geometry and plumbing behind automation lanes

Everything an automation lane needs before there is a lane to look at, kept
apart from the component so the maths can be read and tested without a pointer.

`automationLaneGeometry` is pure: which parameters a clip can automate (its
fader, then each automatable knob of each effect that carries a node id), how a
value maps to a position in the lane, and how a lane is edited. Two decisions
live here and are worth review:

- A log-read knob maps on its own log scale, so the middle of a 100 Hz–20 kHz
  lane is the geometric mean. Dragging and drawing then agree with what the
  knob's own scale already promises.
- `withLane` replaces a lane in place rather than appending. 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.

`automationLaneData` parses the two attributes, cached by their text so the
identity only changes when the text does — the lane holds an optimistic draft
while a point is dragged and compares against that identity, and a fresh object
on every playhead tick would throw the drag away. It binds automation to the
chain the way preview and the render bind it, so a lane whose effect was deleted
is dropped rather than drawn against the wrong axis.

`useAutomationLanes` routes edits through the DOM edit session, targeting the
selected element because that is what the attribute commit path writes to.

Row height reserves each lane at its own height rather than counting it as
another keyframe lane, and `TimelinePropertyLanes` gains a footer slot so the
lanes share the keyframe disclosure — and its `aria-controls`.

`TimelineElement` moves to its own module: playerStore had reached the 600-line
studio ceiling exactly and could not carry another field. It is re-exported from
there, so no importer changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix(studio): make automationLaneData reviewable, and evict one entry not all

The cache key held a literal NUL byte instead of its escape, so git classified
the whole module as binary: it landed as `Bin 0 -> 2677 bytes` with zero
diffable lines, invisible to review, to grep, and to any textual merge. The
escape is behaviour-identical.

With the file readable, two things in it needed fixing.

Eviction cleared the entire map. Clearing changes the identity of every lane's
automation at once, and a lane compares its drag draft against that identity —
so one unrelated element arriving at the limit would release an in-progress drag
and snap the point back. It now drops the oldest entry, and a hit is re-inserted
so it counts as recently used.

Nothing tested this module, which is what let the binary blob through. Now
covered: identity stability, re-parsing when the chain changes but the
automation text does not, a hot entry surviving 40 evictions, and an unreadable
attribute reading as nothing.

The geometry module's exports are ignored for dead-code while its consumer sits
one PR upstack, following the convention already used for the fast-capture
stack.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(studio): carry the audio FX attributes onto every timeline row

Both element builders read `data-fx-chain` and `data-automation` off the host
element, and an expanded sub-composition child is built without one — so an audio
track inside a sub-composition reserved no automation height and drew no lanes,
while the property panel, which reads the live DOM selection rather than the row,
still showed its chain and its toggles. `hostElementState` exists to re-inherit
exactly this class of host-only field; it now covers these two alongside
`hidden`, `timelineLocked` and `timelineRole`.

`parseTimelineFromDOM` had the same gap and now reads both directly.

Also exempts the offline FX render's browser entry from the health gate: it runs
only inside the headless page the engine drives, so its CRAP score is
coverage-driven rather than complexity-driven, and its behaviour is covered by the
engine's real-browser render tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(studio): the automation lane itself

Draws each automated parameter as its own lane under the audio clip, on the same
disclosure caret the keyframe lanes use — that caret is the DAW automation
triangle. One lane per parameter rather than a selector to swap between them, so
two envelopes can be read and edited without hiding either.

Double-click the line to add a point, drag to shape it, right-click a point to
remove it.

Three things here took more than one attempt, and the comments say why:

- **A dragged point did not move.** The live write deliberately skips the preview
  refresh — that is what keeps dragging from restarting playback — so the stored
  value does not move under the pointer. The lane keeps a local draft.
- **Releasing snapped it back.** The draft was dropped when the drag ended, which
  is before the persisted write comes around; it now lives until the automation
  it was drawn over actually changes.
- **A press was eaten.** Not stopping propagation let the timeline start its own
  gesture and swallow the second half of a double-click. The lane owns the press
  once it is live — and when it is not, it selects its clip instead, since lanes
  sit below the clip bar where the timeline's own selection handler never sees
  them.

The envelope is inset by the grab radius so a point at the clip's first or last
frame is drawn whole rather than half outside the lane, and clip time still lines
up with screen position because the inset and the offset cancel.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix(studio): let a track disclose its automation without a tween

The lane was mounted inside the property-lanes wrapper, which renders only for a
track's GSAP keyframe clip — so an audio clip with no tween resolved to nothing:
no disclosure caret, no reserved height, no lanes. Verified on a composition with
one `<audio>`, an envelope, and no tweens anywhere: 0 carets, 0 lanes. The
attribute still wrote and the render still baked it, so the feature failed
silently for exactly the tracks it exists for. Same composition now: 1 caret, and
expanding it draws the Volume lane.

Automation counts as something to disclose. `resolveTrackKeyframeClip` takes a
counter alongside the keyframe lane counts and qualifies a clip on either; the
header asks the same counter about the clip it already holds. A function rather
than another map threaded through the props: every caller then reads one cached
parse, so the height a row reserves and the lanes drawn in it cannot drift apart.

That drift is also fixed for the lane's own offset, which passed the raw tween
count where every other consumer uses distinct property groups. Two tweens on one
property drew one keyframe lane but pushed the automation lane down by two,
spilling into the next track; one tween on two properties did the inverse and
drew it over a diamond lane, stealing its pointer events. It now reads the same
`laneCounts` map the reserved height and the drawn lanes use.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(studio): automate a parameter without reloading the preview

The write path and the volume half of the panel surface.

**A commit that persists without reloading.** For attributes the runtime applies
to the live graph itself — an FX chain, its automation — a reload would only
interrupt playback to reach the state the preview already has. `skipRefresh` and
`refreshAfter` were already independent options; this exposes the combination
that skips the reload but still re-reads the selection.

Both halves are needed, and they were fighting each other. Without the reload,
audio no longer chops on an edit. Without the resync, the panel keeps reading the
selection snapshot it was built with, so a second edit computes from a pre-edit
value and appears to do nothing — deleting one effect made every later delete a
no-op. `handleDomAttributeLiveCommit` is untouched and still used for knob
dragging, where a per-move re-render is exactly what you do not want.

**Volume.** An automated track's slider is disabled, since a level set there
would be overwritten by the envelope on the next tick, and the toggle beside it
adds or deletes the lane. Adding seeds it with a single point at the level the
slider already shows, so automating a track never changes how loud it is.

**One shared reader** for both panel sections, which is what surfaced that
resolving against an absent chain would have deleted every FX lane the moment
someone automated a volume: the volume section does not parse the chain, so
"no chain" now means "do not resolve" rather than "drop what cannot be resolved".

The toggle itself lives with the FX controls it is shared with, and says
`Automated` / `Automate` through the studio's own Tooltip rather than a native
browser hover.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix(studio): stop the last two automation writes reloading the preview

The quiet commit added here was only used by the FX group. Two writers still went
through the refreshing one, so they reloaded the preview and restarted every
playing track — the exact chop the live write during a drag exists to avoid:

- releasing a dragged breakpoint, so the audio hitched at the end of every point
  you moved;
- clicking the volume toggle, while the same click on an effect parameter was
  already silent.

Both are quiet now: still persisted, still resyncing the selection so a following
edit computes from the value just written.

Also fixes the seeded volume. `Number(dataAttributes.volume ?? "1")` is 0 for an
attribute that is present but empty, so automating such a track started its lane
at silence while the engine read the same empty value as unity.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(studio): automate and un-automate each effect parameter

The per-parameter surface in the FX panel.

An automated parameter's control is disabled — a value typed there would be
overwritten by the envelope on the next tick, so the lane is the value now — and
the toggle beside it adds or deletes that parameter's lane. Adding seeds the lane
with a single point at the value the control already holds, so switching to an
envelope never changes the sound, only where the value comes from.

Parameters no envelope can drive have no toggle at all: the worklet-backed
dynamics expose no AudioParams, a WaveShaper's curve and a convolution impulse
are rebuilt wholesale rather than scheduled. Neither does a chain node with no
id, since a lane addresses nodes by id — so adding an effect now mints one.

Carve moves onto the same non-reloading write, and decodes its source in an
`OfflineAudioContext`: opening a second output device mid-playback makes the
running track glitch while the hardware is reconfigured. Turning carve off now
also drops the filters it generated, which otherwise kept dipping the bed with
nothing in the panel to explain it.

`AudioFxGroup` moves into its own module — PropertyPanelFlat was at its size
budget — which also gave the panel's write behaviour somewhere to be tested: what
it writes, seeded at the current value, preserving the lanes it is not touching,
and clearing the attribute when the last one goes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* feat(studio): only offer voiceover carve when there is a voice to carve against

Carve is a relationship between two tracks — it analyses another track's voice
and dips this bed where that voice sits. In a composition with a single audio
track there is nothing to listen to, so the block offered an empty source picker
and an Analyse button that could never do anything.

It is now shown only when the composition holds another audio track, and still
shown when carve is already configured: hiding a live setting because its voice
track was removed would leave the bed being dipped from out of sight.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(studio): cover carve visibility through the real element

The panel derives carve's source list from the selected element's document, so
a selection with no element has no sources — which the new visibility rule
correctly reads as 'nothing to carve against'. The suite mounted exactly that,
so it was asserting on a hidden block.

Selections now carry a real <audio> with a sibling track, and the two cases the
rule exists for are pinned directly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(studio): keep FX panel writes from clobbering each other

Three writes in the audio panel each read the source file, mutate one
attribute and write it back. Fired without ordering they read the same
content and the last one lands, dropping the others.

- Deleting an effect left its automation lanes in the attribute. Ids are
  minted lowest-free, so the next effect added took the same id and
  inherited the dead envelope: disabled and "Automated" without the
  author ever automating it, and baked into the render.
- Switching carve off wrote the chain (dropping the filters it generated)
  and the carve settings at once, so either the filters stayed with no
  carve to explain them or the settings survived with no filters.
- The three carve dials committed per input event, patching the source
  and resyncing the selection dozens of times per drag. They now preview
  live and persist on release, like the FX knobs already do.

Volume automation reads through the quiet commit too, so removing a lane
resyncs the panel instead of leaving the slider disabled.

* feat(engine): let an FX tail decay instead of cutting it at the clip

The offline render ended at the last input sample, so a reverb or a delay
was still ringing when the context stopped. Measured on a 1.5 s tone
through a default reverb, the render cut at 1.524 s while the tail was
still at -29.7 dB — an audible chop, and the one place the render did not
match preview.

The length does not have to be guessed. Every tail here follows from its
own settings: a convolution is exactly as long as its impulse, and
`synthesizeReverbImpulse` derives that from room size; a delay's repeats
fall by `feedback` every `time`, so the count down to -60 dB is a log.
Everything else settles with its input — an all-pass chain has group
delay, not a tail, and a 9-second compressor release has no signal to
release once the clip stops.

`chainTailSeconds` sums them (the chain is serial, so a delay in front of
a reverb hands each repeat to the room), reads a lane's maximum rather
than the static knob where one is automated, and caps at 5 s — 5 s
between repeats at 0.95 feedback is eleven minutes of decay, and the
panel can dial exactly that.

The mixer's per-track atrim now allows the clip plus its tail; the atrim
after apad still holds every track to the composition's length, so a tail
can run over what follows but never extends the video.

Same fixture after: a smooth decay to -72 dB, last non-zero sample at
3.306 s against the 3.4 s the settings predict.

* feat(studio): curve, snap and type a value in an automation lane

Four gestures from Ableton's envelope editor, which is the muscle memory
an automation lane inherits.

Alt-drag the line between two breakpoints to bend it, Alt-double-click to
straighten. `curve` was already honoured everywhere it is read — drawn in
the lane, sampled in preview, baked into the render through
setValueCurveAtTime — with no gesture anywhere that could set it, so every
envelope anyone could draw was linear in practice. The curve is solved,
not accumulated (x^e = f, so e = ln f / ln x), which keeps the segment
under the pointer instead of drifting away over a long drag; the test
asserts that by sampling with the renderer's own sampler.

Shift locks a drag to one axis and fines the vertical travel to a quarter.
Which axis won is decided in pixels — seconds and dB are not comparable
numbers, and comparing them would make the lock depend on the zoom.

A dragged point snaps to the beat grid and to its neighbouring points,
with Alt to ignore it. The radius is tight on purpose: a lane is often a
few seconds wide, where a generous radius makes a point unplaceable
between two beats.

Double-click a point to type its value. -6.0 dB is not a pixel you can
find, and there was no way to enter one.

The gesture layer moves to useAutomationLaneGestures and the path builder
to envelopePath: the component was at the studio's 600-line ceiling, and
both are worth testing without a render. trackShowsBeatStrip comes out of
TimelineLanes for the same reason.

* feat(studio): pure range ops for automation lane selections

Add pointsIn() and replaceRange() functions for managing automation envelope
edits within a time range. The key invariant: envelope values outside the
selection never move. Implemented by anchoring the boundaries at t0 and t1
by sampling the original lane, so cutting middle sections cannot reshape
the rest. Inner points from shape generators can suppress redundant anchors
at merge distance.

* fix(studio): budget replaceRange's inner points before capping, not after

* feat(studio): automation selection slice

* feat(studio): drag-select a time range on an automation lane

Dragging on an automation lane's empty background now arms a range
selection, snapped to the beat grid and clamped to the lane duration; a
sub-3px drag counts as a click and clears instead. Point drags and
Alt-drag segment bends still take priority, since the range arm only
runs where the existing point/segment hit-test already returned null.

useAutomationLanes binds the selection slice per element/lane so the
rect renders from the store, matching the read pattern the writes
already use.

* feat(studio): delete an automation selection from the keyboard

Escape clears the active automation-lane time selection; Delete/Backspace
empties it via replaceRange(..., inner: []), which pins anchor points at
both edges and leaves the envelope outside the selection untouched. Mounted
in TimelineLanes.tsx next to the useAutomationLanes() call that already
lives there. Also adds a stale-selection guard in TimelineAutomationLaneSlot
that clears the selection if its lane's target stops existing on the bound
element's automation (e.g. the automated effect was deleted).

* test(studio): cover the automation selection stale-target guard

* feat(studio): ramp, swell and dip generators for automation selections

* fix(studio): let an automation range keep Delete from the clip

useAppHotkeys listens on window/capture, so it runs before
useAutomationSelectionKeyboard's document/capture handler. With a range
selected, Delete fell straight through to the clip-delete branch and
destroyed the whole audio clip the lane belongs to; Backspace hit the
reset-keyframes branch on the way and wiped the clip's keyframes.

Guard both by returning early when automationSelection is set, mirroring
the selectedKeyframes precedent six lines above. No preventDefault: the
downstream handler still needs the key.

dispatchPlainKey is exported so the arbitration between keyframes, an
automation range and the clip can be pinned without standing up the hook.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore: suppress unused export for automationShapes (consumed upstack)

* feat(studio): simplify dense automation runs

Implements Ramer-Douglas-Peucker point-thinning for audio automation
lane breakpoints, working in unit space for correct log-scaled
parameter handling.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore: add automationSimplify to fallow complexity ignore

The Ramer-Douglas-Peucker algorithm in automationSimplify.ts has
inherent complexity (12 cyclomatic / 20 cognitive) that is by design
and not refactorable. Added to health.ignore list and ignoreExports
list since it's consumed by the UI layer one PR upstack.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(studio): internal clipboard for automation ranges

* feat(studio): copy and paste automation ranges across lanes

Extends the automation-selection keyboard hook with Cmd/Ctrl+C (copy the
active range) and Cmd/Ctrl+V (paste onto the selected clip's lane, at the
selection's start or the playhead, chaining the selection to the pasted
span so a second paste lands right after the first). Paste falls through
untouched when no target lane resolves, so clip-level paste keeps working.

Also fixes a latent test-isolation bug: setup() never unmounted the
previous test's Host, so document keydown listeners leaked across tests
and could consume later events before the current test's own listener ran.

* feat(studio): shape and simplify menu on an automation selection

Right-click inside an active time-selection rectangle on an automation
lane now opens a menu offering the four utility shapes (Ramp up, Ramp
down, Swell, Dip) and Simplify, composing generateShape/simplifyPoints
with pointsIn/replaceRange from the prior selection tasks. A point's own
right-click still stops propagation and deletes it, unaffected.

* feat(studio): retime an automation selection

Add retimeRange pure operation that scales interior points proportionally
into a new time span, then uses replaceRange to update the lane while
preserving the envelope outside the union of old and new ranges.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(studio): repair the automation paste path and finish the key arbitration

Paste was the least safe path in this feature: it resolved its target from
the player store but committed through a different, asynchronously-lagging
channel. Six review findings against this branch, plus the Cmd+C/Cmd+V half
of the arbitration wa-15 started for Delete.

- Write channel: resolvePasteTarget bails unless the binding's
  commitTargetKey equals the element it resolved. useAutomationLanes exposes
  that key, resolved through resolveTimelineIdForSelection — the same
  resolver applyDomSelection uses — and read in the same render as the
  commit handlers, so a handler and the key cannot describe different
  moments. Before this, clicking clip B then immediately pasting serialized
  B's automation onto A and left B untouched.
- Chaining: the paste anchor comes from sel.t1, not sel.t0, so a second
  Cmd+V lands after the first instead of on top of it. The old comment
  claimed the new behaviour while the code did the opposite, and no test
  pressed Cmd+V twice.
- Empty copy: copyRange returns false rather than arming a clipboard whose
  every paste is a destructive flatten, and samples the range's edges so
  copying a smooth stretch yields a real segment instead of no points.
- Playhead: the playhead branch requires the playhead to be inside the clip
  rather than silently clamping an out-of-clip playhead to the clip's start.
- Keys: one chord helper normalizes with toLowerCase() and gates on
  !shiftKey && !altKey, matching useAppHotkeys. CapsLock no longer kills the
  shortcut and Ctrl+Alt+V no longer pastes where the app declines.
- Arbitration: useAppHotkeys consults automationOwnsKey before its c/v
  branch, so an active range keeps Cmd+C/Cmd+V from the clip clipboard the
  same way it keeps Delete. Without it Cmd+V duplicated the clip while the
  automation paste wrote the same file, and Cmd+C armed both clipboards.
  It returns without preventDefault — the downstream handler needs the key —
  and declines when the automation clipboard is empty so clip paste still
  works. dispatchModifierKey is exported to pin this, like dispatchPlainKey.
- Double-action: the hook now returns early on e.defaultPrevented.
  useAppHotkeys is on window/capture and deliberately lets a keyframe
  selection outrank a range on Delete; without this that press deleted the
  keyframes there AND emptied the range here.

- Project scoping: the clipboard scopes itself. Every entry point carries the
  project it speaks for and a mismatch empties the module, the shape
  keyframeSlice already uses to discard a request from a previous session.
  Scoping it inside the module rather than clearing it from the session seam
  is deliberate: the failure is silent and destructive — a range copied in
  project A pasted into B is remapped through A's captured sourceRange for an
  FX node B may not have, and the keystroke is consumed so clip paste never
  runs — so no future caller should be able to forget the guard. The mark
  isLastPasteSpan reads is scoped transitively, through the same check.
- Session reset: createTimelineResetState clears automationSelection. It is
  as ephemeral as selectedKeyframes, and a range surviving a project switch
  can match a same-keyed clip in the new project and redirect a paste through
  sel.elementKey === paste.elementKey to a stale t0.

Five of the six paste fixes above shipped without a test that fails without
them, which is how the branch reached review with a comment describing
chaining that the code did not do. Each now has one: a second Cmd+V landing
after the first, a commit-target mismatch declining, an out-of-clip playhead
declining, an empty-lane copy leaving an earlier clipboard intact, and Cmd+V
with CapsLock on. All five fail against this branch's parent.

* test(studio): probe retimeRange's actual guarantee, not sample-continuity past a moved edge

The failing test probed t=5.1, which sits inside the reshaped transition
segment between the new edge (t=5) and the existing point (t=6). When
growing past an existing breakpoint, the transition TO that point
legitimately reshapes — the edge moved (t=3→t=5) even though the far
point (t=6) did not.

The real guarantee: all BREAKPOINTS strictly outside the union keep
exact (t, v) values. Corrected test to:
1. Verify sample continuity on unaffected side: t=[0,1,1.9]
2. Verify the breakpoint at t=6 keeps exact value: (t:6, v:0)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(studio): stretch an automation selection by its edges

Add an edge-handle drag to a selection's rect: grabbing within 8px of
either edge retimes the selection via the already-landed retimeRange,
scaling interior points proportionally and clamping the dragged edge
against its partner and the clip's duration. Priority is point-drag >
curve-drag > edge-stretch > new-range-select, so a point sitting on an
edge still wins the press. Cursor shows col-resize while hovering or
dragging a handle.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(studio): retime edge-stretch from a fixed points snapshot

moveEdge fed retimeRange the live draft on every pointermove while
origin.t0/t1 stayed pinned to the drag's start. retimeRange is a
relative transform that scales a lane's own current point positions,
so repeated pointermoves compounded the scale factor (interior points
drift toward the far edge) and could drop points that retimed past the
selection's original bound out of the next move's `inner` set entirely.

Snapshot lane.points at arm time (armBackgroundGesture) alongside the
existing frozen origin, and always retime from that snapshot in
moveEdge instead of the live draft. finishEdgeDrag is unchanged: it
already just persists the last (now-correct) preview.

Adds a regression test asserting a multi-pointermove edge-drag (both
edges) lands on the exact same final points as a single-shot drag to
the same target — the case that exposed the bug, since the existing
suite only ever tested a single move.

* fix(studio): clamp selection-start paste, sharpen clipboard test, cleanup

- useAutomationSelectionKeyboard: clamp the selection-start paste branch
  to [0, element.duration - clip.span], same as the playhead branch
  already does. An unclamped paste near a clip's end could write points
  past element.duration and leave the resulting selection's edge
  ungrabbable off the visible lane.
- automationClipboard.test.ts: swap the cross-parameter mapping test's
  target from fx.r.wet (numerically identical to VOLUME_RANGE) to the
  log-scaled fx.n1.frequency, so the test actually discriminates real
  unit-space mapping from a linear guess or a verbatim value copy.
- automationLaneSelection.ts: drop the lone `!` non-null assertion in
  decimateEvenly's budget-of-1 branch for a guarded pattern, matching
  the loop right below it and the repo's no-`!` convention.
- .fallowrc.jsonc: remove the two ignoreExports entries for
  AUTOMATION_SHAPES and simplifyPoints — both are now genuinely
  consumed (AutomationSelectionMenu.tsx, TimelineAutomationLane.tsx).
- AutomationSelectionMenu.tsx: port TrackGapContextMenu's viewport-edge
  clamping so a right-click near the bottom/right of the timeline
  doesn't render the shape/simplify menu partially off-screen.

* fix(studio): give edge-stretch the gesture contract the other four follow

Seven review findings against this branch, five of which were one defect:
edge-stretch was added as a fifth mutually-exclusive gesture on the lane
without joining the threshold / live-preview / revert-on-cancel contract the
point drag, curve bend, range drag and double-click all obey. Patching them
one at a time would have been more code and less coherent, so this makes the
stretch structurally parallel to its sibling range drag instead, and extracts
it to useAutomationEdgeStretch on the way out — the gestures file had ~60
lines of headroom under the 600-line studio cap, and shaving comments to fit
a refactor in is not a plan.

- Threshold. A press within the 8px halo of either edge used to persist a
  no-op commit and push an undo entry that changed nothing (commitDataAttribute
  has no unchanged-value short-circuit). Worse, it made the pre-existing "click
  the background to clear the selection" escape unreachable anywhere near an
  edge. Below 3px of travel — the same threshold the range drag uses — the
  press now clears the selection and writes nothing at all.
- Live preview. moveEdge never fired onRangeSelect and the hook discarded the
  drag's live position, so the highlight rect and both edge lines stayed pinned
  at the pre-drag bounds for the whole gesture and snapped into place on
  release: the user dragged an invisible handle. It now reports bounds on every
  move, exactly as the marquee drag does and for the same reason.
- Revert on cancel. pointercancel means the browser abandoned the gesture; it
  was routed to the same handler as pointerup, which persisted whatever partial
  retime it had reached. It now restores the arm-time snapshot through the
  preview channel — there is nothing persisted to undo — and puts the selection
  back. A new cancelDrag handler owns that, so a release and an abandonment are
  no longer the same event.
- Lost capture. capturePointer took the capture on e.target, i.e. whichever
  child the press landed on. A child that unmounts mid-drag takes the capture
  with it, silently, with no pointercancel — after which edgeDrag stayed
  non-null and every later button-less pointermove kept retiming and writing.
  Capture is now taken on the svg, which outlives every gesture on it, and a
  move reporting no buttons held ends the drag as a cancel.
- Hit priority. A breakpoint sitting exactly on the selection's edge used to
  win the press. Since replaceRange pins an anchor at the union bound and
  finishEdgeDrag leaves the selection edge at that same time, EVERY range
  operation — stretch, delete, shape insert — leaves a point exactly on the
  edge it just created: the second stretch of the same edge resolved to a
  point-drag, at the one height (on the envelope) where a user naturally grabs
  it. The feature was not repeatable. An active selection's edge now outranks a
  point on it; clearing the selection reaches the point again, which is tested.
- Clamp order. The dragged edge was bounded against its partner AFTER the
  0-floor, so a selection thinner than the minimum width yielded a negative t0,
  which core's cleanPoint then collapses onto a duplicate t=0 on the serialize
  round-trip — silent envelope corruption. The floor is now applied last. The
  minimum width is its own MIN_SELECTION_SEC rather than a borrowed
  POINT_MERGE_SEC: when two breakpoints are the same breakpoint is a different
  question from how thin a time selection may get.

One finding does not survive: edgeAt's `d0 <= d1` tiebreak was reported as
making the t1 edge ungrabbable on a narrow selection, but that comparison IS
nearest-wins, and a press right of the midpoint already resolved to t1. The
midpoint split here is the same rule written so it is legible rather than
inferred, and the test for it is labelled as characterizing behaviour, not
fixing it. What was genuinely unreachable inside a narrow halo — starting a
fresh range, or clearing the old one without Escape — the threshold above fixes.

Also settles what retimeRange does with a breakpoint sitting ON a dragged
edge, which was never decided: pointsIn is endpoint-inclusive, so it is
interior and travels with the stretch. It has to be, because the commonest
stretch of all is grabbing an edge to drag exactly that point outward, and
anchoring it would delete it and flatten the span instead. The price is that
the retimed point lands on the union's own boundary where a preservation anchor
would go, and anchor() stands down within a merge radius — one time cannot hold
two values — so the segment leaving the union reshapes. That is the one place
replaceRange's outside-never-moves invariant bends, and both halves are now
pinned: the exact points and the sampled slope for the on-edge case, and the
full two-sided invariant for a selection whose edges are off any breakpoint.
The earlier right-side probe at t=5.1 that caught this was deleted during
development as inherent; it was reporting the real behaviour.

* fix(core): make audio automation survive being rescheduled mid-playback

Anything landing inside a running value curve is refused unless the parameter is
cancelled first, and two paths were not cancelling: the chain observer wrote each
knob straight onto its AudioParam before rescheduling, and a bent segment read as
straight because only the curve exponent was checked, never the via point the
timeline actually writes. The first threw NotSupportedError into the console and
abandoned the rest of the envelope; the second played a dragged bend as a ramp.

Measured against Chrome, in a live context and in an offline one suspended
mid-curve: any cancel frees the span, and only a missing cancel is refused.
clearParamLane takes the strongest form on purpose, because curve-over-curve
refusals were reported with a cancel at the new schedule time already in place
and have never reproduced; emit keeps a ramp fallback as the backstop for
whatever that mechanism turns out to be.

Dynamic carve is what exercises all of it, so it lands here too:

- a `gain` primitive, so a carve can match levels as well as carve bands
- carve settings collapse to one `strength`, with carveProfile deriving the six
  numbers that always moved together anyway
- analyseCarveDynamics / analyseCarveDuck turn the analysis into envelopes, with
  a slow release so the bed does not snap back the instant a word ends
- worklets are awaited inside attach, so adding a compressor to a carved bed no
  longer kills its envelopes and freezes every later edit
- per-track failure detail in the render's audio stage, which was being discarded

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(studio): select automation points with a box, and stop them crossing

Replaces the time-range selection with a rectangle. A lane selection is a set of
breakpoints, not a span, so it now has value bounds as well as time bounds and a
point is caught only if it falls inside both — which is what lets you take the
peaks of an envelope and leave the dips between them. Delete, the group drag and
the rings drawn on caught points all read the one rule, so what looks selected is
exactly what those act on. Copy, paste, shape insert and simplify still work on
the box's time span, because they act on the envelope over a stretch of time.

Dragging is bounded by its neighbours in both the single and group cases. A point
cannot cross another, and cannot land exactly on one either: the lane collapses
points that share a `t`, keeping the later one, so arriving on top of a neighbour
deleted it. It stops a millisecond short, which is under a pixel at any zoom the
lane offers and keeps both points. Only stationary neighbours constrain a group,
per member rather than per end, since a box can select a non-contiguous set.

Edge-stretch is removed rather than fixed. Dragging a selection's edges to retime
the points inside it was the feature this branch opened for, and it is not wanted:
the hook, retimeRange, the edge handles, the col-resize cursor and the pointercancel
revert path all go, along with the ~360 lines of tests that pinned them.

Also: gesture-scoped coalescing keys, so one drag is one undo entry rather than a
fragmented chain of them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(studio): put #3207's edge-stretch back, folded into the unified hook

The review blocks this PR for deleting a feature two PRs downstack:

  "#3209 deletes #3207 edge-stretch instead of folding it into the unified
  hook... merging the stack would ship #3207 and then silently remove its
  user-facing retime/edge-stretch feature."

Verified, all four claims: `useAutomationEdgeStretch.ts` (248 lines) and its
test were deleted, `retimeRange` was dropped from
`automationLaneSelection.ts`, and the consolidated hook has no edge
hit-test, arm/move/finish path, or resize cursor.

Restored: the module, `retimeRange`, the selection regressions, and the
lane wiring (`col-resize` cursor, `pointercancel` reverting a partial
retime rather than persisting it).

It is not a straight revert, because #3209 changed the selection from a
time range to a box. Edge-stretch now takes `{t0,t1,v0,v1}` and moves only
the time edges — the value extent rides through untouched, which keeps it
the same gesture it was.

**One arbitration call worth a second opinion.** #3207's rule was that a
selection's edge outranks a point sitting on it, because every range
operation leaves a breakpoint exactly on the edge it created — a
point-first rule made the second stretch of an edge resolve to a
point-drag. Under a box that rule now contradicts #3209's own test
("stops the group at a point it did not select"), which presses at t=0
v=1 — simultaneously the t0 edge and a selected point.

I inverted it: selected content wins, the edge stretches everywhere it is
not also selected content. The reasoning is that a box makes the point
visibly part of the selection, and dragging selected content has to move
it. That restores #3209's test and keeps the stretch usable along the rest
of the edge — but it is a product decision between two deliberate designs,
so flag it if #3207's original precedence was load-bearing.

954 player tests pass, including the 17 restored ones.

* feat(engine): render audio FX in an OfflineAudioContext

Reads `data-fx-chain` off an audio element and runs the chain over the trimmed
WAV before volume automation is baked in — effects should see the raw signal,
and the envelope belongs on their output.

The processing happens in an OfflineAudioContext inside the headless browser
the engine already drives, running the same graph builders the studio previews
with. That is the point of the approach: one implementation per effect, so the
render agreeing with the preview is a property of the architecture rather than
a tolerance to police. Reimplementing each effect as an FFmpeg filter would
mean two implementations to keep in step, and for the dynamics processors and
modulated delays there is no filter that behaves the same way.

`build:audio-fx-runtime` bundles the graph builders into an injectable IIFE,
following the same pattern as the existing runtime artifacts, so the browser
runs exactly the code the studio does.

The page loads from a file:// URL rather than about:blank because AudioWorklet
is only exposed in a secure context — the compressor, limiter, gate and
bitcrush processors would otherwise fail to register with an opaque error.
file:// qualifies and needs no listening socket.

The chain is serialised into the attribute the way colour grading carries its
config, so there is no side-car file to resolve or lose.

An FX failure is fatal for the whole mix rather than a per-track soft failure.
Every other audio failure mode degrades gracefully — the track drops, siblings
continue — but substituting the dry signal for a processed one ships a render
that sounds plausible and is not what the author set up. Since the per-element
work races under Promise.all, an internal AbortController chained off the
caller's signal aborts in-flight siblings before workDir is removed.

* feat(core): voiceover carve analysis

Finds the bands a voice occupies so a music bed can be dipped there, letting
the voice sit in front without ducking the whole track.

Carve is a relationship between two tracks rather than an effect on one, so it
stays out of the FX chain. What it emits is an ordinary chain of peaking
filters, so a carve composes with whatever else is on the track and needs no
separate rendering path.

Selection is weighted toward intelligibility rather than raw voice energy.
Ranking purely by power lands on the fundamental almost every time, because
that is where a voice is loudest — but the masking that actually hurts a
voiceover happens higher up, and dipping 160 Hz mostly just thins the bed. The
bias is a control, not a constant: at 0 it follows raw energy, at 1 it weights
toward 1-3 kHz.

Ranking happens in dB, which matters more than it looks. Speech spreads 20-30 dB
across these bands — it falls off roughly 6 dB per octave above the fundamental
— so a weighting has to be on that scale to move anything at all. A
multiplicative weight of `1 - bias + bias * shaped` is bounded below by
`1 - bias`, capping its influence at 10*log10(1/(1 - bias)): 5.2 dB at the 0.7
default, 3 dB at 0.5. That is no influence against a real voice — every bias
short of ~0.95 would rank exactly like bias 0 and carve the fundamental, the
outcome the bias exists to prevent, while looking decisive against a fixture
whose bands sit 2 dB apart. So the bias is a dB penalty, zero at 2 kHz and worth
up to 30 dB at full strength, and relative cut depths come from a dB difference
rather than a ratio of weighted linear powers.

The bias reweights ranking without overriding the spectrum — a band the voice
has no energy in is not worth carving, and scores -Infinity rather than
competing — so a strongly low-pitched voice can still select low at full bias.
What the tests hold is that biasing never selects lower than the unbiased
ranking, that the DEFAULT bias reaches the presence region on a voice with a
realistic tilt, and that bias 0 still follows raw power exactly.

Includes a radix-2 FFT rather than a dependency; one Welch-style averaged
spectrum over third-octave bands does not justify pulling in a DSP library.

* fix(engine): keep the FX render 16-bit, stereo, and correctly sized

Three defects in the offline FX path, none of which any test could see.

**Float output silently disabled sample-accurate volume automation.** The writer
emitted 32-bit IEEE float; the very next mixer step bakes the volume envelope
into the samples and accepts only 16-bit PCM, returning null otherwise. So
enabling any effect downgraded that track to the ffmpeg expression path — capped
at 32 straight segments, quantising a curved envelope, and on a dense one falling
back to base volume. It now writes 16-bit PCM, clamped rather than wrapped so a
limiter at 0 dB or a resonant filter cannot turn overshoot into a click. A test
asserts the baker accepts the writer's own output and actually fades it.

**Everything was folded to mono.** `prepareAudioTrack` goes out of its way to
emit stereo — its pan filter exists to dodge ffmpeg's 3 dB mono-to-stereo
rematrix — and this folded it, then wrote one channel. So adding a single peaking
EQ collapsed a bed's width and cost ~3 dB in the render, while preview stayed
stereo. Channels now travel as one plane each, through an OfflineAudioContext of
the same width, and come back interleaved.

**Small results decoded the wrong length.** `new Float32Array(buf.buffer)`
discards byteOffset and byteLength, and Node pools small allocations: a 400-byte
payload sits at offset 8 inside an 8 KiB pool, so a clip under ~1024 samples
decoded as 2048 samples of unrelated memory — and the empty-result guard could
not see it. The reader has the mirror-image fix: a float data chunk on an odd
boundary (ffmpeg's pcm_f32le writes fmt(18) + fact, landing `data` at 58) now
copies instead of throwing RangeError on an unaligned view.

The tail limitation is now stated rather than mis-stated: the context is exactly
as long as the input, so a reverb or delay still ringing is cut there. The old
comment claimed the opposite. How far a tail may run past a clip's end changes
the clip's length in the mix, so it is a product decision, not one to make here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(producer): report an FX render failure as an audio error

`processCompositionAudio` reports per-track failures in its result, but an FX
failure it cannot degrade past — a browser that will not launch, a chain that
will not build — rejects instead. `runAudioStage` had no try, so that rejection
escaped to the orchestrator as an unclassified pipeline exception, losing the
stage/owner/retryable classification this stage exists to attach, and skipping
its abort check on the way out.

It now lands in `audioError` alongside every other cause, while an abort still
keeps its own shape rather than being reported as an audio problem.

Not done here: committing the generated `audio-fx-runtime-inline.ts` so a fresh
clone typechecks packages/engine without building first. The bundle is built from
the stub, and the stub changes three times across this stack — so the artifact
differs per branch and would conflict on every restack. Its model,
position-edits-render-inline.ts, is committed only because it is stable. Building
before testing is this monorepo's existing contract (studio's tests need core's
dist too), so the gap is not specific to audio FX and is better closed by a build
ordering gate than by committing a per-branch artifact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(engine): skip the browser FX render cases when there is no browser

CI's `Test` job was red on this PR with four failures, all the same cause:

  Failed to launch the browser process: spawn
  /home/runner/.cache/hyperframes/chrome/chrome-headless-shell

The job installs ffmpeg and no browser, deliberately — every other suite
that needs an external binary already guards on it
(`describe.skipIf(!HAS_FFMPEG)`). These cases were the only ones assuming
a Chrome, so they failed on an absent dependency rather than on anything
about the code.

Guards on `resolveHeadlessShellPath()` — the same resolver
`acquireBrowser` launches through, so the check cannot drift from the
thing it guards the way a hard-coded cache path would. A configured path
that does not exist throws; that is caught and read as "cannot run here".

Checked both directions rather than just the green one: with a browser all
11 cases run and pass, and with `HYPERFRAMES_BROWSER_PATH` pointed at a
missing binary exactly 3 skip and the other 8 still run. A guard that
silently skipped everything would have looked identical in CI.

They keep their value where it exists — every developer machine, and any
job that has run `hyperframes browser ensure`.

Not touched: the CodeQL failure on this PR is a run from 2026-08-07, five
days and several force-pushes stale. None of the 17 open repo alerts are
in files this PR changes; it re-runs on this push.

* chore(engine): suppress the temp-file alert with the reason it is safe

CodeQL flags `writeWav`'s `writeFileSync` as js/insecure-temporary-file
(high) — the one new alert on #3021, and the reason its CodeQL check is
red.

It is a false positive, and the comment says why rather than just silencing
it: `path` is always inside a directory made by `mkdtempSync`, never a
name assembled directly under `tmpdir()`. Both callers are covered — the
browser host page writes into `mkdtempSync(join(tmpdir(), "hf-fx-host-"))`,
and the render output goes to the producer work dir, itself
`mkdtempSync(join(tempRoot, "producer-project-"))`. mkdtemp picks the
random suffix and creates the directory 0700 in one syscall, so the
predictable filename inside it cannot be pre-created or symlinked by
another user, which is the attack the rule is about. The analyzer sees the
dataflow reach `tmpdir()` and not the mkdtemp in between.

Suppressed inline rather than dismissed in the UI, so the justification
lives next to the code and the rule stays live for anything added later in
this file. Matches the repo's existing convention — `planV2.ts:222`
carries an `lgtm[js/insecure-temporary-file]` for a different reason on
the same rule.

Correcting myself: I first reported this alert as not real, having
intersected the PR's files against the default-branch alert list, which
does not contain PR-ref alerts. Querying ?ref=refs/pull/3021/merge returns
it straight away.

* test(engine): probe ffmpeg and Chrome instead of assuming them

Two failures on #3021's Test job, both about the environment rather than
the code under test.

**Bare `ffmpeg` is not on PATH in CI.** The 16-bit fixture shelled out to
`execFileSync("ffmpeg", ...)` and died with ENOENT. The job does provide
ffmpeg, through `prepare-ffmpeg-bin`, which is what `getFfmpegBinary()`
resolves — every other ffmpeg-dependent suite in this package already goes
through it. Now this one does too, and the case is `skipIf(!HAS_FFMPEG)`
so a contributor without ffmpeg skips rather than fails.

**The browser guard trusted the wrong thing.** It asked
`resolveHeadlessShellPath()` and treated a returned path as "a browser is
here". CI's cache holds a chrome-headless-shell that resolves and then
fails to spawn — a partial download is indistinguishable from a working
one by `existsSync`, which is all that resolver checks. So the three
browser cases ran anyway and failed on the launch.

It now runs `--version` and requires exit 0, which is the same probe the
ffmpeg suites use: ask the binary, do not infer from the filesystem.

Checked both directions rather than just the green one. With a working
browser all 11 cases run and pass; with `HYPERFRAMES_BROWSER_PATH` pointed
at a binary that exits non-zero — CI's exact situation — exactly 3 skip
and the other 8 still run. A guard that quietly skipped everything would
have looked identical on the CI summary.

* feat(core): register the audio-fx-rack canary at 0%

Lands the rollout switch dark, per the registry's own procedure: "Start at
percentage: 0 and merge that — a canary at 0 is dead code you can land
safely and ramp without a code review."

Declared at the bottom of the stack so every branch above can read it. The
gate itself goes in at wa-4-fx-panel, where the rack first appears.

Scope is deliberate and stated in the description: it gates the AUTHORING
surface only. A composition that already carries `data-fx-chain` still
plays and renders it. A canary should stage who can REACH a feature, not
make an attribute somebody already wrote silently inert — an agent that
writes a chain through the skill would otherwise produce a file whose audio
processing vanishes with no error.

* feat(studio): audio FX panel generated from the registry

Controls for the whole chain: add, remove, reorder, bypass, and every knob each
effect declares.

Nothing in the panel knows what a compressor is. The registry supplies each
parameter's range, step, unit and scale and the panel renders what it finds, so
adding an effect or a knob upstream needs no change here, and the panel cannot
offer a value the renderer would reject — a typed-in figure is clamped into the
declared range on the way through.

Frequency and time controls span three or four decades, so those declare a log
scale and the slider maps exponentially; a linear slider would spend most of
its travel somewhere useless.

Reorder is a first-class control because chain order changes the sound: a
reverb before a compressor is not the same as after.

Carve gets its own block rather than an entry in the add menu, with a picker
for the voice track to listen to. It processes this track based on another one,
which is how a sidechain control works — it lives on the track that changes,
and names the source.

* feat(studio): show the Audio FX section on audio tracks

Adds `audioFx` to the editing-affordances contract and renders the FX panel in
the inspector when an `<audio>` element is selected.

The section is audio-only. A `<video>` carries its sound on a separate
`<audio>` element, so an FX chain on the video would have nothing to process.

Chain and carve settings are written straight back onto the element as
serialised attributes, the way colour grading carries its config, so
persistence is an ordinary attribute write and needs no new server route. A
chain that cannot be parsed renders as empty rather than breaking the panel,
and the attribute is left untouched until the user changes something.

The collapsed group summarises what is on the track ("2 effects + carve") so
the state is visible without expanding it.

Wired into PropertyPanelFlat rather than PropertyPanel: STUDIO_FLAT_INSPECTOR_ENABLED
defaults to true, so the flat inspector is what actually renders.

* refactor(studio): lift audioFxSummary out of PropertyPanelFlat

`PropertyPanelFlat.tsx` is 612 lines here against the repo's 600-line cap,
so the required File size check is red — the sole reason this PR is
blocked. The review says as much: "mechanical fix (~5 min), not a design
problem. Code itself is LGTM."

Moves `audioFxSummary` to `audioFxSummary.ts`, the same file a later
branch creates for it. Deliberately the smallest cut that clears the cap
rather than the whole `AudioFxGroup` extraction: every later commit in the
stack edits AudioFxGroup, so moving it here would collide with each of
them, while almost nothing touches this function.

595 lines.

* feat(core,studio): hear the FX chain in preview, and run the carve analysis

Splices an element's FX chain into the playback graph so preview stops being
silent about effects, and wires the carve button that was previously inert.

The chain goes between the decoded source and its gain stage: effects see the
raw signal and volume automation rides on their output, matching the order the
offline render uses. Since preview and render call the same graph builders,
what is heard while scrubbing is what gets written.

The splice lives in the transport rather than on the `<audio>` element. The
transport plays each track from a decoded AudioBuffer and mutes the element to
avoid doubling, so capturing the element with createMediaElementSource would
have processed a stream nothing is listening to — it looked like it worked
because the call succeeded, and the audio was unchanged.

A chain that cannot be built plays dry rather than silencing the track, which
is the right failure in preview: the author keeps working and hears the source.
The render still refuses, because shipping the dry signal there would be wrong.

Carve now analyses for real: it decodes the chosen voice track, ranks its bands
and writes the resulting peaking filters onto this track. Generated nodes are
tagged `fromCarve`, so re-running replaces the previous carve instead of
stacking another set on top of hand-added effects.

Known limitation: the graph is built when a source is scheduled, so a knob
turned mid-playback takes effect on the next play or seek rather than
immediately. Live re-parameterisation needs the transport to hold the handle
and forward updates.

* fix(studio,core): stop parameter drags from restarting playback

Dragging a knob wrote the chain through the persisting attribute path on every
input event. That path refreshes the preview, which reloads the composition and
reschedules audio — so a single drag reloaded dozens of times and playback
stuttered the whole way.

Drags now go through `onSetAttributeLive`, the same path colour grading uses for
scrubs: it coalesces undo entries and sets `skipRefresh`, so no reload happens.
The persisting write fires once, when the gesture ends — pointer-up or blur for
a slider, Enter or blur for a typed value. A select commits immediately since
there is no drag to wait for.

While dragging, the control is driven from local state. Waiting for the value to
round-trip through the element attribute made the knob lag behind the pointer.

For the change to be audible without a reload, the graph now follows the
attribute: the chain installed by the transport observes the element and
re-parameterises itself in place, so a value change lands on the next
128-sample quantum. A shape change (effect added, bypassed, pole count) cannot
be patched into a running graph, so it still waits for the next schedule rather
than cutting the audio mid-play.

The regression test drags a slider through several values and asserts the
persisting handler is untouched until release.

* feat(studio): put the audio FX rack behind its canary

Gates the rack on `isCanaryEnabled("audio-fx-rack")`, which is registered
at 0% — so the whole 47-PR stack can land without showing anyone a feature
that has not been measured yet.

The gate sits on the AUTHORING surface and nowhere else. The runtime and
the render still honour a `data-fx-chain` already on an element, so a
composition written through the skill or by `carve.mjs` keeps its
processing rather than going silently dry for anyone outside the cohort. A
canary should stage who can REACH a feature, not make an attribute somebody
already wrote stop working with no error.

Gated at the panel rather than in `resolveEditingSections`: the affordance
resolver is a pure function in core describing what an element CAN support,
and rollout state is not a property of an `<audio>` tag.

Pinned the 0% with a test, and checked it fails at 25 — a ramp should have
to break something that says "this ships dark" out loud.

One gap, stated rather than papered over: the gate itself has no unit test.
I wrote one and deleted it, because `PropertyPanel.test.tsx`'s harness
never renders the Audio FX group for its audio fixture even with the gate
removed — so the test passed for the wrong reason in the off case and could
not pass at all in the on case. A test that cannot fail for the right
reason is worse than none. Verifying the gate needs the panel harness to
mount that section first, which is its own change.

* fix(core): register FX worklets before building nodes that need them

An AudioWorkletNode cannot be constructed before its processor is registered —
it throws, and the surrounding chain is lost with it. `attachElementFxChain`
built the chain first and only then called `ensureAudioFxWorklets`, so every
worklet-backed effect (compressor, limiter, gate, bitcrush) threw on
construction and the track fell back to dry. Instrumenting the preview showed
`hf-compressor: InvalidStateError` with addModule never called at all.

When the module has not landed yet the track now plays dry and the graph is
swapped in once registration resolves, so the effect arrives a moment late
instead of never.

Registration is also tracked per context rather than in one module-level
promise. A processor registered on one AudioContext does not exist on another,
so the shared promise made every context after the first believe it was ready
when it was not — the studio's transport owns its own context, which is exactly
that case.

With the worklets actually running, the compressor's per-sample log10 and pow
became real audio-thread work. Samples below the knee have a gain of exactly
unity and need neither, so the envelope is now compared in the linear domain
and the transcendentals only run for samples that are actually being
compressed.

* refactor(studio): split the FX node row out of FxSection

Clears the health findings the FX stack left behind: the chain-node render
callback was a 70-line closure over half of FxSection's state, and the two
reorder arrows were the same button written twice.

Also drops two exports with no consumers, and registers the audio FX runtime
stub as an entry point — it is bundled by file path, so nothing imports it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): automation envelope model for audio tracks

Adds the data model behind Ableton-style automation lanes: breakpoint
envelopes over track volume or one knob of one effect in the track's FX
chain, stored on the element as `data-automation`.

Times are clip-local, so an envelope travels with the clip when it moves —
the clip-envelope model rather than arrangement automation.

`sampleAutomationLane` is the single interpolator. The lane drawing, the
preview scheduler and the render bake all call it, so the picture and the
sound cannot disagree about the curve. Log-scaled parameters interpolate in
log space, matching what their own knob already promises.

FX nodes gain a stable `id`, minted by count rather than randomly so the
document is the same on every machine. Lanes address nodes by id, so
reordering a chain never re-points a lane at a different effect, and a lane
whose effect was deleted is dropped rather than left to reattach.

Also warns when a track carries both a volume lane and a GSAP volume tween,
since only the lane is heard and the tween silently does nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(studio): lift the audio FX group out of PropertyPanelFlat

`PropertyPanelFlat.tsx` was 672 lines against the repo's 600-line cap, so
the required File size check was red — the sole reason #3014 and #3022 are
blocked. Both reviews say the same thing: "mechanical fix, not a design
problem. Code itself is LGTM."

Moves `AudioFxGroup` and `audioFxSummary` into
`propertyPanelAudioFxGroup.tsx`, which is where a later branch puts them
anyway — done here so the file is under the cap from the point it first
crosses it, rather than ten branches later.

533 lines now. The four audio imports it no longer needs go with it.

Not fixed here: three `FxSection carve` tests fail on this branch with
"Cannot read properties of undefined (reading 'toFixed')". Confirmed
pre-existing by stashing this change and re-running — that is the separate
`Test` failure the review also flags.

* feat(core): expose the AudioParams behind automatable FX knobs

Marks the knobs an automation lane can drive and has each graph builder hand
back the AudioParam behind them, so a scheduler can write to a running effect
without knowing what the effect is.

A knob is not always one AudioParam. A wet/dry mix is two gains moving in
opposition, and a knob in milliseconds drives a delay time in seconds, so
each target carries the mapping out of the knob's own declared unit.

What stays unautomatable is stated where it is decided: a WaveShaper curve, a
convolution impulse and a one-pole filter's coefficients are all rebuilt
wholesale rather than scheduled, and the four worklet effects take values by
postMessage rather than through AudioParams.

The registry flag is written by hand, so a test builds every effect and
checks the exposure both ways — nothing flagged is missing, nothing exposed
is unflagged. A flag that lied would offer a lane that silently did nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(core): play automation envelopes in preview

Schedules each lane onto the AudioParams behind its knob using native ramps
and value curves. Nothing evaluates the envelope per frame: it is handed to
the audio thread once, so it stays sample-accurate however busy the main
thread is, and the offline render will schedule it the same way.

Timing comes from the transport, so an envelope survives seeking into the
middle of a clip, a clip that has not started yet, and a playback rate that
compresses clip seconds into context seconds.

A straight line is only scheduled as a ramp when nothing bends it — no
curvature, a linear parameter scale, and no unit mapping. Log-scaled
parameters and mapped ones are sampled instead, since a delay knob in
milliseconds and a wet/dry pair moving in opposition are not linear in the
parameter they drive.

Lanes with nowhere to write are skipped rather than reported: a one-pole
filter exposes no frequency param, and the worklet effects expose none at
all. Editing an envelope mid-playback re-aims it at the live playhead rather
than restarting the track.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): make the volume lane audible in preview

The envelope was scheduled onto the transport's gain AudioParam, but the
runtime rewrites that gain every tick from `data-volume` and the GSAP-seeked
value — so it was erased within a frame. Volume automation was correct in the
render and inaudible while previewing.

The lane now feeds the per-tick path where the probed volume keyframes already
sit, checked ahead of them so the two cannot fight, and the transport no
longer schedules volume at all: one mechanism instead of two racing.

The cost is honest — in preview the level steps per tick rather than per
sample, exactly as the existing keyframe path does. The render still bakes it
into the PCM sample-accurately, and FX parameters are still scheduled on their
own AudioParams, since nothing rewrites those.

Parsed lanes are cached by attribute text: the runtime asks once per tick per
track, and parsing there would run the JSON parser 60 times a second for a
value that only changes on an edit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(engine): bake automation envelopes into the render

The offline render schedules FX lanes with the same scheduler preview uses,
inside the OfflineAudioContext that already runs the same graph builders. The
input WAV is the clip's own audio from its first sample, so clip-local time
is offline time and the envelope needs no offset.

Volume lanes take the existing PCM bake rather than a second mechanism: the
lane is converted to keyframes, so a straight fade stays two of them and only
a bent segment is sampled — the baker interpolates linearly and would
otherwise quietly straighten the curve. A volume lane supersedes keyframes
probed from the timeline, which `lint` already warns about.

A browser test sweeps a lowpass from below a 2 kHz tone to well above it and
measures both ends. Parsing the envelope is not the same as scheduling it,
and only running the real thing tells the two apart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): apply chain edits to the running graph

A structural edit — an effect added, removed, bypassed, or a filter's pole
count switched — was dropped. `buildFxChain`'s update reports false when the
change is not merely new values, and the attribute observer ignored that, so
the edit only took hold when the persisting write reloaded the composition.
That reload restarted every playing track, which is what was heard as the
audio chopping.

The graph is now swapped in place: the old effects are detached, the new ones
built and connected between the same source and gain, and any lanes
re-scheduled onto the new nodes. The source node is never touched, so playback
does not restart.

A track with no chain is watched too, rather than wired through and forgotten,
so adding its first effect is heard the same way. That means the function
always returns a disposer instead of null for the empty case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(studio): drop the FX panel's dead __testables export

Fallow audit flagged it — no test imports the module.

* fix(core,studio): clear the remaining Fallow audit findings on the FX panel

- Split FxSection's per-node row into FxNodeRow + FxNodeControls so the
  CRAP score (31.6, threshold 30) splits across two smaller units instead
  of moving wholesale with one extraction.
- Dedupe the repeated "open the add menu, read its items" block in
  propertyPanelFxSection.test.tsx into openAddMenuItems().
- Merge build-audio-fx-runtime.ts and build-position-edits-render.ts into
  one build-inline-artifact.ts, config-selected by CLI arg — the two
  scripts were a byte-for-byte clone save for names.
- Exempt canary.test.ts's rawFnv (a deliberate independent
  reimplementation used to cross-check canaryBucket, per its own
  docstring) and the property-panel test files' shared renderInto/mount
  scaffolding (pre-existing across 9 files, 2 outside this stack) in
  .fallowrc.jsonc, consistent with this file's existing exemptions for
  the same class of intentional/pre-existing duplication.

* fix(ci): allowlist the build-script consolidation in the no-main-deletions guard

build-audio-fx-runtime.ts and build-position-edits-render.ts were merged into
build-inline-artifact.ts to kill a fallow duplication finding; the deletion
guard flagged that as an accidental loss since main still has both originals.

* fix(core): dedupe the wet/dry mix math between delayFeedback and chorusLfo

Both effect builders set wet.gain to the mix and dry.gain to its complement
in identical two-line blocks; fallow kept re-flagging it as a 10-line clone
on every unrelated change. Extracted setWetDryMix.

* 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): 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.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Vance Ingalls
2026-08-13 01:10:29 -07:00
committed by GitHub
co-authored by Claude Opus 5
parent f9a20692f8
commit 69face9dc6
44 changed files with 4580 additions and 516 deletions
File diff suppressed because it is too large Load Diff
@@ -1,13 +1,17 @@
/**
* Breakpoint automation over an audio clip, edited the way a DAW edits it:
* double-click the line to add a point, drag one to shape it, right-click a
* point to remove it, Alt-drag the line between two points to bend it, and
* double-click a point to type an exact value.
* double-click the line to add a point, drag one to shape it, right-click or
* Shift+click a point to remove it, Alt-drag the line between two points to bend
* it, and double-click a point to type an exact value.
*
* Modifiers follow Ableton's, because that is the muscle memory an automation
* lane inherits: Shift locks a drag to one axis and fines the value down, Alt
* over a segment curves it, and Alt during a point drag ignores the grid.
*
* Drag the background to draw a selection box around a set of breakpoints, then
* Delete to remove them, drag any one of them to move the whole set, or
* right-click inside the box for shapes over its span.
*
* The lane knows nothing about any particular effect. Which parameters it can
* offer, their ranges, units and whether they read logarithmically all come
* from the FX registry, so an effect gained upstream needs no change here — the
@@ -30,29 +34,66 @@ import {
type HfAutomationLane,
type HfAutomationPoint,
} from "@hyperframes/core/audio-automation";
import {
envelopePath,
fromUnit,
GRAB_PX,
laneFor,
PAD_X,
toUnit,
withLane,
} from "./automationLaneGeometry";
import { envelopePath, fromUnit, laneFor, PAD_X, toUnit, withLane } from "./automationLaneGeometry";
import { useAutomationLaneGestures } from "./useAutomationLaneGestures";
import { AutomationValueInput } from "./AutomationValueInput";
import { AutomationSelectionMenu } from "./AutomationSelectionMenu";
import { AUTOMATION_LANE_H } from "./automationLaneHeight";
import { generateShape, type AutomationShapeId } from "./automationShapes";
import { simplifyPoints } from "./automationSimplify";
import { pointsIn, replaceRange } from "./automationLaneSelection";
import { pointInSelection, pointsIn, replaceRange } from "./automationLaneSelection";
import { getTimelineLaneTop } from "./timelineLayout";
import { defaultTimelineTheme } from "./timelineTheme";
import type { TimelineElement } from "../store/playerStore";
import type { UseAutomationLanesResult } from "./useAutomationLanes";
/** Pointer shape: a stretch handle wins over everything else it might also
* sit above, a read-only lane can only be selected, a live one edited. */
/**
* Drawn radius of a breakpoint.
*
* Independent of the grab radius, which is how close a pointer has to be to catch
* one: the two were the same number scaled, and tying them meant a dot could not be
* made easier to see without also changing what it caught. A touch over half the
* grab radius reads clearly at lane height without swallowing a dense run.
*/
const POINT_R = 4.9;
/** Separator between stacked lanes — the same token a track row divides with. Read
* off the default theme rather than threaded as a prop: nothing overrides the
* timeline theme for lanes today, and a prop for one colour is plumbing to nowhere. */
const LANE_BORDER = defaultTimelineTheme.rowBorder;
/** Selection box on one lane. Value bounds included: a point at the right time
* but the wrong value is not in it. */
type SelectionBox = { t0: number; t1: number; v0: number; v1: number };
/** Is this breakpoint inside the selection box? The rule itself is shared with
* Delete and with the group drag, so what is drawn as caught is exactly what
* those act on; this only adds tolerance for there being no selection at all. */
function pointInBox(point: HfAutomationPoint, box: SelectionBox | null | undefined): boolean {
return !!box && pointInSelection(point, box);
}
/** A breakpoint's drawn radius and stroke, pulled out of the render loop so the
* map callback stays a single JSX return — the ternaries below are what pushed
* it over the complexity budget when they lived inline. */
function pointCircleStyle(
inRange: boolean,
dragging: boolean,
): { radius: number; stroke: string; strokeWidth: number } {
return {
radius: POINT_R * (dragging ? 1.3 : inRange ? 1.15 : 1),
// A white ring rather than a different fill: the fill is the parameter's
// own colour, and a lane with two envelopes on it is read by colour first.
stroke: inRange ? "#fff" : "rgba(0,0,0,0.5)",
strokeWidth: inRange ? 1.5 : 1,
};
}
/** Pointer shape: a read-only lane can only be selected, a live one edited. */
function laneCursor(readOnly: boolean | undefined, dragging: boolean, stretching: boolean): string {
// A stretch handle wins over everything it might also sit above: the handle is
// a few px wide and always overlaps whatever is under the selection edge, so
// any other cursor there would advertise a gesture the press will not start.
if (stretching) return "col-resize";
if (readOnly) return "pointer";
return dragging ? "grabbing" : "crosshair";
@@ -85,9 +126,9 @@ export interface TimelineAutomationLaneProps {
readOnly?: boolean;
/** Called when a read-only lane is pressed: selects the clip so it goes live. */
onSelect?(): void;
/** Active selection on THIS lane, or null. */
rangeSelection?: { t0: number; t1: number } | null | undefined;
onRangeSelect?: ((t0: number, t1: number) => void) | undefined;
/** Active selection box on THIS lane, or null. */
rangeSelection?: SelectionBox | null | undefined;
onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;
onRangeClear?: (() => void) | undefined;
}
@@ -223,6 +264,16 @@ export function TimelineAutomationLane({
/** Client-coordinate position of an open selection menu, or null when closed. */
const [menuAt, setMenuAt] = useState<{ x: number; y: number } | null>(null);
/**
* Whether the pointer is over this lane, which is what decides if the
* breakpoints are drawn.
*
* A stack of envelopes across a long clip is hundreds of discs, and at rest the
* shape of each is the thing worth reading — the handles matter only to someone
* about to grab one. The line stays visible either way; this hides just the
* points.
*/
const [hovered, setHovered] = useState(false);
const insertShape = useCallback(
(shape: AutomationShapeId): void => {
@@ -234,7 +285,10 @@ export function TimelineAutomationLane({
t0: rangeSelection.t0,
t1: rangeSelection.t1,
});
commitPoints(replaceRange({ lane, range, ...rangeSelection, inner }), true);
commitPoints(
replaceRange({ lane, range, t0: rangeSelection.t0, t1: rangeSelection.t1, inner }),
true,
);
},
[rangeSelection, lane, range, commitPoints],
);
@@ -242,7 +296,10 @@ export function TimelineAutomationLane({
const simplifySelection = useCallback((): void => {
if (!rangeSelection) return;
const inner = simplifyPoints(pointsIn(lane, rangeSelection.t0, rangeSelection.t1), range);
commitPoints(replaceRange({ lane, range, ...rangeSelection, inner }), true);
commitPoints(
replaceRange({ lane, range, t0: rangeSelection.t0, t1: rangeSelection.t1, inner }),
true,
);
}, [rangeSelection, lane, range, commitPoints]);
// A point's own right-click already stops propagation and still deletes;
@@ -251,8 +308,10 @@ export function TimelineAutomationLane({
const onSvgContextMenu = useCallback(
(e: ReactMouseEvent<SVGSVGElement>): void => {
if (readOnly || !rangeSelection) return;
const { t } = pointAt(e.clientX, e.clientY);
if (t < rangeSelection.t0 || t > rangeSelection.t1) return;
// Inside the drawn box, not merely inside its span: the menu's own actions
// read the span, but a right-click well above or below the box is a press
// on empty lane as far as the author can see.
if (!pointInSelection(pointAt(e.clientX, e.clientY), rangeSelection)) return;
e.preventDefault();
setMenuAt({ x: e.clientX, y: e.clientY });
},
@@ -270,16 +329,19 @@ export function TimelineAutomationLane({
style={{ top: topPx, left: 0, right: 0, height: h }}
data-automation-lane={target}
>
{/* Name at the lane's top-left, like a DAW's lane header. Shown in full —
a clip starting at zero leaves no gutter to clamp it into — and
click-through, so it can sit over the envelope without blocking it. */}
{/* Separator above each lane, in the same colour a track row divides with, so
a stack of envelopes reads as rows rather than as one tall field. Drawn as
an overlay rather than a CSS border: the lane's height is fixed and its svg
is positioned against the same box, so a border would shift the drawing a
pixel off the geometry every hit test is computed from. */}
<div
className="hf-automation-name pointer-events-none absolute whitespace-nowrap font-mono text-[9px] text-panel-text-4"
style={{ left: 4, top: 2, zIndex: 2 }}
>
{range.label}
</div>
data-automation-lane-border=""
className="hf-automation-lane-border pointer-events-none absolute"
style={{ top: 0, left: 0, right: 0, height: 1, background: LANE_BORDER, zIndex: 1 }}
/>
{/* No name drawn here: the label column carries it, on the same tree
connector as the keyframe rows. Painted in the lane it sat on top of the
envelope it described and scrolled horizontally away from its own row. */}
<svg
ref={svgRef}
className="hf-automation-svg absolute"
@@ -298,6 +360,8 @@ export function TimelineAutomationLane({
}}
width={widthPx + PAD_X * 2}
height={h}
onPointerEnter={() => setHovered(true)}
onPointerLeave={() => setHovered(false)}
onPointerDown={gestures.onPointerDown}
onPointerMove={gestures.onPointerMove}
onPointerUp={gestures.endDrag}
@@ -309,10 +373,13 @@ export function TimelineAutomationLane({
>
<title>
{readOnly
? "Click to select this clip, then double-click to add a point"
: "Double-click to add a point, drag to shape, double-click a point to type a value, right-click to remove. Alt-drag the line to curve it. Shift locks an axis; Alt ignores the grid."}
? "Drag a box to select points, which also selects this clip; then double-click to add a point"
: "Double-click to add a point, drag to shape, double-click a point to type a value, right-click or Shift+click to remove it. Drag the background to draw a box around points, then Delete to remove them or drag one to move them all. Alt-drag the line to curve it. Shift locks an axis mid-drag; Alt ignores the grid."}
</title>
<rect x={PAD_X} y={0} width={widthPx} height={h} fill="rgba(0,0,0,0.18)" rx={3} />
{/* No plate behind the envelope: the lane used to darken its clip's width,
which drew a box inside the row and made a stack of lanes read as tiles
rather than as rows of one timeline. The row background shows through, and
the separator above each lane is what divides them now. */}
{/* Mid rail, so a value reads against something. */}
<line
x1={PAD_X}
@@ -323,29 +390,23 @@ export function TimelineAutomationLane({
strokeDasharray="3 4"
/>
{rangeSelection ? (
<>
<rect
data-automation-selection=""
x={xOf(rangeSelection.t0)}
y={0}
width={Math.max(0, xOf(rangeSelection.t1) - xOf(rangeSelection.t0))}
height={h}
fill={accentColor}
opacity={0.15}
pointerEvents="none"
/>
{[rangeSelection.t0, rangeSelection.t1].map((t) => (
<line
key={t}
x1={xOf(t)}
x2={xOf(t)}
y1={0}
y2={h}
stroke={accentColor}
opacity={0.5}
/>
))}
</>
<rect
data-automation-selection=""
x={xOf(rangeSelection.t0)}
// v1 is the upper bound, which is the SMALLER y: the value axis runs
// up the lane and the screen axis runs down it.
y={yOf(rangeSelection.v1)}
width={Math.max(0, xOf(rangeSelection.t1) - xOf(rangeSelection.t0))}
height={Math.max(0, yOf(rangeSelection.v0) - yOf(rangeSelection.v1))}
fill={accentColor}
opacity={0.15}
// Outlined as well as tinted. A box dragged thin along either axis is
// nearly invisible as a fill, and the author still has to be able to
// see what they drew before pressing Delete.
stroke={accentColor}
strokeOpacity={0.6}
pointerEvents="none"
/>
) : null}
<path
d={path}
@@ -354,24 +415,41 @@ export function TimelineAutomationLane({
strokeWidth={1.5}
opacity={lane.points.length === 0 ? 0.35 : 0.95}
/>
{lane.points.map((p, i) => (
<circle
key={`${i}-${p.t}`}
data-automation-point={i}
cx={xOf(p.t)}
cy={yOf(p.v)}
r={i === dragIndex ? GRAB_PX * 0.8 : GRAB_PX * 0.55}
fill={accentColor}
stroke="rgba(0,0,0,0.5)"
strokeWidth={1}
style={{ cursor: readOnly ? "default" : "grab" }}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
removeAt(i);
}}
/>
))}
{lane.points.map((p, i) => {
// Endpoint-inclusive, the same rule Delete uses, so what looks caught by
// the range is exactly what the range will remove. The tinted rectangle
// says where the selection is; this says which points it has.
const inRange = pointInBox(p, rangeSelection);
const { radius, stroke, strokeWidth } = pointCircleStyle(inRange, i === dragIndex);
return (
<circle
key={`${i}-${p.t}`}
data-automation-point={i}
{...(inRange ? { "data-automation-point-in-range": "" } : {})}
cx={xOf(p.t)}
cy={yOf(p.v)}
r={radius}
fill={accentColor}
stroke={stroke}
strokeWidth={strokeWidth}
// Hidden rather than unmounted, so the hit area survives: a point
// dragged past the lane's edge fires pointerleave mid-gesture, and a
// handle that vanishes then would drop the drag. A drag in progress
// and a selected range both keep them up for the same reason — the
// range is the subject of a pending Delete, and which points it
// caught cannot depend on where the mouse is.
style={{
cursor: readOnly ? "default" : "grab",
opacity: hovered || dragIndex !== null || rangeSelection ? 1 : 0,
}}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
removeAt(i);
}}
/>
);
})}
{playheadSec !== null && currentValue !== null ? (
<circle
data-automation-playhead=""
@@ -497,10 +575,15 @@ export function TimelineAutomationLaneSlot({
readOnly={bound.readOnly}
rangeSelection={
bound.selection?.target === lane.target
? { t0: bound.selection.t0, t1: bound.selection.t1 }
? {
t0: bound.selection.t0,
t1: bound.selection.t1,
v0: bound.selection.v0,
v1: bound.selection.v1,
}
: null
}
onRangeSelect={(t0, t1) => bound.onRangeSelect(lane.target, t0, t1)}
onRangeSelect={(t0, t1, v0, v1) => bound.onRangeSelect(lane.target, t0, t1, v0, v1)}
onRangeClear={bound.onRangeClear}
/>
);
@@ -56,14 +56,14 @@ function mountSlot(binding: Partial<AutomationLaneBinding>) {
describe("TimelineAutomationLaneSlot stale-selection guard", () => {
it("clears the selection when its lane's target no longer exists", () => {
const { onRangeClear } = mountSlot({
selection: { elementKey: "bgm", target: "fx.gone.wet", t0: 1, t1: 2 },
selection: { elementKey: "bgm", target: "fx.gone.wet", t0: 1, t1: 2, v0: 0, v1: 1 },
});
expect(onRangeClear).toHaveBeenCalledTimes(1);
});
it("leaves an in-scope selection alone", () => {
const { onRangeClear } = mountSlot({
selection: { elementKey: "bgm", target: "volume", t0: 1, t1: 2 },
selection: { elementKey: "bgm", target: "volume", t0: 1, t1: 2, v0: 0, v1: 1 },
});
expect(onRangeClear).not.toHaveBeenCalled();
});
@@ -196,6 +196,26 @@ export function TimelineLanes({
keyframeClipKey != null && expandedClipIds.has(keyframeClipKey);
// Link the sticky caret to the canvas lanes with a stable display-row id.
const lanesId = `${lanesIdPrefix}-track-${row}`;
// The header's remove buttons write through the same binding the lanes
// themselves edit through, so a deletion persists exactly like dragging
// a point does — and the binding reports read-only for an unselected
// clip, which is what leaves the buttons off rather than offering one
// that cannot act.
const headerLanes =
keyframeClip && keyframeClipKey
? automationLanes.bind(
keyframeClip,
selectedElementId === keyframeClipKey || selectedElementIds.has(keyframeClipKey),
)
: null;
const removeAutomationLane =
headerLanes && !headerLanes.readOnly
? (target: string) =>
headerLanes.onCommit({
version: 1,
lanes: headerLanes.lanes.filter((lane) => lane.target !== target),
})
: undefined;
return (
<TimelineTrackRow
key={rowKey}
@@ -239,6 +259,7 @@ export function TimelineLanes({
}}
onToggleTrackHidden={onToggleTrackHidden}
onTogglePropertyGroupKeyframe={onTogglePropertyGroupKeyframe}
onRemoveAutomationLane={removeAutomationLane}
onSeek={onSeek}
rovingTargetId={keyboard.rovingTargetId}
/>
@@ -9,7 +9,8 @@ import { TimelineTrackHeader } from "./TimelineTrackHeader";
import { defaultTimelineTheme } from "./timelineTheme";
import type { TimelineElement } from "../store/playerStore";
import type { TimelineEditCallbacks } from "./timelineCallbacks";
import { LABEL_COL_W } from "./timelineLayout";
import { getTimelineLaneTop, LABEL_COL_W } from "./timelineLayout";
import { AUTOMATION_LANE_H } from "./automationLaneHeight";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -68,6 +69,7 @@ interface RenderHeaderOptions {
onSeek?: (time: number) => void;
onTogglePropertyGroupKeyframe?: TimelineEditCallbacks["onTogglePropertyGroupKeyframe"];
onToggleTrackHidden?: TimelineEditCallbacks["onToggleTrackHidden"];
onRemoveAutomationLane?: (target: string) => void;
}
function renderHeader(options: RenderHeaderOptions = {}): {
@@ -100,6 +102,7 @@ function renderHeader(options: RenderHeaderOptions = {}): {
onToggleClipExpanded={vi.fn()}
onToggleTrackHidden={next.onToggleTrackHidden ?? vi.fn()}
onTogglePropertyGroupKeyframe={next.onTogglePropertyGroupKeyframe}
onRemoveAutomationLane={next.onRemoveAutomationLane}
onSeek={next.onSeek}
/>,
);
@@ -414,4 +417,115 @@ describe("TimelineTrackHeader", () => {
assertAligned([POSITION, OPACITY]);
act(() => view.root.unmount());
});
/**
* Automation lanes are named in the label column, on the same tree as the
* keyframe rows not painted inside the lane, where the name sat on top of
* the envelope it belonged to and scrolled away from its own row.
*/
describe("audio automation rows", () => {
const BED: TimelineElement = {
id: "bed",
label: "Music Bed",
tag: "audio",
start: 0,
duration: 10,
track: 0,
fxChain: JSON.stringify({
version: 1,
nodes: [{ type: "peaking", id: "n1", params: { frequency: 1600, gain: -6, q: 1.4 } }],
}),
automation: JSON.stringify({
version: 1,
lanes: [
{
target: "volume",
points: [
{ t: 0, v: 1 },
{ t: 5, v: 0.4 },
],
},
{
target: "fx.n1.gain",
points: [
{ t: 0, v: 0 },
{ t: 5, v: -6 },
],
},
],
}),
} as TimelineElement;
it("names every envelope in the label column", () => {
const { host, root } = renderHeader({ keyframeClip: BED, animations: [] });
const rows = Array.from(host.querySelectorAll<HTMLElement>("[data-automation-lane-label]"));
expect(rows.map((r) => r.getAttribute("data-automation-lane-label"))).toEqual([
"fx.n1.gain",
"volume",
]);
// A band is named by its frequency: with several of them, "Peaking EQ" says
// nothing about which is which. Bands sit above the level lanes.
// Two lines per row: what the effect is, then which knob the envelope
// drives. One line truncated mid-word in a column this narrow.
expect(rows.map((r) => r.querySelector("[data-automation-lane-name]")?.textContent)).toEqual([
"Peaking EQ 1.6 kHz",
"Volume",
]);
expect(rows.map((r) => r.querySelector("[data-automation-lane-param]")?.textContent)).toEqual(
[
"Gain",
// Volume has no effect behind it, so it has no second line at all.
undefined,
],
);
act(() => root.unmount());
});
it("hides them when the track is collapsed", () => {
const { host, root } = renderHeader({
keyframeClip: BED,
animations: [],
expanded: false,
});
expect(host.querySelectorAll("[data-automation-lane-label]")).toHaveLength(0);
act(() => root.unmount());
});
it("removes just that envelope from the label column", () => {
// The panel's automate toggle can only reach a parameter it still shows; a
// carve's own lanes are not in it at all, so without this an envelope could
// be created and never deleted.
const onRemoveAutomationLane = vi.fn();
const { host, root } = renderHeader({
keyframeClip: BED,
animations: [],
onRemoveAutomationLane,
});
const button = host.querySelector<HTMLButtonElement>(
'button[aria-label="Remove Peaking EQ 1.6 kHz · Gain automation"]',
);
expect(button).not.toBeNull();
act(() => button?.click());
expect(onRemoveAutomationLane).toHaveBeenCalledWith("fx.n1.gain");
act(() => root.unmount());
});
it("offers no remove button when the lanes are read-only", () => {
const { host, root } = renderHeader({ keyframeClip: BED, animations: [] });
expect(host.querySelectorAll('button[aria-label$="automation"]')).toHaveLength(0);
act(() => root.unmount());
});
it("stacks each envelope's row where its lane is drawn", () => {
// Same rhythm the canvas uses: automation begins below the keyframe lanes
// and steps by its own taller row height.
const { host, root } = renderHeader({ keyframeClip: BED, animations: [OPACITY] });
const tops = Array.from(
host.querySelectorAll<HTMLElement>("[data-automation-lane-label]"),
).map((r) => r.style.top);
const base = getTimelineLaneTop(1);
expect(tops).toEqual([`${base}px`, `${base + AUTOMATION_LANE_H}px`]);
act(() => root.unmount());
});
});
});
@@ -5,6 +5,13 @@ import type { TimelineElement } from "../store/playerStore";
import type { TimelineEditCallbacks } from "./timelineCallbacks";
import { getTimelinePropertyLanes } from "./TimelinePropertyLanes";
import { automationLaneCountOf } from "./useTimelineTrackLayout";
import {
automationLaneLabel,
automationLaneLabelParts,
elementAutomationLanes,
elementFxChain,
} from "./automationLaneData";
import { AUTOMATION_LANE_H } from "./automationLaneHeight";
import { clipTimingStart } from "../../hooks/gsapShared";
import { LayerDisclosureRow } from "./LayerDisclosureRow";
import { TrackClipCount } from "./TrackClipCount";
@@ -19,6 +26,32 @@ import { valueReadout } from "./trackHeaderLaneValues";
import { trackDisplaySuffix } from "./timelineTrackDisplay";
import { timelineLogicalRowCellId, timelinePropertyRowId } from "./timelineNavigationIdentity";
/** One envelope's label-column row content, resolved against the FX chain. */
interface AutomationRowInfo {
target: string;
label: string;
name: string;
param: string;
}
/**
* Each envelope's name, resolved against the chain the same way the lane
* resolves its axis a band is named by its frequency, not by its effect. The
* lane list is already in drawing order, which is the order these rows have to
* follow: a name beside the wrong envelope is worse than an awkward order.
*/
function resolveAutomationRows(keyframeClip: TimelineElement | null): AutomationRowInfo[] {
if (!keyframeClip) return [];
const chain = elementFxChain(keyframeClip);
return elementAutomationLanes(keyframeClip).flatMap((lane) => {
const parts = automationLaneLabelParts(lane.target, chain);
const label = automationLaneLabel(lane.target, chain);
return parts && label
? [{ target: lane.target, label, name: parts.name, param: parts.param }]
: [];
});
}
interface TimelineTrackHeaderProps {
/** The track's real key: a FRACTIONAL z-order sort value. Routes callbacks;
* never shown or announced. */
@@ -48,6 +81,9 @@ interface TimelineTrackHeaderProps {
onToggleClipExpanded: () => void;
onToggleTrackHidden: TimelineEditCallbacks["onToggleTrackHidden"];
onTogglePropertyGroupKeyframe?: TimelineEditCallbacks["onTogglePropertyGroupKeyframe"];
/** Drop one envelope. Absent while the lanes are read-only, which is what
* hides the control rather than offering a button that cannot act. */
onRemoveAutomationLane?: (target: string) => void;
onSeek?: (time: number) => void;
}
@@ -292,6 +328,102 @@ function PropertyGroupHeaderRow({
);
}
/**
* One envelope's row in the label column.
*
* Named here rather than inside the lane, on the same tree connector the
* keyframe rows use: an automation lane is a child of its clip exactly as a
* property group is, and drawing its name over the envelope put the label on top
* of the curve it describes and scrolled it away from its own row.
*/
function AutomationLaneHeaderRow({
target,
label,
name,
param,
top,
isLastLane,
gutterBackground,
columnWidth,
onRemove,
}: {
target: string;
/** The whole thing on one line, for the tooltip and the remove button's name. */
label: string;
/** What the effect is — "Peaking EQ 1.6 kHz". */
name: string;
/** Which knob the envelope drives. Empty when there is no second line to draw. */
param: string;
top: number;
isLastLane: boolean;
gutterBackground: string;
columnWidth: number;
onRemove?: (target: string) => void;
}) {
return (
<div
data-automation-lane-label={target}
data-timeline-lane-top={top}
className="absolute left-0 flex items-center gap-1 overflow-hidden px-1.5 text-[10px] text-white/65"
style={{
top,
width: columnWidth,
height: AUTOMATION_LANE_H,
background: gutterBackground,
}}
>
{/* Tree connector, as the keyframe rows draw it: spine down the row, branch
tick at the name's own height. */}
<span className="relative h-full w-3 shrink-0" aria-hidden="true">
<span
className="absolute left-1.5 top-0 w-px bg-white/15"
style={{ height: isLastLane ? "50%" : "100%" }}
/>
<span className="absolute left-1.5 top-1/2 h-px w-1.5 bg-white/15" />
</span>
{/* Two lines: what the effect is, then which knob the envelope drives. On
one line a band's own name was the first thing truncated in a column this
narrow "Peaking EQ 1.6 k…" losing exactly the part that tells two
bands apart. */}
<span className="flex min-w-0 flex-1 flex-col justify-center leading-tight" title={label}>
<span data-automation-lane-name="" className="truncate font-mono text-[9px] text-white/70">
{name}
</span>
{param ? (
<span
data-automation-lane-param=""
className="truncate font-mono text-[9px] text-white/40"
>
{param}
</span>
) : null}
</span>
{/* Beside the name it labels, because that is the only place an envelope is
named at all: a carve writes its own lanes, and the FX panel's automate
toggle can only reach a parameter it still lists so without this an
envelope could be created and never removed. */}
{onRemove && (
<button
type="button"
aria-label={`Remove ${label} automation`}
title={`Remove ${label} automation`}
// h-6 w-6 is the 24x24 WCAG 2.2 target; the glyph stays small.
className="flex h-6 w-6 shrink-0 items-center justify-center border-0 bg-transparent p-0 text-[11px] text-white/35 hover:text-white focus-visible:outline focus-visible:outline-1 focus-visible:outline-[#3CE6AC]"
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
// A control in the label column owns its click; it does not also hit
// the track row behind it and change the selection.
event.stopPropagation();
onRemove(target);
}}
>
×
</button>
)}
</div>
);
}
export function TimelineTrackHeader({
trackNumber,
trackDisplayNumber,
@@ -309,6 +441,7 @@ export function TimelineTrackHeader({
onToggleClipExpanded,
onToggleTrackHidden,
onTogglePropertyGroupKeyframe,
onRemoveAutomationLane,
onSeek,
rovingTargetId = null,
}: TimelineTrackHeaderProps) {
@@ -327,6 +460,7 @@ export function TimelineTrackHeader({
// left an audio clip's envelopes unreachable, since the track could not expand.
const disclosable =
lanes.length > 0 || (keyframeClip ? automationLaneCountOf(keyframeClip) : 0) > 0;
const automationRows = resolveAutomationRows(keyframeClip);
const isKeyframeLayer = !!keyframeClip && disclosable;
return (
@@ -396,7 +530,7 @@ export function TimelineTrackHeader({
lanesId={lanesId}
lane={lane}
laneIndex={laneIndex}
isLastLane={laneIndex === lanes.length - 1}
isLastLane={laneIndex === lanes.length - 1 && automationRows.length === 0}
expandedElement={keyframeClip}
currentTime={currentTime}
clipPercentage={clipPercentage}
@@ -407,6 +541,24 @@ export function TimelineTrackHeader({
rovingTargetId={rovingTargetId}
/>
))}
{/* Below the keyframe rows and stepping by its own height, which is how
TimelineAutomationLaneSlot lays the envelopes out on the canvas. The
two have to agree or a name labels the wrong curve. */}
{isExpanded &&
automationRows.map((row, index) => (
<AutomationLaneHeaderRow
key={row.target}
target={row.target}
label={row.label}
name={row.name}
param={row.param}
top={getTimelineLaneTop(lanes.length) + index * AUTOMATION_LANE_H}
isLastLane={index === automationRows.length - 1}
gutterBackground={theme.gutterBackground}
columnWidth={showTrackLabel ? LABEL_COL_W : contentOrigin}
onRemove={onRemoveAutomationLane}
/>
))}
</>
)}
</div>
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { createAutomationGestureKeys } from "./automationGestureKeys";
const keys = () => {
let n = 0;
return createAutomationGestureKeys(() => `g${++n}`);
};
describe("createAutomationGestureKeys", () => {
it("holds one key across every move of a drag", () => {
// Each move persists; history merges same-key entries inside 300ms. Separate
// keys, or a window that can expire mid-drag, is what made undo take back a
// fragment of the move instead of the move.
const g = keys();
expect([g.live().key, g.live().key, g.live().key]).toEqual(["g1", "g1", "g1"]);
});
it("never lets the window expire", () => {
expect(keys().live().ms).toBe(Number.POSITIVE_INFINITY);
expect(keys().commit().ms).toBe(Number.POSITIVE_INFINITY);
});
it("ends the gesture on the release, under the same key", () => {
const g = keys();
g.live();
expect(g.commit().key).toBe("g1");
});
it("starts a fresh key for the next drag", () => {
const g = keys();
g.live();
g.commit();
expect(g.live().key).toBe("g2");
});
it("gives a standalone commit its own key", () => {
// Deleting a range, pasting one, typing a value: one write, one step each.
const g = keys();
expect(g.commit().key).toBe("g1");
expect(g.commit().key).toBe("g2");
});
it("does not join a commit to a gesture that already ended", () => {
const g = keys();
g.live();
g.commit();
expect(g.commit().key).toBe("g2");
});
});
@@ -0,0 +1,49 @@
/**
* Undo grouping for a lane gesture.
*
* Dragging a point persists on every move and once more on release. History
* coalesces entries that share a key and land within 300ms of each other, and
* these writes did neither: the moves and the release used different keys, and a
* drag slower than the window split into several entries. Undo then took back
* whatever fragment happened to be last, leaving the point near where the drag
* had dropped it which reads as undo not working at all.
*
* So a gesture mints one key and holds it: every move and the release that ends
* it record under that key with no window to expire, and the next gesture gets a
* fresh one so two drags never collapse into a single step.
*/
export interface CoalesceHint {
key: string;
/** No expiry: a gesture is one step however long the pointer is held. */
ms: number;
}
export interface AutomationGestureKeys {
/** A continuous write. Opens a gesture if one is not already open. */
live(): CoalesceHint;
/** The persisting write that ends a gesture — or a standalone edit. */
commit(): CoalesceHint;
}
export function createAutomationGestureKeys(
mint: () => string = () => `automation-gesture:${++counter}`,
): AutomationGestureKeys {
let open: string | null = null;
const hint = (key: string): CoalesceHint => ({ key, ms: Number.POSITIVE_INFINITY });
return {
live: () => {
open ??= mint();
return hint(open);
},
commit: () => {
// A commit with no drag before it — a Delete, a paste, a typed value — is
// its own step, so it mints rather than joining anything.
const key = open ?? mint();
open = null;
return hint(key);
},
};
}
let counter = 0;
@@ -1,6 +1,11 @@
// @vitest-environment happy-dom
import { describe, expect, it } from "vitest";
import { elementAutomation, elementFxChain } from "./automationLaneData";
import {
automationLaneLabel,
automationLaneLabelParts,
elementAutomation,
elementFxChain,
} from "./automationLaneData";
import type { TimelineElement } from "../store/timelineElement";
const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({
@@ -13,6 +18,9 @@ const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({
...over,
});
/** The chain as the lane code sees it: parsed, not the attribute text. */
const parseChain = (chain: unknown) => elementFxChain(el({ fxChain: JSON.stringify(chain) }))!;
const CHAIN = JSON.stringify({
version: 1,
nodes: [{ type: "lowpass", id: "n1", params: { frequency: 400, q: 0.9, poles: "2" } }],
@@ -63,4 +71,91 @@ describe("automationLaneData", () => {
expect(elementAutomation(el({ automation: "{nope" })).lanes).toEqual([]);
expect(elementFxChain(el({ fxChain: "{nope" }))).toBeNull();
});
describe("lane order", () => {
// A stack of EQ bands reads as a spectrum, so it has to be laid out like one:
// the top of the stack is the top of the audible range. Attribute order is
// whatever the carve happened to mint, which is the opposite — bands come out
// ascending.
const bandChain = JSON.stringify({
version: 1,
nodes: [
{ type: "peaking", id: "n1", params: { frequency: 400, gain: -6, q: 1.4 } },
{ type: "peaking", id: "n2", params: { frequency: 1600, gain: -9, q: 1.4 } },
{ type: "peaking", id: "n3", params: { frequency: 1000, gain: -3, q: 1.4 } },
{ type: "gain", id: "n4", params: { gain: -6 } },
],
});
const bandLanes = JSON.stringify({
version: 1,
lanes: [
{ target: "volume", points: [{ t: 0, v: 1 }] },
{ target: "fx.n1.gain", points: [{ t: 0, v: -6 }] },
{ target: "fx.n2.gain", points: [{ t: 0, v: -9 }] },
{ target: "fx.n3.gain", points: [{ t: 0, v: -3 }] },
{ target: "fx.n4.gain", points: [{ t: 0, v: -6 }] },
],
});
it("puts the highest frequency at the top", () => {
const lanes = elementAutomation(el({ automation: bandLanes, fxChain: bandChain })).lanes;
expect(lanes.map((l) => l.target)).toEqual([
"fx.n2.gain", // 1.6 kHz
"fx.n3.gain", // 1 kHz
"fx.n1.gain", // 400 Hz
// Neither of these is a band, so they sit under the spectrum in the order
// they were written.
"volume",
"fx.n4.gain",
]);
});
it("keeps the same object identity, so a drag survives the sort", () => {
const a = elementAutomation(el({ automation: bandLanes, fxChain: bandChain }));
const b = elementAutomation(el({ automation: bandLanes, fxChain: bandChain }));
expect(a).toBe(b);
});
});
describe("automationLaneLabel", () => {
const chain = parseChain({
version: 1,
nodes: [
{ type: "peaking", id: "n1", params: { frequency: 1600, gain: -9, q: 1.4 } },
{ type: "peaking", id: "n2", params: { frequency: 400, gain: -6, q: 1.4 } },
{ type: "gain", id: "n3", params: { gain: -6 } },
],
});
it("names the effect and the band it sits at", () => {
// Three lanes all reading "Peaking EQ · Gain" say nothing about which band
// each one is; a bare frequency does not say whether it is a bell or a
// shelf. Both, then the parameter.
expect(automationLaneLabel("fx.n1.gain", chain)).toBe("Peaking EQ 1.6 kHz · Gain");
expect(automationLaneLabel("fx.n2.gain", chain)).toBe("Peaking EQ 400 Hz · Gain");
});
it("falls back to the effect's name when it has no frequency", () => {
expect(automationLaneLabel("fx.n3.gain", chain)).toBe("Gain · Gain");
expect(automationLaneLabel("volume", chain)).toBe("Volume");
});
it("has nothing to say about a target that does not resolve", () => {
expect(automationLaneLabel("fx.gone.gain", chain)).toBeNull();
expect(automationLaneLabelParts("fx.gone.gain", chain)).toBeNull();
});
it("splits the name from the parameter, which the column stacks", () => {
expect(automationLaneLabelParts("fx.n1.gain", chain)).toEqual({
name: "Peaking EQ 1.6 kHz",
param: "Gain",
});
expect(automationLaneLabelParts("fx.n3.gain", chain)).toEqual({
name: "Gain",
param: "Gain",
});
// Volume is one word with no effect behind it, so there is no second line.
expect(automationLaneLabelParts("volume", chain)).toEqual({ name: "Volume", param: "" });
});
});
});
@@ -15,7 +15,9 @@
import {
parseAutomation,
parseAutomationTarget,
resolveAutomation,
resolveAutomationRange,
type HfAutomation,
type HfAutomationLane,
} from "@hyperframes/core/audio-automation";
@@ -79,7 +81,8 @@ export function elementAutomation(element: TimelineElement): HfAutomation {
// through a separator no attribute can contain.
return cached(automationCache, `${raw}\u0000${element.fxChain ?? ""}`, () => {
try {
return resolveAutomation(parseAutomation(raw), chain ?? undefined);
const resolved = resolveAutomation(parseAutomation(raw), chain ?? undefined);
return { ...resolved, lanes: orderLanes(resolved.lanes, chain) };
} catch {
// Unreadable automation draws no lanes rather than breaking the row.
return EMPTY;
@@ -91,3 +94,83 @@ export function elementAutomation(element: TimelineElement): HfAutomation {
export function elementAutomationLanes(element: TimelineElement): HfAutomationLane[] {
return elementAutomation(element).lanes;
}
/** The frequency the lane's effect sits at, when it has one. */
function laneFrequency(target: string, chain: HfAudioFxChain | null): number | null {
const parsed = parseAutomationTarget(target);
if (!parsed || parsed.kind !== "fx") return null;
const node = chain?.nodes.find((n) => n.id === parsed.nodeId);
const freq = node?.params?.["frequency"];
return typeof freq === "number" ? freq : null;
}
/**
* Lane order: the audible spectrum, top down, then everything else.
*
* A stack of EQ bands is read as a spectrum, so it has to be laid out like one
* high at the top, the way every analyser and every EQ curve is drawn. Attribute
* order is whatever minted the nodes, which for a carve is ascending: exactly
* upside down. Lanes with no frequency to place them a level stage, the track's
* own volume keep their written order and sit under the bands, like a fader
* below the EQ section of a channel strip.
*
* Sorted here, in the one function both the canvas lanes and the label column
* read, because a label whose row disagrees with the envelope it names is worse
* than either order.
*/
function orderLanes(lanes: HfAutomationLane[], chain: HfAudioFxChain | null): HfAutomationLane[] {
const withFreq: { lane: HfAutomationLane; freq: number }[] = [];
const rest: HfAutomationLane[] = [];
for (const lane of lanes) {
const freq = laneFrequency(lane.target, chain);
if (freq === null) rest.push(lane);
else withFreq.push({ lane, freq });
}
withFreq.sort((a, b) => b.freq - a.freq);
return [...withFreq.map((e) => e.lane), ...rest];
}
/** A frequency as an author reads it: 400 Hz, 1.6 kHz, 10 kHz. */
function formatHz(freq: number): string {
if (freq < 1000) return `${Math.round(freq)} Hz`;
const k = freq / 1000;
return `${k >= 10 ? Math.round(k) : Number(k.toFixed(1))} kHz`;
}
/**
* What a lane is called in the timeline, as its two lines.
*
* `name` is the effect and, when it has one, the frequency it sits at: "Peaking
* EQ 1.6 kHz". The frequency is what tells two bands apart three lanes all
* reading "Peaking EQ" say nothing about which is which and the effect still
* has to be named, since a chain mixes filter types and a bare frequency does not
* say whether it is a bell or a shelf.
*
* `param` is which knob the envelope drives, on its own line: a band can carry a
* gain lane and a Q lane, and stacking the two lines is what keeps a name legible
* in a column this narrow instead of truncating mid-word.
*
* Null when the target does not resolve against the chain the same condition
* that stops the lane being drawn at all.
*/
export function automationLaneLabelParts(
target: string,
chain: HfAudioFxChain | null,
): { name: string; param: string } | null {
const range = resolveAutomationRange(target, chain ?? undefined);
if (!range) return null;
// The registry's label is "<effect> · <param>", or just "<param>" for volume.
const parts = range.label.split(" · ");
const param = parts.at(-1) ?? range.label;
const effect = parts.length > 1 ? parts.slice(0, -1).join(" · ") : null;
const freq = laneFrequency(target, chain);
const name = [effect, freq === null ? null : formatHz(freq)].filter(Boolean).join(" ");
return { name: name || param, param: name ? param : "" };
}
/** The whole label on one line, for a tooltip or an accessible name. */
export function automationLaneLabel(target: string, chain: HfAudioFxChain | null): string | null {
const parts = automationLaneLabelParts(target, chain);
if (!parts) return null;
return parts.param ? `${parts.name} · ${parts.param}` : parts.name;
}
@@ -0,0 +1,194 @@
/**
* Pure position math for the two multi-point drags on an automation lane: a
* group move (dragging a whole box-selected set by one delta) and a single
* point's move (the modifiers and neighbour clamp one breakpoint honours).
*
* Split out of useAutomationLaneGestures.ts so the hook's own onPointerDown
* and movePoint stay orchestration read the pointer, call one of these,
* apply the result rather than carrying this branching themselves.
*/
import type { AutomationRange, HfAutomationLane } from "@hyperframes/core/audio-automation";
import {
applyShiftConstraint,
dominantDragAxis,
MIN_POINT_GAP_SEC,
snapLaneTime,
} from "./automationLaneGeometry";
import { pointInSelection } from "./automationLaneSelection";
/** Snap radius in clip seconds, shared with the single-point and group drags. */
export const SNAP_SEC = 0.04;
export type AutomationSelectionBox = { t0: number; t1: number; v0: number; v1: number };
/** Which points a press on `pressed` should drag together: the whole box-selected
* set if it contains more than one member, otherwise none (an ordinary
* single-point drag, selection or no). */
function resolveGroupDragIndices(
lane: HfAutomationLane,
pressed: HfAutomationLane["points"][number] | undefined,
rangeSelection: AutomationSelectionBox | null | undefined,
): number[] {
if (!rangeSelection || !pressed || !pointInSelection(pressed, rangeSelection)) return [];
return lane.points.flatMap((p, i) => (pointInSelection(p, rangeSelection) ? [i] : []));
}
export interface GroupDragSnapshot {
points: HfAutomationLane["points"];
indices: number[];
anchor: { t: number; v: number };
selection: AutomationSelectionBox;
}
/** Snapshot to arm a group drag from a press on `pressed`, or null when the
* press does not land on a multi-point selection an ordinary single-point
* drag, selection or no. */
export function armGroupDrag(
lane: HfAutomationLane,
pressed: HfAutomationLane["points"][number] | undefined,
rangeSelection: AutomationSelectionBox | null | undefined,
): GroupDragSnapshot | null {
const indices = resolveGroupDragIndices(lane, pressed, rangeSelection);
if (indices.length <= 1 || !pressed) return null;
return {
points: lane.points.map((p) => ({ ...p })),
indices,
anchor: { t: pressed.t, v: pressed.v },
selection: rangeSelection ? { ...rangeSelection } : { t0: 0, t1: 0, v0: 0, v1: 0 },
};
}
export interface GroupMoveResult {
points: HfAutomationLane["points"];
selection: AutomationSelectionBox;
hint: string;
}
/**
* Move a selected set by one delta, taken from the point under the pointer.
*
* The whole group has to stop when its first member reaches a boundary, not
* each point on its own: clamping individually squashes the shape flat against
* the edge, and the gesture is meant to preserve it. Deltas are in the
* parameter's own units, so on a logarithmic axis a group moves by Hz rather
* than by octaves the same as dragging one point does.
*/
export function computeGroupMove(input: {
group: GroupDragSnapshot;
raw: { t: number; v: number };
shiftKey: boolean;
altKey: boolean;
range: AutomationRange;
duration: number;
snapTimes: readonly number[] | undefined;
xOf(t: number): number;
yOf(v: number): number;
}): GroupMoveResult {
const { group, raw, shiftKey, altKey, range, duration, snapTimes, xOf, yOf } = input;
const moving = group.indices.map((i) => group.points[i]!);
let dt = raw.t - group.anchor.t;
let dv = raw.v - group.anchor.v;
if (shiftKey) {
// The axis lock, as a single-point drag has it: keep whichever the pointer
// has travelled further along and drop the other.
const alongTime = Math.abs(dt * (xOf(1) - xOf(0)));
const alongValue = Math.abs((dv * (yOf(range.min) - yOf(range.max))) / (range.max - range.min));
if (alongTime >= alongValue) dv = 0;
else dt = 0;
} else if (!altKey) {
// Snap the point under the pointer, and move the set by that same amount.
const others = group.points.filter((_, i) => !group.indices.includes(i)).map((p) => p.t);
dt =
snapLaneTime(group.anchor.t + dt, [...(snapTimes ?? []), ...others], SNAP_SEC) -
group.anchor.t;
}
const times = moving.map((p) => p.t);
const values = moving.map((p) => p.v);
// No member may cross a point that is staying put. Only stationary
// neighbours constrain: two selected points travel together, so the gap
// between them never changes. Per member rather than per end of the group,
// because a box can select a non-contiguous set — the peaks of an envelope
// and not the dip between them.
const gapTo = (step: 1 | -1): number[] =>
group.indices.flatMap((i) => {
const neighbour = group.points[i + step];
if (!neighbour || group.indices.includes(i + step)) return [];
// Short of the neighbour, not onto it — the lane collapses points that
// share a time, and a group drag must not consume what it runs into.
return [Math.max(0, Math.abs(neighbour.t - group.points[i]!.t) - MIN_POINT_GAP_SEC)];
});
dt = Math.min(
Math.max(dt, -Math.min(Math.min(...times), ...gapTo(-1))),
Math.min(duration - Math.max(...times), ...gapTo(1)),
);
dv = Math.min(Math.max(dv, range.min - Math.min(...values)), range.max - Math.max(...values));
// No re-sort: clamped to the neighbours, the lane's order cannot change
// under a drag, so the point under the pointer keeps its index.
const points = group.points.map((p, i) =>
group.indices.includes(i) ? { ...p, t: p.t + dt, v: p.v + dv } : p,
);
return {
points,
// The box travels with the points — both axes, or a vertical nudge would
// slide its own points out of the box that caught them and a second nudge
// would move fewer of them.
selection: {
t0: group.selection.t0 + dt,
t1: group.selection.t1 + dt,
v0: group.selection.v0 + dv,
v1: group.selection.v1 + dv,
},
hint: `${group.indices.length} points ${dt >= 0 ? "+" : ""}${dt.toFixed(2)}s`,
};
}
/** Where Shift last locked a single-point drag's axis. */
export type ShiftAxis = "time" | "value" | null;
/** The clip-local time and value a single dragged point should land on,
* honouring the modifiers held with it and the neighbours it cannot cross. */
export function computeSinglePointMove(input: {
raw: { t: number; v: number };
origin: { t: number; v: number } | null;
shiftKey: boolean;
altKey: boolean;
shiftAxis: ShiftAxis;
range: AutomationRange;
duration: number;
snapTimes: readonly number[] | undefined;
lane: HfAutomationLane;
dragIndex: number;
xOf(t: number): number;
yOf(v: number): number;
}): { t: number; v: number; shiftAxis: ShiftAxis } {
const { raw, origin, shiftKey, altKey, range, duration, snapTimes, lane, dragIndex, xOf, yOf } =
input;
let shiftAxis = shiftKey ? input.shiftAxis : null;
let { t, v } = raw;
if (shiftKey && origin) {
shiftAxis ??= dominantDragAxis({ origin, raw, xOf, yOf });
({ t, v } = applyShiftConstraint({ range, origin, raw, xOf, yOf, axis: shiftAxis }));
}
// Shift is a deliberate free-hand move as much as Alt is, so neither snaps.
if (!altKey && !shiftKey) {
const neighbours = lane.points.filter((_, i) => i !== dragIndex).map((p) => p.t);
t = snapLaneTime(t, [...(snapTimes ?? []), ...neighbours], SNAP_SEC);
}
// A breakpoint cannot cross another in time, and cannot land exactly on one
// either: the lane collapses points that share a `t`, so arriving on top of a
// neighbour deletes it. It stops a hair short instead, which reads as touching
// and keeps both points. Applied after the snap, which can itself put the
// point on a beat past a neighbour.
const floor = (lane.points[dragIndex - 1]?.t ?? -Infinity) + MIN_POINT_GAP_SEC;
const ceiling = (lane.points[dragIndex + 1]?.t ?? Infinity) - MIN_POINT_GAP_SEC;
const held = lane.points[dragIndex]?.t ?? t;
t =
ceiling >= floor
? Math.min(ceiling, Math.max(floor, Math.min(duration, Math.max(0, t))))
: // Neighbours closer together than the gap leave nowhere to go, so the
// point stays where it is rather than being flung to one side.
held;
return { t, v, shiftAxis };
}
@@ -79,29 +79,97 @@ describe("curveForDrag", () => {
const a = { t: 0, v: 1 };
const b = { t: 4, v: 0 };
/** The segment the drag describes, as the model would store it. */
const bentLane = (bend: { viaX: number; viaY: number } | null) => ({
target: "volume",
points: [{ ...a, ...(bend ?? {}) }, b],
});
it("puts the curved segment through the point that was dragged", () => {
// The whole contract: whatever curve comes back, sampling the segment at the
// dragged time has to give the dragged value back — otherwise the line runs
// away from the pointer.
// The whole contract: sampling the segment at the dragged time gives the dragged
// value back, so the line never runs away from the pointer. Anywhere in the
// segment, at any depth.
for (const [t, v] of [
[1, 0.9],
[2, 0.8],
[3, 0.15],
[0.4, 0.75],
[1.6, 0.65],
[2, 0.6],
[2, 0.1],
[2.8, 0.4],
[3.6, 0.5],
] as const) {
const curve = curveForDrag({ range: VOLUME_RANGE, a, b, t, v });
expect(curve).not.toBeNull();
const lane = { target: "volume", points: [{ ...a, curve: curve ?? 0 }, b] };
expect(sampleAutomationLane(lane, t, "linear")).toBeCloseTo(v, 2);
const bend = curveForDrag({ range: VOLUME_RANGE, a, b, t, v });
expect(bend).not.toBeNull();
expect(sampleAutomationLane(bentLane(bend), t, "linear")).toBeCloseTo(v, 2);
}
});
it("stays inside the range the model will accept", () => {
// Anything outside ±1 is clamped on parse, so a drag past the limit has to
// saturate rather than round-trip to something else.
const curve = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.05, v: 0.02 });
expect(curve).not.toBeNull();
expect(Math.abs(curve ?? 0)).toBeLessThanOrEqual(1);
expect(applyCurve(0.5, curve ?? 0)).toBeGreaterThan(0);
it("follows the pointer into the corner of a segment, as deep as it is dragged", () => {
// The extreme: 10% along, pulled almost to the floor of a falling ramp. The old
// exponent saturated a third of the segment away from the pointer, and a later
// slope cap stopped following it too. Reached exactly now, and the shape it draws
// stays one smooth arc — checked by sampling it, not by trusting it.
const bend = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.4, v: 0.05 });
expect(bend).not.toBeNull();
const drawn = bentLane(bend);
expect(sampleAutomationLane(drawn, 0.4, "linear")).toBeCloseTo(0.05, 2);
let previous: number | null = null;
let worst = 1;
for (let i = 1; i < 60; i += 1) {
const t = (4 * i) / 60;
const h = 0.01;
const slope =
(sampleAutomationLane(drawn, t + h, "linear") -
sampleAutomationLane(drawn, t - h, "linear")) /
(2 * h);
if (previous !== null && Math.abs(previous) > 1e-6) {
const ratio = Math.abs(slope) > Math.abs(previous) ? slope / previous : previous / slope;
worst = Math.max(worst, Math.abs(ratio));
}
previous = slope;
}
// Gradual: a crease would show up here as a step change in slope.
expect(worst).toBeLessThan(3);
});
it("biases the bend toward whichever point the pointer is nearer", () => {
// The behaviour a single exponent could not give: grabbing the line near the
// right-hand point has to bulge it on the RIGHT. Measured as where the curve
// deviates furthest from the straight line it replaced.
const apexOf = (bend: { viaX: number; viaY: number } | null): number => {
const lane = bentLane(bend);
let best = 0;
let at = 0;
for (let i = 1; i < 40; i++) {
const t = (4 * i) / 40;
const straight = 1 - t / 4;
const gap = Math.abs(sampleAutomationLane(lane, t, "linear") - straight);
if (gap > best) {
best = gap;
at = t;
}
}
return at;
};
const nearA = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.6, v: 0.55 });
const nearB = curveForDrag({ range: VOLUME_RANGE, a, b, t: 3.4, v: 0.45 });
expect(apexOf(nearA)).toBeLessThan(1.6);
expect(apexOf(nearB)).toBeGreaterThan(2.4);
// And the two sit on opposite sides of centre, which is the whole complaint:
// every bend used to land on the same side whatever the pointer did.
expect(apexOf(nearA)).toBeLessThan(apexOf(nearB));
});
it("stays inside the normalised segment the model will accept", () => {
// Both coordinates are clamped clear of the ends on parse, so a drag right up
// against a breakpoint has to describe an interior point, not the breakpoint.
const bend = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.05, v: 0.02 });
expect(bend).not.toBeNull();
expect(bend?.viaX).toBeGreaterThan(0);
expect(bend?.viaX).toBeLessThan(1);
expect(bend?.viaY).toBeGreaterThan(0);
expect(bend?.viaY).toBeLessThan(1);
expect(applyCurve(0.5, 0)).toBe(0.5);
});
it("declines a segment with no room to bend", () => {
@@ -11,6 +11,7 @@ import {
fxAutomationTarget,
resolveAutomationRange,
sampleAutomationLane,
steadyViaPoint,
VOLUME_RANGE,
VOLUME_TARGET,
type AutomationRange,
@@ -21,6 +22,17 @@ 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;
/**
* Closest two breakpoints may sit in clip seconds while still being two points.
*
* A drag clamps to this short of its neighbour rather than onto it. Landing on the
* exact same time is not a step, it is a deletion: the lane's own normalisation
* collapses points that share a `t`, keeping the later one so dragging a point
* fully into its neighbour used to consume that neighbour. A millisecond is under a
* pixel at any zoom the lane offers, so the two still read as touching.
*/
export const MIN_POINT_GAP_SEC = 0.001;
/** 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. */
@@ -98,16 +110,21 @@ export function formatValue(range: AutomationRange, value: number): string {
}
/**
* The `curve` that bends a segment through a dragged point.
* The via point that bends a segment through a dragged pointer: the pointer's own
* position in the segment's normalised space, which is all the model needs.
*
* `applyCurve` raises normalised progress to `2^(2*curve)`, so a point the
* pointer holds at progress `x` and unit height `f` fixes the exponent:
* `x^e = f`, hence `e = ln f / ln x` and `curve = log2(e) / 2`. Solving rather
* than accumulating a delta means the segment passes through the pointer
* instead of drifting away from it over a long drag.
* There is nothing to solve any more, and that is the point. This used to fit an
* exponent `x^e = f`, so `curve = log2(ln f / ln x) / 2` and an exponent is
* one knob for two questions. It spent it on the wrong one: every upward bend it
* could draw deviated most inside the first fifth of the segment, so grabbing the
* line near its right-hand breakpoint still bulged it on the left. And reaching a
* pointer near either end needed an exponent the model refuses `e` runs past 15
* at `x = 0.9`, clamped to 4 so the line stopped following the pointer
* altogether, missing it by up to a third of the segment's height. Naming the
* point the curve passes through says both things at once, exactly, anywhere.
*
* Null when the segment cannot express the shape: a flat segment has no room to
* bend, and progress or height at the very ends divides by zero.
* Null when the segment cannot take a bend: a flat segment draws the same line
* whatever the shape, and a pointer at the very ends is the ends.
*/
export function curveForDrag(input: {
range: AutomationRange;
@@ -115,7 +132,7 @@ export function curveForDrag(input: {
b: { t: number; v: number };
t: number;
v: number;
}): number | null {
}): { viaX: number; viaY: number } | null {
const { range, a, b, t, v } = input;
const span = b.t - a.t;
if (span <= 0) return null;
@@ -126,7 +143,11 @@ export function curveForDrag(input: {
if (Math.abs(ub - ua) < 0.001) return null;
const f = (toUnit(range, v) - ua) / (ub - ua);
if (f <= 0.001 || f >= 0.999) return null;
return Math.max(-1, Math.min(1, Math.log2(Math.log(f) / Math.log(x)) / 2));
// Reported as the model will honour it, not as the pointer asked. A bend is held
// to a steady curve, so a pointer dragged past that stops being followed — and
// the write, the preview and the readout all have to say the same thing about
// where the line actually went.
return steadyViaPoint(x, f);
}
/**
@@ -137,6 +158,32 @@ export function curveForDrag(input: {
* Which axis "won" is decided in pixels, not in seconds and dB those are
* different units and comparing them would make the lock depend on the zoom.
*/
/** Which way a gesture is going, in pixels — the only comparable unit. */
export function dominantDragAxis(input: {
origin: { t: number; v: number };
raw: { t: number; v: number };
xOf(t: number): number;
yOf(v: number): number;
}): "time" | "value" {
const { origin, raw, xOf, yOf } = input;
return Math.abs(xOf(raw.t) - xOf(origin.t)) > Math.abs(yOf(raw.v) - yOf(origin.v))
? "time"
: "value";
}
/**
* The pointer, constrained to one axis.
*
* The axis is handed in rather than worked out here, because it has to be decided
* once for the gesture and held. Recomputed per event it followed whichever way
* the last move happened to lean, so a hand drifting sideways during a vertical
* drag flipped the lock and the point moved in both which is indistinguishable
* from no lock at all.
*
* Locking to time holds the value exactly. Locking to value holds the time and
* moves the value at a quarter speed: the same gesture is the fine adjustment,
* because a fader spanning 60px of lane has no other way to be set precisely.
*/
export function applyShiftConstraint(input: {
range: AutomationRange;
origin: { t: number; v: number };
@@ -144,11 +191,12 @@ export function applyShiftConstraint(input: {
/** Same projections the lane draws with, so the comparison is on screen. */
xOf(t: number): number;
yOf(v: number): number;
/** Decided on the gesture's first travel; worked out here when absent. */
axis?: "time" | "value";
}): { t: number; v: number } {
const { range, origin, raw, xOf, yOf } = input;
if (Math.abs(xOf(raw.t) - xOf(origin.t)) > Math.abs(yOf(raw.v) - yOf(origin.v))) {
return { t: raw.t, v: origin.v };
}
const { range, origin, raw } = input;
const axis = input.axis ?? dominantDragAxis(input);
if (axis === "time") return { t: raw.t, v: origin.v };
const from = toUnit(range, origin.v);
return { t: origin.t, v: fromUnit(range, from + (toUnit(range, raw.v) - from) * 0.25) };
}
@@ -202,7 +250,9 @@ export function envelopePath(input: {
const a = lane.points[i];
const b = lane.points[i + 1];
if (!a || !b) continue;
if (!a.curve && range.scale === "linear") {
// A via point bends the segment with no `curve` of its own, so the
// straight-line shortcut has to rule out both.
if (!a.curve && a.viaX === undefined && range.scale === "linear") {
pts.push(`L ${xOf(b.t)} ${yOf(b.v)}`);
continue;
}
@@ -6,6 +6,10 @@
* 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.
* of diamonds: a fader envelope drawn 28px high cannot be aimed. 48 was still
* too tight in use the drawing area is the height minus 6px of padding either
* side, so 48 left 36px for the whole 0..1 fader and a breakpoint's 11px grab
* disc covered a third of the axis. 72 leaves 60px, which is what makes a value
* aimable and two points at similar values separately grabbable.
*/
export const AUTOMATION_LANE_H = 48;
export const AUTOMATION_LANE_H = 72;
@@ -2,7 +2,7 @@
* Range operations over one automation lane.
*
* `replaceRange` is the only mutator every range feature (delete, shapes,
* paste, stretch) composes, and it carries the invariant that makes them safe:
* paste) composes, and it carries the invariant that makes them safe:
* the envelope OUTSIDE the selection never moves. It samples the lane at both
* edges first and pins anchor points there, so cutting the middle out of a
* ramp cannot reshape the rest of the clip.
@@ -76,6 +76,24 @@ export function replaceRange(input: {
return [...outside, ...edges, ...cappedInner].sort((a, b) => a.t - b.t);
}
/**
* Whether a breakpoint falls inside the selection box, edges included.
*
* The one rule three places need: what Delete removes, what the lane rings, and
* what a group drag moves. They have to agree a point drawn as caught but left
* behind by the drag is worse than either answer.
*
* Both axes, which is what makes a selection a box: a point at the right time but
* the wrong value is not in it. Values compare in the parameter's own units, and
* that is correct on a logarithmic axis too the mapping to screen is monotonic,
* so a box drawn around some pixels holds exactly the values it looks like it does.
*/
export function pointInSelection(
point: { t: number; v: number },
box: { t0: number; t1: number; v0: number; v1: number },
): boolean {
return point.t >= box.t0 && point.t <= box.t1 && point.v >= box.v0 && point.v <= box.v1;
}
/**
* Retime a selection: interior points scale proportionally into the new span,
* then replaceRange runs over the UNION of old and new spans growing eats
@@ -56,8 +56,11 @@ export interface UseAutomationEdgeStretchInput {
duration: number;
readOnly?: boolean | undefined;
/** Active selection on this lane, so its edges have something to grab. */
rangeSelection?: { t0: number; t1: number } | null | undefined;
onRangeSelect?: ((t0: number, t1: number) => void) | undefined;
rangeSelection?: { t0: number; t1: number; v0: number; v1: number } | null | undefined;
/** Whether the pointer is over a point the current selection contains. Such a
* press is a group drag, not a stretch see `arm`. */
pointInSelectionAt?: ((clientX: number, clientY: number) => boolean) | undefined;
onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;
onRangeClear?: (() => void) | undefined;
/** Value readout owned by the lane's gesture hook. */
onHint(text: string | null): void;
@@ -89,7 +92,7 @@ export interface UseAutomationEdgeStretchResult {
export function clampEdge(
edge: "t0" | "t1",
raw: number,
origin: { t0: number; t1: number },
origin: { t0: number; t1: number; v0: number; v1: number },
duration: number,
): number {
if (edge === "t0") {
@@ -108,6 +111,7 @@ export function useAutomationEdgeStretch({
duration,
readOnly,
rangeSelection,
pointInSelectionAt,
onRangeSelect,
onRangeClear,
onHint,
@@ -117,7 +121,7 @@ export function useAutomationEdgeStretch({
* points as they stood at arm time. */
const [drag, setDrag] = useState<{
edge: "t0" | "t1";
origin: { t0: number; t1: number };
origin: { t0: number; t1: number; v0: number; v1: number };
current: number;
points: HfAutomationPoint[];
} | null>(null);
@@ -158,6 +162,18 @@ export function useAutomationEdgeStretch({
if (readOnly || !rangeSelection) return false;
const edge = edgeAt(e.clientX);
if (!edge) return false;
// Selected CONTENT outranks the edge it sits on.
//
// #3207 had the opposite rule, and it was right for a time-only selection:
// every range operation leaves a breakpoint exactly on the edge it created,
// so a point-first rule made the second stretch of an edge resolve to a
// point-drag. A box selection changes the question — a point on the edge is
// now visibly INSIDE the selection, with the value axis saying so, and
// dragging selected content has to move it or the box means nothing.
//
// So the edge still stretches everywhere it is not also selected content,
// which is most of its length.
if (pointInSelectionAt?.(e.clientX, e.clientY)) return false;
e.preventDefault();
capturePointer(e);
setHover(false);
@@ -170,7 +186,7 @@ export function useAutomationEdgeStretch({
});
return true;
},
[readOnly, rangeSelection, edgeAt, lane],
[readOnly, rangeSelection, edgeAt, lane, pointInSelectionAt],
);
/** Preview the stretch: the partner edge stays put as the retime's anchor, and
@@ -190,7 +206,7 @@ export function useAutomationEdgeStretch({
const newT0 = edge === "t0" ? current : origin.t0;
const newT1 = edge === "t1" ? current : origin.t1;
onHint(`${newT0.toFixed(2)}s → ${newT1.toFixed(2)}s`);
onRangeSelect?.(newT0, newT1);
onRangeSelect?.(newT0, newT1, origin.v0, origin.v1);
commitPoints(
retimeRange({
lane: { target: lane.target, points },
@@ -221,7 +237,12 @@ export function useAutomationEdgeStretch({
}
crossed.current = false;
commitPoints(lane.points, true);
onRangeSelect?.(edge === "t0" ? current : origin.t0, edge === "t1" ? current : origin.t1);
onRangeSelect?.(
edge === "t0" ? current : origin.t0,
edge === "t1" ? current : origin.t1,
origin.v0,
origin.v1,
);
}, [drag, onHint, onRangeClear, commitPoints, lane, onRangeSelect]);
const cancel = useCallback((): void => {
@@ -234,7 +255,7 @@ export function useAutomationEdgeStretch({
// A live write is a preview, so putting the snapshot back through the same
// channel is the whole revert — there is nothing persisted to undo.
commitPoints(points, false);
onRangeSelect?.(origin.t0, origin.t1);
onRangeSelect?.(origin.t0, origin.t1, origin.v0, origin.v1);
}, [drag, onHint, commitPoints, onRangeSelect]);
const updateHover = useCallback(
@@ -4,7 +4,7 @@
* Its own hook because the lane component sits at the studio's file ceiling and
* because these are the parts worth testing on their own: which of a press,
* a drag and a modifier resolves to moving a point, bending a segment,
* stretching a selection's edge, or nothing at all.
* drawing a selection box, or nothing at all.
*
* Modifiers follow Ableton's, since that is the muscle memory an automation lane
* inherits: Shift locks a drag to one axis and fines the value down, Alt over a
@@ -13,20 +13,21 @@
import { useCallback, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
import type { AutomationRange, HfAutomationLane } from "@hyperframes/core/audio-automation";
import {
applyShiftConstraint,
curveForDrag,
formatValue,
GRAB_PX,
POINT_MERGE_SEC,
snapLaneTime,
} from "./automationLaneGeometry";
import { curveForDrag, formatValue, GRAB_PX, POINT_MERGE_SEC } from "./automationLaneGeometry";
import { pointInSelection } from "./automationLaneSelection";
import { capturePointer } from "./automationLanePointer";
import { useAutomationEdgeStretch } from "./useAutomationEdgeStretch";
import { useAutomationRangeDrag } from "./useAutomationRangeDrag";
import {
armGroupDrag,
computeGroupMove,
computeSinglePointMove,
type GroupDragSnapshot,
type ShiftAxis,
} from "./automationLaneDragMath";
/** Snap radius in clip seconds. Tight on purpose: a lane is often a few seconds
* wide, where a generous radius makes a point unplaceable between two beats. */
const SNAP_SEC = 0.04;
/** How far a press may travel and still count as a click rather than a drag. */
const CLICK_SLOP_PX = 3;
/** A point's position, or the origin when the index no longer resolves. */
function originOf(point: HfAutomationLane["points"][number] | undefined): { t: number; v: number } {
@@ -49,12 +50,12 @@ export interface UseAutomationLaneGesturesInput {
snapTimes?: readonly number[] | undefined;
readOnly?: boolean | undefined;
onSelect?: (() => void) | undefined;
/** Live range-select callbacks; absent = background drags do nothing (read-only lanes). */
onRangeSelect?: ((t0: number, t1: number) => void) | undefined;
/** Live box-select callbacks; absent = background drags do nothing (read-only lanes). */
onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;
onRangeClear?: (() => void) | undefined;
duration: number; // clamp bound for range endpoints
/** Active selection on this lane, so its edges have something to grab. */
rangeSelection?: { t0: number; t1: number } | null | undefined;
duration: number; // clamp bound for box endpoints
/** Active selection box on this lane, so a press inside it can drag its points. */
rangeSelection?: { t0: number; t1: number; v0: number; v1: number } | null | undefined;
}
export interface UseAutomationLaneGesturesResult {
@@ -62,21 +63,20 @@ export interface UseAutomationLaneGesturesResult {
dragIndex: number | null;
/** Segment being bent, identified by the point that owns its curve. */
curveIndex: number | null;
/** Edge being stretched, for the cursor. */
edgeDrag: "t0" | "t1" | null;
/** Whether the pointer sits over a stretch handle with no gesture live
* the col-resize cursor hint before a press commits to the drag. */
edgeHover: boolean;
/** Value readout to show while a gesture is live. */
hint: string | null;
hitIndex(clientX: number, clientY: number): number | null;
segmentIndex(clientX: number, clientY: number): number | null;
onPointerDown(e: ReactPointerEvent<SVGSVGElement>): void;
onPointerMove(e: ReactPointerEvent<SVGSVGElement>): void;
endDrag(e: ReactPointerEvent<SVGSVGElement>): void;
/** The browser took the gesture away (`pointercancel`): a stretch reverts
* rather than persisting whatever partial retime it had reached. */
/** Edge being stretched, for the cursor. Null when no stretch is live. */
edgeDrag: "t0" | "t1" | null;
/** Pointer resting over a stretch handle with nothing armed, so the cursor
* can advertise the gesture before it starts. */
edgeHover: boolean;
/** `pointercancel`: a live stretch reverts; anything else ends normally. */
cancelDrag(e: ReactPointerEvent<SVGSVGElement>): void;
endDrag(e: ReactPointerEvent<SVGSVGElement>): void;
/** Adds a point, opens the value field on one, or straightens a segment. */
onDoubleClick(e: ReactPointerEvent<SVGSVGElement>): void;
/** The point whose value is being typed, and the text so far. */
@@ -105,16 +105,19 @@ export function useAutomationLaneGestures({
const [dragIndex, setDragIndex] = useState<number | null>(null);
const [curveIndex, setCurveIndex] = useState<number | null>(null);
const [hint, setHint] = useState<string | null>(null);
/** Where a point drag began, so Shift can lock an axis and fine the value. */
const dragOrigin = useRef<{ t: number; v: number } | null>(null);
/** Point whose value is being typed, and the text so far. */
const [editing, setEditing] = useState<{ index: number; text: string } | null>(null);
/** A background drag in progress: its start and live end, in clip seconds. */
const [rangeDrag, setRangeDrag] = useState<{ from: number; to: number } | null>(null);
/** Whether the live drag has crossed the pixel threshold that turns a press
* into an actual range, rather than a click that should just clear one. */
const rangeCrossed = useRef(false);
/**
* Stretching a selection by one of its time edges (#3207).
*
* Kept as its own module rather than inlined: it is a fifth mutually-exclusive
* gesture on a hook already at the file's complexity budget, and it owns a
* snapshot the other gestures have no use for `retimeRange` scales against
* the bounds captured when the drag armed, so running it against the live
* draft would compound the scale factor on every pointermove.
*
* Only the time edges stretch. The value extent rides through untouched, which
* is what keeps this the same gesture it was before the selection became a box.
*/
const stretch = useAutomationEdgeStretch({
getBox,
lane,
@@ -125,10 +128,74 @@ export function useAutomationLaneGestures({
duration,
readOnly,
rangeSelection,
// The stretch stands down on a press that lands on selected content — that
// gesture belongs to the group drag below.
pointInSelectionAt: (clientX, clientY) => {
if (!rangeSelection) return false;
const i = hitIndex(clientX, clientY);
const p = i === null ? null : lane.points[i];
return p ? pointInSelection(p, rangeSelection) : false;
},
onRangeSelect,
onRangeClear,
onHint: setHint,
});
/** Where a point drag began, so Shift can lock an axis and fine the value. */
const dragOrigin = useRef<{ t: number; v: number } | null>(null);
/**
* The set a group drag moves, snapshotted on the press.
*
* Snapshotted rather than recomputed per move for two reasons: every point is
* moving, so "which ones are selected" has to mean what it meant when the
* gesture started, and the deltas have to accumulate from the original
* positions or a rounded move would drift on every pointermove.
*/
const groupDrag = useRef<GroupDragSnapshot | null>(null);
/** Point whose value is being typed, and the text so far. */
const [editing, setEditing] = useState<{ index: number; text: string } | null>(null);
const rangeDrag = useAutomationRangeDrag({
pointAt,
xOf,
yOf,
duration,
snapTimes,
onRangeSelect,
onRangeClear,
});
/** Where a press on a point landed, and whether it has travelled since. A press
* that goes nowhere is a click, which is a different gesture from a drag even
* though both start the same way see the Shift branch in `endDrag`. */
const pressAt = useRef<{ x: number; y: number } | null>(null);
const pressTravelled = useRef(false);
/**
* The axis Shift locked, decided on the gesture's first travel and held until
* the drag ends or Shift is let go. Deciding per event followed whichever way
* the last move leaned, so a drifting hand unlocked the axis mid-drag.
*/
const shiftAxis = useRef<ShiftAxis>(null);
// The value field's own handlers, above the gestures that close it: a press on the
// lane applies whatever was typed, so onPointerDown lists commitEdit as a
// dependency and cannot be declared before it.
const setEditingText = useCallback((text: string): void => {
setEditing((current) => (current ? { index: current.index, text } : null));
}, []);
const cancelEdit = useCallback((): void => setEditing(null), []);
/** Apply a typed value, or drop the edit when it is not a number. */
const commitEdit = useCallback((): void => {
const active = editing;
setEditing(null);
if (!active) return;
const typed = Number(active.text);
if (!Number.isFinite(typed)) return;
const clamped = Math.min(range.max, Math.max(range.min, typed));
commitPoints(
lane.points.map((p, i) => (i === active.index ? { ...p, v: clamped } : p)),
true,
);
}, [editing, lane, range, commitPoints]);
/** Index of a point under the pointer, or null. */
const hitIndex = useCallback(
@@ -172,25 +239,6 @@ export function useAutomationLaneGestures({
[hitIndex, segmentIndex],
);
/**
* What a press on the lane's empty background arms: a new range selection,
* and only when a caller wants to hear about one a read-only lane never
* reaches here at all.
*/
const armRangeDrag = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (!onRangeSelect) return;
e.preventDefault();
capturePointer(e);
const raw = pointAt(e.clientX, e.clientY).t;
const clamped = Math.min(duration, Math.max(0, raw));
const t = e.altKey ? clamped : snapLaneTime(clamped, snapTimes ?? [], SNAP_SEC);
rangeCrossed.current = false;
setRangeDrag({ from: t, to: t });
},
[onRangeSelect, pointAt, duration, snapTimes],
);
const onPointerDown = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (e.button !== 0) return;
@@ -198,21 +246,30 @@ export function useAutomationLaneGestures({
// timeline's own gesture (scrub / marquee / clip drag), which then eats the
// rest of the sequence — including the second half of a double-click.
e.stopPropagation();
// A press anywhere on the lane closes the value field, applying what was
// typed — the same thing Enter and a blur do. It cannot rely on the blur: the
// gesture branches below call preventDefault to keep the timeline from
// scrubbing, and that suppresses the focus change the blur would come from,
// so the field sat open until Enter however far away the next click landed.
if (editing) commitEdit();
if (readOnly) {
// The lane sits below the clip bar, so the timeline's selection handler
// never sees this press; selecting here is the only way in.
// never sees this press; selecting here is the only way in. The press then
// goes on to arm a range drag rather than being spent on the selection: a
// press that only selected made the first drag over any lane do nothing
// visible, so a range took two gestures and looked broken on the first.
onSelect?.();
rangeDrag.arm(e);
return;
}
// An active selection's edge outranks a point sitting on it. Every range
// operation — stretch, delete, shape insert — leaves a breakpoint exactly
// on the edge it just created, so a point-first rule meant the second
// stretch of the same edge resolved to a point-drag and the feature was
// not repeatable. Clear the selection to reach that point again.
// operation leaves a breakpoint exactly on the edge it just created, so a
// point-first rule made the second stretch of the same edge resolve to a
// point-drag — which is how the feature silently stopped working.
if (stretch.arm(e)) return;
const gesture = gestureAt(e);
if (!gesture) {
armRangeDrag(e);
rangeDrag.arm(e);
return;
}
e.preventDefault();
@@ -222,9 +279,27 @@ export function useAutomationLaneGestures({
return;
}
dragOrigin.current = originOf(lane.points[gesture.index]);
// Pressing one of a selected set drags the whole set. Pressing a point
// outside the selection is an ordinary single-point drag, selection or no.
groupDrag.current = armGroupDrag(lane, lane.points[gesture.index], rangeSelection);
pressAt.current = { x: e.clientX, y: e.clientY };
pressTravelled.current = false;
setDragIndex(gesture.index);
},
[gestureAt, lane, readOnly, onSelect, armRangeDrag, stretch],
[
gestureAt,
lane,
readOnly,
onSelect,
rangeDrag,
editing,
commitEdit,
// The press decides whether it starts a group drag, so it has to see the
// selection as it is now — captured stale, a point pressed straight after
// selecting a range read the previous selection, or none.
rangeSelection,
stretch,
],
);
/** Bend the segment under the pointer, which is what Alt-dragging the line does. */
@@ -235,74 +310,103 @@ export function useAutomationLaneGestures({
const b = lane.points[curveIndex + 1];
if (!a || !b) return;
const { t, v } = pointAt(clientX, clientY);
const curve = curveForDrag({ range, a, b, t, v });
if (curve === null) return;
setHint(`curve ${curve.toFixed(2)}`);
const bend = curveForDrag({ range, a, b, t, v });
if (bend === null) return;
// Read out where the bend now sits along the segment, which is what the
// pointer is choosing: a percentage means more here than a curve exponent
// the author never types.
setHint(`bend ${Math.round(bend.viaX * 100)}%`);
commitPoints(
lane.points.map((p, i) => (i === curveIndex ? { ...p, curve } : p)),
// `curve` is dropped rather than carried: the via point supersedes it, and
// leaving a stale exponent behind would make the segment's shape depend on
// which of the two the reader happened to honour.
lane.points.map((p, i) =>
i === curveIndex ? { ...p, curve: undefined, viaX: bend.viaX, viaY: bend.viaY } : p,
),
false,
);
},
[curveIndex, lane, pointAt, range, commitPoints],
);
/**
* Move a selected set by one delta, taken from the point under the pointer.
*
* The whole group has to stop when its first member reaches a boundary, not
* each point on its own: clamping individually squashes the shape flat against
* the edge, and the gesture is meant to preserve it. Deltas are in the
* parameter's own units, so on a logarithmic axis a group moves by Hz rather
* than by octaves the same as dragging one point does.
*/
const moveGroup = useCallback(
(e: ReactPointerEvent<SVGSVGElement>, group: GroupDragSnapshot): void => {
const { points, selection, hint } = computeGroupMove({
group,
raw: pointAt(e.clientX, e.clientY),
shiftKey: e.shiftKey,
altKey: e.altKey,
range,
duration,
snapTimes,
xOf,
yOf,
});
onRangeSelect?.(selection.t0, selection.t1, selection.v0, selection.v1);
setHint(hint);
commitPoints(points, false);
},
[commitPoints, duration, onRangeSelect, pointAt, range, snapTimes, xOf, yOf],
);
/** Move the point being dragged, honouring the modifiers held with it. */
const movePoint = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (dragIndex === null) return;
const raw = pointAt(e.clientX, e.clientY);
const origin = dragOrigin.current;
let { t, v } =
e.shiftKey && origin ? applyShiftConstraint({ range, origin, raw, xOf, yOf }) : raw;
// Shift is a deliberate free-hand move as much as Alt is, so neither snaps.
if (!e.altKey && !e.shiftKey) {
const neighbours = lane.points.filter((_, i) => i !== dragIndex).map((p) => p.t);
t = snapLaneTime(t, [...(snapTimes ?? []), ...neighbours], SNAP_SEC);
const group = groupDrag.current;
if (group) {
moveGroup(e, group);
return;
}
if (!e.shiftKey) shiftAxis.current = null;
const {
t,
v,
shiftAxis: nextAxis,
} = computeSinglePointMove({
raw: pointAt(e.clientX, e.clientY),
origin: dragOrigin.current,
shiftKey: e.shiftKey,
altKey: e.altKey,
shiftAxis: shiftAxis.current,
range,
duration,
snapTimes,
lane,
dragIndex,
xOf,
yOf,
});
shiftAxis.current = nextAxis;
const next = lane.points.map((p, i) => (i === dragIndex ? { ...p, t, v } : p));
// Re-sort so dragging a point past a neighbour behaves, and keep the
// dragged one addressable by following where it landed.
const moved = next[dragIndex];
next.sort((a, b) => a.t - b.t);
if (moved) setDragIndex(next.indexOf(moved));
setHint(`${formatValue(range, v)} @ ${t.toFixed(2)}s`);
commitPoints(next, false);
},
[dragIndex, lane, pointAt, range, commitPoints, snapTimes, xOf, yOf],
);
/** Update the live range-drag as the pointer moves, firing `onRangeSelect`
* once it has covered enough pixels to count as an actual range rather
* than a click that should just clear one. */
const moveRangeDrag = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (rangeDrag === null) return;
const raw = pointAt(e.clientX, e.clientY).t;
const clamped = Math.min(duration, Math.max(0, raw));
const t = e.altKey ? clamped : snapLaneTime(clamped, snapTimes ?? [], SNAP_SEC);
setRangeDrag({ from: rangeDrag.from, to: t });
if (Math.abs(xOf(t) - xOf(rangeDrag.from)) <= 3) return;
rangeCrossed.current = true;
onRangeSelect?.(Math.min(rangeDrag.from, t), Math.max(rangeDrag.from, t));
},
[rangeDrag, pointAt, duration, snapTimes, xOf, onRangeSelect],
[dragIndex, duration, lane, pointAt, range, commitPoints, snapTimes, xOf, yOf, moveGroup],
);
const onPointerMove = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (stretch.edge !== null) {
e.stopPropagation();
// A capture lost without a `pointercancel` — the child it was taken on
// unmounted, or the browser handed the gesture elsewhere — leaves no
// gesture-end event at all, and every later hover would keep retiming.
// A move with no button held is the only signal left that it is over.
// A button-less move means the browser handed the gesture back without a
// pointerup — revert rather than leaving a half-applied retime.
if (e.buttons === 0) stretch.cancel();
else stretch.move(e);
return;
}
if (rangeDrag !== null) {
if (rangeDrag.dragging) {
e.stopPropagation();
moveRangeDrag(e);
rangeDrag.move(e);
return;
}
if (curveIndex === null && dragIndex === null) {
@@ -310,20 +414,16 @@ export function useAutomationLaneGestures({
return;
}
e.stopPropagation();
const from = pressAt.current;
if (from && Math.hypot(e.clientX - from.x, e.clientY - from.y) > CLICK_SLOP_PX) {
pressTravelled.current = true;
}
if (curveIndex !== null) bendSegment(e.clientX, e.clientY);
else movePoint(e);
},
[stretch, rangeDrag, moveRangeDrag, curveIndex, dragIndex, bendSegment, movePoint],
[rangeDrag, curveIndex, dragIndex, bendSegment, movePoint, stretch],
);
/** A sub-threshold press clears the selection rather than leaving a
* zero-width one behind. */
const finishRangeDrag = useCallback((): void => {
if (!rangeCrossed.current) onRangeClear?.();
rangeCrossed.current = false;
setRangeDrag(null);
}, [onRangeClear]);
const endDrag = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (stretch.edge !== null) {
@@ -331,25 +431,42 @@ export function useAutomationLaneGestures({
stretch.finish();
return;
}
if (rangeDrag !== null) {
if (rangeDrag.dragging) {
e.stopPropagation();
finishRangeDrag();
rangeDrag.finish();
return;
}
if (dragIndex === null && curveIndex === null) return;
e.stopPropagation();
const index = dragIndex;
const shiftClicked = index !== null && e.shiftKey && !pressTravelled.current;
setDragIndex(null);
setCurveIndex(null);
dragOrigin.current = null;
groupDrag.current = null;
shiftAxis.current = null;
pressAt.current = null;
setHint(null);
// Shift+click removes the point. Decided on RELEASE, not on the press: Shift
// held through a drag is the axis lock, and acting on the press would take
// that gesture away. A press that never travelled was a click.
if (shiftClicked) {
commitPoints(
lane.points.filter((_, i) => i !== index),
true,
);
return;
}
commitPoints(lane.points, true);
},
[stretch, rangeDrag, finishRangeDrag, curveIndex, dragIndex, lane, commitPoints],
[rangeDrag, curveIndex, dragIndex, lane, commitPoints, stretch],
);
/** `pointercancel`: the browser abandoned the gesture, so a stretch reverts
* instead of persisting the partial retime `endDrag` would have committed.
* Anything else ends the way a release ends it. */
/**
* `pointercancel`: the browser abandoned the gesture, so a stretch reverts
* rather than persisting the partial retime `endDrag` would have committed.
* Anything else ends the way a release ends it.
*/
const cancelDrag = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (stretch.edge !== null) {
@@ -399,38 +516,18 @@ export function useAutomationLaneGestures({
[lane, pointAt, commitPoints, readOnly, hitIndex, segmentIndex],
);
const setEditingText = useCallback((text: string): void => {
setEditing((current) => (current ? { index: current.index, text } : null));
}, []);
const cancelEdit = useCallback((): void => setEditing(null), []);
/** Apply a typed value, or drop the edit when it is not a number. */
const commitEdit = useCallback((): void => {
const active = editing;
setEditing(null);
if (!active) return;
const typed = Number(active.text);
if (!Number.isFinite(typed)) return;
const clamped = Math.min(range.max, Math.max(range.min, typed));
commitPoints(
lane.points.map((p, i) => (i === active.index ? { ...p, v: clamped } : p)),
true,
);
}, [editing, lane, range, commitPoints]);
return {
dragIndex,
curveIndex,
edgeDrag: stretch.edge,
edgeHover: stretch.hover,
cancelDrag,
hint,
hitIndex,
segmentIndex,
onPointerDown,
onPointerMove,
endDrag,
cancelDrag,
onDoubleClick,
editing,
setEditingText,
@@ -78,6 +78,9 @@ describe("useAutomationLanes", () => {
});
it("gives one lane per automated parameter, in draw order", () => {
// Draw order is the spectrum: a lane belonging to an effect that sits at a
// frequency is placed by that frequency, high first, and lanes with none —
// the track's own volume — follow in written order.
const automation = JSON.stringify({
version: 1,
lanes: [
@@ -87,7 +90,7 @@ describe("useAutomationLanes", () => {
],
});
const bound = bindOnce(el({ automation, fxChain: CHAIN }));
expect(bound.lanes.map((l) => l.target)).toEqual(["volume", "fx.n2.frequency", "fx.n2.q"]);
expect(bound.lanes.map((l) => l.target)).toEqual(["fx.n2.frequency", "fx.n2.q", "volume"]);
});
it("reads an element with neither attribute as an empty volume lane", () => {
@@ -10,7 +10,7 @@
* read only, which is also what stops a stray drag from editing the wrong track.
*/
import { useCallback, useMemo } from "react";
import { useCallback, useMemo, useRef } from "react";
import {
HF_AUDIO_AUTOMATION_ATTR,
serializeAutomation,
@@ -27,6 +27,7 @@ import { getTimelineElementIdentity } from "../lib/timelineElementHelpers";
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
import type { AutomationSelection } from "../store/automationSelectionSlice";
import { elementAutomation, elementFxChain } from "./automationLaneData";
import { createAutomationGestureKeys } from "./automationGestureKeys";
export interface AutomationLaneBinding {
automation: HfAutomation;
@@ -54,12 +55,13 @@ export interface AutomationLaneBinding {
* element's key; it lags only in the window a non-gesture caller can hit.
*/
commitTargetKey: string | null;
/** This element's active time selection, or null if none / it belongs to a
/** This element's active selection box, or null if none / it belongs to a
* different element. */
selection: AutomationSelection | null;
/** Live write while dragging a range on the given lane; does not persist
* the selection is ephemeral store state, not part of the composition. */
onRangeSelect(target: string, t0: number, t1: number): void;
/** Live write while dragging a selection box on the given lane; does not
* persist the selection is ephemeral store state, not part of the
* composition. */
onRangeSelect(target: string, t0: number, t1: number, v0: number, v1: number): void;
onRangeClear(): void;
}
@@ -68,6 +70,9 @@ export interface UseAutomationLanesResult {
}
export function useAutomationLanes(): UseAutomationLanesResult {
// One per hook instance, held across renders: a gesture spans many commits and
// they all have to record under the same key for undo to take the whole drag.
const gestureKeys = useRef(createAutomationGestureKeys());
// 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();
@@ -97,14 +102,32 @@ export function useAutomationLanes(): UseAutomationLanesResult {
const write = (next: HfAutomation, persist: boolean): void => {
if (!domEdit || !isSelected) return;
const value = next.lanes.length > 0 ? serializeAutomation(next) : "";
// Every write of one gesture under one key, so undo takes back the whole
// drag rather than the last fragment history happened to keep.
const coalesce = persist ? gestureKeys.current.commit() : gestureKeys.current.live();
// Quiet, not the refreshing commit: releasing a dragged point used to
// reload the preview, which restarts every playing track — the same chop
// the live write during the drag exists to avoid. Quiet still persists
// and still resyncs the selection, so the next edit sees this one.
if (persist) void domEdit.handleDomAttributeQuietCommit(HF_AUDIO_AUTOMATION_ATTR, value);
if (persist) {
void domEdit.handleDomAttributeQuietCommit(HF_AUDIO_AUTOMATION_ATTR, value, coalesce);
}
// 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);
else {
// Preview only, because a gesture writes on every pointermove: the
// preview and the running audio follow the pointer, and the release
// below is the one write that reaches the file and the undo stack.
void domEdit.handleDomAttributeLiveCommit(
HF_AUDIO_AUTOMATION_ATTR,
value || null,
undefined,
{
coalesce,
previewOnly: true,
},
);
}
};
return {
@@ -121,9 +144,15 @@ export function useAutomationLanes(): UseAutomationLanesResult {
readOnly: !domEdit || !isSelected,
commitTargetKey: domEdit ? commitTargetKey : null,
selection: automationSelection?.elementKey === elementKey ? automationSelection : null,
onRangeSelect: (target, t0, t1) => {
if (!domEdit || !isSelected) return;
setAutomationSelection({ elementKey, target, t0, t1 });
// Not gated on `isSelected`, unlike the writes above. A selection is
// ephemeral store state, and the drag that draws one on a read-only lane is
// the same press that selects the clip — refusing it here meant the first
// drag on a lane silently did nothing and the author had to drag again.
// Nothing can be written through it while the lane is read-only: every
// consumer resolves the binding again and finds `readOnly`.
onRangeSelect: (target, t0, t1, v0, v1) => {
if (!domEdit) return;
setAutomationSelection({ elementKey, target, t0, t1, v0, v1 });
},
onRangeClear: () => clearAutomationSelection(),
};
@@ -0,0 +1,114 @@
/**
* Drawing a new selection box over an automation lane's empty background.
*
* Its own module for the same reason useAutomationEdgeStretch is: a sixth
* mutually-exclusive gesture on a hook already at the file's complexity
* budget, and one with no use for anything the others snapshot.
*/
import { useCallback, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
import { snapLaneTime } from "./automationLaneGeometry";
import { capturePointer } from "./automationLanePointer";
import { SNAP_SEC } from "./automationLaneDragMath";
export interface UseAutomationRangeDragInput {
pointAt(clientX: number, clientY: number): { t: number; v: number };
xOf(t: number): number;
yOf(v: number): number;
duration: number;
snapTimes?: readonly number[] | undefined;
onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;
onRangeClear?: (() => void) | undefined;
}
export interface UseAutomationRangeDragResult {
/** Whether a box is being drawn right now. */
dragging: boolean;
/** Arms a new box at the press, or declines when no caller wants to hear
* about one (a read-only lane). */
arm(e: ReactPointerEvent<SVGSVGElement>): void;
move(e: ReactPointerEvent<SVGSVGElement>): void;
/** A sub-threshold press clears the selection rather than leaving a
* zero-width one behind. */
finish(): void;
}
/**
* A corner of the selection box under the pointer.
*
* Time is clamped to the clip and snaps to the grid, because the box's span is
* also what a shape insert or a paste acts over and those want beat-aligned
* edges. The value is taken as it lies: there is no grid on a parameter axis,
* and rounding a dB bound would move which points the box catches.
*/
function boxCornerAt(
e: ReactPointerEvent<SVGSVGElement>,
input: Pick<UseAutomationRangeDragInput, "pointAt" | "duration" | "snapTimes">,
): { t: number; v: number } {
const raw = input.pointAt(e.clientX, e.clientY);
const clamped = Math.min(input.duration, Math.max(0, raw.t));
return {
t: e.altKey ? clamped : snapLaneTime(clamped, input.snapTimes ?? [], SNAP_SEC),
v: raw.v,
};
}
export function useAutomationRangeDrag({
pointAt,
xOf,
yOf,
duration,
snapTimes,
onRangeSelect,
onRangeClear,
}: UseAutomationRangeDragInput): UseAutomationRangeDragResult {
const [box, setBox] = useState<{
from: { t: number; v: number };
to: { t: number; v: number };
} | null>(null);
/** Whether the live drag has crossed the pixel threshold that turns a press
* into an actual box, rather than a click that should just clear one. */
const crossed = useRef(false);
const arm = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (!onRangeSelect) return;
e.preventDefault();
capturePointer(e);
const corner = boxCornerAt(e, { pointAt, duration, snapTimes });
crossed.current = false;
setBox({ from: corner, to: corner });
},
[onRangeSelect, pointAt, duration, snapTimes],
);
const move = useCallback(
(e: ReactPointerEvent<SVGSVGElement>): void => {
if (box === null) return;
const to = boxCornerAt(e, { pointAt, duration, snapTimes });
const { from } = box;
setBox({ from, to });
const travelled = Math.max(
Math.abs(xOf(to.t) - xOf(from.t)),
Math.abs(yOf(to.v) - yOf(from.v)),
);
if (travelled <= 3) return;
crossed.current = true;
onRangeSelect?.(
Math.min(from.t, to.t),
Math.max(from.t, to.t),
Math.min(from.v, to.v),
Math.max(from.v, to.v),
);
},
[box, pointAt, duration, snapTimes, xOf, yOf, onRangeSelect],
);
const finish = useCallback((): void => {
if (!crossed.current) onRangeClear?.();
crossed.current = false;
setBox(null);
}, [onRangeClear]);
return { dragging: box !== null, arm, move, finish };
}
@@ -0,0 +1,83 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it } from "vitest";
import { syncStoredAutomationFromPreview } from "./automationStoreSync";
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
const TWO_POINTS = '{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1}]}]}';
const RESTORED =
'{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1},{"t":4,"v":0}]}]}';
const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({
id: "bgm",
key: "bgm",
tag: "audio",
start: 0,
duration: 10,
track: 1,
domId: "bgm",
...over,
});
/** A stand-in preview document carrying the attributes an undo would have written. */
function previewWith(attrs: Record<string, string>): Document {
const doc = document.implementation.createHTMLDocument("preview");
const audio = doc.createElement("audio");
audio.id = "bgm";
for (const [name, value] of Object.entries(attrs)) audio.setAttribute(name, value);
doc.body.append(audio);
return doc;
}
beforeEach(() => {
usePlayerStore.getState().reset();
});
describe("syncStoredAutomationFromPreview", () => {
it("reads back an envelope an undo restored on the preview", () => {
// The bug: a soft undo patches the preview document and re-runs the timeline, but
// the store keeps its own copy of the attributes and that copy is what a lane
// draws — so an undone delete stayed invisible until the page was reloaded.
usePlayerStore.setState({ elements: [el({ automation: TWO_POINTS })] });
syncStoredAutomationFromPreview(previewWith({ "data-automation": RESTORED }));
expect(usePlayerStore.getState().elements[0]?.automation).toBe(RESTORED);
});
it("reads back an undone FX chain too, since a lane's targets come from it", () => {
const chain = '{"version":1,"nodes":[{"type":"lowpass","id":"n1","params":{}}]}';
usePlayerStore.setState({ elements: [el()] });
syncStoredAutomationFromPreview(previewWith({ "data-fx-chain": chain }));
expect(usePlayerStore.getState().elements[0]?.fxChain).toBe(chain);
});
it("clears an attribute the undo removed", () => {
usePlayerStore.setState({ elements: [el({ automation: TWO_POINTS })] });
syncStoredAutomationFromPreview(previewWith({}));
expect(usePlayerStore.getState().elements[0]?.automation).toBeUndefined();
});
it("finds the node by data-hf-id when the dom id does not match", () => {
// Studio stamps hf-ids; an element discovered under a suffixed dom id still has
// to resolve, or the sync silently skips it.
const doc = document.implementation.createHTMLDocument("preview");
const audio = doc.createElement("audio");
audio.setAttribute("data-hf-id", "hf-snao");
audio.setAttribute("data-automation", RESTORED);
doc.body.append(audio);
usePlayerStore.setState({ elements: [el({ domId: "bgm-2", hfId: "hf-snao" })] });
syncStoredAutomationFromPreview(doc);
expect(usePlayerStore.getState().elements[0]?.automation).toBe(RESTORED);
});
it("keeps the same array when nothing changed, so nothing re-renders", () => {
usePlayerStore.setState({ elements: [el({ automation: RESTORED })] });
const before = usePlayerStore.getState().elements;
syncStoredAutomationFromPreview(previewWith({ "data-automation": RESTORED }));
expect(usePlayerStore.getState().elements).toBe(before);
});
it("does nothing without a preview document", () => {
usePlayerStore.setState({ elements: [el({ automation: TWO_POINTS })] });
syncStoredAutomationFromPreview(null);
expect(usePlayerStore.getState().elements[0]?.automation).toBe(TWO_POINTS);
});
});
@@ -0,0 +1,56 @@
/**
* Keeping the player store's automation attributes true.
*
* The store is what a lane draws from, and it is populated by element discovery a
* message from the preview runtime, which only arrives on load. Anything that edits
* an envelope afterwards writes to the preview document and the source file, and the
* store would go on holding the value it was born with until a reload.
*
* One reader, called from the two places a change lands: the resync every dom-edit
* attribute commit already runs, and the soft restore an undo or redo applies. It
* reads the preview rather than being told, because those callers know a file
* changed, not which attribute and because three separate writers shipped without
* remembering to sync, which is what a single sink prevents.
*/
import { HF_AUDIO_AUTOMATION_ATTR } from "@hyperframes/core/audio-automation";
import { HF_AUDIO_FX_ATTR } from "@hyperframes/core/audio-fx";
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
/** The preview node an element stands for, by dom id and then by `data-hf-id`. */
function previewNodeFor(doc: Document, element: TimelineElement): Element | null {
const domId = element.domId ?? element.id;
const byId = domId ? doc.getElementById(domId) : null;
if (byId) return byId;
return element.hfId ? doc.querySelector(`[data-hf-id="${element.hfId}"]`) : null;
}
/**
* Re-read every element's automation and FX-chain attributes from the preview
* document, for a change that reached the DOM without going through this store.
*
* That is undo and redo. A soft restore patches the reverted attributes onto the
* live preview and re-runs the timeline deliberately, so the frame does not blank
* but the store it does not touch is the one the lanes read, so an undone delete
* stayed invisible until a reload. A full restore already clears the store and waits
* for discovery, so it needs nothing from here.
*
* Reads rather than being told: an undo restores whole files, so the attribute it
* reverted is only known by looking.
*/
export function syncStoredAutomationFromPreview(doc: Document | null | undefined): void {
if (!doc) return;
usePlayerStore.setState((state) => {
let changed = false;
const elements = state.elements.map((element) => {
const node = previewNodeFor(doc, element);
if (!node) return element;
const automation = node.getAttribute(HF_AUDIO_AUTOMATION_ATTR) ?? undefined;
const fxChain = node.getAttribute(HF_AUDIO_FX_ATTR) ?? undefined;
if (automation === element.automation && fxChain === element.fxChain) return element;
changed = true;
return { ...element, automation, fxChain };
});
return changed ? { elements } : {};
});
}
@@ -2,12 +2,28 @@ import { describe, expect, it } from "vitest";
import { usePlayerStore } from "./playerStore";
describe("automationSelectionSlice", () => {
it("stores one ordered selection and clears it", () => {
it("stores one ordered selection box and clears it", () => {
const store = usePlayerStore.getState();
store.setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 1 });
// Dragged up and to the left: both axes arrive backwards.
store.setAutomationSelection({
elementKey: "bgm",
target: "volume",
t0: 2,
t1: 1,
v0: 0.8,
v1: 0.3,
});
const sel = usePlayerStore.getState().automationSelection;
// Ordered on write, so every consumer can assume t0 < t1.
expect(sel).toEqual({ elementKey: "bgm", target: "volume", t0: 1, t1: 2 });
// Ordered on write, so every consumer can assume t0 <= t1 and v0 <= v1 —
// which is what lets a point test be two range checks rather than four.
expect(sel).toEqual({
elementKey: "bgm",
target: "volume",
t0: 1,
t1: 2,
v0: 0.3,
v1: 0.8,
});
usePlayerStore.getState().clearAutomationSelection();
expect(usePlayerStore.getState().automationSelection).toBeNull();
});
@@ -1,5 +1,5 @@
/**
* The active time selection on one automation lane.
* The active selection box on one automation lane.
*
* A store slice, not lane-local state, for the same reason keyframe selection
* is one: Delete/copy/paste handlers and the shape menu live outside the lane
@@ -13,9 +13,19 @@ export interface AutomationSelection {
elementKey: string;
/** Lane target: "volume" or "fx.<nodeId>.<param>". */
target: string;
/** Clip-local seconds; always t0 < t1 (ordered on write). */
/** Clip-local seconds; always t0 <= t1 (ordered on write). */
t0: number;
t1: number;
/**
* The box's value bounds, in the parameter's own units; always v0 <= v1.
*
* What makes the selection a box rather than a time span: a point is caught
* only if it falls inside both axes. Span operations copy, paste, shape
* insert, simplify still read t0/t1 alone, because they act on the envelope
* over a stretch of time rather than on a set of breakpoints.
*/
v0: number;
v1: number;
}
export interface AutomationSelectionSlice {
@@ -31,7 +41,13 @@ export function createAutomationSelectionSlice(
automationSelection: null,
setAutomationSelection: (sel) =>
set({
automationSelection: sel.t0 <= sel.t1 ? sel : { ...sel, t0: sel.t1, t1: sel.t0 },
automationSelection: {
...sel,
t0: Math.min(sel.t0, sel.t1),
t1: Math.max(sel.t0, sel.t1),
v0: Math.min(sel.v0, sel.v1),
v1: Math.max(sel.v0, sel.v1),
},
}),
clearAutomationSelection: () => set({ automationSelection: null }),
};