Skip to content

Write HTML. Render video. Built for agents.

feat(studio): retime and edge-stretch an automation selection (#3207)

Vance Ingalls120ea37c2fbd
diff --git a/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx b/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx
index a7f57d4b68..f8ab1a3d76 100644
--- a/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx
+++ b/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx
@@ -221,6 +221,40 @@ describe("useAutomationSelectionKeyboard", () => {
});
});
+ it("Cmd+V at a selection near the clip's end clamps the paste inside its duration", () => {
+ // The playhead branch already clamps to duration - span; the
+ // selection-start branch didn't, so pasting a 2s clip at a selection
+ // sitting at t0=5.5 on a 6s clip used to write points out to t=7.5 —
+ // past element.duration — and leave the selection itself out of bounds.
+ clearAutomationClipboard();
+ usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });
+ usePlayerStore
+ .getState()
+ .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });
+ const { onCommit } = setup({});
+ combo("c");
+ expect(readClipboard(null)?.span).toBe(2);
+
+ // A 0.1s-wide selection right near the clip's 6s end.
+ usePlayerStore
+ .getState()
+ .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 5.5, t1: 5.6 });
+ combo("v");
+ const written = onCommit.mock.calls.at(-1)?.[0];
+ const times = (written?.lanes?.[0]?.points ?? []).map((p: { t: number }) => p.t);
+ for (const t of times) {
+ expect(t).toBeGreaterThanOrEqual(0);
+ expect(t).toBeLessThanOrEqual(bgmElement.duration);
+ }
+ // Clamped to duration (6) - span (2) = 4, not the unclamped 5.5.
+ expect(usePlayerStore.getState().automationSelection).toEqual({
+ elementKey: "bgm",
+ target: "volume",
+ t0: 4,
+ t1: 6,
+ });
+ });
+
it("refuses to paste when the dom-edit layer would write to a different clip", () => {
// selectedElementId says "bgm" but the commit channel is still on the
// previously selected clip — writing here would serialize bgm's automation
diff --git a/packages/studio/src/player/components/AutomationSelectionMenu.tsx b/packages/studio/src/player/components/AutomationSelectionMenu.tsx
index 4a2bd0d057..f157f6e266 100644
--- a/packages/studio/src/player/components/AutomationSelectionMenu.tsx
+++ b/packages/studio/src/player/components/AutomationSelectionMenu.tsx
@@ -30,11 +30,19 @@ export const AutomationSelectionMenu = memo(function AutomationSelectionMenu({
const menuRef = useContextMenuDismiss(onClose);
const row =
"block w-full px-2 py-1 text-left text-[11px] text-panel-text-1 hover:bg-panel-bg-3 disabled:opacity-40";
+ // Same edge-clamping precedent as TrackGapContextMenu: without it a
+ // right-click near the bottom/right of the timeline renders this menu
+ // partially off-screen.
+ const menuWidth = 140;
+ const menuHeight = AUTOMATION_SHAPES.length * 24 + 32;
+ const overflowY = y + menuHeight - window.innerHeight;
+ const adjustedX = x + menuWidth > window.innerWidth ? x - menuWidth : x;
+ const adjustedY = overflowY > 0 ? y - overflowY - 8 : y;
return createPortal(
<div
ref={menuRef}
className="hf-automation-menu fixed z-50 min-w-[140px] rounded border border-panel-border-input bg-panel-bg-2 py-1 shadow-lg"
- style={{ left: x, top: y }}
+ style={{ left: adjustedX, top: adjustedY }}
>
{AUTOMATION_SHAPES.map((shape) => (
<button
diff --git a/packages/studio/src/player/components/TimelineAutomationLane.test.tsx b/packages/studio/src/player/components/TimelineAutomationLane.test.tsx
index c84a019201..961c5f42b6 100644
--- a/packages/studio/src/player/components/TimelineAutomationLane.test.tsx
+++ b/packages/studio/src/player/components/TimelineAutomationLane.test.tsx
@@ -85,6 +85,8 @@ function fire(
clientX?: number;
clientY?: number;
button?: number;
+ /** Buttons still held. A move reporting none is how a lost capture shows up. */
+ buttons?: number;
altKey?: boolean;
shiftKey?: boolean;
} = {},
@@ -485,6 +487,27 @@ const mount = (automation: HfAutomation, over: Record<string, unknown> = {}) =>
return { container, svg, props };
};
+/** `mount`, plus the re-render a real store update causes — the persisted
+ * automation and the new selection coming back down as props. */
+const mountRerenderable = (automation: HfAutomation, over: Record<string, unknown> = {}) => {
+ const base = laneProps({ automation, ...over });
+ const props = {
+ ...base,
+ onPreview: base.onPreview as ReturnType<typeof vi.fn>,
+ onCommit: base.onCommit as ReturnType<typeof vi.fn>,
+ };
+ const { container, rerender } = renderRerenderable(<TimelineAutomationLane {...props} />);
+ const svg = container.querySelector("svg")!;
+ stubBox(svg, BOX);
+ return {
+ container,
+ svg,
+ props,
+ rerender: (next: Record<string, unknown>) =>
+ rerender(<TimelineAutomationLane {...props} {...next} />),
+ };
+};
+
describe("TimelineAutomationLane modifiers", () => {
it("bends a segment when it is Alt-dragged, and leaves the points where they were", () => {
// `curve` was honoured everywhere it is read — drawn, sampled in preview,
@@ -686,3 +709,348 @@ describe("TimelineAutomationLane selection menu", () => {
expect(document.querySelector(".hf-automation-menu")).toBeNull();
});
});
+
+describe("TimelineAutomationLane stretch", () => {
+ // Most edges here are off any existing point, which is the EASY case. The
+ // normal state after any range operation is the opposite — delete, shape
+ // insert and stretch all leave a breakpoint exactly on the edge they created
+ // — so the priority test below is the one that decides whether the feature is
+ // repeatable, not an edge case.
+
+ /** Press, drag and release the right edge of a stretchable selection — the
+ * shape most of this block's tests share, differing only in where the
+ * drag ends up. */
+ function dragRightEdge(svg: Element, from: number, to: number): void {
+ fire(svg, "pointerdown", at(from, 0.5));
+ fire(svg, "pointermove", at(to, 0.5));
+ fire(svg, "pointerup", at(to, 0.5));
+ }
+
+ const stretchable: HfAutomation = {
+ version: 1,
+ lanes: [
+ {
+ target: "volume",
+ points: [
+ { t: 0, v: 1 },
+ { t: 1, v: 0.5 },
+ { t: 2, v: 0.8 },
+ { t: 4, v: 0 },
+ ],
+ },
+ ],
+ };
+
+ it("dragging the right edge retimes the interior and persists on release", () => {
+ const onRangeSelect = vi.fn();
+ const { svg, props } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onRangeSelect,
+ });
+ dragRightEdge(svg, 2.5, 3.3); // off any point, dragged out to 3.3
+
+ expect(props.onCommit).toHaveBeenCalledTimes(1);
+ const written = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;
+ const points = written.lanes[0]?.points ?? [];
+ // Interior points (t=1, t=2) scale by the new/old span ratio (2.8 / 2 = 1.4).
+ expect(points.some((p) => Math.abs(p.t - 1.2) < 0.01 && p.v === 0.5)).toBe(true);
+ expect(points.some((p) => Math.abs(p.t - 2.6) < 0.01 && p.v === 0.8)).toBe(true);
+
+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.3, 1));
+ });
+
+ it("moves the selection with the pointer instead of snapping it on release", () => {
+ // The highlight and both edge lines render from the rangeSelection prop, so
+ // a stretch that only reported its bounds on release dragged an invisible
+ // handle: the rect stayed pinned at the pre-drag bounds for the whole
+ // gesture. The marquee drag fires live for exactly this reason.
+ const onRangeSelect = vi.fn();
+ const { svg } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onRangeSelect,
+ });
+ fire(svg, "pointerdown", at(2.5, 0.5));
+ fire(svg, "pointermove", at(3, 0.5));
+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3, 1));
+ fire(svg, "pointermove", at(3.3, 0.5));
+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.3, 1));
+ });
+
+ it("a bare click on an edge clears the selection instead of committing a no-op", () => {
+ // Without a movement threshold this pushed an undo entry that changed
+ // nothing, and — because the halo covers both edges — it also made the
+ // "click the background to clear" escape unreachable near either one.
+ const onRangeSelect = vi.fn();
+ const onRangeClear = vi.fn();
+ const { svg, props } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onRangeSelect,
+ onRangeClear,
+ });
+ fire(svg, "pointerdown", at(2.5, 0.5));
+ fire(svg, "pointerup", at(2.5, 0.5));
+ expect(props.onCommit).not.toHaveBeenCalled();
+ expect(props.onPreview).not.toHaveBeenCalled();
+ expect(onRangeSelect).not.toHaveBeenCalled();
+ expect(onRangeClear).toHaveBeenCalledTimes(1);
+ });
+
+ it("a press that jitters under the threshold still clears rather than retiming", () => {
+ const onRangeClear = vi.fn();
+ const { svg, props } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onRangeClear,
+ });
+ fire(svg, "pointerdown", at(2.5, 0.5));
+ // ~2px at 100 px/s: a hand resting on the button, not a drag.
+ fire(svg, "pointermove", at(2.52, 0.5));
+ fire(svg, "pointerup", at(2.52, 0.5));
+ expect(props.onPreview).not.toHaveBeenCalled();
+ expect(props.onCommit).not.toHaveBeenCalled();
+ expect(onRangeClear).toHaveBeenCalledTimes(1);
+ });
+
+ it("reverts an interrupted stretch rather than persisting the partial retime", () => {
+ // pointercancel means the browser abandoned the gesture. Routing it to the
+ // same handler as pointerup persisted whatever half-drag it had reached,
+ // with no way back other than undo.
+ const onRangeSelect = vi.fn();
+ const { svg, props } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onRangeSelect,
+ });
+ fire(svg, "pointerdown", at(2.5, 0.5));
+ fire(svg, "pointermove", at(3.3, 0.5));
+ fire(svg, "pointercancel", at(3.3, 0.5));
+
+ expect(props.onCommit).not.toHaveBeenCalled();
+ // The envelope goes back through the preview channel — nothing to undo —
+ // and the selection returns to the bounds the drag started from.
+ const reverted = (props.onPreview.mock.calls.at(-1)?.[0] as HfAutomation | undefined)?.lanes[0]
+ ?.points;
+ expect(reverted).toEqual(stretchable.lanes[0]?.points);
+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, 2.5);
+ });
+
+ it("gives up a stretch whose pointer capture vanished without a cancel", () => {
+ // A capture taken on a child that unmounts mid-drag is lost silently: no
+ // pointercancel, no pointerup. Every later hover kept retiming and writing.
+ const { svg, props } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ });
+ fire(svg, "pointerdown", at(2.5, 0.5));
+ fire(svg, "pointermove", { ...at(3.3, 0.5), buttons: 1 });
+ fire(svg, "pointermove", { ...at(3.4, 0.5), buttons: 0 });
+ const writes = props.onPreview.mock.calls.length;
+
+ fire(svg, "pointermove", { ...at(3.8, 0.5), buttons: 0 });
+ fire(svg, "pointermove", { ...at(1, 0.5), buttons: 0 });
+ expect(props.onPreview.mock.calls.length).toBe(writes);
+ expect(props.onCommit).not.toHaveBeenCalled();
+ });
+
+ it("previews the stretch on move without persisting, then commits once on release", () => {
+ const onPreview = vi.fn();
+ const onCommit = vi.fn();
+ const { svg } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onPreview,
+ onCommit,
+ });
+ fire(svg, "pointerdown", at(2.5, 0.5));
+ fire(svg, "pointermove", at(3, 0.5));
+ fire(svg, "pointermove", at(3.3, 0.5));
+ expect(onPreview).toHaveBeenCalledTimes(2);
+ expect(onCommit).not.toHaveBeenCalled();
+ fire(svg, "pointerup", at(3.3, 0.5));
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ });
+
+ /** A breakpoint sitting exactly on the selection's right edge — the state every
+ * range operation leaves behind, and the one a stretch has to be able to grab
+ * a second time. */
+ const pointOnEdge: HfAutomation = {
+ version: 1,
+ lanes: [
+ {
+ target: "volume",
+ points: [
+ { t: 0, v: 1 },
+ { t: 1.5, v: 0.5 },
+ { t: 2, v: 0.8 },
+ { t: 4, v: 0 },
+ ],
+ },
+ ],
+ };
+
+ it("the selection's edge wins over a point sitting exactly on it", () => {
+ // The regression this pins is the feature not being repeatable: stretching
+ // pins a breakpoint on the edge it just created, so a point-first rule made
+ // the SECOND stretch of that edge a point-drag every time — at the one
+ // height (on the envelope) where the user naturally grabs it.
+ const onRangeSelect = vi.fn();
+ const { svg } = mount(pointOnEdge, {
+ rangeSelection: { t0: 1, t1: 2 },
+ onRangeSelect,
+ });
+ fire(svg, "pointerdown", at(2, 0.8)); // the point at t=2, which is also the right edge
+ fire(svg, "pointermove", at(3, 0.8));
+ fire(svg, "pointerup", at(3, 0.8));
+ expect(onRangeSelect).toHaveBeenLastCalledWith(1, expect.closeTo(3, 1));
+ });
+
+ it("leaves that point reachable once the selection is gone", () => {
+ // The escape hatch the rule above depends on: no selection, no handle, so
+ // the point is an ordinary point again.
+ const onRangeSelect = vi.fn();
+ const { svg, props } = mount(pointOnEdge, { rangeSelection: null, onRangeSelect });
+ fire(svg, "pointerdown", at(2, 0.8));
+ fire(svg, "pointermove", at(3, 0.8));
+ fire(svg, "pointerup", at(3, 0.8));
+ const written = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;
+ const times = (written.lanes[0]?.points ?? []).map((p) => p.t);
+ expect(times).toContain(3);
+ });
+
+ it("stretches the same edge twice in a row", () => {
+ // The whole point of the priority rule, end to end: two stretches of the
+ // right edge, the second grabbing the breakpoint the first one left there.
+ const onRangeSelect = vi.fn();
+ const { svg, props, rerender } = mountRerenderable(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2 },
+ onRangeSelect,
+ });
+ dragRightEdge(svg, 2, 2.6);
+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(2.6, 1));
+ const afterFirst = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;
+ // A breakpoint landed on the new edge, which is what used to disarm it.
+ expect((afterFirst.lanes[0]?.points ?? []).some((p) => Math.abs(p.t - 2.6) < 0.05)).toBe(true);
+
+ // The store comes back with the persisted envelope and the new selection.
+ rerender({ automation: afterFirst, rangeSelection: { t0: 0.5, t1: 2.6 } });
+ dragRightEdge(svg, 2.6, 3.4);
+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.4, 1));
+ expect(props.onCommit).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps the far edge grabbable on a selection narrower than its own halos", () => {
+ // A selection this thin — a pasted short span, or any span at low zoom — has
+ // both handles under one press, so which edge a press takes is decided
+ // entirely by the midpoint split. Characterizing it here because nothing
+ // else does: every other test in this block has halos far enough apart that
+ // the rule never comes up.
+ const onRangeSelect = vi.fn();
+ const { svg } = mount(stretchable, {
+ rangeSelection: { t0: 2, t1: 2.08 }, // 8px wide at 100 px/s: both halos overlap
+ onRangeSelect,
+ });
+ fire(svg, "pointerdown", at(2.07, 0.5)); // nearer t1, inside t0's halo too
+ fire(svg, "pointermove", at(3, 0.5));
+ fire(svg, "pointerup", at(3, 0.5));
+ // t0 stayed put and t1 moved out: the press resolved to the right edge.
+ expect(onRangeSelect).toHaveBeenLastCalledWith(2, expect.closeTo(3, 1));
+ });
+
+ it("clamps the dragged edge so it cannot cross its partner", () => {
+ const onRangeSelect = vi.fn();
+ const { svg } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onRangeSelect,
+ });
+ dragRightEdge(svg, 2.5, 0.3); // dragged past the left edge (t0=0.5)
+ const [, t1] = onRangeSelect.mock.calls.at(-1) as [number, number];
+ expect(t1).toBeGreaterThan(0.5);
+ });
+
+ it("clamps the dragged edge to the lane's own duration", () => {
+ const onRangeSelect = vi.fn();
+ const { svg } = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onRangeSelect,
+ });
+ dragRightEdge(svg, 2.5, 10); // far past the clip's own duration (4s)
+ const [, t1] = onRangeSelect.mock.calls.at(-1) as [number, number];
+ expect(t1).toBeLessThanOrEqual(4);
+ });
+
+ it("retimes identically whether the right edge arrives in one move or several", () => {
+ // moveEdge must always retime from the points snapshotted at arm time,
+ // never from the live draft — retimeRange is a RELATIVE transform (it
+ // scales the lane's OWN current point positions by newSpan/oldSpan), so
+ // feeding it the live draft on every pointermove compounds the scale
+ // factor instead of applying it once. A real drag fires dozens of moves;
+ // this asserts the FINAL preview is identical regardless of how many.
+ const onPreviewSingle = vi.fn();
+ const single = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onPreview: onPreviewSingle,
+ });
+ fire(single.svg, "pointerdown", at(2.5, 0.5));
+ fire(single.svg, "pointermove", at(3.3, 0.5));
+ const singleShot = (onPreviewSingle.mock.calls.at(-1)?.[0] as HfAutomation | undefined)
+ ?.lanes[0]?.points;
+ expect(singleShot).toBeDefined();
+
+ const onPreviewMulti = vi.fn();
+ const multi = mount(stretchable, {
+ rangeSelection: { t0: 0.5, t1: 2.5 },
+ onPreview: onPreviewMulti,
+ });
+ fire(multi.svg, "pointerdown", at(2.5, 0.5));
+ // At least 3 separate pointermoves crossing the same span, not one jump.
+ fire(multi.svg, "pointermove", at(2.7, 0.5));
+ fire(multi.svg, "pointermove", at(2.9, 0.5));
+ fire(multi.svg, "pointermove", at(3.1, 0.5));
+ fire(multi.svg, "pointermove", at(3.3, 0.5));
+ const afterFourMoves = (onPreviewMulti.mock.calls.at(-1)?.[0] as HfAutomation | undefined)
+ ?.lanes[0]?.points;
+ expect(afterFourMoves).toBeDefined();
+
+ // Both interior points (t=1, t=2) land exactly where a single-shot retime
+ // puts them — not compounded, and not dropped.
+ expect(afterFourMoves).toEqual(singleShot);
+ expect(afterFourMoves?.length).toBe(6);
+ expect(afterFourMoves?.some((p) => Math.abs(p.t - 1.2) < 0.001 && p.v === 0.5)).toBe(true);
+ expect(afterFourMoves?.some((p) => Math.abs(p.t - 2.6) < 0.001 && p.v === 0.8)).toBe(true);
+ });
+
+ it("retimes identically whether the left edge arrives in one move or several", () => {
+ const onPreviewSingle = vi.fn();
+ const single = mount(stretchable, {
+ rangeSelection: { t0: 1, t1: 3 },
+ onPreview: onPreviewSingle,
+ });
+ fire(single.svg, "pointerdown", at(1, 0.5));
+ fire(single.svg, "pointermove", at(0.2, 0.5));
+ const singleShot = (onPreviewSingle.mock.calls.at(-1)?.[0] as HfAutomation | undefined)
+ ?.lanes[0]?.points;
+ expect(singleShot).toBeDefined();
+
+ const onPreviewMulti = vi.fn();
+ const multi = mount(stretchable, {
+ rangeSelection: { t0: 1, t1: 3 },
+ onPreview: onPreviewMulti,
+ });
+ fire(multi.svg, "pointerdown", at(1, 0.5));
+ fire(multi.svg, "pointermove", at(0.7, 0.5));
+ fire(multi.svg, "pointermove", at(0.4, 0.5));
+ fire(multi.svg, "pointermove", at(0.2, 0.5));
+ const afterThreeMoves = (onPreviewMulti.mock.calls.at(-1)?.[0] as HfAutomation | undefined)
+ ?.lanes[0]?.points;
+ expect(afterThreeMoves).toBeDefined();
+ expect(afterThreeMoves).toEqual(singleShot);
+ });
+
+ it("shows a resize cursor when hovering an edge with nothing else live", () => {
+ const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });
+ fire(svg, "pointermove", at(3, 0.5)); // near the right edge, nothing pressed
+ expect(svg.style.cursor).toBe("col-resize");
+ });
+
+ it("keeps the normal cursor away from the selection's edges", () => {
+ const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });
+ fire(svg, "pointermove", at(2, 0.5)); // middle of the selection, not an edge
+ expect(svg.style.cursor).not.toBe("col-resize");
+ });
+});
diff --git a/packages/studio/src/player/components/TimelineAutomationLane.tsx b/packages/studio/src/player/components/TimelineAutomationLane.tsx
index 835c8111c5..cdd702991c 100644
--- a/packages/studio/src/player/components/TimelineAutomationLane.tsx
+++ b/packages/studio/src/player/components/TimelineAutomationLane.tsx
@@ -50,8 +50,10 @@ import { getTimelineLaneTop } from "./timelineLayout";
import type { TimelineElement } from "../store/playerStore";
import type { UseAutomationLanesResult } from "./useAutomationLanes";
-/** Pointer shape: a read-only lane can only be selected, a live one edited. */
-function laneCursor(readOnly: boolean | undefined, dragging: boolean): string {
+/** 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. */
+function laneCursor(readOnly: boolean | undefined, dragging: boolean, stretching: boolean): string {
+ if (stretching) return "col-resize";
if (readOnly) return "pointer";
return dragging ? "grabbing" : "crosshair";
}
@@ -204,8 +206,9 @@ export function TimelineAutomationLane({
onRangeSelect,
onRangeClear,
duration,
+ rangeSelection,
});
- const { dragIndex, curveIndex, hint, editing } = gestures;
+ const { dragIndex, curveIndex, edgeDrag, edgeHover, hint, editing } = gestures;
const removeAt = useCallback(
(index: number): void => {
@@ -285,7 +288,11 @@ export function TimelineAutomationLane({
top: 0,
width: widthPx + PAD_X * 2,
height: h,
- cursor: laneCursor(readOnly, dragIndex !== null || curveIndex !== null),
+ cursor: laneCursor(
+ readOnly,
+ dragIndex !== null || curveIndex !== null,
+ edgeDrag !== null || edgeHover,
+ ),
opacity: readOnly ? 0.55 : 1,
touchAction: "none",
}}
@@ -294,7 +301,7 @@ export function TimelineAutomationLane({
onPointerDown={gestures.onPointerDown}
onPointerMove={gestures.onPointerMove}
onPointerUp={gestures.endDrag}
- onPointerCancel={gestures.endDrag}
+ onPointerCancel={gestures.cancelDrag}
onDoubleClick={gestures.onDoubleClick}
onContextMenu={onSvgContextMenu}
role="group"
diff --git a/packages/studio/src/player/components/automationClipboard.test.ts b/packages/studio/src/player/components/automationClipboard.test.ts
index 38527a5ebf..ff7a510ec0 100644
--- a/packages/studio/src/player/components/automationClipboard.test.ts
+++ b/packages/studio/src/player/components/automationClipboard.test.ts
@@ -39,19 +39,34 @@ describe("automation clipboard", () => {
});
it("maps values through unit space onto a different parameter", () => {
- const wet = resolveAutomationRange("fx.r.wet", {
+ // fx.n1.frequency (lowpass cutoff) is log-scaled (min:20, max:20000):
+ // linear unit math and a literal copy of the source value would both
+ // read as a passing test on a range that happens to be numerically
+ // identical to VOLUME_RANGE (e.g. fx.r.wet), so this target has to be
+ // genuinely log for the test to discriminate real unit-space mapping.
+ const frequency = resolveAutomationRange("fx.n1.frequency", {
version: 1,
- nodes: [{ type: "reverb", id: "r", params: {} }],
+ nodes: [{ type: "lowpass", id: "n1", params: {} }],
});
- expect(wet).toBeTruthy();
- if (!wet) return;
+ expect(frequency).toBeTruthy();
+ if (!frequency) return;
+ expect(frequency.scale).toBe("log");
copyRange("project-a", duck, VOLUME_RANGE, 2, 4);
const entry = readClipboard("project-a");
if (!entry) return;
- const pts = pastePoints(entry, wet, 0);
- // volume 1 (unit 1) → wet max; volume 0.25 (unit 0.25) → a quarter up wet's axis
- expect(pts[0]?.v).toBeCloseTo(wet.max, 5);
- expect(pts[1]?.v).toBeCloseTo(wet.min + 0.25 * (wet.max - wet.min), 5);
+ const pts = pastePoints(entry, frequency, 0);
+ // volume 1 (unit 1) → frequency max; volume 0.25 (unit 0.25) → a quarter
+ // up frequency's LOG axis, i.e. exp(ln(min) + 0.25*(ln(max)-ln(min))) —
+ // NOT the naive linear guess (min + 0.25*(max-min)) and nowhere near a
+ // literal copy of 0.25.
+ expect(pts[0]?.v).toBeCloseTo(frequency.max, 5);
+ const expectedLog = Math.exp(
+ Math.log(frequency.min) + 0.25 * (Math.log(frequency.max) - Math.log(frequency.min)),
+ );
+ const naiveLinear = frequency.min + 0.25 * (frequency.max - frequency.min);
+ expect(pts[1]?.v).toBeCloseTo(expectedLog, 5);
+ expect(pts[1]?.v).not.toBeCloseTo(naiveLinear, 0);
+ expect(pts[1]?.v).not.toBeCloseTo(0.25, 0);
});
it("reads null when nothing was copied", () => {
diff --git a/packages/studio/src/player/components/automationLanePointer.ts b/packages/studio/src/player/components/automationLanePointer.ts
new file mode 100644
index 0000000000..cbafb07792
--- /dev/null
+++ b/packages/studio/src/player/components/automationLanePointer.ts
@@ -0,0 +1,20 @@
+/**
+ * Pointer capture for a lane gesture. Its own module only because both gesture
+ * hooks need it and `automationLaneGeometry` is deliberately DOM-free.
+ */
+
+/**
+ * Keep the rest of a gesture even if the pointer leaves the lane. Without it a
+ * drag that strays outside the svg stops sending moves and the point sticks.
+ *
+ * Captured on the svg the handler is bound to, NOT on `e.target`: the target is
+ * whatever child the press happened to land on — a breakpoint circle, a
+ * selection line — and a child that unmounts mid-drag takes the capture with it,
+ * silently and with no `pointercancel` to notice it by. The svg outlives every
+ * gesture on it.
+ *
+ * Structurally typed so this stays testable without React's event types.
+ */
+export function capturePointer(e: { currentTarget: Element; pointerId: number }): void {
+ e.currentTarget.setPointerCapture?.(e.pointerId);
+}
diff --git a/packages/studio/src/player/components/automationLaneSelection.test.ts b/packages/studio/src/player/components/automationLaneSelection.test.ts
index a7f0296add..b894984f74 100644
--- a/packages/studio/src/player/components/automationLaneSelection.test.ts
+++ b/packages/studio/src/player/components/automationLaneSelection.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { pointsIn, replaceRange } from "./automationLaneSelection";
+import { pointsIn, replaceRange, retimeRange } from "./automationLaneSelection";
import { sampleAutomationLane, VOLUME_RANGE } from "@hyperframes/core/audio-automation";
import type { HfAutomationLane } from "@hyperframes/core/audio-automation";
@@ -94,3 +94,90 @@ describe("replaceRange", () => {
expect(Math.max(...innerTimes)).toBeGreaterThan(3.0);
});
});
+
+describe("retimeRange", () => {
+ it("scales interior points proportionally into the new span", () => {
+ const pts = retimeRange({ lane: ramp, range: VOLUME_RANGE, t0: 2, t1: 3, newT0: 2, newT1: 5 });
+ const moved = pts.find((p) => p.v === 0.4); // the t=3 point
+ expect(moved?.t).toBe(5);
+ });
+
+ it("preserves the envelope outside the union of old and new spans", () => {
+ const before: HfAutomationLane = { target: "volume", points: ramp.points };
+ const after: HfAutomationLane = {
+ target: "volume",
+ points: retimeRange({ lane: ramp, range: VOLUME_RANGE, t0: 2, t1: 3, newT0: 2, newT1: 5 }),
+ };
+ // Nothing to the left of t0=2 moved (newT0 === t0 here), so sampled
+ // continuity holds all the way up to the edited region.
+ for (const t of [0, 1, 1.9]) {
+ expect(sampleAutomationLane(after, t, "linear")).toBeCloseTo(
+ sampleAutomationLane(before, t, "linear"),
+ 5,
+ );
+ }
+ // The next real breakpoint past the edited region keeps its own exact value.
+ const farPoint = after.points.find((p) => p.t === 6);
+ expect(farPoint).toEqual({ t: 6, v: 0 });
+ });
+
+ it("preserves the envelope on BOTH sides when no breakpoint sits on the moved edge", () => {
+ // The right side is where the invariant is worth asserting — `newT0 === t0`
+ // makes the left side of the test above trivially true, and an earlier
+ // right-side probe at t=5.1 was DELETED as inherent when it was reporting
+ // the real behaviour below. With the selection's edges off any breakpoint,
+ // the guarantee holds exactly, in both directions.
+ const before: HfAutomationLane = { target: "volume", points: ramp.points };
+ const after: HfAutomationLane = {
+ target: "volume",
+ points: retimeRange({
+ lane: ramp,
+ range: VOLUME_RANGE,
+ t0: 2.2,
+ t1: 2.9,
+ newT0: 2.2,
+ newT1: 4,
+ }),
+ };
+ for (const t of [0, 1, 2, 4.5, 5, 5.5, 6]) {
+ expect(sampleAutomationLane(after, t, "linear")).toBeCloseTo(
+ sampleAutomationLane(before, t, "linear"),
+ 5,
+ );
+ }
+ });
+
+ it("moves a breakpoint sitting exactly on the dragged edge, reshaping the segment past it", () => {
+ // The design decision this pins, because it is not free either way.
+ // `pointsIn` is endpoint-inclusive, so a breakpoint ON the edge is interior
+ // and travels with the stretch. It has to: every range operation leaves a
+ // breakpoint exactly on the edge it created, so treating that point as an
+ // anchor instead would make the commonest stretch — grabbing the edge to
+ // drag that very point outward — delete it and flatten the span.
+ //
+ // The cost is that the retimed point lands ON the union's boundary, where a
+ // preservation anchor would also go, and `anchor()` stands down within a
+ // merge radius. Two different values cannot occupy one time; the segment
+ // leaving the union reshapes, which is the "envelope outside the selection
+ // never moves" invariant bending exactly here and nowhere else.
+ const pts = retimeRange({ lane: ramp, range: VOLUME_RANGE, t0: 2, t1: 3, newT0: 2, newT1: 5 });
+ expect(pts).toEqual([
+ { t: 0, v: 1 },
+ { t: 2, v: 0.6 },
+ { t: 5, v: 0.4 }, // the t=3 point, retimed onto the new edge
+ { t: 6, v: 0 },
+ ]);
+ // The old 3→6 segment sloped -0.133/s; the new 5→6 slopes -0.4/s, so the
+ // envelope past the union genuinely moves. Asserted, not tolerated: if this
+ // number changes, the decision above changed with it.
+ const after: HfAutomationLane = { target: "volume", points: pts };
+ expect(sampleAutomationLane(after, 5.5, "linear")).toBeCloseTo(0.2, 5);
+ expect(sampleAutomationLane(ramp, 5.5, "linear")).toBeCloseTo(0.0667, 4);
+ });
+
+ it("rejects a degenerate span", () => {
+ expect(
+ retimeRange({ lane: ramp, range: VOLUME_RANGE, t0: 2, t1: 3, newT0: 4, newT1: 4 }),
+ ).toEqual(ramp.points);
+ });
+});
diff --git a/packages/studio/src/player/components/automationLaneSelection.ts b/packages/studio/src/player/components/automationLaneSelection.ts
index 3e8e1fb703..66e384e6f1 100644
--- a/packages/studio/src/player/components/automationLaneSelection.ts
+++ b/packages/studio/src/player/components/automationLaneSelection.ts
@@ -42,7 +42,10 @@ function anchor(
function decimateEvenly<T>(items: readonly T[], budget: number): T[] {
if (budget <= 0) return [];
if (items.length <= budget) return [...items];
- if (budget === 1) return [items[0]!];
+ if (budget === 1) {
+ const item = items[0];
+ return item ? [item] : [];
+ }
const out: T[] = [];
const step = (items.length - 1) / (budget - 1);
for (let i = 0; i < budget; i += 1) {
@@ -72,3 +75,43 @@ export function replaceRange(input: {
const cappedInner = inner.length <= budget ? inner : decimateEvenly(inner, budget);
return [...outside, ...edges, ...cappedInner].sort((a, b) => a.t - b.t);
}
+
+/**
+ * Retime a selection: interior points scale proportionally into the new span,
+ * then replaceRange runs over the UNION of old and new spans — growing eats
+ * whatever it covers, shrinking pins anchors where the envelope re-enters.
+ *
+ * Interior is `pointsIn`, so a breakpoint sitting exactly ON an edge travels
+ * with the stretch. Deliberate: every range operation leaves a breakpoint on the
+ * edge it created, so treating that point as a fixed anchor would make the
+ * commonest stretch of all — grabbing the edge to drag that point outward —
+ * delete it instead. The price is that such a point lands on the union's own
+ * boundary, where `anchor` then stands down (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 it is pinned by name
+ * in automationLaneSelection.test.ts.
+ */
+export function retimeRange(input: {
+ lane: HfAutomationLane;
+ range: AutomationRange;
+ t0: number;
+ t1: number;
+ newT0: number;
+ newT1: number;
+}): HfAutomationPoint[] {
+ const { lane, range, t0, t1, newT0, newT1 } = input;
+ const oldSpan = t1 - t0;
+ const newSpan = newT1 - newT0;
+ if (oldSpan <= 0 || newSpan <= 0) return lane.points;
+ const inner = pointsIn(lane, t0, t1).map((p) => ({
+ ...p,
+ t: newT0 + ((p.t - t0) * newSpan) / oldSpan,
+ }));
+ return replaceRange({
+ lane,
+ range,
+ t0: Math.min(t0, newT0),
+ t1: Math.max(t1, newT1),
+ inner,
+ });
+}
diff --git a/packages/studio/src/player/components/useAutomationEdgeStretch.test.ts b/packages/studio/src/player/components/useAutomationEdgeStretch.test.ts
new file mode 100644
index 0000000000..691066d22b
--- /dev/null
+++ b/packages/studio/src/player/components/useAutomationEdgeStretch.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { clampEdge } from "./useAutomationEdgeStretch";
+
+describe("clampEdge", () => {
+ it("keeps the dragged edge inside the clip", () => {
+ expect(clampEdge("t0", -5, { t0: 1, t1: 3 }, 4)).toBe(0);
+ expect(clampEdge("t1", 99, { t0: 1, t1: 3 }, 4)).toBe(4);
+ });
+
+ it("keeps the dragged edge clear of its partner", () => {
+ expect(clampEdge("t0", 3.5, { t0: 1, t1: 3 }, 4)).toBeCloseTo(2.98, 5);
+ expect(clampEdge("t1", 0.5, { t0: 1, t1: 3 }, 4)).toBeCloseTo(1.02, 5);
+ });
+
+ it("never yields a negative time, even when the partner bound is itself below zero", () => {
+ // A selection thinner than the minimum width has no legal t0 at all. Bounding
+ // against the partner AFTER the 0-floor returned that illegal value, and
+ // core's cleanPoint collapses a negative time onto a duplicate t=0 on the
+ // next serialize round-trip — silent envelope corruption, not a visible bug.
+ expect(clampEdge("t0", -1, { t0: 0.004, t1: 0.01 }, 4)).toBe(0);
+ expect(clampEdge("t0", 0.008, { t0: 0.004, t1: 0.01 }, 4)).toBe(0);
+ });
+
+ it("never yields a time past the clip when the partner bound is past it", () => {
+ expect(clampEdge("t1", 99, { t0: 3.995, t1: 4 }, 4)).toBe(4);
+ });
+});
diff --git a/packages/studio/src/player/components/useAutomationEdgeStretch.ts b/packages/studio/src/player/components/useAutomationEdgeStretch.ts
new file mode 100644
index 0000000000..faae242e46
--- /dev/null
+++ b/packages/studio/src/player/components/useAutomationEdgeStretch.ts
@@ -0,0 +1,248 @@
+/**
+ * Stretching an automation selection by one of its edges.
+ *
+ * Its own module because edge-stretch is a fifth mutually-exclusive gesture on a
+ * lane that already sits near the studio's file ceiling, and because it has to
+ * follow the same three-part contract the other gestures do — a movement
+ * threshold before anything is written, a live preview the user can see, and a
+ * revert when the browser abandons the gesture. It was first written without
+ * them, and every one of its bugs came from that: a bare click near an edge
+ * pushed an undo entry that changed nothing, the highlight stayed frozen at the
+ * pre-drag bounds so the handle was invisible while it moved, and a
+ * `pointercancel` persisted whatever partial retime it had reached.
+ *
+ * `retimeRange` is a RELATIVE transform — it scales a lane's own current point
+ * positions by newSpan/oldSpan — so it must always run against the snapshot
+ * taken when the drag armed, never the live draft, or the scale factor compounds
+ * on every pointermove.
+ */
+
+import { useCallback, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
+import type {
+ AutomationRange,
+ HfAutomationLane,
+ HfAutomationPoint,
+} from "@hyperframes/core/audio-automation";
+import { capturePointer } from "./automationLanePointer";
+import { retimeRange } from "./automationLaneSelection";
+
+/** Hit radius for grabbing a selection's edge, in screen px — independent of a
+ * point's own grab radius so the two zones can be reasoned about on their own. */
+const EDGE_GRAB_PX = 8;
+
+/** Screen px a press has to travel before it counts as a stretch rather than a
+ * click. The sibling range-drag uses the same 3px, and for the same reason:
+ * below it, a press is the "clear the selection" escape, and writing anything
+ * would put a no-op entry in undo. */
+const EDGE_DRAG_PX = 3;
+
+/**
+ * Narrowest selection a stretch can leave behind, in clip seconds. Its own
+ * constant rather than a borrowed `POINT_MERGE_SEC`: that one is about when two
+ * breakpoints are the same breakpoint, which is a different question from how
+ * thin a time selection may get and still be grabbable.
+ */
+const MIN_SELECTION_SEC = 0.02;
+
+export interface UseAutomationEdgeStretchInput {
+ getBox(): DOMRect | null;
+ lane: HfAutomationLane;
+ range: AutomationRange;
+ /** Pointer position as a clip-local time and a parameter value. */
+ pointAt(clientX: number, clientY: number): { t: number; v: number };
+ xOf(t: number): number;
+ commitPoints(points: HfAutomationLane["points"], persist: boolean): void;
+ /** Clamp bound for the dragged edge. */
+ 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;
+ onRangeClear?: (() => void) | undefined;
+ /** Value readout owned by the lane's gesture hook. */
+ onHint(text: string | null): void;
+}
+
+export interface UseAutomationEdgeStretchResult {
+ /** Edge being stretched, for the cursor. Null when no stretch is live. */
+ edge: "t0" | "t1" | null;
+ /** Pointer sits over a handle with no gesture live — the col-resize hint. */
+ hover: boolean;
+ /** Take the press as a stretch, or decline it so another gesture can have it. */
+ arm(e: ReactPointerEvent<SVGSVGElement>): boolean;
+ move(e: ReactPointerEvent<SVGSVGElement>): void;
+ /** Pointer released: persist the stretch, or clear the selection when the
+ * press never travelled far enough to be one. */
+ finish(): void;
+ /** The browser abandoned the gesture: put the envelope and the selection back
+ * the way they were, with nothing persisted. */
+ cancel(): void;
+ updateHover(e: ReactPointerEvent<SVGSVGElement>): void;
+}
+
+/** The dragged edge, clamped inside the clip AND clear of its partner. The
+ * 0/duration bound is applied LAST so a selection thinner than
+ * `MIN_SELECTION_SEC` can never push its own t0 negative — core's `cleanPoint`
+ * collapses negative times onto a duplicate t=0 on the next serialize.
+ * Exported for that ordering's own test: reaching it through the pointer needs
+ * a selection so thin that no drag can clear the movement threshold. */
+export function clampEdge(
+ edge: "t0" | "t1",
+ raw: number,
+ origin: { t0: number; t1: number },
+ duration: number,
+): number {
+ if (edge === "t0") {
+ return Math.max(0, Math.min(raw, origin.t1 - MIN_SELECTION_SEC));
+ }
+ return Math.min(duration, Math.max(raw, origin.t0 + MIN_SELECTION_SEC));
+}
+
+export function useAutomationEdgeStretch({
+ getBox,
+ lane,
+ range,
+ pointAt,
+ xOf,
+ commitPoints,
+ duration,
+ readOnly,
+ rangeSelection,
+ onRangeSelect,
+ onRangeClear,
+ onHint,
+}: UseAutomationEdgeStretchInput): UseAutomationEdgeStretchResult {
+ /** The live stretch: which edge, the selection it started from (fixed, as the
+ * retime's untouched anchor), the edge's own live position, and the lane's
+ * points as they stood at arm time. */
+ const [drag, setDrag] = useState<{
+ edge: "t0" | "t1";
+ origin: { t0: number; t1: number };
+ current: number;
+ points: HfAutomationPoint[];
+ } | null>(null);
+ /** Whether the drag has travelled far enough to write anything at all. */
+ const crossed = useRef(false);
+ const [hover, setHover] = useState(false);
+
+ /**
+ * Which edge of the active selection is within grab range of the pointer's
+ * screen x, over the full lane height — the handle spans the rect.
+ *
+ * A selection narrower than two halos has both edges under one press. The
+ * midpoint split says which one wins — the same rule a nearest-distance
+ * comparison expresses, written so that is legible rather than inferred, since
+ * on a narrow selection it is the ONLY thing deciding the gesture. Pressing a
+ * handle without moving clears the selection (see `finish`), which is what
+ * gets a user out of a halo too small to aim inside.
+ */
+ const edgeAt = useCallback(
+ (clientX: number): "t0" | "t1" | null => {
+ if (!rangeSelection) return null;
+ const box = getBox();
+ if (!box) return null;
+ const px = clientX - box.left;
+ const x0 = xOf(rangeSelection.t0);
+ const x1 = xOf(rangeSelection.t1);
+ const near0 = Math.abs(x0 - px) <= EDGE_GRAB_PX;
+ const near1 = Math.abs(x1 - px) <= EDGE_GRAB_PX;
+ if (near0 && near1) return px <= (x0 + x1) / 2 ? "t0" : "t1";
+ if (near0) return "t0";
+ return near1 ? "t1" : null;
+ },
+ [rangeSelection, getBox, xOf],
+ );
+
+ const arm = useCallback(
+ (e: ReactPointerEvent<SVGSVGElement>): boolean => {
+ if (readOnly || !rangeSelection) return false;
+ const edge = edgeAt(e.clientX);
+ if (!edge) return false;
+ e.preventDefault();
+ capturePointer(e);
+ setHover(false);
+ crossed.current = false;
+ setDrag({
+ edge,
+ origin: rangeSelection,
+ current: edge === "t0" ? rangeSelection.t0 : rangeSelection.t1,
+ points: lane.points,
+ });
+ return true;
+ },
+ [readOnly, rangeSelection, edgeAt, lane],
+ );
+
+ /** Preview the stretch: the partner edge stays put as the retime's anchor, and
+ * the selection itself follows the pointer so the handle being dragged is
+ * visible — the same live `onRangeSelect` the marquee drag fires. */
+ const move = useCallback(
+ (e: ReactPointerEvent<SVGSVGElement>): void => {
+ if (drag === null) return;
+ const { edge, origin, points } = drag;
+ const current = clampEdge(edge, pointAt(e.clientX, e.clientY).t, origin, duration);
+ setDrag({ edge, origin, current, points });
+ if (!crossed.current) {
+ const from = edge === "t0" ? origin.t0 : origin.t1;
+ if (Math.abs(xOf(current) - xOf(from)) <= EDGE_DRAG_PX) return;
+ crossed.current = true;
+ }
+ 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);
+ commitPoints(
+ retimeRange({
+ lane: { target: lane.target, points },
+ range,
+ t0: origin.t0,
+ t1: origin.t1,
+ newT0,
+ newT1,
+ }),
+ false,
+ );
+ },
+ [drag, pointAt, duration, xOf, onHint, onRangeSelect, commitPoints, lane.target, range],
+ );
+
+ const finish = useCallback((): void => {
+ if (drag === null) return;
+ const { edge, origin, current } = drag;
+ setDrag(null);
+ onHint(null);
+ // A press that never travelled is the "clear the selection" click, exactly
+ // as it is anywhere else on the background. Persisting here instead pushed
+ // an undo entry that changed nothing AND made that escape unreachable
+ // within a halo of either edge.
+ if (!crossed.current) {
+ onRangeClear?.();
+ return;
+ }
+ crossed.current = false;
+ commitPoints(lane.points, true);
+ onRangeSelect?.(edge === "t0" ? current : origin.t0, edge === "t1" ? current : origin.t1);
+ }, [drag, onHint, onRangeClear, commitPoints, lane, onRangeSelect]);
+
+ const cancel = useCallback((): void => {
+ if (drag === null) return;
+ const { origin, points } = drag;
+ setDrag(null);
+ onHint(null);
+ if (!crossed.current) return;
+ crossed.current = false;
+ // 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);
+ }, [drag, onHint, commitPoints, onRangeSelect]);
+
+ const updateHover = useCallback(
+ (e: ReactPointerEvent<SVGSVGElement>): void => {
+ if (!readOnly) setHover(edgeAt(e.clientX) !== null);
+ },
+ [readOnly, edgeAt],
+ );
+
+ return { edge: drag?.edge ?? null, hover, arm, move, finish, cancel, updateHover };
+}
diff --git a/packages/studio/src/player/components/useAutomationLaneGestures.ts b/packages/studio/src/player/components/useAutomationLaneGestures.ts
index cb00c83efe..73f1a23553 100644
--- a/packages/studio/src/player/components/useAutomationLaneGestures.ts
+++ b/packages/studio/src/player/components/useAutomationLaneGestures.ts
@@ -3,8 +3,8 @@
*
* 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, or
- * nothing at all.
+ * a drag and a modifier resolves to moving a point, bending a segment,
+ * stretching a selection's edge, 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
@@ -21,6 +21,8 @@ import {
POINT_MERGE_SEC,
snapLaneTime,
} from "./automationLaneGeometry";
+import { capturePointer } from "./automationLanePointer";
+import { useAutomationEdgeStretch } from "./useAutomationEdgeStretch";
/** 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. */
@@ -31,15 +33,6 @@ function originOf(point: HfAutomationLane["points"][number] | undefined): { t: n
return point ? { t: point.t, v: point.v } : { t: 0, v: 0 };
}
-/**
- * Keep the rest of the gesture even if the pointer leaves the lane. Without it a
- * drag that strays outside the svg stops sending moves and the point sticks.
- */
-function capturePointer(e: ReactPointerEvent<SVGSVGElement>): void {
- const target = e.target;
- if (target instanceof Element) target.setPointerCapture?.(e.pointerId);
-}
-
export interface UseAutomationLaneGesturesInput {
/** The lane's box on screen. A getter, not the ref: the hook only ever needs
* the rectangle, and a ref read inside a callback is a lint the rule is right
@@ -60,6 +53,8 @@ export interface UseAutomationLaneGesturesInput {
onRangeSelect?: ((t0: number, t1: 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;
}
export interface UseAutomationLaneGesturesResult {
@@ -67,6 +62,11 @@ 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;
@@ -74,6 +74,9 @@ export interface UseAutomationLaneGesturesResult {
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. */
+ cancelDrag(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. */
@@ -97,6 +100,7 @@ export function useAutomationLaneGestures({
onRangeSelect,
onRangeClear,
duration,
+ rangeSelection,
}: UseAutomationLaneGesturesInput): UseAutomationLaneGesturesResult {
const [dragIndex, setDragIndex] = useState<number | null>(null);
const [curveIndex, setCurveIndex] = useState<number | null>(null);
@@ -111,6 +115,21 @@ export function useAutomationLaneGestures({
* into an actual range, rather than a click that should just clear one. */
const rangeCrossed = useRef(false);
+ const stretch = useAutomationEdgeStretch({
+ getBox,
+ lane,
+ range,
+ pointAt,
+ xOf,
+ commitPoints,
+ duration,
+ readOnly,
+ rangeSelection,
+ onRangeSelect,
+ onRangeClear,
+ onHint: setHint,
+ });
+
/** Index of a point under the pointer, or null. */
const hitIndex = useCallback(
(clientX: number, clientY: number): number | null => {
@@ -153,6 +172,25 @@ 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;
@@ -166,21 +204,15 @@ export function useAutomationLaneGestures({
onSelect?.();
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.
+ if (stretch.arm(e)) return;
const gesture = gestureAt(e);
if (!gesture) {
- // Neither a point nor an Alt-held segment: the press landed on the
- // lane's empty background. That is a range selection's gesture, not
- // nothing — but only when a caller wants to hear about one; a
- // read-only lane already returned above, so this is a live one with no
- // range feature wired up.
- 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 });
+ armRangeDrag(e);
return;
}
e.preventDefault();
@@ -192,7 +224,7 @@ export function useAutomationLaneGestures({
dragOrigin.current = originOf(lane.points[gesture.index]);
setDragIndex(gesture.index);
},
- [gestureAt, lane, readOnly, onSelect, onRangeSelect, pointAt, duration, snapTimes],
+ [gestureAt, lane, readOnly, onSelect, armRangeDrag, stretch],
);
/** Bend the segment under the pointer, which is what Alt-dragging the line does. */
@@ -239,46 +271,69 @@ export function useAutomationLaneGestures({
[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],
+ );
+
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.
+ if (e.buttons === 0) stretch.cancel();
+ else stretch.move(e);
+ return;
+ }
if (rangeDrag !== null) {
e.stopPropagation();
- 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) {
- rangeCrossed.current = true;
- onRangeSelect?.(Math.min(rangeDrag.from, t), Math.max(rangeDrag.from, t));
- }
+ moveRangeDrag(e);
+ return;
+ }
+ if (curveIndex === null && dragIndex === null) {
+ stretch.updateHover(e);
return;
}
- if (curveIndex === null && dragIndex === null) return;
e.stopPropagation();
if (curveIndex !== null) bendSegment(e.clientX, e.clientY);
else movePoint(e);
},
- [
- rangeDrag,
- pointAt,
- duration,
- snapTimes,
- xOf,
- onRangeSelect,
- bendSegment,
- curveIndex,
- dragIndex,
- movePoint,
- ],
+ [stretch, rangeDrag, moveRangeDrag, curveIndex, dragIndex, bendSegment, movePoint],
);
+ /** 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) {
+ e.stopPropagation();
+ stretch.finish();
+ return;
+ }
if (rangeDrag !== null) {
e.stopPropagation();
- if (!rangeCrossed.current) onRangeClear?.();
- rangeCrossed.current = false;
- setRangeDrag(null);
+ finishRangeDrag();
return;
}
if (dragIndex === null && curveIndex === null) return;
@@ -289,7 +344,22 @@ export function useAutomationLaneGestures({
setHint(null);
commitPoints(lane.points, true);
},
- [rangeDrag, onRangeClear, curveIndex, dragIndex, lane, commitPoints],
+ [stretch, rangeDrag, finishRangeDrag, curveIndex, dragIndex, lane, commitPoints],
+ );
+
+ /** `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. */
+ const cancelDrag = useCallback(
+ (e: ReactPointerEvent<SVGSVGElement>): void => {
+ if (stretch.edge !== null) {
+ e.stopPropagation();
+ stretch.cancel();
+ return;
+ }
+ endDrag(e);
+ },
+ [stretch, endDrag],
);
const onDoubleClick = useCallback(
@@ -352,12 +422,15 @@ export function useAutomationLaneGestures({
return {
dragIndex,
curveIndex,
+ edgeDrag: stretch.edge,
+ edgeHover: stretch.hover,
hint,
hitIndex,
segmentIndex,
onPointerDown,
onPointerMove,
endDrag,
+ cancelDrag,
onDoubleClick,
editing,
setEditingText,