Files
hyperframes/packages/studio/src/player/store/playerStore.ts
T
Vance IngallsandClaude Opus 5 6bcf739390 fix(studio): audition from the playhead while paused, and let an author out of a menu (#3190)
* fix(studio): close the typecheck and fallow gaps wa-18b-reschedule opened

useAutomationLanes.ts's write() assumed gesture-scoped coalescing and a
preview-only commit that useDomEditAttributeCommits.ts never grew — backported
that option support from its own later commit so the two sides of the API
agree. The paste path and its tests were missing the box selection's v0/v1
bounds a sibling commit added to AutomationSelection. The FX panel's carve
controls still edited the six mechanism numbers (maxCutDb, bands,
intelligibilityBias) after carveProfile() collapsed authoring to one Strength
knob, so those fields no longer existed on HfCarveSettings; UI now edits
strength, and analyseCarveBands is called with carveProfile(strength).

Also closes fallow's complexity, dead-code and duplication findings on this
PR's diff: extracted automationLaneDragMath.ts (pure group/point-move math)
and useAutomationRangeDrag.ts (the marquee-select gesture) out of
useAutomationLaneGestures.ts, pulled a couple of render-loop ternaries and a
resolver into named functions, dropped an export nothing outside its file
used, and shared a step-simplifier between audioCarve's two envelope
builders.

The edge-stretch vs. box-select priority test in TimelineAutomationLane.test
was still pinning the pre-box-select rule (edge wins over a point sitting on
it) that a sibling commit deliberately reversed — a point inside the box is
now selected content, so grabbing it drags the group instead. Updated the
test to the shipped rule instead of the old one.

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

* fix(core): cap the via conic's weight so an edge-clamped via point can't NaN

A via point pulled out past the segment (viaX: 5, viaY: -3) clamps to
(0.999, 0.001) — exactly on the steady region's edge, where edge - viaX is 0.
viaConic divided by that zero to get an infinite weight, and shapeVia turned
Infinity into NaN a few steps later (Infinity - Infinity in the quadratic
coefficient). NaN reaching setValueCurveAtTime silences the automated
parameter for the rest of the render.

Capped the weight at 1e6 instead of leaving it unbounded — past that point
the arc already reads as touching the via point, so nothing visible is lost.
Also hardened shapeVia's existing denominator guard (`<= 0`) to `!(> 0)`,
since NaN fails the original comparison and fell through it.

Review by Miga (PR #3208).

* fix(studio-server): fingerprint the proactive waveform cache key too

The route already keys the waveform cache on the asset's size and mtime as
well as its path, so a rebuilt-in-place file gets fresh peaks instead of
stale ones. generateWaveformCache — the proactive path that runs on upload —
still called buildWaveformCacheKey with the path alone, so it wrote to a
different key than the route reads from (making the pre-generated cache
never found) and kept the exact collision bug this fingerprint exists to fix
on its own path.

Review by Miga (PR #3211).

* style(docs): run oxfmt on the /hyperframes-audio skill docs

Table column widths had drifted out of alignment with oxfmt's own rules,
failing format:check and blocking the Preflight gate every downstream
branch inherits. Whitespace only, no content change.

* fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration

\b treats `_` as a word character, so \bbed\b never matched bed_01,
music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap —
an underscore-separated bed classified as "unknown" and could end up offered
as its own carve source. Replaced the short hints with a boundary that
actually excludes letters and digits on both sides.

clipsOverlap computed end = start + duration without guarding sign, so a
negative duration put end before start — an interval that does not describe
anything, and one specific case showed it silently dropping a real overlap
(a shorter, earlier broken end rejected a clip that genuinely contained the
point). Duration clamps to zero instead: a clip cannot un-play time, and a
zero-length clip at its start is the sane reading of "duration nobody wrote
down as positive."

Review by Miga (PR #3212).

* fix(studio): widen PropertyPanel's resetModules render timeout again

The 20s margin (already once widened for the same reason) is timing out in
CI's full-monorepo Test run — the resetModules()+fresh-import render this
test needs is uncached and competes with every other package's test suite
for the same worker pool, and the same test passes in well under 2s
standalone. Went to 45s rather than re-tuning to whatever number happens to
clear the current CI load, since that number moves every time CI gains a
package.

* fix(studio): stop the single-candidate auto-apply carve firing twice

Two auto-apply effects both fire when sourceOptions.length === 1: the
multi-candidate effect only guards length === 0, so a single candidate
passes it too, and the single-candidate effect passes its own guard right
after — both compute the same sources list and both call setCarve, so the
common case (one narrator, one bed) triggered two decodes, two FFT runs, and
two concurrent attribute writes for one decision.

The multi-candidate effect now defers to its sibling for exactly one
candidate, which already has its own detailed handling for that case.

Review by Miga (PR #3213).

* feat(core): carve against every voice over a bed, always (#3212)

* feat(core): carve against every voice over a bed, always dynamically

A bed usually runs under a whole sequence — a narrator, an interview answer, a
second presenter — and carving against one of them left the others fighting it.
`source` becomes `sources`, and `mixCarveSources` sums every voice onto the BED's
clock before anything is measured. That is what keeps one analysis sufficient: the
chain is fixed, so there is no per-voice filter to switch between, and bands drawn
from all the speech there is with envelopes that rise wherever any of it happens
answer the actual question — where and when is speech masking this bed.

Summed rather than averaged: two people talking at once mask more than either
alone. Audio before the bed starts is dropped rather than folded in at zero, since
it plays over nothing and shifting it would put a cut where there is no voice.

`dynamic` is gone. A fixed depth thins the bed through every pause, and once both
have been heard there is no reason to want it, so every carve follows the speech.

Two helpers the panel and the headless script now share instead of each carrying a
copy — two definitions of "what does this name suggest" drift, and then the two
disagree about which track is the voice:

- `classifyAudioName` reads a track's kind from its id and filename together.
  `unknown` is deliberately common: treating an unrecognised name as "not a voice"
  would hide the one track somebody needs to pick.
- `clipsOverlap` keeps out a voice that never plays while the bed does. An unwritten
  duration counts as unbounded, not zero — refusing a clip whose length the
  composition leaves to the media would drop the commonest case there is.

Files written before this still load: a single `source` reads as a one-voice list,
a stored `dynamic` is ignored, and an absent attribute means the defaults whole.

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

* fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration

\b treats `_` as a word character, so \bbed\b never matched bed_01,
music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap —
an underscore-separated bed classified as "unknown" and could end up offered
as its own carve source. Replaced the short hints with a boundary that
actually excludes letters and digits on both sides.

clipsOverlap computed end = start + duration without guarding sign, so a
negative duration put end before start — an interval that does not describe
anything, and one specific case showed it silently dropping a real overlap
(a shorter, earlier broken end rejected a clip that genuinely contained the
point). Duration clamps to zero instead: a clip cannot un-play time, and a
zero-length clip at its start is the sane reading of "duration nobody wrote
down as positive."

Review by Miga (PR #3212).

---------

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

* fix(studio): port the carve UI off the removed source/dynamic fields

#3212 (accidentally squash-merged into this branch instead of main) changed
HfCarveSettings from a single `source` + `dynamic` toggle to a `sources`
list with dynamic mode removed outright — the multi-voice UI consumer that
goes with that shape lands in the very next PR, so this branch was left with
a type that no longer matched its own code.

Minimal port, not the multi-voice redesign that PR does properly: the
"Listen to" picker and analyse() treat sources[0] as the one voice this UI
still understands, and every dynamic-mode branch (the automated envelope
lanes, the toggle, the checkbox) is gone along with the field — a carve is
now always the static value the analysis computes, matching what the type
change made permanent. Test suite trimmed the same way: the automation-lane
and toggle tests covered behavior that no longer exists.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-13 13:06:56 -07:00

587 lines
23 KiB
TypeScript

import { create } from "zustand";
import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { BeatEditState } from "../../utils/beatEditing";
import type { ClipManifestClip } from "../lib/playbackTypes";
import {
readStudioUiPreferences,
writeStudioUiPreferences,
type TimelineTimeDisplayMode,
} from "../../utils/studioUiPreferences";
import { clampTimelineZoomPercent, computePinnedZoomPercent } from "../components/timelineZoom";
import { createKeyframeSlice, type KeyframeCacheEntry, type KeyframeSlice } from "./keyframeSlice";
import {
createAutomationSelectionSlice,
type AutomationSelectionSlice,
} from "./automationSelectionSlice";
import { createTimelineFocusRequest, type TimelineFocusRequest } from "./timelineFocusState";
import { createThumbnailSlice, type ThumbnailSlice } from "./thumbnailSlice";
export type { KeyframeCacheEntry } from "./keyframeSlice";
export { liveTime } from "./liveTime";
import type { TimelineElement } from "./timelineElement";
export type { TimelineElement };
export type ZoomMode = "fit" | "manual";
type TimelineTool = "select" | "razor";
export interface SelectElementOptions {
preserveSet?: boolean;
}
function resolveElementSelection(
ids: Iterable<string>,
anchor?: string | null,
): { selectedElementIds: Set<string>; selectedElementId: string | null } {
const selectedElementIds = new Set(ids);
if (selectedElementIds.size === 0) {
return { selectedElementIds, selectedElementId: null };
}
if (anchor && selectedElementIds.has(anchor)) {
return { selectedElementIds, selectedElementId: anchor };
}
return {
selectedElementIds,
selectedElementId: selectedElementIds.values().next().value ?? null,
};
}
interface PlayerState extends KeyframeSlice, AutomationSelectionSlice, ThumbnailSlice {
isPlaying: boolean;
currentTime: number;
duration: number;
timelineReady: boolean;
/** Increments exactly once when the Studio switches to a different project. */
timelineSessionEpoch: number;
/** Project owning the current timeline session; null outside a project-scoped reset. */
timelineProjectId: string | null;
/** True while a beat dot is being dragged — hides the playhead guideline. */
beatDragging: boolean;
elements: TimelineElement[];
selectedElementId: string | null;
playbackRate: number;
audioMuted: boolean;
loopEnabled: boolean;
/** Timeline zoom: 'fit' auto-scales to viewport, 'manual' uses manualZoomPercent */
zoomMode: ZoomMode;
/** Timeline zoom percent relative to the fit width when in manual mode */
manualZoomPercent: number;
/**
* Bumped on every live z-index edit (handleDomZIndexReorderCommit apply AND
* rollback). Flashless z commits (skipReload) never reload the iframe or
* bump refreshKey, so DOM-derived views (the Layers panel's z-sorted tree)
* subscribe to this to re-read the live DOM while playback is paused.
*/
zEditVersion: number;
/** Work-area in-point (seconds). When set, loop starts here and A jumps here. */
inPoint: number | null;
/** Work-area out-point (seconds). When set, loop ends here and E jumps here. */
outPoint: number | null;
activeTool: TimelineTool;
setActiveTool: (tool: TimelineTool) => void;
/** Tween-relative percentage of the last-clicked keyframe diamond. Operations
* (drag, resize, rotate) target this instead of recomputing from playhead. */
activeKeyframePct: number | null;
setActiveKeyframePct: (pct: number | null) => void;
/** Motion-path "set destination" mode. Armed from the preview toolbar (replaces
* the old double-click-on-canvas UX); while armed, one canvas click places the
* new path's destination. `available` is published by MotionPathOverlay so the
* toolbar shows the button only when the selected element can take a path. */
motionPathArmed: boolean;
setMotionPathArmed: (armed: boolean) => void;
motionPathCreateAvailable: boolean;
setMotionPathCreateAvailable: (available: boolean) => void;
/** Global toggle for the "Add keyframe" diamond in the timeline toolbar (#1808).
* When false, a manual drag/resize/rotate edit on an element that already has
* a live tween shifts every keyframe by the edit's delta (preserving the
* animation's shape) instead of inserting/updating a keyframe at the playhead. */
autoKeyframeEnabled: boolean;
setAutoKeyframeEnabled: (enabled: boolean) => void;
/** Multi-select: additional selected elements beyond selectedElementId. */
selectedElementIds: Set<string>;
clearSelectedElementIds: () => void;
/** Replace the whole multi-selection at once (marquee live updates). */
setSelectedElementIds: (ids: Set<string>) => void;
/** Timeline magnet toggle — when false, clip drags/trims/drops never snap. */
timelineSnapEnabled: boolean;
setTimelineSnapEnabled: (enabled: boolean) => void;
/** Transport + ruler readout: timecode ("time") or frame number ("frame"). */
timeDisplayMode: TimelineTimeDisplayMode;
setTimeDisplayMode: (mode: TimelineTimeDisplayMode) => void;
/**
* Pin the timeline zoom to its current visual scale before a duration-changing
* edit, so a subsequent duration change (which recomputes fit-pps) stops
* rescaling every clip. No-op once already pinned (mode is "manual").
*/
pinTimelineZoom: (currentPixelsPerSecond: number, fitPixelsPerSecond: number) => void;
/** The timeline's live pixels-per-second + fit basis, published by <Timeline>. */
timelinePps: number;
timelineFitPps: number;
setTimelineScale: (pps: number, fitPps: number) => void;
setSelection: (ids: Iterable<string>, anchor?: string | null) => void;
addSelectedElementId: (id: string) => void;
toggleSelectedElementId: (id: string) => void;
clearSelection: () => void;
setIsPlaying: (playing: boolean) => void;
setCurrentTime: (time: number) => void;
setDuration: (duration: number) => void;
setPlaybackRate: (rate: number) => void;
setAudioMuted: (muted: boolean) => void;
setLoopEnabled: (enabled: boolean) => void;
setTimelineReady: (ready: boolean) => void;
setBeatDragging: (dragging: boolean) => void;
setElements: (elements: TimelineElement[]) => void;
setSelectedElementId: (id: string | null, options?: SelectElementOptions) => void;
/** Move the selection anchor within an active multi-selection without collapsing it. */
setSelectionAnchor: (id: string | null) => void;
updateElement: (
elementId: string,
updates: Partial<
Pick<
TimelineElement,
"start" | "duration" | "track" | "zIndex" | "hasExplicitZIndex" | "playbackStart" | "hidden"
>
>,
) => void;
setZoomMode: (mode: ZoomMode) => void;
setManualZoomPercent: (percent: number) => void;
bumpZEditVersion: () => void;
setInPoint: (time: number | null) => void;
setOutPoint: (time: number | null) => void;
/** Owns the hard project boundary; repeated calls for one project are no-ops. */
beginTimelineSession: (projectId: string) => void;
/** Clears project data without creating a new hard-project session. */
reset: () => void;
/**
* Request a seek from outside the player loop (e.g. Layers panel).
* useTimelinePlayer subscribes and calls adapter.seek() + liveTime.notify().
*/
requestedSeekTime: number | null;
requestSeek: (time: number) => void;
clearSeekRequest: () => void;
/**
* Request the transport start or stop from outside the player loop.
*
* The FX rack auditions a preset by writing it to the running graph, which is
* silent while the transport is paused — so hovering one has to start
* playback, and leaving has to put the playhead back where it was. Hovering is
* not an edit and must not cost the author their place.
*
* A nonce rather than a bare boolean: two hovers in a row both want play, and
* without it the second request is indistinguishable from the first having
* already been served.
*/
playbackRequest: { playing: boolean; returnTo: number | null; nonce: number } | null;
requestPlayback: (playing: boolean, returnTo?: number | null) => void;
clearPlaybackRequest: () => void;
/**
* Request the timeline to scroll a clip into view (e.g. clicking an
* already-added asset card in the sidebar). Consumed and cleared by
* useTimelineRevealClip. The nonce makes repeat requests for the same
* clip observable so a second click re-reveals after the user scrolls away.
*/
clipRevealRequest: { elementId: string; nonce: number } | null;
requestClipReveal: (elementId: string) => void;
clearClipRevealRequest: () => void;
timelineFocus: TimelineFocusRequest | null;
timelineFocusNonce: number;
requestTimelineFocus: (id: string) => void;
clearTimelineFocus: (nonce: number) => void;
lintFindingsByElement: Map<string, { count: number; messages: string[] }>;
setLintFindingsByElement: (map: Map<string, { count: number; messages: string[] }>) => void;
beatAnalysis: MusicBeatAnalysis | null;
setBeatAnalysis: (analysis: MusicBeatAnalysis | null) => void;
/** User edits (add/move/delete) layered over the detected beat grid. */
beatEdits: BeatEditState | null;
setBeatEdits: (edits: BeatEditState | null) => void;
/** Undo/redo stacks for beat edits (in-memory, session-only). */
beatUndo: BeatHistoryEntry[];
beatRedo: BeatHistoryEntry[];
commitBeatEdits: (next: BeatEditState | null, label: string) => void;
undoBeatEdits: () => string | null;
redoBeatEdits: () => string | null;
resetBeatHistory: () => void;
beatPersist: (() => void) | null;
setBeatPersist: (fn: (() => void) | null) => void;
clipManifest: ClipManifestClip[] | null;
setClipManifest: (clips: ClipManifestClip[] | null) => void;
clipParentMap: Map<string, string>;
setClipParentMap: (map: Map<string, string>) => void;
/**
* Sub-composition DOM descendants (groups + their children) that have no
* `data-start`, so they're absent from the clip manifest/tree. Collected
* studio-side from the live preview so the timeline can expand a sub-comp row
* to show its DOM-only children. Keeps the manifest lean (timed clips only).
*/
domClipChildren: DomClipChild[];
setDomClipChildren: (children: DomClipChild[]) => void;
}
/** A sub-comp DOM-only timeline child (no data-start) and its nesting context. */
export interface DomClipChild {
id: string;
parentId: string;
/** The manifest sub-comp host clip id this descendant ultimately lives under. */
hostId: string;
label: string;
stackingContextId: string;
}
interface BeatHistoryEntry {
restore: BeatEditState | null;
at: number;
label: string;
}
export function createTimelineResetState() {
return {
isPlaying: false,
currentTime: 0,
duration: 0,
timelineReady: false,
beatDragging: false,
elements: [],
selectedElementId: null,
zEditVersion: 0,
inPoint: null,
outPoint: null,
activeTool: "select" as const,
activeKeyframePct: null,
motionPathArmed: false,
motionPathCreateAvailable: false,
selectedKeyframes: new Set<string>(),
// Ephemeral like every other selection here. A range surviving a project
// switch can match a same-keyed clip in the new project and redirect a
// paste through `sel.elementKey === paste.elementKey` to a stale t0.
automationSelection: null,
expandedClipIds: new Set<string>(),
focusedEaseSegment: null,
selectedElementIds: new Set<string>(),
requestedSeekTime: null,
lintFindingsByElement: new Map<string, { count: number; messages: string[] }>(),
timelineFocus: null,
keyframeCache: new Map<string, KeyframeCacheEntry>(),
gsapAnimations: new Map<string, GsapAnimation[]>(),
beatAnalysis: null,
beatEdits: null,
beatUndo: [],
beatRedo: [],
beatPersist: null,
clipManifest: null,
clipParentMap: new Map<string, string>(),
domClipChildren: [],
};
}
export const usePlayerStore = create<PlayerState>((set, get) => ({
isPlaying: false,
currentTime: 0,
duration: 0,
timelineReady: false,
timelineSessionEpoch: 0,
timelineProjectId: null,
beatDragging: false,
elements: [],
selectedElementId: null,
playbackRate: readStudioUiPreferences().playbackRate ?? 1,
audioMuted: readStudioUiPreferences().audioMuted ?? false,
loopEnabled: false,
zoomMode: "fit",
manualZoomPercent: 100,
zEditVersion: 0,
timelinePps: 100,
timelineFitPps: 100,
inPoint: null,
outPoint: null,
activeTool: "select",
setActiveTool: (tool) => set({ activeTool: tool }),
...createKeyframeSlice(set, () => ({
timelineProjectId: get().timelineProjectId,
timelineSessionEpoch: get().timelineSessionEpoch,
})),
...createThumbnailSlice(set),
...createAutomationSelectionSlice(set),
activeKeyframePct: null,
setActiveKeyframePct: (pct) => set({ activeKeyframePct: pct }),
motionPathArmed: false,
setMotionPathArmed: (armed) => set({ motionPathArmed: armed }),
motionPathCreateAvailable: false,
setMotionPathCreateAvailable: (available) => set({ motionPathCreateAvailable: available }),
autoKeyframeEnabled: true,
setAutoKeyframeEnabled: (enabled) => set({ autoKeyframeEnabled: enabled }),
selectedElementIds: new Set<string>(),
setSelection: (ids, anchor) => set(resolveElementSelection(ids, anchor)),
addSelectedElementId: (id: string) =>
set((s) => {
const next = new Set(s.selectedElementIds);
next.add(id);
return resolveElementSelection(next, s.selectedElementId);
}),
toggleSelectedElementId: (id: string) =>
set((s) => {
const next = new Set(s.selectedElementIds);
if (next.has(id)) next.delete(id);
else next.add(id);
return resolveElementSelection(next, s.selectedElementId);
}),
clearSelection: () => set({ selectedElementId: null, selectedElementIds: new Set() }),
requestedSeekTime: null,
requestSeek: (time) => set({ requestedSeekTime: time }),
clearSeekRequest: () => set({ requestedSeekTime: null }),
playbackRequest: null,
requestPlayback: (playing, returnTo = null) =>
set((s) => ({
playbackRequest: { playing, returnTo, nonce: (s.playbackRequest?.nonce ?? 0) + 1 },
})),
clearPlaybackRequest: () => set({ playbackRequest: null }),
clipRevealRequest: null,
requestClipReveal: (elementId) =>
set((s) => ({
clipRevealRequest: { elementId, nonce: (s.clipRevealRequest?.nonce ?? 0) + 1 },
})),
clearClipRevealRequest: () => set({ clipRevealRequest: null }),
timelineFocus: null,
timelineFocusNonce: 0,
requestTimelineFocus: (id) =>
set((s) => {
const nonce = s.timelineFocusNonce + 1;
return {
timelineFocusNonce: nonce,
timelineFocus: createTimelineFocusRequest(
id,
s.timelineProjectId,
s.timelineSessionEpoch,
nonce,
),
};
}),
clearTimelineFocus: (nonce) =>
set((s) => (s.timelineFocus?.nonce === nonce ? { timelineFocus: null } : s)),
lintFindingsByElement: new Map(),
setLintFindingsByElement: (map) => set({ lintFindingsByElement: map }),
beatAnalysis: null,
setBeatAnalysis: (analysis) => set({ beatAnalysis: analysis }),
beatEdits: null,
setBeatEdits: (edits) => set({ beatEdits: edits }),
beatUndo: [],
beatRedo: [],
beatPersist: null,
setBeatPersist: (fn) => set({ beatPersist: fn }),
commitBeatEdits: (next, label) => {
set((s) => ({
beatEdits: next,
beatUndo: [...s.beatUndo, { restore: s.beatEdits, at: Date.now(), label }],
beatRedo: [],
}));
get().beatPersist?.();
},
undoBeatEdits: () => {
const s = get();
const entry = s.beatUndo[s.beatUndo.length - 1];
if (!entry) return null;
set({
beatEdits: entry.restore,
beatUndo: s.beatUndo.slice(0, -1),
beatRedo: [...s.beatRedo, { restore: s.beatEdits, at: entry.at, label: entry.label }],
});
get().beatPersist?.();
return entry.label;
},
resetBeatHistory: () => set({ beatUndo: [], beatRedo: [] }),
redoBeatEdits: () => {
const s = get();
const entry = s.beatRedo[s.beatRedo.length - 1];
if (!entry) return null;
set({
beatEdits: entry.restore,
beatRedo: s.beatRedo.slice(0, -1),
beatUndo: [...s.beatUndo, { restore: s.beatEdits, at: entry.at, label: entry.label }],
});
get().beatPersist?.();
return entry.label;
},
clipManifest: null,
setClipManifest: (clips) => set({ clipManifest: clips }),
clipParentMap: new Map(),
setClipParentMap: (map) => set({ clipParentMap: map }),
domClipChildren: [],
setDomClipChildren: (children) => set({ domClipChildren: children }),
setIsPlaying: (playing) => {
if (get().isPlaying === playing) return;
set({ isPlaying: playing });
},
setPlaybackRate: (rate) => {
writeStudioUiPreferences({ playbackRate: rate });
set({ playbackRate: rate });
},
setAudioMuted: (muted) => {
writeStudioUiPreferences({ audioMuted: muted });
set({ audioMuted: muted });
},
setLoopEnabled: (enabled) => set({ loopEnabled: enabled }),
setZoomMode: (mode) => set({ zoomMode: mode }),
clearSelectedElementIds: () => set({ selectedElementIds: new Set() }),
setSelectedElementIds: (ids: Set<string>) => set({ selectedElementIds: new Set(ids) }),
timelineSnapEnabled: readStudioUiPreferences().timelineSnapEnabled ?? true,
setTimelineSnapEnabled: (enabled) => {
writeStudioUiPreferences({ timelineSnapEnabled: enabled });
set({ timelineSnapEnabled: enabled });
},
timeDisplayMode: readStudioUiPreferences().timeDisplayMode ?? "time",
setTimeDisplayMode: (mode) => {
writeStudioUiPreferences({ timeDisplayMode: mode });
set({ timeDisplayMode: mode });
},
pinTimelineZoom: (currentPixelsPerSecond, fitPixelsPerSecond) =>
set((s) => {
// Already pinned (or the user manually zoomed) — never clobber that.
if (s.zoomMode === "manual") return {};
const percent = computePinnedZoomPercent(currentPixelsPerSecond, fitPixelsPerSecond);
writeStudioUiPreferences({
timelineZoomMode: "manual",
timelineManualZoomPercent: percent,
});
return { zoomMode: "manual", manualZoomPercent: percent };
}),
setTimelineScale: (pps, fitPps) => {
const state = get();
if (state.timelinePps === pps && state.timelineFitPps === fitPps) return;
set({ timelinePps: pps, timelineFitPps: fitPps });
},
setInPoint: (time) =>
set((state) => {
const t = time !== null && Number.isFinite(time) ? time : null;
return {
inPoint: t,
outPoint:
t !== null && state.outPoint !== null && t >= state.outPoint ? null : state.outPoint,
// Setting a work-area marker implies the user wants playback bounded by it.
// Auto-enable loop so the playhead respects the marker instead of running past.
loopEnabled: t !== null ? true : state.loopEnabled,
};
}),
setOutPoint: (time) =>
set((state) => {
const t = time !== null && Number.isFinite(time) ? time : null;
return {
outPoint: t,
inPoint: t !== null && state.inPoint !== null && t <= state.inPoint ? null : state.inPoint,
loopEnabled: t !== null ? true : state.loopEnabled,
};
}),
setManualZoomPercent: (percent) =>
set((state) => ({
manualZoomPercent: clampTimelineZoomPercent(percent, state.timelineFitPps),
})),
bumpZEditVersion: () => set((state) => ({ zEditVersion: state.zEditVersion + 1 })),
setCurrentTime: (time) => set({ currentTime: Number.isFinite(time) ? time : 0 }),
setDuration: (duration) => set({ duration: Number.isFinite(duration) ? duration : 0 }),
setTimelineReady: (ready) => set({ timelineReady: ready }),
setBeatDragging: (dragging) => set({ beatDragging: dragging }),
setElements: (elements) => set({ elements }),
// A genuine single selection: always collapse the set to just this element. User
// intent (timeline click, preview click via applyDomSelection) flows here; DOM sync
// echoes that must preserve a group go through setSelectionAnchor instead.
setSelectedElementId: (id, options) =>
set((s) => {
const preserveSet = Boolean(options?.preserveSet && id && s.selectedElementIds.has(id));
const selectedElementIds = preserveSet
? new Set(s.selectedElementIds)
: options?.preserveSet
? new Set<string>()
: id
? new Set([id])
: new Set<string>();
// Selecting a different element drops any active keyframe selection — otherwise
// a stale activeKeyframePct from a prior diamond click would force the next drag
// to "modify" a keyframe on the new element. A diamond click sets the pct AFTER
// calling setSelectedElementId, so this never clobbers a genuine keyframe select.
return id !== s.selectedElementId
? {
selectedElementId: id,
selectedElementIds,
activeKeyframePct: null,
motionPathArmed: false,
focusedEaseSegment: null,
}
: { selectedElementId: id, selectedElementIds };
}),
// Move the anchor within an active multi-selection WITHOUT collapsing it — used by
// DOM->store sync echoes while a group gesture re-patches the preview. A non-member
// id is treated as a genuine new single selection.
setSelectionAnchor: (id) =>
set((s) => {
if (id != null && s.selectedElementIds.size > 1 && s.selectedElementIds.has(id)) {
return {
selectedElementId: id,
focusedEaseSegment: id === s.selectedElementId ? s.focusedEaseSegment : null,
};
}
return {
selectedElementId: id,
selectedElementIds: id ? new Set([id]) : new Set<string>(),
focusedEaseSegment: id === s.selectedElementId ? s.focusedEaseSegment : null,
};
}),
updateElement: (elementId, updates) =>
set((state) => ({
elements: state.elements.map((el) =>
(el.key ?? el.id) === elementId ? { ...el, ...updates } : el,
),
})),
// UI preferences intentionally survive reset. So do timelineSessionEpoch and
// focusedEaseRequestNonce: the epoch advances only when project identity
// changes, while a monotonic nonce prevents collisions with stale consumers.
beginTimelineSession: (projectId) =>
set((state) => {
if (state.timelineProjectId === projectId) return state;
return {
...createTimelineResetState(),
timelineSessionEpoch: state.timelineSessionEpoch + 1,
timelineProjectId: projectId,
};
}),
reset: () => set(createTimelineResetState()),
}));
function isDevBuild(): boolean {
try {
return import.meta.env.DEV === true;
} catch {
// Turbopack and other non-Vite bundlers may not provide import.meta.env.
return false;
}
}
if (isDevBuild() && typeof window !== "undefined") {
// Console handle for dumping live Studio state during bug-bash reproduction.
(window as unknown as { __playerStore?: typeof usePlayerStore }).__playerStore = usePlayerStore;
}