Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): fade handles ride the fade's end and the waveform shows the fade (#4844)
Miguel Ángel07af05c8169d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 410495b19a..a5fd939fde 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -955,7 +955,7 @@ jobs:node packages/studio/tests/e2e/perf-ratchet.mjs check \packages/studio/tests/e2e/perf-ceilings.json studio-open /tmp/studio-open-counts.json \/tmp/base-perf-ceilings.json- - name: Measure the fade handle dots on a narrow clip+ - name: Measure the fade handle tabs on a narrow clipif: success() || failure()run: |set -euo pipefaildiff --git a/packages/studio/src/captions/keyboard.test.ts b/packages/studio/src/captions/keyboard.test.tsindex 982c1f352d..44a4f2b019 100644--- a/packages/studio/src/captions/keyboard.test.ts+++ b/packages/studio/src/captions/keyboard.test.ts@@ -38,6 +38,12 @@ describe("shouldHandleCaptionNudgeKey", () => {expect(shouldHandleCaptionNudgeKey(mockKeyboardEvent("KeyL"))).toBe(false);});+ it("ignores arrows a focused slider owns", () => {+ const slider = document.createElement("div");+ slider.setAttribute("role", "slider");+ expect(shouldHandleCaptionNudgeKey(mockKeyboardEvent("ArrowUp"), slider)).toBe(false);+ });+it("ignores arrows when the event target is an editable element", () => {const input = document.createElement("input");const textarea = document.createElement("textarea");diff --git a/packages/studio/src/captions/keyboard.ts b/packages/studio/src/captions/keyboard.tsindex 93f90381de..0ea2f05450 100644--- a/packages/studio/src/captions/keyboard.ts+++ b/packages/studio/src/captions/keyboard.ts@@ -1,4 +1,5 @@import { isEditableTarget } from "../utils/timelineDiscovery";+import { ownsPlainKeys } from "../utils/typingTarget";const CAPTION_NUDGE_KEYS = new Set(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]);@@ -9,7 +10,7 @@ export function shouldHandleCaptionNudgeKey(target?: EventTarget | null,): boolean {if (event.metaKey || event.ctrlKey || event.altKey) return false;- if (target != null && isEditableTarget(target)) return false;+ if (target != null && ownsPlainKeys(target)) return false;return CAPTION_NUDGE_KEYS.has(event.key);}diff --git a/packages/studio/src/components/editor/useDomEditNudge.test.tsx b/packages/studio/src/components/editor/useDomEditNudge.test.tsxindex 673b3483f5..71f28139af 100644--- a/packages/studio/src/components/editor/useDomEditNudge.test.tsx+++ b/packages/studio/src/components/editor/useDomEditNudge.test.tsx@@ -124,6 +124,37 @@ describe("useDomEditNudge — selection cleanup keyed on stable identity", () =>element.remove();});+ it("leaves arrows on a focused slider alone", () => {+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ const element = document.createElement("div");+ element.id = "dot-a";+ const slider = document.createElement("div");+ slider.setAttribute("role", "slider");+ document.body.append(element, slider);+ const commit = vi.fn();+ act(() => {+ root.render(+ React.createElement(Harness, {+ selection: makeSelection("Dot", element),+ onPathOffsetCommit: commit,+ }),+ );+ });+ act(() => {+ slider.dispatchEvent(+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }),+ );+ vi.advanceTimersByTime(CANVAS_NUDGE_COMMIT_DEBOUNCE_MS + 10);+ });+ expect(commit).not.toHaveBeenCalled();+ act(() => root.unmount());+ host.remove();+ element.remove();+ slider.remove();+ });+it("still flushes the burst when the selection actually changes to a different element", () => {const host = document.createElement("div");document.body.append(host);diff --git a/packages/studio/src/components/editor/useDomEditNudge.ts b/packages/studio/src/components/editor/useDomEditNudge.tsindex 096f77112a..cdfc7ed3f3 100644--- a/packages/studio/src/components/editor/useDomEditNudge.ts+++ b/packages/studio/src/components/editor/useDomEditNudge.ts@@ -7,7 +7,7 @@*/import { useCallback, useEffect, useRef, type RefObject } from "react";import { useMountEffect } from "../../hooks/useMountEffect";-import { isTypingTarget } from "../../utils/typingTarget";+import { ownsPlainKeys } from "../../utils/typingTarget";import { acquireCanvasNudgeKeys } from "../../utils/canvasNudgeGate";import type { DomEditSelection } from "./domEditing";import {@@ -132,7 +132,7 @@ function resolveSingleNudgeTarget(function shouldIgnoreNudgeKey(p: UseDomEditNudgeParams, event: KeyboardEvent): boolean {if (!p.allowCanvasMovement || event.defaultPrevented) return true;if (p.gestureRef.current || p.groupGestureRef.current || p.blockedMoveRef.current) return true;- return isTypingTarget(event.target);+ return ownsPlainKeys(event.target);}export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: () => void } {diff --git a/packages/studio/src/hooks/appHotkeysDispatch.ts b/packages/studio/src/hooks/appHotkeysDispatch.tsindex 3038662a4e..909b6ad5fd 100644--- a/packages/studio/src/hooks/appHotkeysDispatch.ts+++ b/packages/studio/src/hooks/appHotkeysDispatch.ts@@ -3,7 +3,7 @@ import { usePlayerStore } from "../player";import type { TimelineElement } from "../player";import type { DomEditSelection } from "../components/editor/domEditing";import { useDockLayoutStore } from "../components/dock/dockLayoutStore";-import { isTypingTarget } from "../utils/typingTarget";+import { isTypingTarget, ownsPlainKeys } from "../utils/typingTarget";import { isEditableTarget } from "../utils/timelineDiscovery";import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers";import { canSplitElement } from "../utils/timelineElementSplit";@@ -153,6 +153,7 @@ export function dispatchModifierKey(* Delete arbitration between keyframes, an automation range and the clip can* be asserted without standing up the whole hook. */export function dispatchPlainKey(event: KeyboardEvent, key: string, cb: HotkeyCallbacks): void {+ if (ownsPlainKeys(event.target)) return;if (key === STUDIO_PLAIN_KEYS.fullscreen && !event.shiftKey && !event.altKey) {event.preventDefault();if (document.fullscreenElement) void document.exitFullscreen();diff --git a/packages/studio/src/hooks/useAppHotkeys.test.ts b/packages/studio/src/hooks/useAppHotkeys.test.tsindex b98b83b2f0..a080639291 100644--- a/packages/studio/src/hooks/useAppHotkeys.test.ts+++ b/packages/studio/src/hooks/useAppHotkeys.test.ts@@ -60,6 +60,38 @@ afterEach(() => {});});+describe("keys on a focused slider", () => {+ const slider = () => {+ const el = document.createElement("div");+ el.setAttribute("role", "slider");+ document.body.append(el);+ return el;+ };+ const from = (target: HTMLElement, init: KeyboardEventInit) => {+ const event = new KeyboardEvent("keydown", { ...init, bubbles: true, cancelable: true });+ Object.defineProperty(event, "target", { value: target });+ return event;+ };++ it("leaves Delete to the slider instead of deleting the selected clip", () => {+ usePlayerStore.setState({+ elements: [bgmElement],+ selectedElementId: "bgm",+ selectedElementIds: new Set(["bgm"]),+ });+ const cb = callbacks();+ dispatchPlainKey(from(slider(), { key: "Delete" }), "delete", cb);+ expect(cb.handleTimelineElementsDelete).not.toHaveBeenCalled();+ expect(cb.handleTimelineElementDelete).not.toHaveBeenCalled();+ });++ it("still undoes with Cmd+Z while a slider has focus", () => {+ const cb = callbacks();+ dispatchModifierKey(from(slider(), { key: "z", metaKey: true }), "z", cb);+ expect(cb.handleUndo).toHaveBeenCalledTimes(1);+ });+});+describe("dispatchPlainKey — select leftward / rightward", () => {const clips = [{ ...bgmElement, id: "early", key: "early", start: 0, track: 0 },diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.tsindex 6bec46e452..eba9d0ecc4 100644--- a/packages/studio/src/hooks/useAppHotkeys.ts+++ b/packages/studio/src/hooks/useAppHotkeys.ts@@ -2,7 +2,6 @@ import { useCallback, useEffect, useRef } from "react";import { usePlayerStore } from "../player";import type { TimelineElement } from "../player";import type { DomEditSelection } from "../components/editor/domEditing";-import { isTypingTarget } from "../utils/typingTarget";import { useCaptionStore } from "../captions/store";import {applyCaptionModelToIframe,@@ -220,7 +219,7 @@ export function useAppHotkeys({dispatchModifierKey(event, key, cb);return;}- if (!isTypingTarget(event.target)) dispatchPlainKey(event, key, cb);+ dispatchPlainKey(event, key, cb);}, []);// eslint-disable-next-line no-restricted-syntaxdiff --git a/packages/studio/src/hooks/useRenderClipContent.ts b/packages/studio/src/hooks/useRenderClipContent.tsindex c0d22d572b..aa6d7b7200 100644--- a/packages/studio/src/hooks/useRenderClipContent.ts+++ b/packages/studio/src/hooks/useRenderClipContent.ts@@ -9,7 +9,7 @@ import {import type { TimelineElement } from "../player";import type { TimelineClipRenderContext } from "../player/components/TimelineTypes";import { audioPillFlags } from "../player/components/audioClipLink";-import { AudioWaveform } from "../player/components/AudioWaveform";+import { AudioWaveform, rendersWaveform } from "../player/components/AudioWaveform";import { ImageThumbnail } from "../player/components/ImageThumbnail";import { encodePreviewPath, resolveMediaPreviewUrl } from "../player/components/thumbnailUtils";import { usePlayerStore } from "../player/store/playerStore";@@ -135,7 +135,7 @@ export function useRenderClipContent({// Thumbnail generation disabled (perf) -> plain clip bars. Audio still shows// its waveform (cheap, not a frame thumbnail). Toggle: timeline toolbar.if (effectiveMode === "hidden") {- return el.tag === "audio"+ return rendersWaveform(el)? renderAudioClip(el, pid, sessionEpoch, style.label, context, elements): null;}@@ -173,7 +173,7 @@ export function useRenderClipContent({// Audio clips — waveform visualization. Resolve these before the generic// activePreviewUrl thumbnail branch; audio rows need waveform data, not a// captured frame from the currently drilled composition preview.- if (el.tag === "audio") {+ if (rendersWaveform(el)) {return renderAudioClip(el, pid, sessionEpoch, style.label, context, elements);}diff --git a/packages/studio/src/player/components/AudioWaveform.test.tsx b/packages/studio/src/player/components/AudioWaveform.test.tsxindex d4776ad496..f03c11df92 100644--- a/packages/studio/src/player/components/AudioWaveform.test.tsx+++ b/packages/studio/src/player/components/AudioWaveform.test.tsx@@ -20,24 +20,30 @@ afterEach(() => {document.body.innerHTML = "";});+/** A 6 x 20 canvas whose 2D context records every fill as [style, x, y, width, height]. */+function recordingCanvas() {+ const fills: Array<[string, number, number, number, number]> = [];+ const context = {+ scale: vi.fn(),+ clearRect: vi.fn(),+ fillStyle: "",+ fillRect: (x: number, y: number, width: number, height: number) =>+ fills.push([String(context.fillStyle), x, y, width, height]),+ } as unknown as CanvasRenderingContext2D;+ const canvas = document.createElement("canvas");+ Object.defineProperties(canvas, {+ clientWidth: { value: 6 },+ clientHeight: { value: 20 },+ });+ vi.spyOn(canvas, "getContext").mockReturnValue(context);+ return { canvas, fills };+}+describe("AudioWaveform", () => {it("paints a baseline and peak bar for every mapped waveform bin", () => {- const fillRect = vi.fn();- const context = {- scale: vi.fn(),- clearRect: vi.fn(),- fillRect,- fillStyle: "",- } as unknown as CanvasRenderingContext2D;- const canvas = document.createElement("canvas");- Object.defineProperties(canvas, {- clientWidth: { value: 6 },- clientHeight: { value: 20 },- });- vi.spyOn(canvas, "getContext").mockReturnValue(context);+ const { canvas, fills } = recordingCanvas();drawWaveformCanvas(canvas, [0.25, 1], false, 0, 1);- expect(fillRect).toHaveBeenCalledTimes(4);- expect(fillRect.mock.calls.map(([x, y, width, height]) => [x, y, width, height])).toEqual([+ expect(fills.map(([, x, y, width, height]) => [x, y, width, height])).toEqual([[0, 18, 3, 2],[0, 15, 3, 5],[3, 18, 3, 2],@@ -45,6 +51,21 @@ describe("AudioWaveform", () => {]);});+ it("shrinks each bar to the fade's gain and keeps the cut-away part as a ghost", () => {+ const { canvas, fills } = recordingCanvas();+ // A 1 s fade-in on a 2 s clip: the first bar's centre (0.5 s) plays at half gain.+ drawWaveformCanvas(canvas, [1, 1], false, 0, 1, { fadeIn: 1, fadeOut: 0, duration: 2 });+ const bars = fills.filter(([, , y, , height]) => !(y === 18 && height === 2));+ // The heard half, then the ghost only above it, so the two never stack.+ expect(bars.map(([, x, y, width, height]) => [x, y, width, height])).toEqual([+ [0, 10, 3, 10],+ [0, 0, 3, 10],+ [3, 0, 3, 20],+ ]);+ const alpha = (style: string) => Number(style.split(",").at(-1)?.replace(")", ""));+ expect(alpha(bars[1][0])).toBeCloseTo(alpha(bars[0][0]) * 0.27, 2);+ });+it("leases waveform decoding with the clip's project, session, and viewport priority", () => {const host = document.createElement("div");document.body.append(host);diff --git a/packages/studio/src/player/components/AudioWaveform.tsx b/packages/studio/src/player/components/AudioWaveform.tsxindex 1c575aaa80..2d8eef38f9 100644--- a/packages/studio/src/player/components/AudioWaveform.tsx+++ b/packages/studio/src/player/components/AudioWaveform.tsx@@ -1,8 +1,10 @@-import { memo, useCallback, useEffect, useMemo, useRef } from "react";+import { memo, useCallback, useContext, useEffect, useMemo, useRef } from "react";+import { fadeGain } from "@hyperframes/core/audio-fade";import { useMountEffect } from "../../hooks/useMountEffect";import { useThumbnailLease } from "../../hooks/useThumbnailLease";import { createThumbnailKey, type ThumbnailPriority } from "../lib/thumbnailScheduler";import { decimatePeaks, loudnessToOpacity } from "./audioWaveformPeaks";+import { ClipFadesContext, type ClipFadeShape } from "./TimelineClipFades";export interface AudioWaveformProps {audioUrl: string;@@ -22,7 +24,10 @@ export interface AudioWaveformProps {const BAR_STEP = 3;-type BarGeometry = { x: number; width: number; height: number };+export const rendersWaveform = (el: { tag: string }) => el.tag === "audio";+const FADE_GHOST_OPACITY = 0.27;++type BarGeometry = { x: number; width: number; height: number; gain: number };function paintWaveformBars(context: CanvasRenderingContext2D,@@ -33,11 +38,18 @@ function paintWaveformBars(amplitudes: readonly number[],) {bars.forEach((bar, index) => {- const amplitude = amplitudes[index] ?? 0;+ const opacity = loudnessToOpacity(amplitudes[index] ?? 0);context.fillStyle = `rgb(${waveformBaselineRgb})`;context.fillRect(bar.x, height - 2, bar.width, 2);- context.fillStyle = `rgba(${waveformBarRgb},${loudnessToOpacity(amplitude).toFixed(2)})`;- context.fillRect(bar.x, height - bar.height, bar.width, bar.height);+ const paint = (alpha: number, top: number, barHeight: number) => {+ context.fillStyle = `rgba(${waveformBarRgb},${alpha.toFixed(2)})`;+ context.fillRect(bar.x, top, bar.width, barHeight);+ };+ const faded = bar.height * bar.gain;+ if (faded > 0) paint(opacity, height - faded, faded);+ if (faded < bar.height) {+ paint(opacity * FADE_GHOST_OPACITY, height - bar.height, bar.height - faded);+ }});}@@ -47,6 +59,7 @@ export function drawWaveformCanvas(muted: boolean,trimStartFraction: number,trimEndFraction: number,+ fades: ClipFadeShape | null = null,) {const width = Math.max(1, canvas.clientWidth);const height = Math.max(1, canvas.clientHeight);@@ -67,6 +80,9 @@ export function drawWaveformCanvas(x: (index * width) / amplitudes.length,width: Math.max(1, width / amplitudes.length),height: Math.max(3, amplitude * height),+ gain: fades+ ? fadeGain(((index + 0.5) / amplitudes.length) * fades.duration, fades.duration, fades)+ : 1,}));const channelToken = muted ? "--timeline-waveform-muted-rgb" : "--timeline-waveform-bar-rgb";const waveformBarRgb = getComputedStyle(canvas).getPropertyValue(channelToken);@@ -179,11 +195,12 @@ export const AudioWaveform = memo(function AudioWaveform({const peaks =snapshot.status === "ready" && snapshot.value.kind === "waveform" ? snapshot.value.peaks : null;+ const fades = useContext(ClipFadesContext);const draw = useCallback(() => {const canvas = canvasRef.current;if (!canvas || !peaks) return;- drawWaveformCanvas(canvas, peaks, muted, trimStartFraction ?? 0, trimEndFraction ?? 1);- }, [muted, peaks, trimEndFraction, trimStartFraction]);+ drawWaveformCanvas(canvas, peaks, muted, trimStartFraction ?? 0, trimEndFraction ?? 1, fades);+ }, [fades, muted, peaks, trimEndFraction, trimStartFraction]);const setCanvasRef = useCallback((canvas: HTMLCanvasElement | null) => {diff --git a/packages/studio/src/player/components/TimelineClip.test.tsx b/packages/studio/src/player/components/TimelineClip.test.tsxindex fd54c254d2..0e2de43a3c 100644--- a/packages/studio/src/player/components/TimelineClip.test.tsx+++ b/packages/studio/src/player/components/TimelineClip.test.tsx@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";import type { TimelineElement } from "../store/playerStore";import { TimelineClip } from "./TimelineClip";+import { ClipFadesContext } from "./TimelineClipFades";import type { TimelineEditCapabilities } from "./timelineEditing";import { defaultTimelineTheme, type TimelineTheme } from "./timelineTheme";@@ -67,6 +68,43 @@ function renderClip({}describe("TimelineClip", () => {+ it("hands its content the clip's fades, and none to a clip the mixer does not hear", () => {+ const seen: unknown[] = [];+ function Probe() {+ seen.push(React.useContext(ClipFadesContext));+ return null;+ }+ const render = (element: TimelineElement) => {+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ act(() => {+ root.render(+ <TimelineClip+ el={element}+ pps={100}+ clipY={0}+ isSelected={false}+ isHovered={false}+ hasCustomContent+ capabilities={capabilities}+ isComposition={false}+ onHoverStart={vi.fn()}+ onHoverEnd={vi.fn()}+ onClick={vi.fn()}+ onDoubleClick={vi.fn()}+ >+ <Probe />+ </TimelineClip>,+ );+ });+ act(() => root.unmount());+ };+ render({ id: "music", tag: "audio", start: 0, duration: 4, track: 0, fadeIn: 1, fadeOut: 0.5 });+ render({ id: "title", tag: "div", start: 0, duration: 4, track: 0, fadeIn: 1 });+ expect(seen).toEqual([{ fadeIn: 1, fadeOut: 0.5, duration: 4 }, null]);+ });+it("renders the clip label above custom content without showing default timecode", () => {const { host, root } = renderClip({element: { id: "hero", label: "Hero", tag: "div", start: 1, duration: 1, track: 0 },diff --git a/packages/studio/src/player/components/TimelineClip.tsx b/packages/studio/src/player/components/TimelineClip.tsxindex c31206aa2a..26b0913b0f 100644--- a/packages/studio/src/player/components/TimelineClip.tsx+++ b/packages/studio/src/player/components/TimelineClip.tsx@@ -9,7 +9,8 @@ import {import type { TimelineEditCapabilities } from "./timelineEditing";import { isAudioTimelineElement } from "../../utils/timelineInspector";import { timelineClipFocusId } from "./timelineNavigationIdentity";-import { TimelineClipFades } from "./TimelineClipFades";+import { ClipFadesContext, TimelineClipFades, useClipFadeDraft } from "./TimelineClipFades";+import { rendersWaveform } from "./AudioWaveform";interface TimelineClipProps {el: TimelineElement;@@ -82,6 +83,8 @@ export const TimelineClip = memo(function TimelineClip({"--clip-handle": theme.handleColor,} as CSSProperties;const isAudioClip = isAudioTimelineElement(el);+ const hasFades = (isAudioClip || Boolean(el.hasAudio)) && !isGestureActor;+ const fade = useClipFadeDraft(el);const clipClassName = ["timeline-clip","absolute",@@ -206,16 +209,21 @@ export const TimelineClip = memo(function TimelineClip({{startLabel}-{endLabel}s</span>)}- {children}- {/* Fade handles + ramps for anything the mixer hears — audio clips and- videos marked data-has-audio. They write data-fade-in/out on the clip- and are the timeline half of the inspector's Fade rows. */}- {(isAudioClip || el.hasAudio) && !isGestureActor && (+ <ClipFadesContext.Provider value={hasFades ? fade.shape : null}>+ {children}+ </ClipFadesContext.Provider>+ {/* Fade handles for anything the mixer hears: audio clips and videos marked+ data-has-audio. They write data-fade-in/out, the timeline half of the+ inspector's Fade rows. */}+ {hasFades && (<TimelineClipFadesel={el}pps={pps}widthPx={widthPx}showHandles={(isHovered || isSelected) && !isDragging}+ focusable={isSelected}+ hasWaveform={rendersWaveform(el)}+ fade={fade}/>)}</button>diff --git a/packages/studio/src/player/components/TimelineClipFades.test.tsx b/packages/studio/src/player/components/TimelineClipFades.test.tsxindex 80b8386bc6..43a9290cdf 100644--- a/packages/studio/src/player/components/TimelineClipFades.test.tsx+++ b/packages/studio/src/player/components/TimelineClipFades.test.tsx@@ -3,8 +3,8 @@import React, { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";-import type { TimelineElement } from "../store/playerStore";-import { TimelineClipFades } from "./TimelineClipFades";+import { usePlayerStore, type TimelineElement } from "../store/playerStore";+import { TimelineClipFades, useClipFadeDraft } from "./TimelineClipFades";import { TimelineEditProvider } from "../../contexts/TimelineEditContext";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -14,8 +14,15 @@ const mounted: Root[] = [];afterEach(() => {act(() => mounted.splice(0).forEach((root) => root.unmount()));document.body.innerHTML = "";+ usePlayerStore.setState({ currentTime: 0, elements: [], timelineSnapEnabled: true });});+/** TimelineClip owns the draft; this stands in for it. */+function Fades(props: { el: TimelineElement; showHandles: boolean; focusable?: boolean }) {+ const fade = useClipFadeDraft(props.el);+ return <TimelineClipFades {...props} pps={100} widthPx={props.el.duration * 100} fade={fade} />;+}+const clip: TimelineElement = {id: "music",tag: "audio",@@ -29,7 +36,12 @@ const clip: TimelineElement = {function render(el: TimelineElement,- options: { showHandles?: boolean; provide?: boolean; onClipPointerDown?: () => void } = {},+ options: {+ showHandles?: boolean;+ provide?: boolean;+ focusable?: boolean;+ onClipPointerDown?: () => void;+ } = {},) {const host = document.createElement("div");document.body.append(host);@@ -39,36 +51,30 @@ function render(const onSetElementAttributeQuiet = vi.fn().mockResolvedValue(undefined);const onRevertElementAttributeLive = vi.fn();// Stands in for the TimelineClip button the handles live inside.- const node = (+ const tree = (el: TimelineElement) => (<div data-testid="clip" onPointerDown={options.onClipPointerDown}>- <TimelineClipFades- el={el}- pps={100}- widthPx={el.duration * 100}- showHandles={options.showHandles ?? true}- />+ <Fades el={el} showHandles={options.showHandles ?? true} focusable={options.focusable} /></div>);- act(() => {- root.render(- options.provide === false ? (- node- ) : (- <TimelineEditProvider- value={{- onSetElementAttributeLive,- onSetElementAttributeQuiet,- onRevertElementAttributeLive,- }}- >- {node}- </TimelineEditProvider>- ),+ const wrap = (el: TimelineElement) =>+ options.provide === false ? (+ tree(el)+ ) : (+ <TimelineEditProvider+ value={{+ onSetElementAttributeLive,+ onSetElementAttributeQuiet,+ onRevertElementAttributeLive,+ }}+ >+ {tree(el)}+ </TimelineEditProvider>);- });+ act(() => root.render(wrap(el)));return {host,root,+ rerender: (next: TimelineElement) => act(() => root.render(wrap(next))),onSetElementAttributeLive,onSetElementAttributeQuiet,onRevertElementAttributeLive,@@ -81,6 +87,19 @@ function pointer(type: string, clientX: number, pointerId = 1, clientY = 0) {return event;}+/** Pointer down at the first point, then a move to each later one; [clientX, pointerId?]. */+function press(handle: HTMLElement, down: [number, number?], ...moves: Array<[number, number?]>) {+ act(() => handle.dispatchEvent(pointer("pointerdown", ...down)));+ for (const move of moves) act(() => handle.dispatchEvent(pointer("pointermove", ...move)));+}++function armedHandle(host: HTMLElement, edge: "in" | "out") {+ const handle = host.querySelector<HTMLElement>(`[data-testid="clip-fade-handle-${edge}"]`);+ if (!handle) throw new Error(`expected a fade-${edge} handle`);+ armCapture(handle);+ return handle;+}+function armCapture(handle: HTMLElement) {let captured = false;Object.defineProperty(handle, "setPointerCapture", { value: () => (captured = true) });@@ -122,13 +141,9 @@ describe("TimelineClipFades", () => {it("drags the fade-in dot to the right, previewing live and committing once on release", () => {const { host, root, onSetElementAttributeLive, onSetElementAttributeQuiet } = render(clip);- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- if (!handle) throw new Error("expected a fade-in handle");- armCapture(handle);+ const handle = armedHandle(host, "in");// 150 px of rightward travel adds 1.5 s to the 1 s fade-in, wherever the press lands.- act(() => handle.dispatchEvent(pointer("pointerdown", 100)));- act(() => handle.dispatchEvent(pointer("pointermove", 200)));- act(() => handle.dispatchEvent(pointer("pointermove", 250)));+ press(handle, [100], [200], [250]);expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-in", "2.5");expect(onSetElementAttributeQuiet).not.toHaveBeenCalled();// The ramp follows the pointer before anything is persisted.@@ -143,12 +158,9 @@ describe("TimelineClipFades", () => {it("drags the fade-out dot to the left, growing the fade, and never past the fade-in", () => {const { host, root, onSetElementAttributeLive, onSetElementAttributeQuiet } = render(clip);- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-out"]');- if (!handle) throw new Error("expected a fade-out handle");- armCapture(handle);+ const handle = armedHandle(host, "out");// 300 px of leftward travel adds 3 s to the 2 s fade-out, wherever the press lands.- act(() => handle.dispatchEvent(pointer("pointerdown", 1000)));- act(() => handle.dispatchEvent(pointer("pointermove", 700)));+ press(handle, [1000], [700]);expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-out", "5");// Way past the start: clamps to duration − fadeIn = 9 s.act(() => handle.dispatchEvent(pointer("pointermove", 0)));@@ -160,11 +172,8 @@ describe("TimelineClipFades", () => {it("removes the attribute when dragged back to zero", () => {const { host, root, onSetElementAttributeQuiet } = render(clip);- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- if (!handle) throw new Error("expected a fade-in handle");- armCapture(handle);- act(() => handle.dispatchEvent(pointer("pointerdown", 200)));- act(() => handle.dispatchEvent(pointer("pointermove", 0)));+ const handle = armedHandle(host, "in");+ press(handle, [200], [0]);act(() => handle.dispatchEvent(pointer("pointerup", 0)));expect(onSetElementAttributeQuiet).toHaveBeenCalledWith(clip, "data-fade-in", null, "Fade in");act(() => root.unmount());@@ -178,11 +187,8 @@ describe("TimelineClipFades", () => {onRevertElementAttributeLive,onSetElementAttributeQuiet,} = render(clip);- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- if (!handle) throw new Error("expected a fade-in handle");- armCapture(handle);- act(() => handle.dispatchEvent(pointer("pointerdown", 100)));- act(() => handle.dispatchEvent(pointer("pointermove", 300)));+ const handle = armedHandle(host, "in");+ press(handle, [100], [300]);act(() => handle.dispatchEvent(pointer("pointercancel", 300)));// Written back live for a host without the revert, then ended through the lanes' revert.expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-in", "1");@@ -196,11 +202,8 @@ describe("TimelineClipFades", () => {const elsewhere = document.createElement("button");document.body.append(elsewhere);elsewhere.focus();- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- if (!handle) throw new Error("expected a fade-in handle");- armCapture(handle);- act(() => handle.dispatchEvent(pointer("pointerdown", 100)));- act(() => handle.dispatchEvent(pointer("pointermove", 300)));+ const handle = armedHandle(host, "in");+ press(handle, [100], [300]);expect(document.activeElement).toBe(elsewhere);act(() => {document.activeElement?.dispatchEvent(@@ -221,11 +224,8 @@ describe("TimelineClipFades", () => {])("restores the fade and saves nothing when released %s", (_, clientX, clientY) => {const { host, root, onSetElementAttributeLive, onRevertElementAttributeLive, ...rest } =render(clip);- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- if (!handle) throw new Error("expected a fade-in handle");- armCapture(handle);- act(() => handle.dispatchEvent(pointer("pointerdown", 100)));- act(() => handle.dispatchEvent(pointer("pointermove", 300)));+ const handle = armedHandle(host, "in");+ press(handle, [100], [300]);act(() => handle.dispatchEvent(pointer("pointerup", clientX, 1, clientY)));expect(rest.onSetElementAttributeQuiet).not.toHaveBeenCalled();expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-in", "1");@@ -257,12 +257,28 @@ describe("TimelineClipFades", () => {},);- it.each([0.3, 3])("pins the handles to the top corners for a %s s fade-in", (fadeIn) => {+ it.each([+ [0.3, "18px"],+ [3, "288px"],+ ])("puts the fade-in tab at the end of a %s s fade", (fadeIn, left) => {const { host } = render({ ...clip, fadeIn, fadeOut: 0.4 });const inHandle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- const fadeOut = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-out"]');+ const outHandle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-out"]');+ // The 24 px box centres on the fade's end: 0.4 s out of a 1000 px clip ends at 960.+ expect(inHandle?.style.left).toBe(left);+ expect(outHandle?.style.left).toBe("948px");+ const tab = inHandle?.firstElementChild as HTMLElement;+ expect(tab.style.left).toBe("10px");+ });++ it("keeps the tab off the rounded end when there is no fade", () => {+ const { host } = render({ ...clip, fadeIn: undefined, fadeOut: undefined });+ const inHandle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ const outHandle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-out"]');expect(inHandle?.style.left).toBe("0px");- expect(fadeOut?.style.left).toBe(`${1000 - 24}px`);+ expect(outHandle?.style.left).toBe("976px");+ // The tab itself sits 7 px in from each end: 5 px is its left edge, 2 px either side of 7.+ expect(inHandle?.querySelector<HTMLElement>(".timeline-fade-tab")?.style.left).toBe("5px");});it("lengthens a fade by the pointer's inward travel from wherever the press lands", () => {@@ -272,19 +288,17 @@ describe("TimelineClipFades", () => {if (!fadeIn || !fadeOut) throw new Error("expected both handles");armCapture(fadeIn);armCapture(fadeOut);- act(() => fadeIn.dispatchEvent(pointer("pointerdown", 12)));- act(() => fadeIn.dispatchEvent(pointer("pointermove", 162)));+ press(fadeIn, [12], [162]);expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-in", "2.5");act(() => fadeIn.dispatchEvent(pointer("pointerup", 162)));- act(() => fadeOut.dispatchEvent(pointer("pointerdown", 988, 2)));- act(() => fadeOut.dispatchEvent(pointer("pointermove", 888, 2)));+ press(fadeOut, [988, 2], [888, 2]);expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-out", "3");});it("paints the handles above the clip's waveform and thumbnail layers", () => {const { host } = render(clip);- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- expect(Number(handle?.style.zIndex)).toBeGreaterThan(10);+ const layer = host.querySelector<HTMLElement>('[data-testid="clip"]')?.firstElementChild;+ expect(Number((layer as HTMLElement).style.zIndex)).toBeGreaterThan(10);});it("splits a clip narrower than two targets between the handles", () => {@@ -293,19 +307,307 @@ describe("TimelineClipFades", () => {const fadeOut = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-out"]');expect([fadeIn?.style.left, fadeIn?.style.width]).toEqual(["0px", "15px"]);expect([fadeOut?.style.left, fadeOut?.style.width]).toEqual(["15px", "15px"]);- const dot = fadeIn?.firstElementChild as HTMLElement;- expect(getComputedStyle(dot).width).toBe("10px");- // Layout is not real here; tests/e2e/fade-handles.mjs measures the box in Chrome.- expect(getComputedStyle(dot).flexShrink).toBe("0");- expect(getComputedStyle(dot).pointerEvents).toBe("none");+ const tab = fadeIn?.firstElementChild as HTMLElement;+ expect([tab.style.width, tab.style.height]).toEqual(["4px", "15px"]);+ // Layout is not real here; tests/e2e/fade-handles.mjs measures the tab in Chrome.+ expect(tab.style.pointerEvents).toBe("none");+ });++ it("snaps the fade's end to the playhead within the timeline's snap radius", () => {+ usePlayerStore.setState({ currentTime: 4.5 });+ const { host, onSetElementAttributeLive } = render(clip);+ const handle = armedHandle(host, "in");+ // 146 px makes a 2.46 s fade ending at 4.46 s, 4 px from the playhead: it lands on 4.5.+ press(handle, [100], [246]);+ expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-in", "2.5");+ });++ it("leaves the fade unsnapped when the timeline's snapping is off", () => {+ usePlayerStore.setState({ currentTime: 4.5, timelineSnapEnabled: false });+ const { host, onSetElementAttributeLive } = render(clip);+ const handle = armedHandle(host, "in");+ press(handle, [100], [246]);+ expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-in", "2.46");+ });++ it("snaps to another clip's edge", () => {+ usePlayerStore.setState({+ elements: [clip, { id: "title", tag: "div", start: 6, duration: 2, track: 0 }],+ });+ const { host, onSetElementAttributeLive } = render(clip);+ const handle = armedHandle(host, "out");+ // The 2 s fade-out starts at 10 s; 395 px left moves that to 6.05 s, onto the title's start.+ press(handle, [1000], [605]);+ expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-out", "6");+ });++ it.each([+ [1, null],+ [undefined, "0.5"],+ ])("double-click on a %s s fade-in saves %s", (fadeIn, saved) => {+ const { host, onSetElementAttributeQuiet } = render({ ...clip, fadeIn });+ const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ act(() => handle?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })));+ expect(onSetElementAttributeQuiet).toHaveBeenCalledTimes(1);+ expect(onSetElementAttributeQuiet).toHaveBeenCalledWith(+ { ...clip, fadeIn },+ "data-fade-in",+ saved,+ "Fade in",+ );+ });++ const key = (handle: HTMLElement | null, type: "keydown" | "keyup", init: KeyboardEventInit) =>+ act(() => {+ handle?.dispatchEvent(new KeyboardEvent(type, { ...init, bubbles: true }));+ });++ it.each([+ [{ key: "ArrowRight" }, "1.1"],+ [{ key: "ArrowRight", shiftKey: true }, "2"],+ [{ key: "ArrowLeft" }, "0.9"],+ [{ key: "Home" }, null],+ [{ key: "Delete" }, null],+ [{ key: "Backspace" }, null],+ [{ key: "End" }, "8"],+ ])("saves a key press once it is released: %o", (init, saved) => {+ const outer = vi.fn();+ const { host, onSetElementAttributeQuiet } = render(clip, { focusable: true });+ document.body.addEventListener("keydown", outer);+ const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ expect(handle?.tabIndex).toBe(0);+ key(handle, "keydown", init);+ expect(onSetElementAttributeQuiet).not.toHaveBeenCalled();+ key(handle, "keyup", init);+ expect(onSetElementAttributeQuiet).toHaveBeenCalledTimes(1);+ expect(onSetElementAttributeQuiet).toHaveBeenCalledWith(clip, "data-fade-in", saved, "Fade in");+ // The timeline's own arrow-key handling never sees a key the handle used.+ expect(outer).not.toHaveBeenCalled();+ });++ it.each(["ArrowRight", "End"])("saves nothing for %s on a lone fade past the clip's end", (k) => {+ const long = { ...clip, duration: 3, fadeIn: 5, fadeOut: undefined };+ const { host, onSetElementAttributeQuiet } = render(long, { focusable: true });+ const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ key(handle, "keydown", { key: k });+ key(handle, "keyup", { key: k });+ expect(onSetElementAttributeQuiet).not.toHaveBeenCalled();+ });++ it("previews a held key live and saves it as one step", () => {+ const { host, onSetElementAttributeLive, onSetElementAttributeQuiet } = render(clip, {+ focusable: true,+ });+ const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ for (const repeat of [false, true, true]) key(handle, "keydown", { key: "ArrowRight", repeat });+ expect(onSetElementAttributeLive.mock.calls.map(([, , value]) => value)).toEqual([+ "1.1",+ "1.2",+ "1.3",+ ]);+ key(handle, "keyup", { key: "ArrowRight" });+ expect(onSetElementAttributeQuiet).toHaveBeenCalledTimes(1);+ expect(onSetElementAttributeQuiet).toHaveBeenCalledWith(clip, "data-fade-in", "1.3", "Fade in");+ });++ it("ignores keys while the handle is being dragged", () => {+ const { host, onSetElementAttributeQuiet } = render(clip, { focusable: true });+ const handle = armedHandle(host, "in");+ press(handle, [100], [200]);+ key(handle, "keydown", { key: "Home" });+ key(handle, "keyup", { key: "Home" });+ expect(onSetElementAttributeQuiet).not.toHaveBeenCalled();+ });++ it("drops the draft when the save fails, leaving the live value to the save path", async () => {+ const { host, onSetElementAttributeQuiet, onRevertElementAttributeLive } = render(clip);+ onSetElementAttributeQuiet.mockResolvedValueOnce({ status: "failed", reason: "disk full" });+ const handle = armedHandle(host, "in");+ press(handle, [100], [300]);+ act(() => handle.dispatchEvent(pointer("pointerup", 300)));+ await act(async () => {});+ expect(onRevertElementAttributeLive).not.toHaveBeenCalled();+ expect(host.querySelector('[data-testid="clip-fade-in"]')?.getAttribute("points")).toBe(+ "0,0 100,0 0,100",+ );+ });++ it("steps from a pressed value whose save has not landed yet", () => {+ const { host, onSetElementAttributeQuiet } = render(clip, { focusable: true });+ onSetElementAttributeQuiet.mockReturnValue(new Promise(() => {}));+ const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ for (let tap = 0; tap < 2; tap++) {+ key(handle, "keydown", { key: "ArrowRight" });+ key(handle, "keyup", { key: "ArrowRight" });+ }+ expect(onSetElementAttributeQuiet.mock.calls.map(([, , value]) => value)).toEqual([+ "1.1",+ "1.2",+ ]);+ });++ it("saves a held key before a press on the handle starts a drag", () => {+ const { host, onSetElementAttributeQuiet } = render(clip, { focusable: true });+ const handle = armedHandle(host, "in");+ key(handle, "keydown", { key: "ArrowRight" });+ press(handle, [100]);+ expect(onSetElementAttributeQuiet).toHaveBeenCalledWith(clip, "data-fade-in", "1.1", "Fade in");+ });++ it("keeps a handle drawn while it is dragged to where it can no longer move", () => {+ // A fade-in that fills the clip next to a 2 s fade-out, as a trim leaves it.+ const trimmed = { ...clip, fadeIn: 10, fadeOut: 2 };+ const { host, onSetElementAttributeQuiet } = render(trimmed);+ const handle = armedHandle(host, "out");+ // 200 px right shrinks the 2 s fade-out to 0, where it has no room left to move.+ press(handle, [800], [1000]);+ act(() => handle.dispatchEvent(pointer("pointerup", 1000)));+ expect(onSetElementAttributeQuiet).toHaveBeenCalledWith(+ trimmed,+ "data-fade-out",+ null,+ "Fade out",+ );+ });++ it("hides a handle with less than one 0.01 s step to move", () => {+ const { host } = render({ ...clip, duration: 10.0333, fadeIn: 10.03, fadeOut: undefined });+ expect(host.querySelector('[data-testid="clip-fade-handle-out"]')).toBeNull();+ });++ it("never lets a grow key shrink a fade when the pair overruns the clip", () => {+ const overrun = { ...clip, fadeIn: 2, fadeOut: 10 };+ const { host, onSetElementAttributeQuiet } = render(overrun, { focusable: true });+ const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ key(handle, "keydown", { key: "ArrowRight" });+ key(handle, "keyup", { key: "ArrowRight" });+ expect(onSetElementAttributeQuiet).not.toHaveBeenCalled();+ });++ it("keeps stepping from each press while earlier saves land", async () => {+ const saves: Array<() => void> = [];+ const { host, onSetElementAttributeQuiet, rerender } = render(clip, { focusable: true });+ onSetElementAttributeQuiet.mockImplementation(+ () => new Promise<undefined>((resolve) => saves.push(() => resolve(undefined))),+ );+ const handle = () => host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ const tap = () => {+ key(handle(), "keydown", { key: "ArrowRight" });+ key(handle(), "keyup", { key: "ArrowRight" });+ };+ tap();+ tap();+ // The first save lands: the store re-reads 1.1 while 1.2 is still on its way.+ rerender({ ...clip, fadeIn: 1.1 });+ await act(async () => saves[0]());+ tap();+ expect(onSetElementAttributeQuiet.mock.calls.map(([, , value]) => value)).toEqual([+ "1.1",+ "1.2",+ "1.3",+ ]);+ });++ it("keeps a focused handle drawn when a key takes it to where it cannot move", () => {+ const trimmed = { ...clip, fadeIn: 10, fadeOut: 2 };+ const { host, onSetElementAttributeQuiet } = render(trimmed, { focusable: true });+ const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-out"]');+ act(() => handle?.focus());+ key(handle, "keydown", { key: "Home" });+ key(handle, "keyup", { key: "Home" });+ expect(onSetElementAttributeQuiet).toHaveBeenCalledWith(+ trimmed,+ "data-fade-out",+ null,+ "Fade out",+ );+ });++ it("never lets a grow drag shrink a fade when the pair overruns the clip", () => {+ const trimmed = { ...clip, fadeIn: 10, fadeOut: 2 };+ const { host, onSetElementAttributeLive, onSetElementAttributeQuiet } = render(trimmed);+ const handle = armedHandle(host, "out");+ // Leftward grows a fade-out; the fade-in already fills the clip, so it holds at 2 s.+ press(handle, [900], [880]);+ act(() => handle.dispatchEvent(pointer("pointerup", 880)));+ expect(onSetElementAttributeLive).not.toHaveBeenCalledWith(trimmed, "data-fade-out", null);+ expect(onSetElementAttributeQuiet).not.toHaveBeenCalled();+ });++ it("keeps a pending save's draft through a click that never moves", () => {+ const { host, onSetElementAttributeQuiet } = render({ ...clip, fadeIn: undefined });+ onSetElementAttributeQuiet.mockReturnValue(new Promise(() => {}));+ const handle = armedHandle(host, "in");+ const doubleClick = () => {+ press(handle, [12]);+ act(() => handle.dispatchEvent(pointer("pointerup", 12)));+ act(() => handle.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })));+ };+ doubleClick();+ doubleClick();+ // Add 0.5 s, then take it away again, though the first save never landed.+ expect(onSetElementAttributeQuiet.mock.calls.map(([, , value]) => value)).toEqual([+ "0.5",+ null,+ ]);+ });++ it("shrinks a single fade longer than its clip from the clip's end, with no dead travel", () => {+ const long = { ...clip, duration: 3, fadeIn: 5, fadeOut: undefined };+ const { host, onSetElementAttributeLive } = render(long);+ const handle = armedHandle(host, "in");+ press(handle, [200], [195], [100]);+ expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(long, "data-fade-in", "2");+ });++ it("gives a fade that fills the clip the only handle at its end", () => {+ const { host } = render({ ...clip, fadeIn: 10, fadeOut: undefined });+ // The fade-out can neither grow nor shrink, so it does not sit on top of the fade-in's tab.+ expect(host.querySelector('[data-testid="clip-fade-handle-out"]')).toBeNull();+ const inHandle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ expect([inHandle?.style.left, inHandle?.style.width]).toEqual(["976px", "24px"]);+ });++ it("splits two nearby boxes at the midpoint between their tabs on a tiny clip", () => {+ // A 40 px clip with a 30 px fade-in: tabs at 30 and 33 px, boxes meet at 31.5.+ const { host } = render({ ...clip, duration: 0.4, fadeIn: 0.3, fadeOut: undefined });+ const inHandle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');+ const outHandle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-out"]');+ expect([inHandle?.style.left, inHandle?.style.width]).toEqual(["11.5px", "20px"]);+ expect([outHandle?.style.left, outHandle?.style.width]).toEqual(["31.5px", "8.5px"]);+ });++ it("keeps a long fade's hit box on its tab", () => {+ const { host } = render({ ...clip, fadeIn: 8, fadeOut: 0.4 });+ // The 8 s fade ends at 800 px; its 24 px box centres there, not in its half.+ expect(host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]')?.style.left).toBe(+ "788px",+ );+ });++ it("never snaps a fade to its own clip's edges", () => {+ usePlayerStore.setState({+ currentTime: 2,+ elements: [{ id: "before", tag: "audio", start: 0, duration: 2, track: 1 }, clip],+ });+ const { host, onSetElementAttributeLive } = render(clip);+ const handle = armedHandle(host, "in");+ // 0.05 s from the clip's start, where the playhead and the neighbour's end both sit.+ press(handle, [100], [5]);+ expect(onSetElementAttributeLive).toHaveBeenLastCalledWith(clip, "data-fade-in", "0.05");+ });++ it("keeps an unselected clip's handles out of the tab order", () => {+ const { host } = render(clip);+ expect(host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]')?.tabIndex).toBe(+ -1,+ );});it("does not let a press on the dot start the clip's own move gesture", () => {const outer = vi.fn();const { host, root } = render(clip, { onClipPointerDown: outer });- const handle = host.querySelector<HTMLElement>('[data-testid="clip-fade-handle-in"]');- if (!handle) throw new Error("expected a fade-in handle");- armCapture(handle);+ const handle = armedHandle(host, "in");act(() => handle.dispatchEvent(pointer("pointerdown", 100)));expect(outer).not.toHaveBeenCalled();act(() => root.unmount());diff --git a/packages/studio/src/player/components/TimelineClipFades.tsx b/packages/studio/src/player/components/TimelineClipFades.tsxindex 0c1ed29352..ee24790d0f 100644--- a/packages/studio/src/player/components/TimelineClipFades.tsx+++ b/packages/studio/src/player/components/TimelineClipFades.tsx@@ -1,57 +1,151 @@-import { useEffect, useRef, useState, type CSSProperties, type PointerEvent } from "react";+import {+ createContext,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type CSSProperties,+ type KeyboardEvent,+ type PointerEvent,+} from "react";import {HF_AUDIO_FADE_IN_ATTR,HF_AUDIO_FADE_OUT_ATTR,clampFadesToDuration,formatFadeSeconds,+ type AudioFades,} from "@hyperframes/core/audio-fade";-import type { TimelineElement } from "../store/playerStore";+import { usePlayerStore, type TimelineElement } from "../store/playerStore";import { Tooltip } from "../../components/ui";import { useTimelineEditContextOptional } from "../../contexts/TimelineEditContext";import { releasedOutsideWindow } from "./timelinePointerRelease";+import {+ collectTimelineSnapTargets,+ snapTimelineTime,+ TIMELINE_SNAP_PX,+ type TimelineSnapTarget,+ type TimelineSnapType,+} from "./timelineSnapping";type FadeEdge = "in" | "out";+type FadeDraft = { edge: FadeEdge; seconds: number } | null;-const HANDLE_SIZE = 10;+const TAB_WIDTH = 4;+const TAB_HEIGHT = 15;const HANDLE_HIT = 24;+const TAB_INSET = 7;+const TAB_CENTER_IN_HIT = 8;const HANDLE_Z_ABOVE_CLIP_CONTENT = 30;const SUPPRESS_CLIP_NATIVE_TITLE = "";/** Pixels of pointer travel before a press on the handle counts as a drag. */const DRAG_THRESHOLD_PX = 2;+const DEFAULT_FADE_SECONDS = 0.5;+const SNAP_LABEL: Record<TimelineSnapType, string> = {+ playhead: "playhead",+ "clip-edge": "clip edge",+ beat: "beat",+};++export type ClipFadeShape = AudioFades & { duration: number };+export const ClipFadesContext = createContext<ClipFadeShape | null>(null);++// Owned by TimelineClip so the handles and the waveform share the value under the pointer;+// the draft also bridges release until the save lands in the store.+export function useClipFadeDraft(el: TimelineElement) {+ const [draft, setDraft] = useState<FadeDraft>(null);+ const authoredIn = el.fadeIn ?? 0;+ const authoredOut = el.fadeOut ?? 0;+ const { fadeIn, fadeOut } = clampFadesToDuration(+ {+ fadeIn: draft?.edge === "in" ? draft.seconds : authoredIn,+ fadeOut: draft?.edge === "out" ? draft.seconds : authoredOut,+ },+ el.duration,+ );+ const shape = useMemo(+ () => ({ fadeIn, fadeOut, duration: el.duration }),+ [fadeIn, fadeOut, el.duration],+ );+ return { draft, setDraft, shape };+}interface TimelineClipFadesProps {el: TimelineElement;pps: number;widthPx: number;- /** Handles show on hover/selection; the shaded ramps show whenever a fade is set. */+ /** Handles show on hover/selection; the ramps show whenever a fade is set. */showHandles: boolean;+ focusable?: boolean;+ /** Audio clips draw the fade in their waveform; others get the shaded wedge. */+ hasWaveform?: boolean;+ fade: ReturnType<typeof useClipFadeDraft>;+}++type KeyedFade = (current: number, step: number, limit: number) => number | null;+const grow: KeyedFade = (current, step) => current + step;+const shrink: KeyedFade = (current, step) => current - step;+const clear: KeyedFade = () => 0;+const FADE_KEYS: Record<string, KeyedFade> = {+ ArrowRight: grow,+ ArrowUp: grow,+ ArrowLeft: shrink,+ ArrowDown: shrink,+ Home: clear,+ Delete: clear,+ Backspace: clear,+ End: (_current, _step, limit) => limit,+ Enter: (current) => (current === 0 ? DEFAULT_FADE_SECONDS : null),+};++function keyedFadeSeconds(key: string, shift: boolean, current: number, limit: number) {+ return FADE_KEYS[key]?.(current, shift ? 1 : 0.1, limit) ?? null;+}++function topEdgeY(x: number, widthPx: number, heightPx: number, radiusPx: number): number {+ const r = Math.min(radiusPx, widthPx / 2, heightPx / 2);+ const d = x < r ? r - x : x > widthPx - r ? x - (widthPx - r) : 0;+ return d > 0 ? r - Math.sqrt(Math.max(0, r * r - d * d)) : 0;}-/** Corner dots that drag `data-fade-in` / `data-fade-out`; the wedge is the faded region. */-export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineClipFadesProps) {+/** Slim tabs at each fade's end that drag `data-fade-in` / `data-fade-out`. */+// fallow-ignore-next-line complexity+export function TimelineClipFades({+ el,+ pps,+ widthPx,+ showHandles,+ focusable = false,+ hasWaveform = false,+ fade,+}: TimelineClipFadesProps) {const { onSetElementAttributeLive, onSetElementAttributeQuiet, onRevertElementAttributeLive } =useTimelineEditContextOptional();const canEdit = Boolean(onSetElementAttributeLive && onSetElementAttributeQuiet);-- // Draft holds the value under the pointer during a drag; it also bridges- // the gap between release and the store re-reading the file, so the ramp- // does not snap back for a frame.- const [draft, setDraft] = useState<{ edge: FadeEdge; seconds: number } | null>(null);+ const { setDraft } = fade;+ const fades = fade.shape;const [dragging, setDragging] = useState<FadeEdge | null>(null);+ const [focused, setFocused] = useState<FadeEdge | null>(null);+ const [snapType, setSnapType] = useState<TimelineSnapType | null>(null);const authoredIn = el.fadeIn ?? 0;const authoredOut = el.fadeOut ?? 0;- useEffect(() => setDraft(null), [authoredIn, authoredOut]);-- const fades = clampFadesToDuration(- {- fadeIn: draft?.edge === "in" ? draft.seconds : authoredIn,- fadeOut: draft?.edge === "out" ? draft.seconds : authoredOut,- },- el.duration,- );const inPx = Math.min(widthPx, fades.fadeIn * pps);const outPx = Math.min(widthPx, fades.fadeOut * pps);+ const visible =+ fades.fadeIn > 0 || fades.fadeOut > 0 || showHandles || dragging !== null || focused !== null;+ const rootRef = useRef<HTMLDivElement | null>(null);+ const [clipBox, setClipBox] = useState({ height: 0, radius: 0 });+ useLayoutEffect(() => {+ const clip = rootRef.current?.parentElement;+ if (!clip) return;+ const radius = parseFloat(getComputedStyle(clip).borderTopLeftRadius) || 0;+ const height = clip.clientHeight;+ setClipBox((box) =>+ box.height === height && box.radius === radius ? box : { height, radius },+ );+ }, [widthPx, visible]);+const gesture = useRef<{edge: FadeEdge;pointerId: number;@@ -60,11 +154,39 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCliotherSeconds: number;moved: boolean;last: number;+ snapTargets: TimelineSnapTarget[];} | null>(null);const attrFor = (edge: FadeEdge) =>edge === "in" ? HF_AUDIO_FADE_IN_ATTR : HF_AUDIO_FADE_OUT_ATTR;const attrText = (seconds: number) => (seconds > 0 ? formatFadeSeconds(seconds) : null);+ const labelFor = (edge: FadeEdge) => (edge === "in" ? "Fade in" : "Fade out");+ const currentSeconds = (edge: FadeEdge) =>+ fade.draft?.edge === edge ? fade.draft.seconds : edge === "in" ? authoredIn : authoredOut;+ const limitFor = (edge: FadeEdge) =>+ Math.max(0, el.duration - currentSeconds(edge === "in" ? "out" : "in"));++ // When the other fade makes the pair overrun the clip, neither a key nor a drag lowers this one.+ const stepLimit = (current: number, other: number) =>+ Math.max(0, el.duration - other, other > 0 ? current : 0);+ const startSeconds = (edge: FadeEdge) => {+ const current = currentSeconds(edge);+ return Math.min(current, stepLimit(current, currentSeconds(edge === "in" ? "out" : "in")));+ };+ const dragLimit = (g: { otherSeconds: number; originSeconds: number }) =>+ stepLimit(g.originSeconds, g.otherSeconds);++ /** Moves the fade's end onto a playhead or clip edge within the timeline's snap radius. */+ const snapSeconds = (g: NonNullable<typeof gesture.current>, seconds: number) => {+ const knee = g.edge === "in" ? el.start + seconds : el.start + el.duration - seconds;+ const snapped = snapTimelineTime(knee, g.snapTargets, TIMELINE_SNAP_PX / Math.max(pps, 1e-6));+ if (!snapped.target) return { seconds, type: null };+ const next = g.edge === "in" ? snapped.time - el.start : el.start + el.duration - snapped.time;+ const limit = dragLimit(g);+ return next >= 0 && next <= limit+ ? { seconds: next, type: snapped.target.type }+ : { seconds, type: null };+ };const secondsAt = (clientX: number): number => {const g = gesture.current;@@ -72,7 +194,7 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCliconst deltaSeconds = (clientX - g.originClientX) / Math.max(pps, 1e-6);// Fade-in grows to the right, fade-out grows to the left.const raw = g.edge === "in" ? g.originSeconds + deltaSeconds : g.originSeconds - deltaSeconds;- const limit = Math.max(0, el.duration - g.otherSeconds);+ const limit = dragLimit(g);const clamped = Math.min(limit, Math.max(0, raw));return Math.round(clamped * 100) / 100;};@@ -83,14 +205,24 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineClie.stopPropagation();e.preventDefault();e.currentTarget.setPointerCapture(e.pointerId);+ flushKeys();+ const store = usePlayerStore.getState();gesture.current = {edge,pointerId: e.pointerId,originClientX: e.clientX,- originSeconds: edge === "in" ? authoredIn : authoredOut,- otherSeconds: edge === "in" ? authoredOut : authoredIn,+ originSeconds: startSeconds(edge),+ otherSeconds: currentSeconds(edge === "in" ? "out" : "in"),moved: false,- last: edge === "in" ? authoredIn : authoredOut,+ last: startSeconds(edge),+ snapTargets: store.timelineSnapEnabled+ ? collectTimelineSnapTargets({+ elements: store.elements,+ playheadTime: store.currentTime,+ beatTimes: [],+ excludeElementKey: el.key ?? el.id,+ }).filter(({ time }) => time > el.start + 1e-3 && time < el.start + el.duration - 1e-3)+ : [],};setDragging(edge);};@@ -100,7 +232,9 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCliif (!g || g.pointerId !== e.pointerId) return;if (!g.moved && Math.abs(e.clientX - g.originClientX) < DRAG_THRESHOLD_PX) return;g.moved = true;- const seconds = secondsAt(e.clientX);+ const { seconds: raw, type } = snapSeconds(g, secondsAt(e.clientX));+ const seconds = Math.round(raw * 100) / 100;+ setSnapType(type);if (seconds === g.last) return;g.last = seconds;setDraft({ edge: g.edge, seconds });@@ -115,6 +249,7 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCliif (!g || g.pointerId !== e.pointerId) return null;gesture.current = null;setDragging(null);+ setSnapType(null);if (e.currentTarget.hasPointerCapture(e.pointerId)) {e.currentTarget.releasePointerCapture(e.pointerId);}@@ -123,35 +258,69 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCli/** Puts the live document back where the file has it and drops the draft. */const revertGesture = (g: Gesture) => {- if (g.moved) {- onSetElementAttributeLive?.(el, attrFor(g.edge), attrText(g.originSeconds));- onRevertElementAttributeLive?.(el, attrFor(g.edge));- }+ if (!g.moved) return;+ onSetElementAttributeLive?.(el, attrFor(g.edge), attrText(g.originSeconds));+ onRevertElementAttributeLive?.(el, attrFor(g.edge));setDraft(null);};+ // The save syncs the store before it settles, so its own draft can go then; a newer draft stays.+ const commit = (edge: FadeEdge, seconds: number) => {+ const draft = { edge, seconds };+ setDraft(draft);+ const settle = () => setDraft((current) => (current === draft ? null : current));+ void onSetElementAttributeQuiet?.(el, attrFor(edge), attrText(seconds), labelFor(edge)).then(+ settle,+ settle,+ );+ };+const finish = (e: PointerEvent<HTMLDivElement>, cancelled: boolean) => {const g = endGesture(e);if (!g) return;- if (cancelled || !g.moved || releasedOutsideWindow(e)) return revertGesture(g);- setDraft({ edge: g.edge, seconds: g.last });- void onSetElementAttributeQuiet?.(- el,- attrFor(g.edge),- attrText(g.last),- g.edge === "in" ? "Fade in" : "Fade out",- );+ if (cancelled || !g.moved || g.last === g.originSeconds || releasedOutsideWindow(e)) {+ return revertGesture(g);+ }+ commit(g.edge, g.last);+ };++ const onHandleDoubleClick = (edge: FadeEdge) => {+ commit(edge, currentSeconds(edge) > 0 ? 0 : Math.min(DEFAULT_FADE_SECONDS, limitFor(edge)));+ };++ const keyBurst = useRef<{ edge: FadeEdge; seconds: number } | null>(null);+ const flushKeys = () => {+ const burst = keyBurst.current;+ keyBurst.current = null;+ if (burst) commit(burst.edge, burst.seconds);+ };++ // A held key previews live and saves once on release: one undo step per burst.+ const onHandleKeyDown = (edge: FadeEdge) => (e: KeyboardEvent<HTMLDivElement>) => {+ if (gesture.current || !canEdit) return;+ const current = startSeconds(edge);+ const limit = stepLimit(current, currentSeconds(edge === "in" ? "out" : "in"));+ const next = keyedFadeSeconds(e.key, e.shiftKey, current, limit);+ if (next === null) return;+ e.preventDefault();+ e.stopPropagation();+ const seconds = Math.round(Math.min(limit, Math.max(0, next)) * 100) / 100;+ if (seconds === current) return;+ keyBurst.current = { edge, seconds };+ setDraft({ edge, seconds });+ onSetElementAttributeLive?.(el, attrFor(edge), attrText(seconds));};useEffect(() => {if (dragging === null) return;- const cancelOnWindowEscape = (e: KeyboardEvent) => {+ const cancelOnWindowEscape = (e: globalThis.KeyboardEvent) => {const g = gesture.current;if (e.key !== "Escape" || !g) return;e.preventDefault();e.stopPropagation();gesture.current = null;setDragging(null);+ setSnapType(null);revertGesture(g);};window.addEventListener("keydown", cancelOnWindowEscape, { capture: true });@@ -160,21 +329,43 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCliconst showIn = fades.fadeIn > 0;const showOut = fades.fadeOut > 0;- const handlesVisible = showHandles || dragging !== null;- if (!showIn && !showOut && !handlesVisible) return null;+ const handlesVisible = showHandles || dragging !== null || focused !== null;+ if (!visible) return null;const hitWidth = Math.min(HANDLE_HIT, widthPx / 2);- const handleStyle = (edge: FadeEdge): CSSProperties => ({+ const tabX = (edge: FadeEdge) => {+ const knee = edge === "in" ? inPx : widthPx - outPx;+ const inset = Math.min(TAB_INSET, widthPx / 2);+ return Math.min(widthPx - inset, Math.max(inset, knee));+ };+ const boxLeft = (x: number) => Math.min(widthPx - hitWidth, Math.max(0, x - hitWidth / 2));+ const [inX, outX] = [tabX("in"), tabX("out")];+ const mid = (inX + outX) / 2;+ // A handle with no 0.01 s step to move is not drawn, unless in use: its twin owns the spot.+ const drawn = (edge: FadeEdge) =>+ currentSeconds(edge) > 0 ||+ Math.round(limitFor(edge) * 100) >= 1 ||+ dragging === edge ||+ focused === edge;+ const overlap = drawn("in") && drawn("out") && boxLeft(inX) + hitWidth > boxLeft(outX);+ const handleGeometry = (edge: FadeEdge) => {+ const x = edge === "in" ? inX : outX;+ // Boxes that would overlap meet at the midpoint between the two tabs.+ const [left, right] = !overlap+ ? [boxLeft(x), boxLeft(x) + hitWidth]+ : edge === "in"+ ? [Math.max(0, mid - hitWidth), mid]+ : [mid, Math.min(widthPx, mid + hitWidth)];+ const edgeY = topEdgeY(x, widthPx, clipBox.height, clipBox.radius);+ return { left, width: right - left, tabLeft: x - left, top: edgeY + 1 - TAB_CENTER_IN_HIT };+ };+ const handleStyle = (geometry: { left: number; top: number; width: number }): CSSProperties => ({position: "absolute",- top: -(HANDLE_HIT - HANDLE_SIZE) / 2 + 1,- left: edge === "in" ? 0 : widthPx - hitWidth,- width: hitWidth,+ top: geometry.top,+ left: geometry.left,+ width: geometry.width,height: HANDLE_HIT,- display: "flex",- alignItems: "center",- justifyContent: "center",cursor: "ew-resize",- zIndex: HANDLE_Z_ABOVE_CLIP_CONTENT,opacity: handlesVisible ? 1 : 0,pointerEvents: handlesVisible && canEdit ? "auto" : "none",touchAction: "none",@@ -182,7 +373,16 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCli});return (- <>+ <div+ ref={rootRef}+ style={{+ position: "absolute",+ inset: 0,+ borderRadius: "inherit",+ pointerEvents: "none",+ zIndex: HANDLE_Z_ABOVE_CLIP_CONTENT,+ }}+ >{(showIn || showOut) && (<svgaria-hidden="true"@@ -193,119 +393,153 @@ export function TimelineClipFades({ el, pps, widthPx, showHandles }: TimelineCliwidth: "100%",height: "100%",pointerEvents: "none",- zIndex: 5,overflow: "hidden",borderRadius: "inherit",}}viewBox={`0 0 ${Math.max(widthPx, 1)} 100`}preserveAspectRatio="none">- {/* Keep the #4250 wedge geometry, but let the real waveform read through it. */}{showIn && (- <>- <polygon- data-testid="clip-fade-in"- points={`0,0 ${inPx},0 0,100`}- fill="var(--timeline-fade-shade)"- fillOpacity={0.35}- />- <line- x1={0}- y1={100}- x2={inPx}- y2={0}- stroke="var(--clip-handle)"- strokeOpacity={0.9}- strokeWidth={1.25}- vectorEffect="non-scaling-stroke"- />- </>+ <FadeRamp+ testId="clip-fade-in"+ wedge={hasWaveform ? null : `0,0 ${inPx},0 0,100`}+ line={[0, 100, inPx, 0]}+ />)}{showOut && (- <>- <polygon- data-testid="clip-fade-out"- points={`${widthPx - outPx},0 ${widthPx},0 ${widthPx},100`}- fill="var(--timeline-fade-shade)"- fillOpacity={0.35}- />- <line- x1={widthPx - outPx}- y1={0}- x2={widthPx}- y2={100}- stroke="var(--clip-handle)"- strokeOpacity={0.9}- strokeWidth={1.25}- vectorEffect="non-scaling-stroke"- />- </>+ <FadeRamp+ testId="clip-fade-out"+ wedge={hasWaveform ? null : `${widthPx - outPx},0 ${widthPx},0 ${widthPx},100`}+ line={[widthPx - outPx, 0, widthPx, 100]}+ />)}</svg>)}- {canEdit && (- <>- <FadeHandle- direction="in"- value={fades.fadeIn}- max={Math.max(0, el.duration - fades.fadeOut)}- style={handleStyle("in")}- dragging={dragging === "in"}- onPointerDown={onHandlePointerDown("in")}- onPointerMove={onHandlePointerMove}- onPointerUp={(e) => finish(e, false)}- onPointerCancel={(e) => finish(e, true)}- />- <FadeHandle- direction="out"- value={fades.fadeOut}- max={Math.max(0, el.duration - fades.fadeIn)}- style={handleStyle("out")}- dragging={dragging === "out"}- onPointerDown={onHandlePointerDown("out")}- onPointerMove={onHandlePointerMove}- onPointerUp={(e) => finish(e, false)}- onPointerCancel={(e) => finish(e, true)}- />- </>+ {canEdit &&+ (["in", "out"] as const).filter(drawn).map((edge) => {+ const geometry = handleGeometry(edge);+ return (+ <FadeHandle+ key={edge}+ direction={edge}+ clipName={el.label || el.id}+ value={edge === "in" ? fades.fadeIn : fades.fadeOut}+ max={Math.max(0, el.duration - (edge === "in" ? fades.fadeOut : fades.fadeIn))}+ snapLabel={dragging === edge && snapType ? SNAP_LABEL[snapType] : null}+ style={handleStyle(geometry)}+ tabLeft={geometry.tabLeft}+ tabTop={TAB_CENTER_IN_HIT - TAB_HEIGHT / 2}+ focusable={focusable}+ dragging={dragging === edge}+ onPointerDown={onHandlePointerDown(edge)}+ onPointerMove={onHandlePointerMove}+ onPointerUp={(e) => finish(e, false)}+ onPointerCancel={(e) => finish(e, true)}+ onDoubleClick={() => onHandleDoubleClick(edge)}+ onKeyDown={onHandleKeyDown(edge)}+ onKeyUp={flushKeys}+ onFocusChange={(on) => {+ if (!on) flushKeys();+ setFocused(on ? edge : null);+ }}+ />+ );+ })}+ </div>+ );+}++/** A 1 px dashed gain line; clips without a waveform also shade the gain they lose. */+function FadeRamp({+ testId,+ wedge,+ line,+}: {+ testId: string;+ wedge: string | null;+ line: [number, number, number, number];+}) {+ const [x1, y1, x2, y2] = line;+ return (+ <>+ {wedge && (+ <polygon+ data-testid={testId}+ points={wedge}+ fill="var(--timeline-fade-shade)"+ fillOpacity={0.35}+ />)}+ <line+ data-testid={wedge ? undefined : testId}+ x1={x1}+ y1={y1}+ x2={x2}+ y2={y2}+ stroke="var(--clip-handle)"+ strokeOpacity={0.55}+ strokeWidth={1}+ strokeDasharray="2 3"+ vectorEffect="non-scaling-stroke"+ /></>);}function FadeHandle({direction,+ clipName,value,max,+ snapLabel,style,+ tabLeft,+ tabTop,+ focusable,dragging,onPointerDown,onPointerMove,onPointerUp,onPointerCancel,+ onDoubleClick,+ onKeyDown,+ onKeyUp,+ onFocusChange,}: {direction: "in" | "out";+ clipName: string;value: number;max: number;+ snapLabel: string | null;style: CSSProperties;+ tabLeft: number;+ tabTop: number;+ focusable: boolean;dragging: boolean;onPointerDown: (event: PointerEvent<HTMLDivElement>) => void;onPointerMove: (event: PointerEvent<HTMLDivElement>) => void;onPointerUp: (event: PointerEvent<HTMLDivElement>) => void;onPointerCancel: (event: PointerEvent<HTMLDivElement>) => void;+ onDoubleClick: () => void;+ onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;+ onKeyUp: () => void;+ onFocusChange: (focused: boolean) => void;}) {const label = direction === "in" ? "Fade in" : "Fade out";+ const text = `${label} ${formatFadeSeconds(value)} s`;return (- <Tooltip label={`${label} ${formatFadeSeconds(value)} s`}>+ <Tooltip label={snapLabel ? `${text}, snapped to ${snapLabel}` : text}><divrole="slider"- tabIndex={-1}- aria-label={label}+ tabIndex={focusable ? 0 : -1}+ aria-label={`${label}, ${clipName}`}aria-valuemin={0}aria-valuemax={max}aria-valuenow={value}aria-valuetext={`${formatFadeSeconds(value)}s`}data-testid={`clip-fade-handle-${direction}`}+ data-dragging={dragging ? "" : undefined}+ className="timeline-fade-handle"title={SUPPRESS_CLIP_NATIVE_TITLE}style={style}onPointerDown={onPointerDown}@@ -313,30 +547,27 @@ function FadeHandle({onPointerUp={onPointerUp}onPointerCancel={onPointerCancel}onClick={(e) => e.stopPropagation()}- onDoubleClick={(e) => e.stopPropagation()}+ onDoubleClick={(e) => {+ e.stopPropagation();+ onDoubleClick();+ }}+ onKeyDown={onKeyDown}+ onKeyUp={onKeyUp}+ onFocus={() => onFocusChange(true)}+ onBlur={() => onFocusChange(false)}>- <FadeDot active={dragging} />+ <span+ aria-hidden="true"+ className="timeline-fade-tab"+ style={{+ left: tabLeft - TAB_WIDTH / 2,+ top: tabTop,+ width: TAB_WIDTH,+ height: TAB_HEIGHT,+ pointerEvents: "none",+ }}+ /></div></Tooltip>);}--function FadeDot({ active }: { active: boolean }) {- return (- <span- aria-hidden="true"- style={{- display: "block",- flexShrink: 0,- pointerEvents: "none",- width: HANDLE_SIZE,- height: HANDLE_SIZE,- borderRadius: "50%",- background: "var(--timeline-fade-dot)",- boxShadow: "0 0 0 1.5px var(--timeline-fade-dot-ring)",- transform: active ? "scale(1.15)" : undefined,- transition: "transform 80ms ease-out",- }}- />- );-}diff --git a/packages/studio/src/player/components/useTimelineKeyboardActor.ts b/packages/studio/src/player/components/useTimelineKeyboardActor.tsindex 1f1a17829e..f1ba9e341e 100644--- a/packages/studio/src/player/components/useTimelineKeyboardActor.ts+++ b/packages/studio/src/player/components/useTimelineKeyboardActor.ts@@ -22,7 +22,7 @@ function eventTarget(event: FocusEvent | KeyboardEvent): HTMLElement | null {// Header actions stay native Tab stops because they have no row-level shortcut.// The nearest interactive ancestor wins so their events never masquerade as row events.const target = event.target.closest<HTMLElement>(- "button, input, select, textarea, a[href], [contenteditable], [data-timeline-focus-id]",+ "button, input, select, textarea, a[href], [contenteditable], [role='slider'], [data-timeline-focus-id]",);return target?.dataset.timelineFocusId && event.currentTarget.contains(target) ? target : null;}diff --git a/packages/studio/src/player/lib/automationStoreSync.test.ts b/packages/studio/src/player/lib/automationStoreSync.test.tsindex a66b399141..7a7b86e895 100644--- a/packages/studio/src/player/lib/automationStoreSync.test.ts+++ b/packages/studio/src/player/lib/automationStoreSync.test.ts@@ -1,6 +1,6 @@// @vitest-environment happy-domimport { beforeEach, describe, expect, it } from "vitest";-import { syncStoredAutomationFromPreview } from "./automationStoreSync";+import { syncStoredAutomationFromPreview, syncStoredElementAttribute } from "./automationStoreSync";import { usePlayerStore, type TimelineElement } from "../store/playerStore";const TWO_POINTS = '{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1}]}]}';@@ -32,7 +32,24 @@ beforeEach(() => {usePlayerStore.getState().reset();});+describe("syncStoredElementAttribute", () => {+ it("records a saved fade on the stored clip, so the timeline draws what the file holds", () => {+ usePlayerStore.setState({ elements: [el({ fadeIn: 1 })] });+ syncStoredElementAttribute(el(), "data-fade-in", "2.5");+ expect(usePlayerStore.getState().elements[0]?.fadeIn).toBe(2.5);+ syncStoredElementAttribute(el(), "data-fade-in", null);+ expect(usePlayerStore.getState().elements[0]?.fadeIn).toBeUndefined();+ });+});+describe("syncStoredAutomationFromPreview", () => {+ it("reads back a fade an undo restored on the preview", () => {+ usePlayerStore.setState({ elements: [el({ fadeOut: 2 })] });+ syncStoredAutomationFromPreview(previewWith({ "data-fade-in": "0.6" }));+ const stored = usePlayerStore.getState().elements[0];+ expect([stored?.fadeIn, stored?.fadeOut]).toEqual([0.6, undefined]);+ });+it("reads the element the timeline bound, not an earlier same-id copy in a sub-composition", () => {usePlayerStore.setState({ elements: [el({ hfId: "hf-root" })] });const doc = document.implementation.createHTMLDocument("preview");diff --git a/packages/studio/src/player/lib/automationStoreSync.ts b/packages/studio/src/player/lib/automationStoreSync.tsindex 1b1c619054..3e2fe59732 100644--- a/packages/studio/src/player/lib/automationStoreSync.ts+++ b/packages/studio/src/player/lib/automationStoreSync.ts@@ -16,12 +16,18 @@import { HF_AUDIO_AUTOMATION_ATTR } from "@hyperframes/core/audio-automation";import { HF_AUDIO_FX_ATTR } from "@hyperframes/core/audio-fx";+import {+ HF_AUDIO_FADE_IN_ATTR,+ HF_AUDIO_FADE_OUT_ATTR,+ readElementFades,+ readFadeSeconds,+} from "@hyperframes/core/audio-fade";import { usePlayerStore, type TimelineElement } from "../store/playerStore";import { groupInfoFor } from "./timelineGroupInfo";import { getTimelineElementIdentity, previewElementFinder } from "./timelineElementHelpers";/**- * Re-read every element's automation and FX-chain attributes from the preview+ * Re-read every element's automation, FX-chain and fade 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@@ -34,21 +40,21 @@ import { getTimelineElementIdentity, previewElementFinder } from "./timelineElem* reverted is only known by looking.*//**- * What an element's four synced fields SHOULD read, given the preview.+ * What an element's six synced fields SHOULD read, given the preview.*- * Its own two come off its node; the other two are its copy of what its group+ * Its own four come off its node; the other two are its copy of what its group* carries. The timeline derives a group's lanes and chain from these mirrors,- * never from the group element — and the FX rack is not group-aware: selecting- * a group and automating one of its parameters writes `data-automation` on the- * group node through the ordinary element path, which used to refresh an- * element's own two fields and nothing else. So the group's row went on reading- * the value it was born with, and its `∿` never appeared.+ * never from the group element, and automating a group writes `data-automation`+ * on the group node through the ordinary element path, so both halves are re-read.*/function syncedFields(doc: Document, element: TimelineElement, node: Element) {const group = element.audioGroup ? groupInfoFor(doc, element.audioGroup) : null;+ const fades = readElementFades(node);return {automation: node.getAttribute(HF_AUDIO_AUTOMATION_ATTR) ?? undefined,fxChain: node.getAttribute(HF_AUDIO_FX_ATTR) ?? undefined,+ fadeIn: storedFade(fades.fadeIn),+ fadeOut: storedFade(fades.fadeOut),audioGroupAutomation: group?.automation,audioGroupFxChain: group?.fxChain,};@@ -74,27 +80,33 @@ export function syncStoredAutomationFromPreview(doc: Document | null | undefined});}-const STORED_FIELD: Record<string, "automation" | "fxChain"> = {- [HF_AUDIO_AUTOMATION_ATTR]: "automation",- [HF_AUDIO_FX_ATTR]: "fxChain",+/** Discovery's rule (applyFadeMetadataFromElement): a fade of 0 is no fade. */+const storedFade = (seconds: number) => (seconds > 0 ? seconds : undefined);++const STORED_FIELD: Record<string, (value: string | null) => Partial<TimelineElement>> = {+ [HF_AUDIO_AUTOMATION_ATTR]: (value) => ({ automation: value ?? undefined }),+ [HF_AUDIO_FX_ATTR]: (value) => ({ fxChain: value ?? undefined }),+ [HF_AUDIO_FADE_IN_ATTR]: (value) => ({ fadeIn: storedFade(readFadeSeconds(value)) }),+ [HF_AUDIO_FADE_OUT_ATTR]: (value) => ({ fadeOut: storedFade(readFadeSeconds(value)) }),};-/** Record a saved automation or FX-chain value on one element's stored copy. */+/** Record a saved automation, FX-chain or fade value on one element's stored copy. */export function syncStoredElementAttribute(target: TimelineElement,attr: string,value: string | null,): void {- const field = STORED_FIELD[attr];- if (!field) return;+ const fields = STORED_FIELD[attr]?.(value);+ if (!fields) return;const key = getTimelineElementIdentity(target);- const next = value ?? undefined;+ const same = (element: TimelineElement) =>+ (Object.keys(fields) as (keyof TimelineElement)[]).every((k) => element[k] === fields[k]);usePlayerStore.setState((state) => {let changed = false;const elements = state.elements.map((element) => {- if (getTimelineElementIdentity(element) !== key || element[field] === next) return element;+ if (getTimelineElementIdentity(element) !== key || same(element)) return element;changed = true;- return { ...element, [field]: next };+ return { ...element, ...fields };});return changed ? { elements } : {};});diff --git a/packages/studio/src/styles/components.css b/packages/studio/src/styles/components.cssindex d99bfec6ac..7e643fd93b 100644--- a/packages/studio/src/styles/components.css+++ b/packages/studio/src/styles/components.css@@ -253,6 +253,32 @@border-radius: var(--timeline-clip-audio-radius);}+.timeline-fade-tab {+ position: absolute;+ border-radius: 2px;+ background: var(--timeline-fade-dot);+ box-shadow:+ 0 0 0 1px var(--timeline-fade-dot-ring),+ 0 1px 3px var(--timeline-fade-dot-ring);+ transition: transform 140ms cubic-bezier(0.23, 1, 0.32, 1);+}++.timeline-fade-handle:hover .timeline-fade-tab,+.timeline-fade-handle[data-dragging] .timeline-fade-tab {+ transform: scaleY(1.2);+}++.timeline-fade-handle:focus-visible .timeline-fade-tab {+ outline: 2px solid var(--timeline-accent);+ outline-offset: 2px;+}++@media (prefers-reduced-motion: reduce) {+ .timeline-fade-tab {+ transition: none;+ }+}+.timeline-clip.is-audio.is-hovered {background-color: var(--timeline-clip-audio-bg-hover);}diff --git a/packages/studio/src/utils/typingTarget.test.ts b/packages/studio/src/utils/typingTarget.test.tsindex 3adecad4c1..f8865cbb52 100644--- a/packages/studio/src/utils/typingTarget.test.ts+++ b/packages/studio/src/utils/typingTarget.test.ts@@ -1,7 +1,7 @@// @vitest-environment happy-domimport { afterEach, describe, expect, it } from "vitest";-import { isTypingTarget } from "./typingTarget";+import { isTypingTarget, ownsPlainKeys } from "./typingTarget";import { isEditableTarget } from "./timelineDiscovery";afterEach(() => {@@ -41,6 +41,13 @@ describe("isTypingTarget", () => {expect(isTypingTarget(mount('<div role="combobox"></div>'))).toBe(true);});+ it("gives a focused slider its plain keys but leaves Cmd shortcuts to the app", () => {+ const slider = mount('<div role="slider" tabindex="0"></div>');+ expect(ownsPlainKeys(slider)).toBe(true);+ // Undo, copy and group still reach the app while a slider has focus.+ expect(isTypingTarget(slider)).toBe(false);+ });+it("leaves the keys alone for anything that is not being typed into", () => {expect(isTypingTarget(mount("<div>plain</div>"))).toBe(false);expect(isTypingTarget(mount("<button>press</button>"))).toBe(false);diff --git a/packages/studio/src/utils/typingTarget.ts b/packages/studio/src/utils/typingTarget.tsindex c22b314c47..085c8fb719 100644--- a/packages/studio/src/utils/typingTarget.ts+++ b/packages/studio/src/utils/typingTarget.ts@@ -21,6 +21,11 @@ export function isTypingTarget(target: EventTarget | null): boolean {return element.closest(TYPING_SELECTOR) !== null;}+/** Plain keys (arrows, Delete) also belong to a focused slider; Cmd shortcuts still do not. */+export function ownsPlainKeys(target: EventTarget | null): boolean {+ return isTypingTarget(target) || asElement(target)?.closest("[role='slider']") != null;+}+/*** Things a keystroke belongs to rather than to a shortcut. `contenteditable` is* matched by value as well, for a host whose own property is not yet true.diff --git a/packages/studio/tests/e2e/fade-handles.mjs b/packages/studio/tests/e2e/fade-handles.mjsindex a4e4a9a5c2..72481c4625 100644--- a/packages/studio/tests/e2e/fade-handles.mjs+++ b/packages/studio/tests/e2e/fade-handles.mjs@@ -1,10 +1,10 @@#!/usr/bin/env node-// On a clip narrower than two fade hit boxes, each dot must still lay out at 10 x 10.+// On a clip narrower than two fade hit boxes, each tab must still lay out at 4 x 15.// Flex shrinking only happens in real layout, so this measures it in Chrome.import { launchStudioChrome } from "./chrome-executable.mjs";const STUDIO_URL = process.env.STUDIO_URL;-const DOT_PX = 10;+const TAB_PX = { width: 4, height: 15 };const NARROW_CLIP_MAX_PX = 20;if (!STUDIO_URL) {@@ -33,7 +33,7 @@ try {clip: rect(el),handles: ["in", "out"].map((edge) => {const handle = el.querySelector(`[data-testid="clip-fade-handle-${edge}"]`);- return { edge, hit: rect(handle), dot: rect(handle.firstElementChild) };+ return { edge, hit: rect(handle), tab: rect(handle.firstElementChild) };}),};});@@ -42,9 +42,11 @@ try {`fixture clip is ${evidence.clip.width}px wide, not under ${NARROW_CLIP_MAX_PX}px`,);}- for (const { edge, dot } of evidence.handles) {- if (dot.width !== DOT_PX || dot.height !== DOT_PX) {- failures.push(`fade-${edge} dot is ${dot.width}x${dot.height}, expected ${DOT_PX}x${DOT_PX}`);+ for (const { edge, tab } of evidence.handles) {+ if (tab.width !== TAB_PX.width || tab.height !== TAB_PX.height) {+ failures.push(+ `fade-${edge} tab is ${tab.width}x${tab.height}, expected ${TAB_PX.width}x${TAB_PX.height}`,+ );}}} finally {