hyperframes 0.8.83 → 0.8.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -196,7 +196,10 @@ function wrapTimeline(tl) {
196
196
  // src/player/lib/timelineElementHelpers.ts
197
197
  import { HF_AUDIO_GROUP_TAG } from "@hyperframes/core/audio-groups";
198
198
  import { readElementFades } from "@hyperframes/core/audio-fade";
199
- import { readMediaOffsetSeconds } from "@hyperframes/parsers/media-duration";
199
+ import {
200
+ clampPlaybackRate,
201
+ readMediaOffsetSeconds
202
+ } from "@hyperframes/parsers/media-duration";
200
203
  var LAYER_REVEAL_PRIOR_Z_ATTR = "data-hf-reveal-prior-z";
201
204
  var LAYER_REVEAL_PRIOR_POSITION_ATTR = "data-hf-reveal-prior-pos";
202
205
  function readLayerRevealPriorZ(el) {
@@ -228,9 +231,6 @@ function readDurationAttribute(el) {
228
231
  const duration = Number.parseFloat(el.getAttribute("data-duration") ?? "") || Number.parseFloat(el.getAttribute("data-hf-authored-duration") ?? "");
229
232
  return isFinitePositive(duration) ? duration : 0;
230
233
  }
231
- function normalizePlaybackRate(raw) {
232
- return Number.isFinite(raw) && raw > 0 ? Math.max(0.1, Math.min(5, raw)) : 1;
233
- }
234
234
  function isTimelineIgnoredElement(el) {
235
235
  if (el.tagName.toLowerCase() === HF_AUDIO_GROUP_TAG) return true;
236
236
  return Boolean(
@@ -297,7 +297,7 @@ function applyPlaybackMetadataFromElement(entry, el) {
297
297
  );
298
298
  const authoredPlaybackRate = Number.parseFloat(el.getAttribute("data-playback-rate") ?? "");
299
299
  if (Number.isFinite(authoredPlaybackRate) && authoredPlaybackRate > 0) {
300
- entry.playbackRate = normalizePlaybackRate(authoredPlaybackRate);
300
+ entry.playbackRate = clampPlaybackRate(authoredPlaybackRate);
301
301
  }
302
302
  }
303
303
  function setOptional(entry, key, value) {
@@ -343,7 +343,7 @@ function applyMediaMetadataFromElement(entry, el) {
343
343
  }
344
344
  const playbackRate = mediaEl.defaultPlaybackRate;
345
345
  if (entry.playbackRate == null && Number.isFinite(playbackRate) && playbackRate > 0) {
346
- entry.playbackRate = normalizePlaybackRate(playbackRate);
346
+ entry.playbackRate = clampPlaybackRate(playbackRate);
347
347
  }
348
348
  }
349
349
  function getTimelineElementDisplayLabel(input) {
@@ -1868,4 +1868,4 @@ export {
1868
1868
  whenPreviewBooted,
1869
1869
  Player
1870
1870
  };
1871
- //# sourceMappingURL=chunk-LPZMAGS7.js.map
1871
+ //# sourceMappingURL=chunk-7VDQIGOU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/player/lib/time.ts","../src/player/store/liveTime.ts","../src/player/store/playerStore.ts","../src/player/store/playerStoreDevHandle.ts","../src/player/lib/playbackAdapter.ts","../src/player/lib/timelineElementHelpers.ts","../src/player/store/playerStoreSelection.ts","../src/components/dock/panelRegistry.ts","../src/components/dock/dockLayoutSchema.ts","../src/utils/studioUiPreferences.ts","../src/player/components/timelineZoom.ts","../src/player/store/keyframeSlice.ts","../src/player/store/automationSelectionSlice.ts","../src/player/store/editingModeSlice.ts","../src/player/store/timelineFocusState.ts","../src/player/lib/thumbnailPolicy.ts","../src/player/store/thumbnailSlice.ts","../src/player/store/readinessSlice.ts","../src/player/store/rangeSelectionSlice.ts","../src/player/store/timelineResetState.ts","../src/player/components/Player.tsx","../src/hooks/useMountEffect.ts","../src/hooks/previewVariablesStore.ts"],"sourcesContent":["export const STUDIO_PREVIEW_FPS = 30;\n\nexport function formatTime(time: number): string {\n if (!Number.isFinite(time) || time < 0) return \"00:00\";\n const mins = Math.floor(time / 60);\n const secs = Math.floor(time % 60);\n // Zero-pad minutes as well as seconds so every readout is a stable-width\n // MM:SS (e.g. \"00:44\", not \"0:44\"). Minutes past 99 keep their extra digits\n // (\"120:00\"); an hours-style H:MM:SS grouping is applied by callers that need\n // it (see formatTimelineTickLabel), never here.\n return `${mins.toString().padStart(2, \"0\")}:${secs.toString().padStart(2, \"0\")}`;\n}\n\nexport function secondsToFrame(time: number, fps = STUDIO_PREVIEW_FPS): number {\n if (!Number.isFinite(time) || time <= 0) return 0;\n if (!Number.isFinite(fps) || fps <= 0) return 0;\n return Math.round(time * fps);\n}\n\nexport function frameToSeconds(frame: number, fps = STUDIO_PREVIEW_FPS): number {\n if (!Number.isFinite(frame) || frame <= 0) return 0;\n if (!Number.isFinite(fps) || fps <= 0) return 0;\n return frame / fps;\n}\n\nexport function stepFrameTime(time: number, deltaFrames: number, fps = STUDIO_PREVIEW_FPS): number {\n const currentFrame = secondsToFrame(time, fps);\n const nextFrame = Math.max(0, currentFrame + deltaFrames);\n return frameToSeconds(nextFrame, fps);\n}\n\nexport function formatFrameTime(time: number, duration: number, fps = STUDIO_PREVIEW_FPS): string {\n const currentFrame = secondsToFrame(time, fps);\n const totalFrames = secondsToFrame(duration, fps);\n return `${currentFrame}f / ${totalFrames}f`;\n}\n","// ponytail: Playback RAF updates the playhead/time display without per-frame React renders.\ntype TimeListener = (time: number) => void;\nconst timeListeners = new Set<TimeListener>();\n\nexport const liveTime = {\n notify: (time: number) => timeListeners.forEach((listener) => listener(time)),\n subscribe: (listener: TimeListener) => {\n timeListeners.add(listener);\n return () => timeListeners.delete(listener);\n },\n};\n","import { create } from \"zustand\";\nimport { attachPlayerStoreDevHandle } from \"./playerStoreDevHandle\";\nimport { nextSelectionSet, revealTargetsSelection } from \"./playerStoreSelection\";\nimport type { MusicBeatAnalysis } from \"@hyperframes/core/beats\";\nimport type { BeatEditState } from \"../../utils/beatEditing\";\nimport type { ClipManifestClip } from \"../lib/playbackTypes\";\nimport {\n readStudioUiPreferences,\n writeStudioUiPreferences,\n type TimelineTimeDisplayMode,\n} from \"../../utils/studioUiPreferences\";\nimport { clampTimelineZoomPercent, computePinnedZoomPercent } from \"../components/timelineZoom\";\nimport { createKeyframeSlice, type KeyframeSlice } from \"./keyframeSlice\";\nimport {\n createAutomationSelectionSlice,\n type AutomationSelectionSlice,\n} from \"./automationSelectionSlice\";\nimport { createEditingModeSlice, type EditingModeSlice } from \"./editingModeSlice\";\nimport { createTimelineFocusRequest, type TimelineFocusRequest } from \"./timelineFocusState\";\nimport { createThumbnailSlice, type ThumbnailSlice } from \"./thumbnailSlice\";\nimport { createPlaybackReadinessSlice } from \"./readinessSlice\";\nimport { createRangeSelectionSlice, type RangeSelectionSlice } from \"./rangeSelectionSlice\";\nimport { createTimelineResetState } from \"./timelineResetState\";\nexport type { KeyframeCacheEntry } from \"./keyframeSlice\";\nexport { liveTime } from \"./liveTime\";\nexport { createTimelineResetState };\n\nimport type {\n TimelineElement,\n TimelineElementPatch,\n SubCompositionHostState,\n} from \"./timelineElement\";\n\nexport type { TimelineElement, SubCompositionHostState };\nexport type ZoomMode = \"fit\" | \"manual\";\ntype TimelineTool = \"select\" | \"razor\";\n\nexport interface SelectElementOptions {\n preserveSet?: boolean;\n}\n\nfunction resolveElementSelection(\n ids: Iterable<string>,\n anchor?: string | null,\n): { selectedElementIds: Set<string>; selectedElementId: string | null } {\n const selectedElementIds = new Set(ids);\n if (selectedElementIds.size === 0) {\n return { selectedElementIds, selectedElementId: null };\n }\n if (anchor && selectedElementIds.has(anchor)) {\n return { selectedElementIds, selectedElementId: anchor };\n }\n return {\n selectedElementIds,\n selectedElementId: selectedElementIds.values().next().value ?? null,\n };\n}\n\ntype PlayerStoreSlices = KeyframeSlice &\n AutomationSelectionSlice &\n ThumbnailSlice &\n EditingModeSlice &\n ReturnType<typeof createPlaybackReadinessSlice> &\n RangeSelectionSlice;\ninterface PlayerState extends PlayerStoreSlices {\n isPlaying: boolean;\n currentTime: number;\n duration: number;\n /** Increments exactly once when the Studio switches to a different project. */\n timelineSessionEpoch: number;\n /** Project owning the current timeline session; null outside a project-scoped reset. */\n timelineProjectId: string | null;\n /** True while a beat dot is being dragged — hides the playhead guideline. */\n beatDragging: boolean;\n elements: TimelineElement[];\n selectedElementId: string | null;\n playbackRate: number;\n audioMuted: boolean;\n audioVolume: number;\n loopEnabled: boolean;\n /** Timeline zoom: 'fit' auto-scales to viewport, 'manual' uses manualZoomPercent */\n zoomMode: ZoomMode;\n /** Timeline zoom percent relative to the fit width when in manual mode */\n manualZoomPercent: number;\n /**\n * Bumped on every live z-index edit (handleDomZIndexReorderCommit apply AND\n * rollback). Flashless z commits (skipReload) never reload the iframe or\n * bump refreshKey, so DOM-derived views (the Layers panel's z-sorted tree)\n * subscribe to this to re-read the live DOM while playback is paused.\n */\n zEditVersion: number;\n /** Work-area in-point (seconds). When set, loop starts here and A jumps here. */\n inPoint: number | null;\n /** Work-area out-point (seconds). When set, loop ends here and E jumps here. */\n outPoint: number | null;\n\n activeTool: TimelineTool;\n setActiveTool: (tool: TimelineTool) => void;\n\n /** Tween-relative percentage of the last-clicked keyframe diamond. Operations\n * (drag, resize, rotate) target this instead of recomputing from playhead. */\n activeKeyframePct: number | null;\n setActiveKeyframePct: (pct: number | null) => void;\n\n /** Multi-select: additional selected elements beyond selectedElementId. */\n selectedElementIds: Set<string>;\n clearSelectedElementIds: () => void;\n /** Replace the whole multi-selection at once (marquee live updates). */\n setSelectedElementIds: (ids: Set<string>) => void;\n /** Timeline magnet toggle — when false, clip drags/trims/drops never snap. */\n timelineSnapEnabled: boolean;\n setTimelineSnapEnabled: (enabled: boolean) => void;\n /** Keeps the main track gapless on delete; distinct from the magnet above. */\n rippleEditEnabled: boolean;\n setRippleEditEnabled: (enabled: boolean) => void;\n /** Transport + ruler readout: timecode (\"time\") or frame number (\"frame\"). */\n timeDisplayMode: TimelineTimeDisplayMode;\n setTimeDisplayMode: (mode: TimelineTimeDisplayMode) => void;\n /** Pin the timeline zoom to its current scale before a duration change, so\n * it stops rescaling every clip. No-op once already pinned. */\n pinTimelineZoom: (currentPixelsPerSecond: number, fitPixelsPerSecond: number) => void;\n /** The timeline's live pixels-per-second + fit basis, published by <Timeline>. */\n timelinePps: number;\n timelineFitPps: number;\n setTimelineScale: (pps: number, fitPps: number) => void;\n setSelection: (ids: Iterable<string>, anchor?: string | null) => void;\n addSelectedElementId: (id: string) => void;\n toggleSelectedElementId: (id: string) => void;\n clearSelection: () => void;\n\n setIsPlaying: (playing: boolean) => void;\n setCurrentTime: (time: number) => void;\n setDuration: (duration: number) => void;\n setPlaybackRate: (rate: number) => void;\n setAudioMuted: (muted: boolean) => void;\n setAudioVolume: (volume: number) => void;\n setLoopEnabled: (enabled: boolean) => void;\n setBeatDragging: (dragging: boolean) => void;\n setElements: (elements: TimelineElement[]) => void;\n setSelectedElementId: (id: string | null, options?: SelectElementOptions) => void;\n /** Move the selection anchor within an active multi-selection without collapsing it. */\n setSelectionAnchor: (id: string | null) => void;\n updateElement: (elementId: string, updates: TimelineElementPatch) => void;\n setZoomMode: (mode: ZoomMode) => void;\n setManualZoomPercent: (percent: number) => void;\n bumpZEditVersion: () => void;\n setInPoint: (time: number | null) => void;\n setOutPoint: (time: number | null) => void;\n /** Owns the hard project boundary; repeated calls for one project are no-ops. */\n beginTimelineSession: (projectId: string) => void;\n /** Clears project data without creating a new hard-project session. */\n reset: () => void;\n\n /** Request a seek from outside the player loop (e.g. Layers panel);\n * useTimelinePlayer subscribes and calls adapter.seek() + liveTime.notify(). */\n requestedSeekTime: number | null;\n requestSeek: (time: number) => void;\n clearSeekRequest: () => void;\n\n /** Request the transport start or stop from outside the player loop: the FX\n * rack starts playback to audition a preset (silent while paused) and\n * restores the playhead on leave, without costing the author their place.\n * A nonce, not a bare boolean, so two hovers in a row both register. */\n playbackRequest: { playing: boolean; returnTo: number | null; nonce: number } | null;\n requestPlayback: (playing: boolean, returnTo?: number | null) => void;\n clearPlaybackRequest: () => void;\n\n /**\n * Request the timeline to scroll a clip into view (e.g. clicking an\n * already-added asset card in the sidebar). Consumed and cleared by\n * useTimelineRevealClip. The nonce makes repeat requests for the same\n * clip observable so a second click re-reveals after the user scrolls away.\n */\n clipRevealRequest: { elementId: string; nonce: number } | null;\n requestClipReveal: (elementId: string) => void;\n clearClipRevealRequest: () => void;\n\n timelineFocus: TimelineFocusRequest | null;\n timelineFocusNonce: number;\n requestTimelineFocus: (id: string) => void;\n clearTimelineFocus: (nonce: number) => void;\n\n lintFindingsByElement: Map<string, { count: number; messages: string[] }>;\n setLintFindingsByElement: (map: Map<string, { count: number; messages: string[] }>) => void;\n\n beatAnalysis: MusicBeatAnalysis | null;\n setBeatAnalysis: (analysis: MusicBeatAnalysis | null) => void;\n\n /** User edits (add/move/delete) layered over the detected beat grid. */\n beatEdits: BeatEditState | null;\n setBeatEdits: (edits: BeatEditState | null) => void;\n /** Undo/redo stacks for beat edits (in-memory, session-only). */\n beatUndo: BeatHistoryEntry[];\n beatRedo: BeatHistoryEntry[];\n commitBeatEdits: (next: BeatEditState | null, label: string) => void;\n undoBeatEdits: () => string | null;\n redoBeatEdits: () => string | null;\n resetBeatHistory: () => void;\n beatPersist: (() => void) | null;\n setBeatPersist: (fn: (() => void) | null) => void;\n\n clipManifest: ClipManifestClip[] | null;\n setClipManifest: (clips: ClipManifestClip[] | null) => void;\n clipParentMap: Map<string, string>;\n setClipParentMap: (map: Map<string, string>) => void;\n /**\n * Sub-composition DOM descendants (groups + their children) that have no\n * `data-start`, so they're absent from the clip manifest/tree. Collected\n * studio-side from the live preview so the timeline can expand a sub-comp row\n * to show its DOM-only children. Keeps the manifest lean (timed clips only).\n */\n domClipChildren: DomClipChild[];\n setDomClipChildren: (children: DomClipChild[]) => void;\n /**\n * Host-element state for every id'd element inside a sub-composition, keyed by\n * dom id. Collected from the live preview because it is the only place that\n * sees it: these elements are filtered out of `elements` before the flat store\n * is built, and the clip manifest carries timing, not attributes.\n */\n subCompositionHostState: Map<string, SubCompositionHostState>;\n setSubCompositionHostState: (state: Map<string, SubCompositionHostState>) => void;\n}\n\n/** A sub-comp DOM-only timeline child (no data-start) and its nesting context. */\nexport interface DomClipChild {\n id: string;\n parentId: string;\n /** The manifest sub-comp host clip id this descendant ultimately lives under. */\n hostId: string;\n label: string;\n stackingContextId: string;\n /**\n * The child's audio-group state, read off its live element during the DOM\n * walk — the only place that sees it. A sub-composition can declare a group\n * and its members entirely within itself, and those members never reach the\n * flat store, so an expanded child has no twin to inherit membership from.\n */\n audioGroup?: string;\n audioGroupLabel?: string;\n audioGroupVolume?: number;\n audioGroupHidden?: boolean;\n audioGroupFxChain?: string;\n /** The group element's `data-automation`, mirrored the same way. */\n audioGroupAutomation?: string;\n}\n\ninterface BeatHistoryEntry {\n restore: BeatEditState | null;\n at: number;\n label: string;\n}\n\nexport const usePlayerStore = create<PlayerState>((set, get) => ({\n isPlaying: false,\n currentTime: 0,\n duration: 0,\n timelineSessionEpoch: 0,\n timelineProjectId: null,\n beatDragging: false,\n elements: [],\n selectedElementId: null,\n playbackRate: readStudioUiPreferences().playbackRate ?? 1,\n audioMuted: readStudioUiPreferences().audioMuted ?? false,\n audioVolume: readStudioUiPreferences().audioVolume ?? 1,\n loopEnabled: false,\n zoomMode: \"fit\",\n manualZoomPercent: 100,\n zEditVersion: 0,\n timelinePps: 100,\n timelineFitPps: 100,\n inPoint: null,\n outPoint: null,\n\n activeTool: \"select\",\n setActiveTool: (tool) => set({ activeTool: tool }),\n\n ...createKeyframeSlice(set, () => ({\n timelineProjectId: get().timelineProjectId,\n timelineSessionEpoch: get().timelineSessionEpoch,\n })),\n ...createThumbnailSlice(set),\n\n ...createAutomationSelectionSlice(set),\n ...createEditingModeSlice(set),\n ...createRangeSelectionSlice(),\n ...createPlaybackReadinessSlice(set),\n\n activeKeyframePct: null,\n setActiveKeyframePct: (pct) => set({ activeKeyframePct: pct }),\n\n selectedElementIds: new Set<string>(),\n setSelection: (ids, anchor) => set(resolveElementSelection(ids, anchor)),\n addSelectedElementId: (id: string) =>\n set((s) => {\n const next = new Set(s.selectedElementIds);\n next.add(id);\n return resolveElementSelection(next, s.selectedElementId);\n }),\n toggleSelectedElementId: (id: string) =>\n set((s) => {\n const next = new Set(s.selectedElementIds);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n return resolveElementSelection(next, s.selectedElementId);\n }),\n clearSelection: () => set({ selectedElementId: null, selectedElementIds: new Set() }),\n\n requestedSeekTime: null,\n requestSeek: (time) => set({ requestedSeekTime: time }),\n clearSeekRequest: () => set({ requestedSeekTime: null }),\n\n playbackRequest: null,\n requestPlayback: (playing, returnTo = null) =>\n set((s) => ({\n playbackRequest: { playing, returnTo, nonce: (s.playbackRequest?.nonce ?? 0) + 1 },\n })),\n clearPlaybackRequest: () => set({ playbackRequest: null }),\n\n clipRevealRequest: null,\n requestClipReveal: (elementId) =>\n set((s) => ({\n clipRevealRequest: { elementId, nonce: (s.clipRevealRequest?.nonce ?? 0) + 1 },\n })),\n clearClipRevealRequest: () => set({ clipRevealRequest: null }),\n\n timelineFocus: null,\n timelineFocusNonce: 0,\n requestTimelineFocus: (id) =>\n set((s) => {\n const nonce = s.timelineFocusNonce + 1;\n return {\n timelineFocusNonce: nonce,\n timelineFocus: createTimelineFocusRequest(\n id,\n s.timelineProjectId,\n s.timelineSessionEpoch,\n nonce,\n ),\n };\n }),\n clearTimelineFocus: (nonce) =>\n set((s) => (s.timelineFocus?.nonce === nonce ? { timelineFocus: null } : s)),\n\n lintFindingsByElement: new Map(),\n setLintFindingsByElement: (map) => set({ lintFindingsByElement: map }),\n\n beatAnalysis: null,\n setBeatAnalysis: (analysis) => set({ beatAnalysis: analysis }),\n\n beatEdits: null,\n setBeatEdits: (edits) => set({ beatEdits: edits }),\n\n beatUndo: [],\n beatRedo: [],\n beatPersist: null,\n setBeatPersist: (fn) => set({ beatPersist: fn }),\n commitBeatEdits: (next, label) => {\n set((s) => ({\n beatEdits: next,\n beatUndo: [...s.beatUndo, { restore: s.beatEdits, at: Date.now(), label }],\n beatRedo: [],\n }));\n get().beatPersist?.();\n },\n undoBeatEdits: () => {\n const s = get();\n const entry = s.beatUndo[s.beatUndo.length - 1];\n if (!entry) return null;\n set({\n beatEdits: entry.restore,\n beatUndo: s.beatUndo.slice(0, -1),\n beatRedo: [...s.beatRedo, { restore: s.beatEdits, at: entry.at, label: entry.label }],\n });\n get().beatPersist?.();\n return entry.label;\n },\n resetBeatHistory: () => set({ beatUndo: [], beatRedo: [] }),\n redoBeatEdits: () => {\n const s = get();\n const entry = s.beatRedo[s.beatRedo.length - 1];\n if (!entry) return null;\n set({\n beatEdits: entry.restore,\n beatRedo: s.beatRedo.slice(0, -1),\n beatUndo: [...s.beatUndo, { restore: s.beatEdits, at: entry.at, label: entry.label }],\n });\n get().beatPersist?.();\n return entry.label;\n },\n\n clipManifest: null,\n setClipManifest: (clips) => set({ clipManifest: clips }),\n clipParentMap: new Map(),\n setClipParentMap: (map) => set({ clipParentMap: map }),\n domClipChildren: [],\n setDomClipChildren: (children) => set({ domClipChildren: children }),\n subCompositionHostState: new Map(),\n setSubCompositionHostState: (state) => set({ subCompositionHostState: state }),\n\n setIsPlaying: (playing) => {\n if (get().isPlaying === playing) return;\n set({ isPlaying: playing });\n },\n setPlaybackRate: (rate) => {\n writeStudioUiPreferences({ playbackRate: rate });\n set({ playbackRate: rate });\n },\n setAudioMuted: (muted) => {\n writeStudioUiPreferences({ audioMuted: muted });\n set({ audioMuted: muted });\n },\n setAudioVolume: (volume) => {\n const nextVolume = Number.isFinite(volume) ? Math.max(0, Math.min(1, volume)) : 1;\n writeStudioUiPreferences({ audioVolume: nextVolume });\n set({ audioVolume: nextVolume });\n },\n setLoopEnabled: (enabled) => set({ loopEnabled: enabled }),\n setZoomMode: (mode) => set({ zoomMode: mode }),\n clearSelectedElementIds: () => set({ selectedElementIds: new Set() }),\n setSelectedElementIds: (ids: Set<string>) => set({ selectedElementIds: new Set(ids) }),\n timelineSnapEnabled: readStudioUiPreferences().timelineSnapEnabled ?? true,\n setTimelineSnapEnabled: (enabled) => {\n writeStudioUiPreferences({ timelineSnapEnabled: enabled });\n set({ timelineSnapEnabled: enabled });\n },\n rippleEditEnabled: readStudioUiPreferences().rippleEditEnabled ?? true, // default on\n setRippleEditEnabled: (enabled) => {\n writeStudioUiPreferences({ rippleEditEnabled: enabled });\n set({ rippleEditEnabled: enabled });\n },\n timeDisplayMode: readStudioUiPreferences().timeDisplayMode ?? \"time\",\n setTimeDisplayMode: (mode) => {\n writeStudioUiPreferences({ timeDisplayMode: mode });\n set({ timeDisplayMode: mode });\n },\n pinTimelineZoom: (currentPixelsPerSecond, fitPixelsPerSecond) =>\n set((s) => {\n // Already pinned (or the user manually zoomed) — never clobber that.\n if (s.zoomMode === \"manual\") return {};\n const percent = computePinnedZoomPercent(currentPixelsPerSecond, fitPixelsPerSecond);\n writeStudioUiPreferences({\n timelineZoomMode: \"manual\",\n timelineManualZoomPercent: percent,\n });\n return { zoomMode: \"manual\", manualZoomPercent: percent };\n }),\n setTimelineScale: (pps, fitPps) => {\n const state = get();\n if (state.timelinePps === pps && state.timelineFitPps === fitPps) return;\n set({ timelinePps: pps, timelineFitPps: fitPps });\n },\n setInPoint: (time) =>\n set((state) => {\n const t = time !== null && Number.isFinite(time) ? time : null;\n return {\n inPoint: t,\n outPoint:\n t !== null && state.outPoint !== null && t >= state.outPoint ? null : state.outPoint,\n // Setting a work-area marker implies the user wants playback bounded by it.\n // Auto-enable loop so the playhead respects the marker instead of running past.\n loopEnabled: t !== null ? true : state.loopEnabled,\n };\n }),\n setOutPoint: (time) =>\n set((state) => {\n const t = time !== null && Number.isFinite(time) ? time : null;\n return {\n outPoint: t,\n inPoint: t !== null && state.inPoint !== null && t <= state.inPoint ? null : state.inPoint,\n loopEnabled: t !== null ? true : state.loopEnabled,\n };\n }),\n setManualZoomPercent: (percent) =>\n set((state) => ({\n manualZoomPercent: clampTimelineZoomPercent(percent, state.timelineFitPps),\n })),\n bumpZEditVersion: () => set((state) => ({ zEditVersion: state.zEditVersion + 1 })),\n setCurrentTime: (time) => set({ currentTime: Number.isFinite(time) ? time : 0 }),\n setDuration: (duration) => set({ duration: Number.isFinite(duration) ? duration : 0 }),\n setBeatDragging: (dragging) => set({ beatDragging: dragging }),\n setElements: (elements) => set({ elements }),\n // A genuine single selection: always collapse the set to just this element. User\n // intent (timeline click, preview click via applyDomSelection) flows here; DOM sync\n // echoes that must preserve a group go through setSelectionAnchor instead.\n setSelectedElementId: (id, options) =>\n set((s) => {\n const selectedElementIds = nextSelectionSet(s.selectedElementIds, id, options?.preserveSet);\n // Selecting a different element drops any active keyframe selection — otherwise\n // a stale activeKeyframePct from a prior diamond click would force the next drag\n // to \"modify\" a keyframe on the new element. A diamond click sets the pct AFTER\n // calling setSelectedElementId, so this never clobbers a genuine keyframe select.\n // A reveal request survives the selection it is FOR. `openClipFxRack`\n // raises the request and then selects the clip asynchronously, so the\n // selection lands afterwards and used to clear the very request that\n // caused it — the panel then read null and the section never opened.\n // Any OTHER selection still drops it: a request aimed elsewhere is stale.\n //\n // Compared across the ID-SPACE BOUNDARY, which is why this needs saying:\n // a request carries the BARE dom id (`runtimeAudioId`, because the panel\n // and the runtime speak that), while this store's ids are\n // `sourceFile#domId`. A direct `===` was silently never true — the exact\n // shape of failure the id-space split produces.\n const revealSurvives = revealTargetsSelection(s.revealedAudioFxTarget, id);\n return id !== s.selectedElementId\n ? {\n selectedElementId: id,\n selectedElementIds,\n activeKeyframePct: null,\n motionPathArmed: false,\n focusedEaseSegment: null,\n ...(revealSurvives ? {} : { revealedAudioFxTarget: null }),\n }\n : { selectedElementId: id, selectedElementIds };\n }),\n // Move the anchor within an active multi-selection WITHOUT collapsing it — used by\n // DOM->store sync echoes while a group gesture re-patches the preview. A non-member\n // id is treated as a genuine new single selection.\n setSelectionAnchor: (id) =>\n set((s) => {\n if (id != null && s.selectedElementIds.size > 1 && s.selectedElementIds.has(id)) {\n return {\n selectedElementId: id,\n focusedEaseSegment: id === s.selectedElementId ? s.focusedEaseSegment : null,\n };\n }\n return {\n selectedElementId: id,\n selectedElementIds: id ? new Set([id]) : new Set<string>(),\n focusedEaseSegment: id === s.selectedElementId ? s.focusedEaseSegment : null,\n };\n }),\n updateElement: (elementId, updates) =>\n set((state) => ({\n elements: state.elements.map((el) =>\n (el.key ?? el.id) === elementId ? { ...el, ...updates } : el,\n ),\n })),\n // UI preferences intentionally survive reset. So do timelineSessionEpoch and\n // focusedEaseRequestNonce: the epoch advances only when project identity\n // changes, while a monotonic nonce prevents collisions with stale consumers.\n beginTimelineSession: (projectId) =>\n set((state) => {\n if (state.timelineProjectId === projectId) return state;\n return {\n ...createTimelineResetState(),\n timelineSessionEpoch: state.timelineSessionEpoch + 1,\n timelineProjectId: projectId,\n };\n }),\n reset: () => set(createTimelineResetState()),\n}));\n\nattachPlayerStoreDevHandle(usePlayerStore);\n\nexport function isPreviewBooted(projectId: string): boolean {\n const { previewBooted, timelineProjectId } = usePlayerStore.getState();\n return previewBooted && timelineProjectId === projectId;\n}\n\n/** True once projectId's live preview has booted, false once another project replaces it.\n * Open-time work the first frame does not need (server parses, lint) waits on it. */\nexport function whenPreviewBooted(projectId: string): Promise<boolean> {\n const openedFrom = usePlayerStore.getState().timelineProjectId;\n let seen = false;\n const settle = (state: PlayerState): boolean | null => {\n if (state.timelineProjectId === projectId) {\n seen = true;\n return state.previewBooted ? true : null;\n }\n return seen || state.timelineProjectId !== openedFrom ? false : null;\n };\n return new Promise((resolve) => {\n const now = settle(usePlayerStore.getState());\n if (now !== null) return resolve(now);\n const stop = usePlayerStore.subscribe((state) => {\n const result = settle(state);\n if (result === null) return;\n stop();\n resolve(result);\n });\n });\n}\n","/**\n * A console handle on the live store, dev builds only.\n *\n * Split out of `playerStore.ts` to keep it under the studio's 600-line cap. The\n * dev check is its own function because `import.meta.env` is absent under\n * Turbopack and other non-Vite bundlers, where reading it throws.\n */\n\nfunction isDevBuild(): boolean {\n try {\n return import.meta.env.DEV === true;\n } catch {\n return false;\n }\n}\n\n/** Expose `store` as `window.__playerStore` for dumping live Studio state\n * during bug-bash reproduction. No-op outside a dev build or a browser. */\nexport function attachPlayerStoreDevHandle(store: unknown): void {\n if (!isDevBuild() || typeof window === \"undefined\") return;\n (window as unknown as { __playerStore?: unknown }).__playerStore = store;\n}\n","/**\n * Playback adapter utilities: factory for the static-seek adapter used when a\n * composition exposes only a `renderSeek` / `seek` API (no native play/pause\n * support), plus a thin wrapper that normalises GSAP-style `TimelineLike`\n * objects to the `PlaybackAdapter` interface.\n */\n\nimport type {\n PlaybackAdapter,\n RuntimePlaybackAdapter,\n StaticSeekPlaybackClock,\n TimelineLike,\n} from \"./playbackTypes\";\n\n// ---------------------------------------------------------------------------\n// Pure numeric helpers\n// ---------------------------------------------------------------------------\n\nexport function isFinitePositive(value: number): boolean {\n return Number.isFinite(value) && value > 0;\n}\n\nfunction clampTime(time: number, duration: number): number {\n const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);\n const safeTime = Math.max(0, Number.isFinite(time) ? time : 0);\n return safeDuration > 0 ? Math.min(safeTime, safeDuration) : safeTime;\n}\n\nexport function getAdapterDuration(adapter: PlaybackAdapter | null | undefined): number {\n if (!adapter) return 0;\n try {\n const duration = Number(adapter.getDuration());\n return isFinitePositive(duration) ? duration : 0;\n } catch {\n return 0;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Clock factory\n// ---------------------------------------------------------------------------\n\nexport function getDefaultStaticSeekPlaybackClock(win: Window): StaticSeekPlaybackClock {\n return {\n now: () => win.performance.now(),\n requestAnimationFrame: (callback) => win.requestAnimationFrame(callback),\n cancelAnimationFrame: (handle) => win.cancelAnimationFrame(handle),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Static-seek adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps a render-only player (exposes `renderSeek`/`seek` but no native\n * play/pause) and drives playback via `requestAnimationFrame`.\n */\nexport function createStaticSeekPlaybackAdapter(\n player: Pick<RuntimePlaybackAdapter, \"getTime\"> &\n Partial<Pick<RuntimePlaybackAdapter, \"renderSeek\" | \"seek\">>,\n duration: number,\n clock: StaticSeekPlaybackClock,\n getPlaybackRate: () => number = () => 1,\n): PlaybackAdapter {\n const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);\n let currentTime = clampTime(Number(player.getTime?.() ?? 0), safeDuration);\n let playing = false;\n let rafId = 0;\n let playStartTime = currentTime;\n let playStartNow = clock.now();\n\n const renderSeek = (time: number) => {\n currentTime = clampTime(time, safeDuration);\n if (typeof player.renderSeek === \"function\") {\n player.renderSeek(currentTime);\n return;\n }\n player.seek?.(currentTime);\n };\n\n const stopTicker = () => {\n if (rafId) {\n clock.cancelAnimationFrame(rafId);\n rafId = 0;\n }\n };\n\n const tick: FrameRequestCallback = (now) => {\n if (!playing) return;\n const playbackRate = Math.max(0.1, Number(getPlaybackRate()) || 1);\n const elapsed = ((now - playStartNow) / 1000) * playbackRate;\n renderSeek(playStartTime + elapsed);\n if (currentTime >= safeDuration) {\n playing = false;\n rafId = 0;\n return;\n }\n rafId = clock.requestAnimationFrame(tick);\n };\n\n return {\n play: () => {\n if (playing || safeDuration <= 0) return;\n if (currentTime >= safeDuration) renderSeek(0);\n playing = true;\n playStartTime = currentTime;\n playStartNow = clock.now();\n stopTicker();\n rafId = clock.requestAnimationFrame(tick);\n },\n pause: () => {\n playing = false;\n stopTicker();\n },\n seek: (time, options) => {\n renderSeek(time);\n if (options?.keepPlaying) {\n if (playing) {\n playStartTime = currentTime;\n playStartNow = clock.now();\n }\n return;\n }\n // Default seek aligns with wrapTimeline: stop the RAF ticker so the\n // adapter's `playing` flag matches the public seek contract instead of\n // silently driving renderSeek in the background.\n playing = false;\n stopTicker();\n },\n getTime: () => currentTime,\n getDuration: () => safeDuration,\n isPlaying: () => playing,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Static-seek fallback cache\n// ---------------------------------------------------------------------------\n\nexport type StaticSeekCacheEntry = {\n player: RuntimePlaybackAdapter | PlaybackAdapter;\n duration: number;\n adapter: PlaybackAdapter;\n};\n\ntype StaticSeekCacheRef = { current: StaticSeekCacheEntry | null };\ntype WarnedRef = { current: boolean };\n\n/**\n * Pause and drop the cached static-seek adapter. Must be called whenever\n * adapter selection switches to a native adapter — a cached static-seek\n * adapter that was mid-play keeps its private rAF loop seeking the player\n * forever otherwise, fighting the native transport. Also re-arms the\n * downgrade warning so a later re-downgrade is surfaced again.\n */\nexport function releaseStaticSeekCache(cache: StaticSeekCacheRef, warned: WarnedRef): void {\n cache.current?.adapter.pause();\n cache.current = null;\n warned.current = false;\n}\n\n/**\n * Resolve (with caching) the seek-driven fallback adapter. Warns once per\n * downgrade streak: seek-driven playback never starts media elements or\n * WebAudio, so without the warning the downgrade silently loses audio.\n */\nexport function resolveStaticSeekFallback(opts: {\n cache: StaticSeekCacheRef;\n warned: WarnedRef;\n bestAdapter: RuntimePlaybackAdapter | PlaybackAdapter;\n effectiveDuration: number;\n docDuration: number;\n clock: StaticSeekPlaybackClock;\n getPlaybackRate: () => number;\n}): PlaybackAdapter {\n const { cache, warned, bestAdapter, effectiveDuration, docDuration } = opts;\n const cached = cache.current;\n if (cached?.player === bestAdapter && cached.duration === effectiveDuration) {\n return cached.adapter;\n }\n cached?.adapter.pause();\n if (!warned.current) {\n warned.current = true;\n console.warn(\n `[useTimelinePlayer] Selected adapter duration (${getAdapterDuration(bestAdapter)}s) does not cover the document duration (${docDuration}s); falling back to seek-driven playback, which never starts media elements or WebAudio. Audio will not play in preview — extend the GSAP timeline to cover the declared data-duration.`,\n );\n }\n const adapter = createStaticSeekPlaybackAdapter(\n bestAdapter,\n effectiveDuration,\n opts.clock,\n opts.getPlaybackRate,\n );\n cache.current = { player: bestAdapter, duration: effectiveDuration, adapter };\n return adapter;\n}\n\n// ---------------------------------------------------------------------------\n// GSAP timeline wrapper\n// ---------------------------------------------------------------------------\n\nexport function wrapTimeline(tl: TimelineLike): PlaybackAdapter {\n return {\n play: () => tl.play(),\n pause: () => tl.pause(),\n seek: (t, options) => {\n const shouldPause = !options?.keepPlaying;\n if (shouldPause) tl.pause();\n tl.seek(t);\n if (shouldPause) tl.pause();\n },\n getTime: () => tl.time(),\n getDuration: () => tl.duration(),\n isPlaying: () => tl.isActive(),\n };\n}\n","/**\n * Low-level helpers for building and identifying TimelineElement objects.\n *\n * Covers: duration reading, media-element metadata extraction, selector/key/\n * identity builders, and DOM node lookup. These are\n * intentionally dependency-free (no store, no hooks) so they can be used in\n * both the React hook and test environments.\n */\n\nimport type { TimelineElement } from \"../store/playerStore\";\nimport type { ClipManifestClip } from \"./playbackTypes\";\nimport { isFinitePositive } from \"./playbackAdapter\";\nimport { getSourceScopedSelectorIndex } from \"../../utils/sourceScopedSelectorIndex\";\nimport { HF_AUDIO_GROUP_TAG } from \"@hyperframes/core/audio-groups\";\nimport { readElementFades } from \"@hyperframes/core/audio-fade\";\nimport {\n type AttrReader,\n clampPlaybackRate,\n readMediaOffsetSeconds,\n} from \"@hyperframes/parsers/media-duration\";\n\n// ---------------------------------------------------------------------------\n// Layer-reveal lift transparency\n// ---------------------------------------------------------------------------\n\n/**\n * Attributes carrying the pre-lift state of a Layers-panel selection reveal\n * (useLayerRevealOverride): while a layer is selected it PAINTS on top via a\n * temporary inline z-index, but the lift is a purely visual, ephemeral studio\n * affordance — every z reader must keep reporting the element's TRUE z\n * (stored here) so menus, badges, the lane mirror, and the panel sort never\n * reason on the lifted value. A z-reorder commit removes the attributes (the\n * commit is the new truth).\n */\nexport const LAYER_REVEAL_PRIOR_Z_ATTR = \"data-hf-reveal-prior-z\";\nexport const LAYER_REVEAL_PRIOR_POSITION_ATTR = \"data-hf-reveal-prior-pos\";\n\n/** The lifted element's true (pre-lift) z, or null when no lift is active. */\nexport function readLayerRevealPriorZ(el: Element): number | null {\n const raw = el.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);\n if (raw == null) return null;\n const n = Number.parseInt(raw, 10);\n return Number.isFinite(n) ? n : null;\n}\n\n// ---------------------------------------------------------------------------\n// Duration attribute helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read a host element's effective CSS stacking order for the timeline's reverse\n * z→lane mapping. Prefers the inline `style.zIndex` (what the canvas context\n * menu and LayersPanel z-edits write via handleDomZIndexReorderCommit), falls\n * back to computed style; \"auto\" / empty / unparseable ⇒ 0. Works with a\n * detached parse Document (no defaultView) as well as a live iframe. Mirrors\n * canvasContextMenuZOrder.parseZIndex semantics so the two directions agree.\n * Reveal-lift transparent: an active lift reports the stored TRUE z.\n */\nexport function readTimelineElementZIndex(el: Element): number {\n const prior = readLayerRevealPriorZ(el);\n if (prior != null) return prior;\n const html = el as HTMLElement;\n const parseZ = (value: string | null | undefined): number | null => {\n if (value == null || value === \"\" || value === \"auto\") return null;\n const n = Number.parseInt(value, 10);\n return Number.isFinite(n) ? n : null;\n };\n const fromInline = parseZ(html.style?.zIndex);\n if (fromInline != null) return fromInline;\n const view = el.ownerDocument?.defaultView;\n if (view?.getComputedStyle) {\n const fromComputed = parseZ(view.getComputedStyle(html).zIndex);\n if (fromComputed != null) return fromComputed;\n }\n return 0;\n}\n\nfunction readDurationAttribute(el: Element | null | undefined): number {\n if (!el) return 0;\n const duration =\n Number.parseFloat(el.getAttribute(\"data-duration\") ?? \"\") ||\n Number.parseFloat(el.getAttribute(\"data-hf-authored-duration\") ?? \"\");\n return isFinitePositive(duration) ? duration : 0;\n}\n\nexport function isTimelineIgnoredElement(el: Element): boolean {\n // An `<hf-audio-group>` is a mixer bus with no timing of its own, drawn as a group row, never a clip.\n if (el.tagName.toLowerCase() === HF_AUDIO_GROUP_TAG) return true;\n return Boolean(\n el.closest(\n [\n \"[data-hyperframes-ignore]\",\n \"[data-hyperframes-picker-ignore]\",\n \"[data-hf-ignore]\",\n \"[data-hf-color-grading-canvas]\",\n ].join(\",\"),\n ),\n );\n}\n\n/**\n * Furthest clip end (start + RAW `data-duration`) over every non-root clip in the\n * document. Reads the authored attribute, NOT any runtime-computed value — so it\n * is immune to the runtime's clamp that truncates a clip's live duration to the\n * composition length. This is the source of truth for content-driven duration:\n * computing it from the store instead would feed the truncated value back in and\n * make the composition length ratchet down (research HANDOFF-3 §6.1 feedback loop).\n */\nexport function furthestClipEndFromDocument(doc: Document | null | undefined): number {\n if (!doc) return 0;\n const root = doc.querySelector(\"[data-composition-id]\");\n let maxEnd = 0;\n for (const node of Array.from(doc.querySelectorAll(\"[data-start]\"))) {\n if (node === root || isTimelineIgnoredElement(node)) continue;\n const start = Number.parseFloat(node.getAttribute(\"data-start\") ?? \"\");\n const duration = readDurationAttribute(node);\n if (!Number.isFinite(start) || start < 0 || duration <= 0) continue;\n maxEnd = Math.max(maxEnd, start + duration);\n }\n return maxEnd;\n}\n\nexport function readTimelineDurationFromDocument(doc: Document | null | undefined): number {\n if (!doc) return 0;\n const rootDuration = readDurationAttribute(doc.querySelector(\"[data-composition-id]\"));\n if (rootDuration > 0) return rootDuration;\n return furthestClipEndFromDocument(doc);\n}\n\n/**\n * Furthest clip end parsed straight from a composition SOURCE STRING (the HTML\n * being saved). Uses raw `data-duration`, so it is the correct input for syncing\n * the root duration after an edit — reading the store instead would use the\n * runtime-truncated durations and shrink the composition (the feedback loop).\n */\nexport function furthestClipEndFromSource(source: string): number {\n if (!source) return 0;\n return furthestClipEndFromDocument(new DOMParser().parseFromString(source, \"text/html\"));\n}\n\n// ---------------------------------------------------------------------------\n// DOM element type guards\n// ---------------------------------------------------------------------------\n\nfunction isHtmlElement(el: Element): el is HTMLElement {\n const HtmlElementCtor = el.ownerDocument.defaultView?.HTMLElement ?? globalThis.HTMLElement;\n return typeof HtmlElementCtor !== \"undefined\" && el instanceof HtmlElementCtor;\n}\n\nfunction isCompositionHost(el: Element): boolean {\n return (\n el.hasAttribute(\"data-composition-id\") ||\n el.hasAttribute(\"data-composition-src\") ||\n el.hasAttribute(\"data-composition-file\")\n );\n}\n\nexport function resolveMediaElement(el: Element): HTMLMediaElement | HTMLImageElement | null {\n const win = el.ownerDocument.defaultView ?? window;\n const MediaElementCtor = win.HTMLMediaElement ?? globalThis.HTMLMediaElement;\n const ImageElementCtor = win.HTMLImageElement ?? globalThis.HTMLImageElement;\n if (el instanceof MediaElementCtor || el instanceof ImageElementCtor) return el;\n // A composition's media belongs to its own timeline, not the clip's: its length would cap a trim.\n if (isCompositionHost(el)) return null;\n const candidate = el.querySelector(\"video, audio, img\");\n return candidate instanceof MediaElementCtor || candidate instanceof ImageElementCtor\n ? candidate\n : null;\n}\n\n/** The in-point as playback reads it, and the attribute holding it; empty when neither is authored. */\nexport function readPlaybackStartAttributes(\n getAttr: AttrReader,\n): Pick<TimelineElement, \"playbackStart\" | \"playbackStartAttr\"> {\n const playbackStartAttr =\n getAttr(\"data-playback-start\") != null\n ? \"playback-start\"\n : getAttr(\"data-media-start\") != null\n ? \"media-start\"\n : undefined;\n return playbackStartAttr\n ? { playbackStart: readMediaOffsetSeconds(getAttr), playbackStartAttr }\n : {};\n}\n\nexport function playbackStartAttributeForElement(\n element: Pick<TimelineElement, \"kind\" | \"playbackStartAttr\">,\n): \"data-media-start\" | \"data-playback-start\" {\n return element.playbackStartAttr === \"playback-start\" || element.kind === \"composition\"\n ? \"data-playback-start\"\n : \"data-media-start\";\n}\n\nfunction applyPlaybackMetadataFromElement(entry: TimelineElement, el: Element): void {\n Object.assign(\n entry,\n readPlaybackStartAttributes((n) => el.getAttribute(n)),\n );\n\n const authoredPlaybackRate = Number.parseFloat(el.getAttribute(\"data-playback-rate\") ?? \"\");\n if (Number.isFinite(authoredPlaybackRate) && authoredPlaybackRate > 0) {\n entry.playbackRate = clampPlaybackRate(authoredPlaybackRate);\n }\n}\n\n/** Sets or clears an optional field, so a re-parse after the attribute is removed drops it. */\nfunction setOptional<K extends keyof TimelineElement>(\n entry: TimelineElement,\n key: K,\n value: TimelineElement[K] | undefined,\n): void {\n if (value === undefined) delete entry[key];\n else entry[key] = value;\n}\n\nfunction readVolume(el: Element, media: Element): number | undefined {\n const volume = Number.parseFloat(\n el.getAttribute(\"data-volume\") ?? media.getAttribute(\"data-volume\") ?? \"\",\n );\n return Number.isFinite(volume) ? volume : undefined;\n}\n\n/** What the mixer gets: the compiler's `data-has-audio` rule, muted and volume. */\nfunction applyAudioMetadataFromElement(entry: TimelineElement, el: Element): void {\n const media = resolveMediaElement(el) ?? el;\n const muted = el.hasAttribute(\"muted\") || media.hasAttribute(\"muted\");\n const hasAudio = el.getAttribute(\"data-has-audio\");\n const sound = hasAudio === null ? el.tagName === \"VIDEO\" && !muted : hasAudio === \"true\";\n setOptional(entry, \"hasAudio\", sound ? true : undefined);\n setOptional(entry, \"muted\", muted ? true : undefined);\n setOptional(entry, \"volume\", readVolume(el, media));\n}\n\nfunction applyFadeMetadataFromElement(entry: TimelineElement, el: Element): void {\n const fades = readElementFades(el);\n setOptional(entry, \"fadeIn\", fades.fadeIn > 0 ? fades.fadeIn : undefined);\n setOptional(entry, \"fadeOut\", fades.fadeOut > 0 ? fades.fadeOut : undefined);\n}\n\nexport function applyMediaMetadataFromElement(entry: TimelineElement, el: Element): void {\n applyPlaybackMetadataFromElement(entry, el);\n applyAudioMetadataFromElement(entry, el);\n applyFadeMetadataFromElement(entry, el);\n\n const mediaEl = resolveMediaElement(el);\n if (!mediaEl) return;\n\n entry.tag = mediaEl.tagName.toLowerCase();\n const src = mediaEl.getAttribute(\"src\");\n if (src) entry.src = src;\n\n const win = mediaEl.ownerDocument.defaultView ?? window;\n const MediaElementCtor = win.HTMLMediaElement ?? globalThis.HTMLMediaElement;\n if (typeof MediaElementCtor === \"undefined\" || !(mediaEl instanceof MediaElementCtor)) return;\n\n const sourceDurationAttr =\n el.getAttribute(\"data-source-duration\") ?? mediaEl.getAttribute(\"data-source-duration\");\n const sourceDuration = sourceDurationAttr ? parseFloat(sourceDurationAttr) : mediaEl.duration;\n if (Number.isFinite(sourceDuration) && sourceDuration > 0) {\n entry.sourceDuration = sourceDuration;\n }\n\n const playbackRate = mediaEl.defaultPlaybackRate;\n if (entry.playbackRate == null && Number.isFinite(playbackRate) && playbackRate > 0) {\n entry.playbackRate = clampPlaybackRate(playbackRate);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Label helpers\n// ---------------------------------------------------------------------------\n\nexport function getTimelineElementDisplayLabel(input: {\n id?: string | null;\n label?: string | null;\n tag?: string | null;\n}): string {\n const label = input.label?.trim();\n if (label) return label;\n const id = input.id?.trim();\n if (id) return id;\n const tag = input.tag?.trim().toLowerCase();\n return tag ? `${tag} clip` : \"Timeline clip\";\n}\n\n// ---------------------------------------------------------------------------\n// Selector / identity / key builders\n// ---------------------------------------------------------------------------\n\nexport function getTimelineElementSelector(el: Element): string | undefined {\n if (isHtmlElement(el) && el.id) return `#${CSS.escape(el.id)}`;\n const compId = el.getAttribute(\"data-composition-id\");\n if (compId) return `[data-composition-id=\"${CSS.escape(compId)}\"]`;\n if (isHtmlElement(el)) {\n const classes = el.className.split(/\\s+/).filter(Boolean);\n const firstClass = classes.find((className) => className !== \"clip\") ?? classes[0];\n if (firstClass) return `.${CSS.escape(firstClass)}`;\n }\n return undefined;\n}\n\nexport function getTimelineElementSourceFile(el: Element): string | undefined {\n const ownerRoot = el.parentElement?.closest(\"[data-composition-id]\");\n return (\n ownerRoot?.getAttribute(\"data-composition-file\") ??\n ownerRoot?.getAttribute(\"data-composition-src\") ??\n undefined\n );\n}\n\nexport function getTimelineElementSelectorIndex(\n doc: Document,\n el: Element,\n selector: string | undefined,\n): number | undefined {\n return getSourceScopedSelectorIndex(\n doc,\n el,\n selector,\n getTimelineElementSourceFile(el),\n getTimelineElementSourceFile,\n );\n}\n\nexport function buildTimelineElementKey(params: {\n id: string;\n fallbackIndex: number;\n domId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile?: string;\n}): string {\n const scope = params.sourceFile ?? \"index.html\";\n if (params.domId) return `${scope}#${params.domId}`;\n if (params.selector) return `${scope}:${params.selector}:${params.selectorIndex ?? 0}`;\n return `${scope}:${params.id}:${params.fallbackIndex}`;\n}\n\n/**\n * Inverse of {@link buildTimelineElementKey} for the `sourceFile#domId` form.\n * A key with no `#` is a bare dom id and carries no source file of its own, so\n * the caller supplies the scope it wants to look that id up in.\n */\nexport function splitTimelineElementKey(key: string): {\n sourceFile: string | null;\n domId: string;\n} {\n const hashIndex = key.lastIndexOf(\"#\");\n if (hashIndex < 0) return { sourceFile: null, domId: key };\n return { sourceFile: key.slice(0, hashIndex), domId: key.slice(hashIndex + 1) };\n}\n\nexport function buildTimelineElementIdentity(params: {\n preferredId?: string | null;\n label: string;\n fallbackIndex: number;\n domId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile?: string;\n}): { id: string; key: string } {\n const id =\n params.preferredId?.trim() ||\n buildTimelineElementKey({\n id: params.label,\n fallbackIndex: params.fallbackIndex,\n domId: params.domId,\n selector: params.selector,\n selectorIndex: params.selectorIndex,\n sourceFile: params.sourceFile,\n });\n const key = buildTimelineElementKey({\n id,\n fallbackIndex: params.fallbackIndex,\n domId: params.domId,\n selector: params.selector,\n selectorIndex: params.selectorIndex,\n sourceFile: params.sourceFile,\n });\n return { id, key };\n}\n\nexport function getTimelineElementIdentity(element: { key?: string | null; id: string }): string {\n return element.key ?? element.id;\n}\n\n/**\n * The id space the RUNTIME matches on — a bare DOM id, never a store key.\n *\n * Studio addresses rows by `buildTimelineElementKey`'s composite\n * `<sourceFile>#<domId>`, but everything audio in `@hyperframes/core` keys off\n * the live document: `resolveAudioGroups` collects `member.id`,\n * `resolveCarveSourceIds` goes through `getElementById`. Anything crossing into\n * that space — a group membership list, a carve source — has to be\n * converted here first; a composite key silently matches nothing.\n *\n * `null` for a row with no DOM id at all (selector-addressed elements): such an\n * element cannot be grouped, because `resolveAudioGroups` skips\n * members without an `id` and would build a group that is half there.\n */\nexport function runtimeAudioId(element: { domId?: string | null }): string | null {\n return element.domId || null;\n}\n\n/**\n * Timeline store key for a z-reorder entry built OUTSIDE the timeline\n * expansion (canvas context menu / LayersPanel), so the reorder commit can\n * update the store's zIndex synchronously. Matches buildTimelineElementKey's\n * stable branches (`sourceFile#domId`, else the selector-based key). Undefined\n * when the element has neither a DOM id nor a selector — the timeline's\n * fallback branch needs its own fallbackIndex, which these callers don't have,\n * so such an entry simply skips the synchronous store update.\n */\nexport function deriveTimelineStoreKey(params: {\n domId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile?: string;\n}): string | undefined {\n if (!params.domId && !params.selector) return undefined;\n return buildTimelineElementKey({ id: \"\", fallbackIndex: 0, ...params });\n}\n\n/**\n * {@link deriveTimelineStoreKey} for a caller that already has a DOM id in\n * hand (e.g. one it just minted), so the undefined branch never applies.\n */\nexport function deriveTimelineStoreKeyForDomId(domId: string, sourceFile?: string): string {\n return deriveTimelineStoreKey({ domId, sourceFile })!;\n}\n\n// ---------------------------------------------------------------------------\n// DOM node querying\n// ---------------------------------------------------------------------------\n\nfunction getTimelineDomNodes(doc: Document): Element[] {\n const rootComp = doc.querySelector(\"[data-composition-id]\");\n return Array.from(doc.querySelectorAll(\"[data-start]\")).filter(\n (node) => node !== rootComp && !isTimelineIgnoredElement(node),\n );\n}\n\nfunction numbersNearlyEqual(a: number, b: number): boolean {\n return Math.abs(a - b) < 0.001;\n}\n\nconst MANIFEST_CLIP_ATTRS: ReadonlyArray<[string, (clip: ClipManifestClip) => number]> = [\n [\"data-start\", (clip) => clip.start],\n [\"data-duration\", (clip) => clip.duration],\n [\"data-track-index\", (clip) => clip.track],\n];\n\nfunction nodeMatchesClipTag(node: Element, clip: ClipManifestClip): boolean {\n return !clip.tagName || node.tagName.toLowerCase() === clip.tagName.toLowerCase();\n}\n\nfunction nodeMatchesManifestClip(node: Element, clip: ClipManifestClip): boolean {\n if (!nodeMatchesClipTag(node, clip)) return false;\n // An attribute only constrains the match when it parses to a finite number:\n // missing or garbled reads as \"unknown\", not \"mismatch\".\n return MANIFEST_CLIP_ATTRS.every(([attr, expected]) => {\n const actual = Number.parseFloat(node.getAttribute(attr) ?? \"\");\n return !Number.isFinite(actual) || numbersNearlyEqual(actual, expected(clip));\n });\n}\n\n/** Whether `node` sits in the composition the clip was read from, the chain the runtime records outermost first\n * (`resolveNearestCompositionContext` in core's runtime/timeline.ts). A clip without that scope accepts any node. */\nfunction nodeInClipScope(node: Element, clip: ClipManifestClip): boolean {\n const scope = clip.compositionAncestors;\n if (!scope) return true;\n const ids: string[] = [];\n for (let cursor = node.parentElement; cursor; cursor = cursor.parentElement) {\n const id = cursor.getAttribute(\"data-composition-id\");\n if (id) ids.unshift(id);\n }\n return ids.length === scope.length && ids.every((id, index) => id === scope[index]);\n}\n\n/** The first match in the clip's composition across `selectors`; a lone match stands only when none is in scope, as a\n * healed host can stale the clip's chain for a pass. An id can repeat in a sub-composition earlier in the document. */\nfunction findInClipScope(\n doc: Document,\n clip: ClipManifestClip,\n selectors: string[],\n): Element | null {\n let lone: Element | null = null;\n for (const selector of selectors) {\n const nodes = Array.from(doc.querySelectorAll(selector));\n const scoped = nodes.find((node) => nodeInClipScope(node, clip));\n if (scoped) return scoped;\n if (nodes.length === 1) lone ??= nodes[0];\n }\n return lone;\n}\n\nexport type PreviewTarget = Pick<TimelineElement, \"hfId\" | \"domId\" | \"id\" | \"sourceFile\">;\n\n/** Finds a row's preview element by `data-hf-id`, then id, preferring one in the row's own file: both repeat across\n * files. Indexes the document once, so a pass over every row costs one scan. */\nexport function previewElementFinder(\n doc: Document,\n selector = \"[data-hf-id], [id]\",\n): (target: PreviewTarget) => Element | null {\n const byKey = new Map<string, Element[]>();\n const add = (key: string, node: Element) => {\n const nodes = byKey.get(key);\n if (nodes) nodes.push(node);\n else byKey.set(key, [node]);\n };\n for (const node of doc.querySelectorAll(selector)) {\n const hfId = node.getAttribute(\"data-hf-id\");\n const id = node.getAttribute(\"id\");\n if (hfId) add(`hf:${hfId}`, node);\n if (id) add(`id:${id}`, node);\n }\n return (target) => {\n const matches = [\n ...((target.hfId && byKey.get(`hf:${target.hfId}`)) || []),\n ...(byKey.get(`id:${target.domId ?? target.id}`) ?? []),\n ];\n return (\n matches.find((node) => getTimelineElementSourceFile(node) === target.sourceFile) ??\n matches[0] ??\n null\n );\n };\n}\n\nexport function findClipElementById(doc: Document, clip: ClipManifestClip): Element | null {\n if (!clip.id) return null;\n const first = doc.getElementById(clip.id);\n if (!first || nodeInClipScope(first, clip)) return first;\n return findInClipScope(doc, clip, [`[id=\"${CSS.escape(clip.id)}\"]`]);\n}\n\nfunction findTimelineDomNode(doc: Document, clip: ClipManifestClip): Element | null {\n if (!clip.id) return null;\n const first = doc.getElementById(clip.id);\n if (first && nodeInClipScope(first, clip)) return first;\n const id = CSS.escape(clip.id);\n const byOtherKeys = [`[data-hf-id=\"${id}\"]`, `[data-composition-id=\"${id}\"]`, `.${id}`];\n return findInClipScope(doc, clip, first ? [`[id=\"${id}\"]`, ...byOtherKeys] : byOtherKeys);\n}\n\nexport function findTimelineDomNodeForClip(\n doc: Document,\n clip: ClipManifestClip,\n fallbackIndex: number,\n usedNodes = new Set<Element>(),\n getCandidates = () => getTimelineDomNodes(doc),\n): Element | null {\n const byIdentity = findTimelineDomNode(doc, clip);\n if (byIdentity && !usedNodes.has(byIdentity) && nodeMatchesClipTag(byIdentity, clip))\n return byIdentity;\n\n const candidates = getCandidates().filter((node) => !usedNodes.has(node));\n const exact = candidates.find((node) => nodeMatchesManifestClip(node, clip));\n if (exact) return exact;\n\n const positional = candidates[fallbackIndex];\n return positional && nodeMatchesClipTag(positional, clip) ? positional : null;\n}\n\n/** One synchronous hydration pass: snapshot only on a miss, never across reloads. */\nexport function createTimelineDomNodeResolver(doc: Document) {\n let candidates: Element[] | undefined;\n const usedNodes = new Set<Element>();\n const getCandidates = () => (candidates ??= getTimelineDomNodes(doc));\n return (clip: ClipManifestClip, index: number): Element | null => {\n const node = findTimelineDomNodeForClip(doc, clip, index, usedNodes, getCandidates);\n if (node) usedNodes.add(node);\n return node;\n };\n}\n","/**\n * Selection-set arithmetic for the player store, and the reveal request's\n * cross-id-space match.\n *\n * Its own module so `playerStore.ts` stays under the studio's 600-line cap.\n */\n\nimport { splitTimelineElementKey } from \"../lib/timelineElementHelpers\";\n\n/**\n * The id set a selection change leaves behind.\n *\n * `preserveSet` means \"keep the multi-selection if this id is already in it\" —\n * a DOM→store echo re-announcing a member must not collapse the set — and\n * anything else is a genuine single selection.\n */\nexport function nextSelectionSet(\n current: ReadonlySet<string>,\n id: string | null,\n preserveSet: boolean | undefined,\n): Set<string> {\n if (preserveSet) return id && current.has(id) ? new Set(current) : new Set<string>();\n return id ? new Set([id]) : new Set<string>();\n}\n\n/**\n * Is a pending reveal request aimed at the element being selected?\n *\n * Compared across the ID-SPACE BOUNDARY, which is why it is a named function:\n * a request carries the BARE dom id (`runtimeAudioId` — the panel and the\n * runtime speak that), while the store's ids are `sourceFile#domId`. A direct\n * `===` between the two is silently never true, which is the exact shape of\n * failure the split produces and how the reveal came to be dead.\n */\nexport function revealTargetsSelection(\n request: { elementKey: string } | null,\n id: string | null,\n): boolean {\n if (!request || id === null) return false;\n return request.elementKey === splitTimelineElementKey(id).domId;\n}\n","import type { Direction } from \"dockview-react\";\n\nexport const PANEL_IDS = [\n \"preview\",\n \"timeline\",\n \"compositions\",\n \"assets\",\n \"code\",\n \"catalog\",\n \"design\",\n \"layers\",\n \"renders\",\n \"variables\",\n \"slideshow\",\n] as const;\n\nexport type PanelId = (typeof PANEL_IDS)[number];\nexport type PanelZone = \"left\" | \"center\" | \"right\";\n\nexport interface PanelDefinition {\n title: string;\n zone: PanelZone;\n /** Where Window > <panel> puts it when it has no saved place: next to `near`. */\n reopen: { near: PanelId; direction: Direction };\n /** Content stays mounted while its tab is hidden (the preview iframe must not reload). */\n keepMounted?: true;\n}\n\nexport const PANEL_DEFINITIONS = {\n preview: {\n title: \"Preview\",\n zone: \"center\",\n reopen: { near: \"timeline\", direction: \"above\" },\n keepMounted: true,\n },\n timeline: {\n title: \"Timeline\",\n zone: \"center\",\n reopen: { near: \"preview\", direction: \"below\" },\n keepMounted: true,\n },\n compositions: {\n title: \"Compositions\",\n zone: \"left\",\n reopen: { near: \"preview\", direction: \"left\" },\n },\n assets: { title: \"Assets\", zone: \"left\", reopen: { near: \"compositions\", direction: \"within\" } },\n code: { title: \"Code\", zone: \"left\", reopen: { near: \"compositions\", direction: \"within\" } },\n catalog: {\n title: \"Catalog\",\n zone: \"left\",\n reopen: { near: \"compositions\", direction: \"within\" },\n },\n design: { title: \"Design\", zone: \"right\", reopen: { near: \"preview\", direction: \"right\" } },\n layers: { title: \"Layers\", zone: \"right\", reopen: { near: \"design\", direction: \"within\" } },\n renders: { title: \"Renders\", zone: \"right\", reopen: { near: \"design\", direction: \"within\" } },\n variables: { title: \"Variables\", zone: \"right\", reopen: { near: \"design\", direction: \"within\" } },\n slideshow: { title: \"Slideshow\", zone: \"right\", reopen: { near: \"design\", direction: \"within\" } },\n} as const satisfies Record<PanelId, PanelDefinition>;\n\nexport function isPanelId(value: unknown): value is PanelId {\n return typeof value === \"string\" && (PANEL_IDS as readonly string[]).includes(value);\n}\n\nexport function panelsInZone(zone: PanelZone): PanelId[] {\n return PANEL_IDS.filter((id) => PANEL_DEFINITIONS[id].zone === zone);\n}\n","import type { SerializedDockview } from \"dockview-react\";\nimport { isPanelId } from \"./panelRegistry\";\n\nexport const DOCK_PANEL_COMPONENT = \"panel\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction collectLeafViews(node: unknown, into: unknown[]): boolean {\n if (!isRecord(node)) return false;\n if (node.type === \"leaf\") {\n if (!isRecord(node.data) || !Array.isArray(node.data.views)) return false;\n into.push(...node.data.views);\n return true;\n }\n if (node.type === \"branch\") {\n return Array.isArray(node.data) && node.data.every((child) => collectLeafViews(child, into));\n }\n return false;\n}\n\nfunction hasGridShape(grid: Record<string, unknown>): boolean {\n const oriented = grid.orientation === \"HORIZONTAL\" || grid.orientation === \"VERTICAL\";\n return oriented && typeof grid.width === \"number\" && typeof grid.height === \"number\";\n}\n\nfunction panelsAreRegistered(panels: Record<string, unknown>): boolean {\n const ids = Object.keys(panels);\n return (\n ids.length > 0 &&\n ids.every((id) => {\n const state = panels[id];\n return (\n isPanelId(id) &&\n isRecord(state) &&\n state.id === id &&\n state.contentComponent === DOCK_PANEL_COMPONENT\n );\n })\n );\n}\n\nfunction collectFloatingViews(floating: unknown, into: unknown[]): boolean {\n if (floating === undefined) return true;\n if (!Array.isArray(floating)) return false;\n return floating.every((group) => {\n if (!isRecord(group) || !isRecord(group.data) || !Array.isArray(group.data.views)) return false;\n into.push(...group.data.views);\n return true;\n });\n}\n\n/** Parses a stored layout at the trust boundary; null (stale or foreign shape) means use the default preset. */\nexport function parseDockLayout(value: unknown): SerializedDockview | null {\n if (!isRecord(value) || !isRecord(value.grid) || !isRecord(value.panels)) return null;\n const { grid, panels } = value;\n if (!hasGridShape(grid) || !panelsAreRegistered(panels)) return null;\n\n const views: unknown[] = [];\n if (!collectLeafViews(grid.root, views)) return null;\n if (!collectFloatingViews(value.floatingGroups, views)) return null;\n const everyViewIsAPanel = views.every((id) => typeof id === \"string\" && id in panels);\n const everyPanelIsPlaced = Object.keys(panels).every((id) => views.includes(id));\n return everyViewIsAPanel && everyPanelIsPlaced ? (value as unknown as SerializedDockview) : null;\n}\n","import type { SerializedDockview } from \"dockview-react\";\nimport { parseDockLayout } from \"../components/dock/dockLayoutSchema\";\n\nexport type TimelineTimeDisplayMode = \"time\" | \"frame\";\n\nexport interface StudioUiPreferences {\n timelineVisible?: boolean;\n playbackRate?: number;\n audioMuted?: boolean;\n audioVolume?: number;\n thumbnailMode?: \"adaptive\" | \"hidden\";\n recentBlocks?: string[];\n snapEnabled?: boolean;\n gridVisible?: boolean;\n rulerVisible?: boolean;\n safeMarginsVisible?: boolean;\n gridSpacing?: number;\n snapToGrid?: boolean;\n /** Timeline magnet: snap clip drags/trims/drops to playhead, clip edges, and beats. */\n timelineSnapEnabled?: boolean;\n /** Audio level meters at the timeline's right edge; hidden unless enabled here. */\n audioMetersVisible?: boolean;\n /** Keeps the main track gapless: deleting a clip closes the gap. Distinct\n * from `timelineSnapEnabled` (\"Magnet\", drag/trim snapping). */\n rippleEditEnabled?: boolean;\n /** Transport + ruler readout mode: timecode or frame number. */\n timeDisplayMode?: TimelineTimeDisplayMode;\n /**\n * Timeline zoom mode. Persisted so a zoom PINNED on the first edit survives the\n * post-edit iframe reload — otherwise the store reset to \"fit\" and the duration\n * change rescaled every clip (the blink-fix's rescale symptom).\n */\n timelineZoomMode?: \"fit\" | \"manual\";\n /** Manual timeline zoom percent, paired with `timelineZoomMode: \"manual\"`. */\n timelineManualZoomPercent?: number;\n /**\n * Expose Studio's editing capabilities to an agentic browser as WebMCP tools.\n * Absent means on: the browser still gates every actual call behind its own\n * permission prompt, so \"registered\" is not \"reachable without consent\".\n * Changes take effect on the next Studio reload because registration is\n * intentionally scoped to one mount.\n */\n agentToolsEnabled?: boolean;\n /** The dock's serialized panel tree; parsed by `parseDockLayout` on read. */\n dockLayout?: SerializedDockview;\n}\n\nconst STUDIO_UI_PREFERENCES_KEY = \"hf-studio-ui-preferences\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getBrowserStorage(): Storage | null {\n if (typeof window === \"undefined\") return null;\n try {\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\nfunction storageKeyFor(projectId: string | null): string {\n return projectId ? `${STUDIO_UI_PREFERENCES_KEY}:${projectId}` : STUDIO_UI_PREFERENCES_KEY;\n}\n\n// fallow-ignore-next-line complexity\nfunction readStorage(storage: Storage | null, key: string): StudioUiPreferences {\n if (!storage) return {};\n try {\n const raw = storage.getItem(key);\n if (!raw) return {};\n const parsed: unknown = JSON.parse(raw);\n if (!isRecord(parsed)) return {};\n\n const preferences: StudioUiPreferences = {};\n if (typeof parsed.timelineVisible === \"boolean\") {\n preferences.timelineVisible = parsed.timelineVisible;\n }\n if (typeof parsed.playbackRate === \"number\" && Number.isFinite(parsed.playbackRate)) {\n preferences.playbackRate = parsed.playbackRate;\n }\n if (typeof parsed.audioMuted === \"boolean\") {\n preferences.audioMuted = parsed.audioMuted;\n }\n if (\n typeof parsed.audioVolume === \"number\" &&\n Number.isFinite(parsed.audioVolume) &&\n parsed.audioVolume >= 0 &&\n parsed.audioVolume <= 1\n ) {\n preferences.audioVolume = parsed.audioVolume;\n }\n if (parsed.thumbnailMode === \"adaptive\" || parsed.thumbnailMode === \"hidden\") {\n preferences.thumbnailMode = parsed.thumbnailMode;\n } else if (typeof parsed.thumbnailsEnabled === \"boolean\") {\n preferences.thumbnailMode = parsed.thumbnailsEnabled ? \"adaptive\" : \"hidden\";\n }\n if (Array.isArray(parsed.recentBlocks)) {\n preferences.recentBlocks = parsed.recentBlocks.filter(\n (v: unknown): v is string => typeof v === \"string\",\n );\n }\n if (typeof parsed.snapEnabled === \"boolean\") {\n preferences.snapEnabled = parsed.snapEnabled;\n }\n if (typeof parsed.gridVisible === \"boolean\") {\n preferences.gridVisible = parsed.gridVisible;\n }\n if (typeof parsed.rulerVisible === \"boolean\") {\n preferences.rulerVisible = parsed.rulerVisible;\n }\n if (typeof parsed.safeMarginsVisible === \"boolean\") {\n preferences.safeMarginsVisible = parsed.safeMarginsVisible;\n }\n if (typeof parsed.gridSpacing === \"number\" && Number.isFinite(parsed.gridSpacing)) {\n preferences.gridSpacing = parsed.gridSpacing;\n }\n if (typeof parsed.snapToGrid === \"boolean\") {\n preferences.snapToGrid = parsed.snapToGrid;\n }\n if (typeof parsed.timelineSnapEnabled === \"boolean\") {\n preferences.timelineSnapEnabled = parsed.timelineSnapEnabled;\n }\n if (typeof parsed.audioMetersVisible === \"boolean\") {\n preferences.audioMetersVisible = parsed.audioMetersVisible;\n }\n if (typeof parsed.rippleEditEnabled === \"boolean\") {\n preferences.rippleEditEnabled = parsed.rippleEditEnabled;\n }\n if (parsed.timeDisplayMode === \"time\" || parsed.timeDisplayMode === \"frame\") {\n preferences.timeDisplayMode = parsed.timeDisplayMode;\n }\n if (parsed.timelineZoomMode === \"fit\" || parsed.timelineZoomMode === \"manual\") {\n preferences.timelineZoomMode = parsed.timelineZoomMode;\n }\n if (\n typeof parsed.timelineManualZoomPercent === \"number\" &&\n Number.isFinite(parsed.timelineManualZoomPercent)\n ) {\n preferences.timelineManualZoomPercent = parsed.timelineManualZoomPercent;\n }\n if (typeof parsed.agentToolsEnabled === \"boolean\") {\n preferences.agentToolsEnabled = parsed.agentToolsEnabled;\n }\n const dockLayout = parseDockLayout(parsed.dockLayout);\n if (dockLayout) preferences.dockLayout = dockLayout;\n return preferences;\n } catch {\n return {};\n }\n}\n\n/** `projectId` opts a caller into a per-project entry (falls back once to the\n * shared entry so a project's first read isn't blank). Defaults to `null`:\n * most callers read once at mount, never on a live project switch. */\nexport function readStudioUiPreferences(\n storage: Storage | null = getBrowserStorage(),\n projectId: string | null = null,\n): StudioUiPreferences {\n const scoped = readStorage(storage, storageKeyFor(projectId));\n if (!projectId || Object.keys(scoped).length > 0) return scoped;\n return readStorage(storage, STUDIO_UI_PREFERENCES_KEY);\n}\n\nexport function writeStudioUiPreferences(\n patch: StudioUiPreferences,\n storage: Storage | null = getBrowserStorage(),\n projectId: string | null = null,\n) {\n if (!storage) return;\n try {\n const next = {\n ...readStudioUiPreferences(storage, projectId),\n ...patch,\n };\n storage.setItem(storageKeyFor(projectId), JSON.stringify(next));\n } catch {\n /* localStorage may be unavailable or full */\n }\n}\n","import type { ZoomMode } from \"../store/playerStore\";\nimport { STUDIO_PREVIEW_FPS } from \"../lib/time\";\n\nexport const MIN_TIMELINE_ZOOM_PERCENT = 10;\nconst MAX_TIMELINE_FRAME_WIDTH_PX = 48;\n// CapCut-strength steps: one button press / pinch gesture moves the zoom\n// meaningfully (user feedback, twice-doubled: 1.25×/0.8× + 0.0035 felt like\n// \"zooming several times to get anywhere\", then 1.5× + 0.007 still too soft).\n// Kept reciprocal (2 × 0.5 = 1) so in+out round-trips.\nconst ZOOM_OUT_FACTOR = 0.5;\nconst ZOOM_IN_FACTOR = 2;\nconst PINCH_ZOOM_SENSITIVITY = 0.014;\n\nexport function getMaxTimelineZoomPercent(fitPixelsPerSecond: number): number {\n if (!Number.isFinite(fitPixelsPerSecond) || fitPixelsPerSecond <= 0) return 100;\n const frameLevelPixelsPerSecond = STUDIO_PREVIEW_FPS * MAX_TIMELINE_FRAME_WIDTH_PX;\n return Math.max(100, Math.round((frameLevelPixelsPerSecond / fitPixelsPerSecond) * 100));\n}\n\nexport function clampTimelineZoomPercent(percent: number, fitPixelsPerSecond: number): number {\n if (!Number.isFinite(percent)) return 100;\n const maxZoomPercent = getMaxTimelineZoomPercent(fitPixelsPerSecond);\n return Math.max(MIN_TIMELINE_ZOOM_PERCENT, Math.min(maxZoomPercent, Math.round(percent)));\n}\n\nexport function getTimelineZoomPercent(\n zoomMode: ZoomMode,\n manualZoomPercent: number,\n fitPixelsPerSecond: number,\n): number {\n return zoomMode === \"fit\" ? 100 : clampTimelineZoomPercent(manualZoomPercent, fitPixelsPerSecond);\n}\n\n/**\n * The manual-zoom percent that, applied to `fitPixelsPerSecond`, reproduces the\n * CURRENT on-screen pixels-per-second exactly. Used to PIN the timeline zoom on\n * the first edit so a duration change (which recomputes fit-pps) no longer\n * rescales every clip: we switch `zoomMode` to \"manual\" with this percent, so\n * `getTimelinePixelsPerSecond` keeps returning today's pps regardless of the new\n * fit basis.\n *\n * Since `pps = fitPps * (percent / 100)` in manual mode, and while fitting\n * `pps === fitPps`, the pinned percent is `currentPps / fitPps * 100`. Clamped to\n * the manual-zoom range so the pin can't land outside the slider's bounds; falls\n * back to 100 (a no-op pin at the current fit) when either input is unusable.\n */\nexport function computePinnedZoomPercent(\n currentPixelsPerSecond: number,\n fitPixelsPerSecond: number,\n): number {\n if (\n !Number.isFinite(currentPixelsPerSecond) ||\n currentPixelsPerSecond <= 0 ||\n !Number.isFinite(fitPixelsPerSecond) ||\n fitPixelsPerSecond <= 0\n ) {\n return 100;\n }\n return clampTimelineZoomPercent(\n (currentPixelsPerSecond / fitPixelsPerSecond) * 100,\n fitPixelsPerSecond,\n );\n}\n\nexport function getTimelinePixelsPerSecond(\n fitPixelsPerSecond: number,\n zoomMode: ZoomMode,\n manualZoomPercent: number,\n): number {\n if (!Number.isFinite(fitPixelsPerSecond) || fitPixelsPerSecond <= 0) return 100;\n const zoomPercent = getTimelineZoomPercent(zoomMode, manualZoomPercent, fitPixelsPerSecond);\n return zoomMode === \"fit\" ? fitPixelsPerSecond : fitPixelsPerSecond * (zoomPercent / 100);\n}\n\nexport function getNextTimelineZoomPercent(\n direction: \"in\" | \"out\",\n zoomMode: ZoomMode,\n manualZoomPercent: number,\n fitPixelsPerSecond: number,\n): number {\n const current = getTimelineZoomPercent(zoomMode, manualZoomPercent, fitPixelsPerSecond);\n const next = direction === \"in\" ? current * ZOOM_IN_FACTOR : current * ZOOM_OUT_FACTOR;\n return clampTimelineZoomPercent(next, fitPixelsPerSecond);\n}\n\nexport function getPinchTimelineZoomPercent(\n deltaY: number,\n zoomMode: ZoomMode,\n manualZoomPercent: number,\n fitPixelsPerSecond: number,\n): number {\n const current = getTimelineZoomPercent(zoomMode, manualZoomPercent, fitPixelsPerSecond);\n if (!Number.isFinite(deltaY) || deltaY === 0) return current;\n return clampTimelineZoomPercent(\n current * Math.exp(-deltaY * PINCH_ZOOM_SENSITIVITY),\n fitPixelsPerSecond,\n );\n}\n\nconst LOG_MIN = Math.log(MIN_TIMELINE_ZOOM_PERCENT);\n\n/**\n * Maps the frame-level zoom range to a slider position (0–100) using a log scale.\n * Linear would compress the useful low end into a tiny sliver of the slider.\n */\nexport function timelineZoomPercentToSlider(percent: number, fitPixelsPerSecond: number): number {\n const clamped = clampTimelineZoomPercent(percent, fitPixelsPerSecond);\n const logMax = Math.log(getMaxTimelineZoomPercent(fitPixelsPerSecond));\n return ((Math.log(clamped) - LOG_MIN) / (logMax - LOG_MIN)) * 100;\n}\n\n/**\n * Maps a slider position (0–100) to the frame-level zoom range using a log scale.\n * Inverse of `timelineZoomPercentToSlider`.\n */\nexport function timelineSliderToZoomPercent(slider: number, fitPixelsPerSecond: number): number {\n const clampedSlider = Math.max(0, Math.min(100, slider));\n const logMax = Math.log(getMaxTimelineZoomPercent(fitPixelsPerSecond));\n const logValue = LOG_MIN + (clampedSlider / 100) * (logMax - LOG_MIN);\n return clampTimelineZoomPercent(Math.exp(logValue), fitPixelsPerSecond);\n}\n","import type { GsapAnimation } from \"@hyperframes/core/gsap-parser\";\nimport type { StoreApi } from \"zustand\";\nimport type { AnimationKeyframeTarget } from \"../../hooks/gsapTweenSynth\";\n\n/** Minimal keyframe cache types — mirrors GsapKeyframesData without pulling in Node-only gsap-parser. */\nexport interface KeyframeCacheEntry {\n format: string;\n keyframes: Array<{\n percentage: number;\n /** Original tween-relative percentage (server mutations need this, not the clip-relative `percentage`). */\n tweenPercentage?: number;\n /** Which property group the source tween belongs to (position, scale, rotation, visual, etc.). */\n propertyGroup?: string;\n /** Source tween id — lets the inline clip-row ease button target a specific segment. */\n animationId?: string;\n properties: Record<string, number | string>;\n ease?: string;\n /** Source animation/keyframe targets that collide at this clip percentage. */\n collidingAnimationTargets?: AnimationKeyframeTarget[];\n }>;\n ease?: string;\n easeEach?: string;\n}\n\nexport interface FocusedEaseSegment {\n animationId: string;\n collidingAnimationTargets?: AnimationKeyframeTarget[];\n tweenPercentage: number;\n elementId: string;\n projectId: string | null;\n sessionEpoch: number;\n nonce: number;\n}\n\ntype FocusedEaseSegmentTarget = Omit<FocusedEaseSegment, \"projectId\" | \"sessionEpoch\" | \"nonce\">;\n\n/**\n * A request to reveal one automated parameter in the audio FX rack.\n *\n * `elementKey` is the timeline element whose rack it belongs to — a group's own\n * id for a group lane, the clip's key otherwise — so the panel can refuse a\n * request aimed at something it is not showing.\n */\nexport interface RevealedAudioFxTarget {\n elementKey: string;\n /** The lane's own `fx.<node>.<param>` / `volume` target. */\n automationTarget: string;\n projectId: string | null;\n sessionEpoch: number;\n nonce: number;\n}\n\nexport type RevealedAudioFxTargetRequest = Omit<\n RevealedAudioFxTarget,\n \"projectId\" | \"sessionEpoch\" | \"nonce\"\n>;\n\n/** Whether a reveal request still belongs to what is on screen. */\nexport function isRevealedAudioFxRequestCurrent(\n request: RevealedAudioFxTarget,\n state: TimelineSessionIdentity,\n): boolean {\n return (\n request.projectId === state.timelineProjectId &&\n request.sessionEpoch === state.timelineSessionEpoch\n );\n}\n\ninterface TimelineSessionIdentity {\n timelineProjectId: string | null;\n timelineSessionEpoch: number;\n}\n\nexport function isFocusedEaseRequestCurrent(\n request: FocusedEaseSegment,\n state: TimelineSessionIdentity & { selectedElementId: string | null },\n): boolean {\n return (\n request.projectId === state.timelineProjectId &&\n request.sessionEpoch === state.timelineSessionEpoch &&\n request.elementId === state.selectedElementId\n );\n}\n\nexport interface KeyframeSlice {\n /** Selected collapsed (`element:pct`) or expanded (`element:group:animation:clipPct`) diamonds. */\n selectedKeyframes: Set<string>;\n toggleSelectedKeyframe: (key: string) => void;\n clearSelectedKeyframes: () => void;\n\n /** Clips whose keyframe property lanes are expanded in the timeline. */\n expandedClipIds: Set<string>;\n toggleClipExpanded: (id: string) => void;\n setClipExpanded: (id: string, expanded: boolean) => void;\n /** Union-expand clips (keyframed clips are expanded by default on load). */\n expandClips: (ids: readonly string[]) => void;\n\n /**\n * Groups whose member rows the caret has HIDDEN (structural, not lanes).\n *\n * Inverted deliberately. As an expanded-set, \"not in the set\" could not tell\n * never-touched from deliberately-collapsed, so every group defaulted to\n * collapsed — and since nothing seeds the set on create, grouping three\n * tracks made all three vanish behind a header the user had not yet learned\n * to open. Groups are expanded until someone closes one.\n */\n collapsedGroupIds: Set<string>;\n toggleGroupExpanded: (id: string) => void;\n\n /** Rows (clip id or group id) whose automation-lane rows the `∿` button opened. */\n expandedLaneOwnerIds: Set<string>;\n toggleLaneOwnerExpanded: (id: string) => void;\n\n /**\n * Project/session/element-scoped request. Its nonce is monotonic across store\n * resets so a stale consumer can never collide with a later request.\n */\n focusedEaseSegment: FocusedEaseSegment | null;\n focusedEaseRequestNonce: number;\n setFocusedEaseSegment: (target: FocusedEaseSegmentTarget) => void;\n clearFocusedEaseSegment: (nonce: number) => void;\n\n /**\n * \"Show me this automated parameter in the rack\" — raised by clicking an\n * automation lane's label in the timeline, consumed by the property panel.\n *\n * Session-stamped and nonce-guarded exactly like `focusedEaseSegment`: a\n * request outlives the click, so one made against a different project or\n * before a reload must not reopen a rack on whatever is mounted later.\n */\n revealedAudioFxTarget: RevealedAudioFxTarget | null;\n revealedAudioFxNonce: number;\n setRevealedAudioFxTarget: (target: RevealedAudioFxTargetRequest) => void;\n clearRevealedAudioFxTarget: (nonce: number) => void;\n\n /** Keyframe data per element id, populated from parsed GSAP animations. */\n keyframeCache: Map<string, KeyframeCacheEntry>;\n /** Unmerged source tweens per element; expanded property lanes read this, never keyframeCache. */\n gsapAnimations: Map<string, GsapAnimation[]>;\n setGsapAnimations: (elementId: string, animations: GsapAnimation[] | undefined) => void;\n setKeyframeCache: (elementId: string, data: KeyframeCacheEntry | undefined) => void;\n}\n\nexport function createKeyframeSlice(\n set: StoreApi<KeyframeSlice>[\"setState\"],\n getTimelineSessionIdentity: () => TimelineSessionIdentity,\n): KeyframeSlice {\n return {\n selectedKeyframes: new Set(),\n toggleSelectedKeyframe: (key) =>\n set((state) => {\n const next = new Set(state.selectedKeyframes);\n if (next.has(key)) next.delete(key);\n else next.add(key);\n return { selectedKeyframes: next };\n }),\n clearSelectedKeyframes: () => set({ selectedKeyframes: new Set() }),\n\n expandedClipIds: new Set(),\n toggleClipExpanded: (id) =>\n set((state) => {\n const next = new Set(state.expandedClipIds);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n return { expandedClipIds: next };\n }),\n setClipExpanded: (id, expanded) =>\n set((state) => {\n if (state.expandedClipIds.has(id) === expanded) return state;\n const next = new Set(state.expandedClipIds);\n if (expanded) next.add(id);\n else next.delete(id);\n return { expandedClipIds: next };\n }),\n expandClips: (ids) =>\n set((state) => {\n if (ids.every((id) => state.expandedClipIds.has(id))) return state;\n const next = new Set(state.expandedClipIds);\n for (const id of ids) next.add(id);\n return { expandedClipIds: next };\n }),\n\n collapsedGroupIds: new Set(),\n toggleGroupExpanded: (id) =>\n set((state) => {\n const next = new Set(state.collapsedGroupIds);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n return { collapsedGroupIds: next };\n }),\n\n expandedLaneOwnerIds: new Set(),\n toggleLaneOwnerExpanded: (id) =>\n set((state) => {\n const next = new Set(state.expandedLaneOwnerIds);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n return { expandedLaneOwnerIds: next };\n }),\n\n focusedEaseSegment: null,\n focusedEaseRequestNonce: 0,\n setFocusedEaseSegment: (target) =>\n set((state) => {\n const nonce = state.focusedEaseRequestNonce + 1;\n const { timelineProjectId, timelineSessionEpoch } = getTimelineSessionIdentity();\n return {\n focusedEaseRequestNonce: nonce,\n focusedEaseSegment: {\n ...target,\n projectId: timelineProjectId,\n sessionEpoch: timelineSessionEpoch,\n nonce,\n },\n };\n }),\n clearFocusedEaseSegment: (nonce) =>\n set((state) =>\n state.focusedEaseSegment?.nonce === nonce ? { focusedEaseSegment: null } : state,\n ),\n\n revealedAudioFxTarget: null,\n revealedAudioFxNonce: 0,\n setRevealedAudioFxTarget: (target) =>\n set((state) => {\n const nonce = state.revealedAudioFxNonce + 1;\n const { timelineProjectId, timelineSessionEpoch } = getTimelineSessionIdentity();\n return {\n revealedAudioFxNonce: nonce,\n revealedAudioFxTarget: {\n ...target,\n projectId: timelineProjectId,\n sessionEpoch: timelineSessionEpoch,\n nonce,\n },\n };\n }),\n clearRevealedAudioFxTarget: (nonce) =>\n set((state) =>\n state.revealedAudioFxTarget?.nonce === nonce ? { revealedAudioFxTarget: null } : state,\n ),\n\n keyframeCache: new Map(),\n setKeyframeCache: (elementId, data) =>\n set((state) => {\n // A write that changes nothing must not emit a new Map: the cache has\n // several hot writers (per-element effect, file populate, post-commit\n // updater, delete) and every no-op re-rendered every subscriber.\n if (\n data ? state.keyframeCache.get(elementId) === data : !state.keyframeCache.has(elementId)\n )\n return state;\n const next = new Map(state.keyframeCache);\n if (data) next.set(elementId, data);\n else next.delete(elementId);\n return { keyframeCache: next };\n }),\n gsapAnimations: new Map(),\n setGsapAnimations: (elementId, animations) =>\n set((state) => {\n if (\n animations\n ? state.gsapAnimations.get(elementId) === animations\n : !state.gsapAnimations.has(elementId)\n )\n return state;\n const next = new Map(state.gsapAnimations);\n if (animations) next.set(elementId, animations);\n else next.delete(elementId);\n return { gsapAnimations: next };\n }),\n };\n}\n","/**\n * The active selection box on one automation lane.\n *\n * A store slice, not lane-local state, for the same reason keyframe selection\n * is one: Delete/copy/paste handlers and the shape menu live outside the lane\n * component and need to read it. Ephemeral by construction — nothing\n * serializes store state, and the selection must never survive into a render.\n */\nimport type { StoreApi } from \"zustand\";\n\nexport interface AutomationSelection {\n /** TimelineElement key (key ?? id) of the clip that owns the lane. */\n elementKey: string;\n /** Lane target: \"volume\" or \"fx.<nodeId>.<param>\". */\n target: string;\n /** Clip-local seconds; always t0 <= t1 (ordered on write). */\n t0: number;\n t1: number;\n /**\n * The box's value bounds, in the parameter's own units; always v0 <= v1.\n *\n * What makes the selection a box rather than a time span: a point is caught\n * only if it falls inside both axes. Span operations — copy, paste, shape\n * insert, simplify — still read t0/t1 alone, because they act on the envelope\n * over a stretch of time rather than on a set of breakpoints.\n */\n v0: number;\n v1: number;\n}\n\nexport interface AutomationSelectionSlice {\n automationSelection: AutomationSelection | null;\n setAutomationSelection: (sel: AutomationSelection) => void;\n clearAutomationSelection: () => void;\n}\n\nexport function createAutomationSelectionSlice(\n set: StoreApi<AutomationSelectionSlice>[\"setState\"],\n): AutomationSelectionSlice {\n return {\n automationSelection: null,\n setAutomationSelection: (sel) =>\n set({\n automationSelection: {\n ...sel,\n t0: Math.min(sel.t0, sel.t1),\n t1: Math.max(sel.t0, sel.t1),\n v0: Math.min(sel.v0, sel.v1),\n v1: Math.max(sel.v0, sel.v1),\n },\n }),\n clearAutomationSelection: () => set({ automationSelection: null }),\n };\n}\n","/**\n * The two editing-mode toggles the timeline toolbar owns.\n *\n * A store slice rather than toolbar-local state because both are read far from\n * where they are set: the motion-path arm is consumed by the canvas click\n * handler and published by MotionPathOverlay, and the auto-keyframe flag\n * decides what a drag/resize/rotate does inside the edit commit path.\n *\n * `motionPathArmed` is also cleared by playerStore on selection change — arming\n * survives neither a new element nor a project switch, so those resets stay\n * with the state they clear alongside.\n */\nimport type { StoreApi } from \"zustand\";\n\nexport interface EditingModeSlice {\n /** Motion-path \"set destination\" mode. Armed from the preview toolbar\n * (replaces the old double-click-on-canvas UX); while armed, one canvas\n * click places the new path's destination. */\n motionPathArmed: boolean;\n setMotionPathArmed: (armed: boolean) => void;\n /** Published by MotionPathOverlay so the toolbar shows the button only when\n * the selected element can actually take a path. */\n motionPathCreateAvailable: boolean;\n setMotionPathCreateAvailable: (available: boolean) => void;\n /** Global toggle for the \"Add keyframe\" diamond in the timeline toolbar\n * (#1808). When false, a manual drag/resize/rotate edit on an element that\n * already has a live tween shifts every keyframe by the edit's delta\n * (preserving the animation's shape) instead of inserting/updating a\n * keyframe at the playhead. */\n autoKeyframeEnabled: boolean;\n setAutoKeyframeEnabled: (enabled: boolean) => void;\n}\n\nexport function createEditingModeSlice(\n set: StoreApi<EditingModeSlice>[\"setState\"],\n): EditingModeSlice {\n return {\n motionPathArmed: false,\n setMotionPathArmed: (armed) => set({ motionPathArmed: armed }),\n motionPathCreateAvailable: false,\n setMotionPathCreateAvailable: (available) => set({ motionPathCreateAvailable: available }),\n autoKeyframeEnabled: true,\n setAutoKeyframeEnabled: (enabled) => set({ autoKeyframeEnabled: enabled }),\n };\n}\n","export interface TimelineFocusRequest {\n id: string;\n projectId: string | null;\n sessionEpoch: number;\n nonce: number;\n}\n\nexport function createTimelineFocusRequest(\n id: string,\n projectId: string | null,\n sessionEpoch: number,\n nonce: number,\n): TimelineFocusRequest {\n return { id, projectId, sessionEpoch, nonce };\n}\n","export type ThumbnailMode = \"adaptive\" | \"hidden\";\nexport type ThumbnailRuntimePolicy = \"follow-preference\" | \"force-hidden\" | \"legacy-default\";\n\n// \"Adaptive\" currently means the scheduler pauses rich work while scrolling.\n// The mode name leaves room for finer-grained runtime heuristics later.\n\nconst rawPolicy = import.meta.env?.VITE_STUDIO_TIMELINE_THUMBNAIL_POLICY;\n\nconst studioThumbnailRuntimePolicy: ThumbnailRuntimePolicy =\n rawPolicy === \"force-hidden\" || rawPolicy === \"legacy-default\" ? rawPolicy : \"follow-preference\";\n\nexport function defaultThumbnailMode(\n storedMode: ThumbnailMode | undefined,\n policy: ThumbnailRuntimePolicy = studioThumbnailRuntimePolicy,\n): ThumbnailMode {\n return storedMode ?? (policy === \"legacy-default\" ? \"hidden\" : \"adaptive\");\n}\n\nexport function effectiveThumbnailMode(\n preferredMode: ThumbnailMode,\n policy: ThumbnailRuntimePolicy = studioThumbnailRuntimePolicy,\n): ThumbnailMode {\n return policy === \"force-hidden\" ? \"hidden\" : preferredMode;\n}\n","import type { StoreApi } from \"zustand\";\nimport { readStudioUiPreferences, writeStudioUiPreferences } from \"../../utils/studioUiPreferences\";\nimport { defaultThumbnailMode, type ThumbnailMode } from \"../lib/thumbnailPolicy\";\n\n/** Revision that moves every composition's thumbnails at once. */\nconst EVERY_COMPOSITION = \"*\";\n\n/** Mounts may be written `./scene.html`; the server reports `scene.html`. */\nfunction revisionKey(path: string): string {\n return (path.split(/[?#]/)[0] ?? \"\").replace(/\\\\/g, \"/\").replace(/^\\.?\\//, \"\");\n}\n\nexport interface ThumbnailSlice {\n thumbnailMode: ThumbnailMode;\n /** Monotonic identity, per composition path, for persisted content shown by mounted thumbnails. */\n thumbnailRevisions: Readonly<Record<string, number>>;\n setThumbnailMode: (mode: ThumbnailMode) => void;\n /** `null` moves every composition, e.g. after a root or asset change. */\n bumpThumbnailRevisions: (compositions: readonly string[] | null) => void;\n}\n\nexport function thumbnailRevisionOf(\n revisions: Readonly<Record<string, number>>,\n compositionPath: string,\n): number {\n return (revisions[EVERY_COMPOSITION] ?? 0) + (revisions[revisionKey(compositionPath)] ?? 0);\n}\n\nexport function createThumbnailSlice(set: StoreApi<ThumbnailSlice>[\"setState\"]): ThumbnailSlice {\n return {\n thumbnailMode: defaultThumbnailMode(readStudioUiPreferences().thumbnailMode),\n thumbnailRevisions: {},\n setThumbnailMode: (mode) => {\n writeStudioUiPreferences({ thumbnailMode: mode });\n set({ thumbnailMode: mode });\n },\n bumpThumbnailRevisions: (compositions) =>\n set(({ thumbnailRevisions }) => {\n const next = { ...thumbnailRevisions };\n for (const path of compositions?.map(revisionKey) ?? [EVERY_COMPOSITION]) {\n next[path] = (next[path] ?? 0) + 1;\n }\n return { thumbnailRevisions: next };\n }),\n };\n}\n","/** Gates `timelineReady` on the composition's declared readiness inputs\n * (media, compute, and the paint-and-idle default) instead of just a known\n * duration. The generation counter is module-scope, not store state: it\n * guards an in-flight settlement, not something a component reads, so\n * bumping it shouldn't trigger a render. */\nimport type { StoreApi } from \"zustand\";\nimport { settleCompositionReadiness } from \"@hyperframes/core/composition-readiness\";\n\nexport interface PlaybackReadinessSlice {\n timelineReady: boolean;\n /** Latched when the project's first preview shows its first frame (or fails), kept through edit\n * reloads, so work that must not compete with the boot waits for it once. */\n previewBooted: boolean;\n setTimelineReady: (ready: boolean) => void;\n markPreviewBooted: () => void;\n /** Sets timelineReady once doc's readiness inputs settle, or immediately\n * if doc is null. A wait a later call supersedes never wins the race.\n * Waits for doc's load step first: it pauses and rewinds the preview, so a\n * Play enabled before it would be undone. */\n requestTimelineReady: (doc: Document | null) => void;\n /** Called by the preview's load step for the document it ran on. */\n markPreviewLoadStep: (doc: Document) => void;\n}\n\nlet timelineReadyGeneration = 0;\nconst loadStepDocs = new WeakSet<Document>();\nlet awaitingLoadStep: { doc: Document; generation: number } | null = null;\n\n/** For a full timeline reset: bumps the generation so any requestTimelineReady\n * wait in flight can never resolve into what replaced it. */\nexport function resetPlaybackReadinessState(): Pick<\n PlaybackReadinessSlice,\n \"timelineReady\" | \"previewBooted\"\n> {\n timelineReadyGeneration++;\n return { timelineReady: false, previewBooted: false };\n}\n\nexport function createPlaybackReadinessSlice(\n set: StoreApi<PlaybackReadinessSlice>[\"setState\"],\n): PlaybackReadinessSlice {\n const settle = (doc: Document, generation: number) =>\n settleCompositionReadiness(doc, () => {\n if (generation === timelineReadyGeneration) set({ timelineReady: true });\n });\n return {\n timelineReady: false,\n previewBooted: false,\n markPreviewBooted: () => set({ previewBooted: true }),\n setTimelineReady: (ready) => {\n timelineReadyGeneration++;\n set({ timelineReady: ready });\n },\n requestTimelineReady: (doc) => {\n const generation = ++timelineReadyGeneration;\n if (!doc) return set({ timelineReady: true });\n if (!loadStepDocs.has(doc)) {\n awaitingLoadStep = { doc, generation };\n return;\n }\n settle(doc, generation);\n },\n markPreviewLoadStep: (doc) => {\n loadStepDocs.add(doc);\n if (awaitingLoadStep?.doc !== doc) return;\n const { generation } = awaitingLoadStep;\n awaitingLoadStep = null;\n settle(doc, generation);\n },\n };\n}\n","export interface TimelineTimeRange {\n t0: number;\n t1: number;\n}\n\nexport interface RangeSelectionSlice {\n /** Shift-drag ruler range in seconds, normalized so t0 <= t1. */\n rangeSelection: TimelineTimeRange | null;\n}\n\nexport function createRangeSelectionSlice(): RangeSelectionSlice {\n return { rangeSelection: null };\n}\n","import type { GsapAnimation } from \"@hyperframes/core/gsap-parser\";\nimport type { KeyframeCacheEntry } from \"./keyframeSlice\";\nimport { resetPlaybackReadinessState } from \"./readinessSlice\";\nimport type { SubCompositionHostState } from \"./timelineElement\";\n\nexport function createTimelineResetState() {\n return {\n isPlaying: false,\n currentTime: 0,\n duration: 0,\n ...resetPlaybackReadinessState(),\n beatDragging: false,\n elements: [],\n selectedElementId: null,\n zEditVersion: 0,\n inPoint: null,\n outPoint: null,\n rangeSelection: null,\n activeTool: \"select\" as const,\n activeKeyframePct: null,\n motionPathArmed: false,\n motionPathCreateAvailable: false,\n selectedKeyframes: new Set<string>(),\n // Ephemeral like every other selection here. A range surviving a project\n // switch can match a same-keyed clip in the new project and redirect a\n // paste through `sel.elementKey === paste.elementKey` to a stale t0.\n automationSelection: null,\n expandedClipIds: new Set<string>(),\n // Per-composition: ids from comp A match nothing in B, silencing all of it.\n collapsedGroupIds: new Set<string>(),\n expandedLaneOwnerIds: new Set<string>(),\n focusedEaseSegment: null,\n revealedAudioFxTarget: null,\n selectedElementIds: new Set<string>(),\n requestedSeekTime: null,\n lintFindingsByElement: new Map<string, { count: number; messages: string[] }>(),\n timelineFocus: null,\n keyframeCache: new Map<string, KeyframeCacheEntry>(),\n gsapAnimations: new Map<string, GsapAnimation[]>(),\n beatAnalysis: null,\n beatEdits: null,\n beatUndo: [],\n beatRedo: [],\n beatPersist: null,\n clipManifest: null,\n clipParentMap: new Map<string, string>(),\n domClipChildren: [],\n subCompositionHostState: new Map<string, SubCompositionHostState>(),\n };\n}\n","import { buildProjectApiPath } from \"../../utils/projectRouting\";\nimport { forwardRef, useEffect, useRef, useState } from \"react\";\nimport { isLottieAnimationLoaded } from \"@hyperframes/core/runtime/lottie-readiness\";\nimport { useMountEffect } from \"../../hooks/useMountEffect\";\nimport { applyPreviewVariablesToUrl } from \"../../hooks/previewVariablesStore\";\nimport { HyperframesLoader } from \"../../components/ui\";\nimport { usePlayerStore } from \"../store/playerStore\";\n// Importing \"@hyperframes/player\" registers a class extending HTMLElement at\n// module load, which throws under SSR, hence the dynamic import behind a\n// `typeof window` guard. Kicking it here rather than in the mount effect puts\n// the chunk request in flight before the shell's first layout. Clearing the memo\n// on rejection stops one failure poisoning every later mount; the browser's\n// module map still caches a failed fetch, so recovery is a page reload.\nlet playerModule: Promise<unknown> | null = null;\n\nexport function loadPlayerModule(): Promise<unknown> {\n playerModule ??= import(\"@hyperframes/player\").catch((err: unknown) => {\n playerModule = null;\n throw err;\n });\n return playerModule;\n}\n\nif (typeof window !== \"undefined\") void loadPlayerModule().catch(() => {});\n\ninterface PlayerProps {\n projectId?: string;\n directUrl?: string;\n onLoad: () => void;\n /** Fires once the loaded document is painted and every loader (shader, assets) has cleared. */\n onReadyToShowChange?: (ready: boolean) => void;\n onPreviewError?: (message: string) => void;\n onCompositionLoadingChange?: (loading: boolean) => void;\n onPainted?: (details: { iframe: HTMLIFrameElement; startedAt: number; loadId: number }) => void;\n portrait?: boolean;\n style?: React.CSSProperties;\n suppressLoadingOverlay?: boolean;\n}\n\ninterface HyperframesPlayerElement extends HTMLElement {\n iframeElement: HTMLIFrameElement;\n ready?: boolean;\n painted?: boolean;\n}\n\nconst MEDIA_HAVE_FUTURE_DATA = 3;\nconst MEDIA_NETWORK_NO_SOURCE = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getShaderTransitionLoading(event: Event): boolean | null {\n if (!(event instanceof CustomEvent)) return null;\n const detail: unknown = event.detail;\n if (!isRecord(detail)) return null;\n const state = detail.state;\n if (!isRecord(state)) return null;\n return state.loading === true && state.ready !== true;\n}\n\nconst COMPOSITION_LOADING_OVERLAY_DELAY_MS = 400;\nconst PREVIEW_BOOT_DEADLINE_MS = 5000;\nconst DEFAULT_PREVIEW_ERROR = \"The composition preview did not become ready.\";\n\nexport function shouldShowCompositionLoadingOverlay(compositionLoading: boolean): boolean {\n return compositionLoading;\n}\n\nexport function readPreviewErrorMessage(event: Event): string {\n if (!(event instanceof CustomEvent) || !isRecord(event.detail)) return DEFAULT_PREVIEW_ERROR;\n return typeof event.detail.message === \"string\" && event.detail.message.trim()\n ? event.detail.message\n : DEFAULT_PREVIEW_ERROR;\n}\n\nfunction enableInteractiveIframe(player: HyperframesPlayerElement): void {\n const root = player.shadowRoot;\n if (!root) return;\n\n const container = root.querySelector<HTMLElement>(\".hfp-container\");\n const iframe = root.querySelector<HTMLIFrameElement>(\".hfp-iframe\");\n\n container?.style.setProperty(\"pointer-events\", \"auto\");\n iframe?.style.setProperty(\"pointer-events\", \"auto\");\n}\n\nfunction isPreviewMediaElement(el: Element): el is HTMLMediaElement {\n const tagName = el.tagName.toLowerCase();\n return tagName === \"video\" || tagName === \"audio\";\n}\n\n// Assets are considered ready when every `<video>`/`<audio>` has enough data\n// to play through without buffering, and every registered Lottie animation has\n// finished loading.\n//\n// Returns whichever value was returned last on cross-origin / transient DOM\n// races so a brief access failure (e.g. an iframe that just swapped src)\n// doesn't flicker the overlay state — we keep showing whatever was most\n// recently true.\nexport function hasUnloadedAssets(iframe: HTMLIFrameElement, lastResult: boolean): boolean {\n try {\n const win = iframe.contentWindow as unknown as (Window & { __hfLottie?: unknown[] }) | null;\n const doc = iframe.contentDocument;\n if (!win || !doc) return lastResult;\n\n for (const el of doc.querySelectorAll(\"video, audio\")) {\n if (\n isPreviewMediaElement(el) &&\n !el.error &&\n el.networkState !== MEDIA_NETWORK_NO_SOURCE &&\n el.readyState < MEDIA_HAVE_FUTURE_DATA\n ) {\n return true;\n }\n }\n\n const lotties = win.__hfLottie;\n if (lotties?.length) {\n for (const anim of lotties) {\n if (!isLottieAnimationLoaded(anim)) return true;\n }\n }\n\n return false;\n } catch {\n return lastResult;\n }\n}\n\n/**\n * Renders a composition preview using the <hyperframes-player> web component.\n *\n * The web component handles iframe scaling, dimension detection, and\n * ResizeObserver internally. This wrapper bridges its inner iframe to the\n * forwarded ref so useTimelinePlayer can access it for clip manifest parsing,\n * timeline probing, and DOM inspection.\n */\nexport const Player = forwardRef<HTMLIFrameElement, PlayerProps>(\n (\n {\n projectId,\n directUrl,\n onLoad,\n onReadyToShowChange,\n onPreviewError,\n onCompositionLoadingChange,\n onPainted,\n portrait,\n style,\n suppressLoadingOverlay,\n },\n ref,\n ) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const loadCountRef = useRef(0);\n const assetPollRef = useRef<ReturnType<typeof setInterval> | null>(null);\n const assetFadeRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const retryPreviewRef = useRef<(() => void) | null>(null);\n const loadStartedAtRef = useRef(0);\n const loadIdRef = useRef(0);\n const retryCountRef = useRef(0);\n // Read at call time: this element outlives its first props (a shadow preview is\n // promoted in place), so mount-time closures would go stale.\n const onLoadRef = useRef(onLoad);\n onLoadRef.current = onLoad;\n const onReadyToShowChangeRef = useRef(onReadyToShowChange);\n onReadyToShowChangeRef.current = onReadyToShowChange;\n const onPreviewErrorRef = useRef(onPreviewError);\n onPreviewErrorRef.current = onPreviewError;\n const [loaded, setLoaded] = useState(false);\n const [assetsLoading, setAssetsLoading] = useState(false);\n const [assetOverlayVisible, setAssetOverlayVisible] = useState(false);\n const [assetOverlayFading, setAssetOverlayFading] = useState(false);\n const [assetWaitLong, setAssetWaitLong] = useState(false);\n const [shaderTransitionLoading, setShaderTransitionLoading] = useState(false);\n const [compositionLoading, setCompositionLoading] = useState(true);\n const [painted, setPainted] = useState(false);\n const [compositionOverlayDeferred, setCompositionOverlayDeferred] = useState(true);\n const [previewError, setPreviewError] = useState<string | null>(null);\n\n // eslint-disable-next-line no-restricted-syntax\n useEffect(() => {\n if (!compositionLoading) {\n setCompositionOverlayDeferred(true);\n return;\n }\n const timer = setTimeout(\n () => setCompositionOverlayDeferred(false),\n COMPOSITION_LOADING_OVERLAY_DELAY_MS,\n );\n return () => clearTimeout(timer);\n }, [compositionLoading]);\n\n useMountEffect(() => {\n const container = containerRef.current;\n if (!container) return;\n\n const previewSource =\n directUrl || (projectId ? buildProjectApiPath(projectId, \"/preview\") : null);\n if (!previewSource) return;\n\n let canceled = false;\n let cleanup: (() => void) | undefined;\n\n void loadPlayerModule().then(() => {\n if (canceled) return;\n\n // Create the web component imperatively to avoid JSX custom-element typing.\n const player = document.createElement(\"hyperframes-player\") as HyperframesPlayerElement;\n const srcUrl = new URL(previewSource, window.location.origin);\n applyPreviewVariablesToUrl(srcUrl);\n const src = srcUrl.pathname + srcUrl.search;\n const retryPreview = () => {\n retryCountRef.current += 1;\n const retryUrl = new URL(src, window.location.origin);\n retryUrl.searchParams.set(\"_hfStudioRetry\", String(retryCountRef.current));\n setPreviewError(null);\n setCompositionLoading(true);\n loadStartedAtRef.current = performance.now();\n loadIdRef.current += 1;\n player.setAttribute(\"src\", retryUrl.pathname + retryUrl.search);\n };\n retryPreviewRef.current = retryPreview;\n const iframe = player.iframeElement;\n const preventToggle = (e: Event) => e.stopImmediatePropagation();\n const handleShaderTransitionState = (event: Event) => {\n const loading = getShaderTransitionLoading(event);\n if (loading !== null) setShaderTransitionLoading(loading);\n };\n const handleReady = () => {\n setPreviewError(null);\n setCompositionLoading(false);\n };\n const handlePainted = () => {\n setPainted(true);\n onPainted?.({ iframe, startedAt: loadStartedAtRef.current, loadId: loadIdRef.current });\n };\n const handleError = (event: Event) => {\n const message = readPreviewErrorMessage(event);\n onPreviewErrorRef.current?.(message);\n setPreviewError(message);\n setCompositionLoading(false);\n };\n const handleLoad = () => {\n loadCountRef.current++;\n setLoaded(true);\n setPreviewError(null);\n setShaderTransitionLoading(false);\n setCompositionLoading(!player.ready);\n setPainted(Boolean(player.painted));\n // Reveal animation on reload (hot-reload, composition switch)\n if (loadCountRef.current > 1) {\n container.classList.remove(\"preview-revealing\");\n void container.offsetWidth;\n container.classList.add(\"preview-revealing\");\n const onEnd = () => container.classList.remove(\"preview-revealing\");\n container.addEventListener(\"animationend\", onEnd, { once: true });\n }\n onLoadRef.current();\n\n // Show a loading overlay until every `<video>`/`<audio>` and Lottie\n // asset is ready. Without this users can click play before audio has\n // buffered — the runtime is resilient (queued play() resolves once\n // data arrives), but the overlay communicates why the first frame\n // or first audio beat may lag.\n //\n // Skip the overlay on subsequent loads (content refreshes via\n // refreshPlayer). The browser has already cached the assets from\n // the first load, so they resolve near-instantly and the overlay\n // just creates a disruptive flash.\n //\n // Poll with a 10 s safety cap (100 ticks × 100 ms). If the cap\n // trips we hide the overlay so the UI doesn't appear stuck forever,\n // but we log a debug warning so the case is diagnosable — a long\n // cold video or a broken asset can legitimately exceed 10 s on a\n // slow network.\n if (assetPollRef.current) clearInterval(assetPollRef.current);\n const isContentRefresh = loadCountRef.current > 1;\n let lastUnloaded = isContentRefresh ? false : hasUnloadedAssets(iframe, false);\n if (lastUnloaded) {\n setAssetsLoading(true);\n let attempts = 0;\n assetPollRef.current = setInterval(() => {\n attempts += 1;\n lastUnloaded = hasUnloadedAssets(iframe, lastUnloaded);\n if (!lastUnloaded || attempts > 100) {\n if (lastUnloaded && attempts > 100) {\n console.debug(\n \"[studio] asset readiness poll hit the 10s cap — continuing with unloaded assets\",\n );\n }\n if (assetPollRef.current) clearInterval(assetPollRef.current);\n assetPollRef.current = null;\n setAssetsLoading(false);\n }\n }, 100);\n } else {\n setAssetsLoading(false);\n }\n };\n\n // Attach lifecycle listeners before assigning src or connecting the\n // custom element. A warm local iframe can otherwise finish before\n // Studio observes its load and never initialize the timeline.\n iframe.addEventListener(\"load\", handleLoad);\n player.addEventListener(\"click\", preventToggle, { capture: true });\n player.addEventListener(\"shadertransitionstate\", handleShaderTransitionState);\n player.addEventListener(\"ready\", handleReady);\n player.addEventListener(\"painted\", handlePainted);\n player.addEventListener(\"error\", handleError);\n\n // Bridge the inner iframe to the forwarded ref for useTimelinePlayer.\n if (typeof ref === \"function\") {\n ref(iframe);\n } else if (ref) {\n (ref as React.MutableRefObject<HTMLIFrameElement | null>).current = iframe;\n }\n\n player.setAttribute(\"shader-capture-scale\", \"1\");\n player.setAttribute(\"shader-loading\", \"player\");\n player.setAttribute(\"low-power-idle\", \"\");\n player.setAttribute(\"width\", String(portrait ? 1080 : 1920));\n player.setAttribute(\"height\", String(portrait ? 1920 : 1080));\n player.style.width = \"100%\";\n player.style.height = \"100%\";\n player.style.display = \"block\";\n player.style.background = \"transparent\";\n loadStartedAtRef.current = performance.now();\n loadIdRef.current += 1;\n player.setAttribute(\"src\", src);\n container.appendChild(player);\n\n // Inject pasteboard shadow: let the shadow around the canvas bleed\n // into the surrounding pasteboard area (overflow: visible on the container)\n // and add a subtle outline + drop-shadow so the canvas boundary reads\n // against the gray pasteboard, consistent with professional editors.\n if (player.shadowRoot) {\n const pasteboardStyle = document.createElement(\"style\");\n pasteboardStyle.textContent =\n \".hfp-container{overflow:visible}\" +\n \".hfp-iframe{box-shadow:0 0 0 1px rgba(255,255,255,0.08),0 4px 32px rgba(0,0,0,.7)}\";\n player.shadowRoot.appendChild(pasteboardStyle);\n }\n\n enableInteractiveIframe(player);\n\n cleanup = () => {\n iframe.removeEventListener(\"load\", handleLoad);\n player.removeEventListener(\"click\", preventToggle, { capture: true });\n player.removeEventListener(\"shadertransitionstate\", handleShaderTransitionState);\n player.removeEventListener(\"ready\", handleReady);\n player.removeEventListener(\"painted\", handlePainted);\n player.removeEventListener(\"error\", handleError);\n if (assetPollRef.current) clearInterval(assetPollRef.current);\n assetPollRef.current = null;\n // `remove()` rather than `container.removeChild(player)`: by the time\n // this cleanup runs the element may already be detached — React can\n // re-render the container, a crossfade refresh can swap it, or a\n // translation/extension can reparent it. `removeChild` then throws\n // NotFoundError, which the error boundary turns into a full-screen\n // \"Something went wrong\". `remove()` is a no-op when already detached.\n player.remove();\n if (retryPreviewRef.current === retryPreview) retryPreviewRef.current = null;\n // Clear the forwarded ref only if it still points to THIS iframe.\n // During crossfade refreshes the retiring Player unmounts after the\n // new Player has already assigned its iframe to the same ref — blindly\n // nulling it would break seeking in the new Player.\n // Callback refs are skipped — we can't read back the current value to\n // guard against clobbering a newer assignment. The mutable-ref branch\n // (the only path used today) is guarded by identity check.\n if (typeof ref === \"function\") {\n // no-op: can't safely guard callback refs\n } else if (ref) {\n const mutableRef = ref as React.MutableRefObject<HTMLIFrameElement | null>;\n if (mutableRef.current === iframe) {\n mutableRef.current = null;\n }\n }\n };\n });\n\n return () => {\n canceled = true;\n cleanup?.();\n };\n });\n\n // Surface a \"Continue anyway\" escape hatch once the asset wait drags on.\n // eslint-disable-next-line no-restricted-syntax\n useEffect(() => {\n if (!assetsLoading) {\n setAssetWaitLong(false);\n return;\n }\n const timer = setTimeout(() => setAssetWaitLong(true), 3000);\n return () => clearTimeout(timer);\n }, [assetsLoading]);\n\n useEffect(() => {\n if (assetFadeRef.current) {\n clearTimeout(assetFadeRef.current);\n assetFadeRef.current = null;\n }\n\n if (assetsLoading) {\n setAssetOverlayVisible(true);\n setAssetOverlayFading(false);\n return;\n }\n\n setAssetOverlayFading(true);\n assetFadeRef.current = setTimeout(() => {\n setAssetOverlayVisible(false);\n setAssetOverlayFading(false);\n assetFadeRef.current = null;\n }, 240);\n\n return () => {\n if (assetFadeRef.current) {\n clearTimeout(assetFadeRef.current);\n assetFadeRef.current = null;\n }\n };\n }, [assetsLoading]);\n\n const handleContinueAnyway = () => {\n if (assetPollRef.current) {\n clearInterval(assetPollRef.current);\n assetPollRef.current = null;\n }\n setAssetsLoading(false);\n };\n\n const firstFrameShown =\n loaded && painted && !compositionLoading && !shaderTransitionLoading && !previewError;\n const readyToShow = firstFrameShown && !assetsLoading;\n // Work waiting on the boot starts at the first frame, while media still buffers.\n useEffect(() => {\n if (firstFrameShown) usePlayerStore.getState().markPreviewBooted();\n }, [firstFrameShown]);\n // `painted` means the player's own loader has finished fading; two frames of grace on top.\n useEffect(() => {\n if (!readyToShow) {\n onReadyToShowChangeRef.current?.(false);\n return;\n }\n let second = 0;\n const first = requestAnimationFrame(() => {\n second = requestAnimationFrame(() => onReadyToShowChangeRef.current?.(true));\n });\n return () => {\n cancelAnimationFrame(first);\n cancelAnimationFrame(second);\n };\n }, [readyToShow]);\n\n useEffect(() => {\n if (previewError) usePlayerStore.getState().markPreviewBooted();\n }, [previewError]);\n\n useEffect(() => {\n const timer = setTimeout(\n () => usePlayerStore.getState().markPreviewBooted(),\n PREVIEW_BOOT_DEADLINE_MS,\n );\n return () => clearTimeout(timer);\n }, [projectId]);\n\n const showCompositionOverlay =\n !suppressLoadingOverlay &&\n !compositionOverlayDeferred &&\n shouldShowCompositionLoadingOverlay(compositionLoading);\n const showAssetOverlay =\n assetOverlayVisible && !shaderTransitionLoading && !showCompositionOverlay && !previewError;\n\n useEffect(() => {\n onCompositionLoadingChange?.(showCompositionOverlay || showAssetOverlay);\n }, [onCompositionLoadingChange, showCompositionOverlay, showAssetOverlay]);\n\n return (\n <div\n className=\"relative w-full h-full max-w-full max-h-full overflow-hidden flex items-center justify-center\"\n style={style}\n >\n <div ref={containerRef} className=\"w-full h-full\" />\n {showCompositionOverlay && (\n <div\n className=\"absolute inset-0 bg-black flex items-center justify-center z-30 select-none\"\n data-hyperframes-ignore=\"\"\n data-testid=\"composition-loading-overlay\"\n draggable={false}\n onDragStart={(event) => event.preventDefault()}\n onMouseDown={(event) => event.preventDefault()}\n onPointerDown={(event) => event.preventDefault()}\n >\n <HyperframesLoader\n title=\"Loading composition\"\n detail=\"Preparing the Studio preview.\"\n size={56}\n />\n </div>\n )}\n {showAssetOverlay && (\n <div\n className=\"absolute inset-0 bg-black flex items-center justify-center z-20 select-none\"\n data-hyperframes-ignore=\"\"\n draggable={false}\n style={{\n opacity: assetOverlayFading ? 0 : 1,\n pointerEvents: assetOverlayFading ? \"none\" : \"auto\",\n transition: \"opacity 180ms ease-in\",\n }}\n onDragStart={(event) => event.preventDefault()}\n onMouseDown={(event) => event.preventDefault()}\n >\n <div className=\"flex flex-col items-center gap-3\">\n <HyperframesLoader\n title=\"Preparing preview assets\"\n detail=\"Waiting for media and motion assets before playback starts.\"\n size={56}\n />\n {assetWaitLong && (\n <button\n type=\"button\"\n onClick={handleContinueAnyway}\n className=\"px-3 py-1.5 text-[11px] rounded-md border border-neutral-700 text-neutral-300 hover:border-neutral-500 hover:bg-neutral-800 transition-colors\"\n >\n Continue anyway\n </button>\n )}\n </div>\n </div>\n )}\n {previewError && (\n <div\n className=\"absolute inset-0 z-40 flex items-center justify-center bg-black/90 px-6 text-center\"\n data-hyperframes-ignore=\"\"\n data-testid=\"composition-preview-error\"\n >\n <div className=\"max-w-sm\">\n <p className=\"text-sm font-semibold text-white\">Preview failed to load</p>\n <p className=\"mt-1 text-xs text-neutral-400\">{previewError}</p>\n <button\n type=\"button\"\n className=\"mt-4 rounded-md bg-white px-3 py-1.5 text-xs font-semibold text-black transition-colors hover:bg-neutral-200\"\n onClick={() => retryPreviewRef.current?.()}\n >\n Retry preview\n </button>\n </div>\n </div>\n )}\n </div>\n );\n },\n);\n\nPlayer.displayName = \"Player\";\n","import { useEffect } from \"react\";\n\n/**\n * Run an effect exactly once on mount (and optional cleanup on unmount).\n * This is the ONLY sanctioned way to call useEffect in this codebase.\n *\n * If you need to react to prop/state changes, use one of:\n * - Derived state (compute inline, no hook needed)\n * - Event handlers (onClick, onChange, etc.)\n * - `key` prop to force remount\n * - Data-fetching library (useQuery, useSWR)\n *\n * @see https://react.dev/learn/you-might-not-need-an-effect\n */\nexport function useMountEffect(effect: () => void | (() => void)) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(effect, []);\n}\n","import { create } from \"zustand\";\n\n/**\n * Ephemeral composition-variable overrides for the preview iframe.\n *\n * Values here are NEVER persisted to the composition — they ride the preview\n * URL as `?variables=<json>` (see the studio-server preview routes), which the\n * server injects as `window.__hfVariables` exactly like render-time injection,\n * so what the user previews is what `hyperframes render --variables` produces.\n * `null` means \"preview with declared defaults\".\n */\ninterface PreviewVariablesState {\n values: Record<string, unknown> | null;\n setValues: (values: Record<string, unknown> | null) => void;\n}\n\nexport const usePreviewVariablesStore = create<PreviewVariablesState>((set) => ({\n values: null,\n setValues: (values) => set({ values: values && Object.keys(values).length > 0 ? values : null }),\n}));\n\n/**\n * Apply the current preview-variable overrides to a preview URL (both the\n * Player's initial mount and refreshPlayer's soft reload route through this,\n * so a hard remount can't silently drop the active overrides).\n */\nexport function applyPreviewVariablesToUrl(url: URL): void {\n const values = usePreviewVariablesStore.getState().values;\n if (values) {\n url.searchParams.set(\"variables\", JSON.stringify(values));\n } else {\n url.searchParams.delete(\"variables\");\n }\n}\n"],"mappings":";;;;;;;;;AAAO,IAAM,qBAAqB;AAE3B,SAAS,WAAW,MAAsB;AAC/C,MAAI,CAAC,OAAO,SAAS,IAAI,KAAK,OAAO,EAAG,QAAO;AAC/C,QAAM,OAAO,KAAK,MAAM,OAAO,EAAE;AACjC,QAAM,OAAO,KAAK,MAAM,OAAO,EAAE;AAKjC,SAAO,GAAG,KAAK,SAAS,EAAE,SAAS,GAAG,GAAG,CAAC,IAAI,KAAK,SAAS,EAAE,SAAS,GAAG,GAAG,CAAC;AAChF;AAEO,SAAS,eAAe,MAAc,MAAM,oBAA4B;AAC7E,MAAI,CAAC,OAAO,SAAS,IAAI,KAAK,QAAQ,EAAG,QAAO;AAChD,MAAI,CAAC,OAAO,SAAS,GAAG,KAAK,OAAO,EAAG,QAAO;AAC9C,SAAO,KAAK,MAAM,OAAO,GAAG;AAC9B;AAEO,SAAS,eAAe,OA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;AAAA;AAAA,kBACC,OAAM;AAAA,kBACN,QAAO;AAAA,kBACP,MAAM;AAAA;AAAA,cACR;AAAA;AAAA,UACF;AAAA,UAED,oBACC;AAAA,YAAC;AAAA;AAAA,cACC,WAAU;AAAA,cACV,2BAAwB;AAAA,cACxB,WAAW;AAAA,cACX,OAAO;AAAA,gBACL,SAAS,qBAAqB,IAAI;AAAA,gBAClC,eAAe,qBAAqB,SAAS;AAAA,gBAC7C,YAAY;AAAA,cACd;AAAA,cACA,aAAa,CAAC,UAAU,MAAM,eAAe;AAAA,cAC7C,aAAa,CAAC,UAAU,MAAM,eAAe;AAAA,cAE7C,+BAAC,SAAI,WAAU,oCACb;AAAA;AAAA,kBAAC;AAAA;AAAA,oBACC,OAAM;AAAA,oBACN,QAAO;AAAA,oBACP,MAAM;AAAA;AAAA,gBACR;AAAA,gBACC,iBACC;AAAA,kBAAC;AAAA;AAAA,oBACC,MAAK;AAAA,oBACL,SAAS;AAAA,oBACT,WAAU;AAAA,oBACX;AAAA;AAAA,gBAED;AAAA,iBAEJ;AAAA;AAAA,UACF;AAAA,UAED,gBACC;AAAA,YAAC;AAAA;AAAA,cACC,WAAU;AAAA,cACV,2BAAwB;AAAA,cACxB,eAAY;AAAA,cAEZ,+BAAC,SAAI,WAAU,YACb;AAAA,oCAAC,OAAE,WAAU,oCAAmC,oCAAsB;AAAA,gBACtE,oBAAC,OAAE,WAAU,iCAAiC,wBAAa;AAAA,gBAC3D;AAAA,kBAAC;AAAA;AAAA,oBACC,MAAK;AAAA,oBACL,WAAU;AAAA,oBACV,SAAS,MAAM,gBAAgB,UAAU;AAAA,oBAC1C;AAAA;AAAA,gBAED;AAAA,iBACF;AAAA;AAAA,UACF;AAAA;AAAA;AAAA,IAEJ;AAAA,EAEJ;AACF;AAEA,OAAO,cAAc;","names":["isRecord","useEffect","create","isRecord","useEffect"]}
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6
6
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
7
7
  <title>HyperFrames Studio</title>
8
- <script type="module" crossorigin src="/assets/index-BYhK_KMc.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-gjbSm-vt.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/assets/index-BWJqxeaH.css">
10
10
  </head>
11
11
  <body>
@@ -65,7 +65,7 @@ import {
65
65
  whenPreviewBooted,
66
66
  wrapTimeline,
67
67
  writeStudioUiPreferences
68
- } from "./chunk-LPZMAGS7.js";
68
+ } from "./chunk-7VDQIGOU.js";
69
69
  import {
70
70
  Button,
71
71
  ContextMenu,
@@ -25622,7 +25622,8 @@ var RENDERED_FIELDS = [
25622
25622
  "audioGroupVolume",
25623
25623
  "audioGroupHidden",
25624
25624
  "fadeIn",
25625
- "fadeOut"
25625
+ "fadeOut",
25626
+ "src"
25626
25627
  ];
25627
25628
  function timelineElementsChanged(previous, next) {
25628
25629
  if (next.length !== previous.length) return true;
@@ -35416,12 +35417,9 @@ function useInlineTextEdit({
35416
35417
  element.removeEventListener("drop", onDrop);
35417
35418
  };
35418
35419
  }, [session, commit, cancel]);
35419
- useEffect44(
35420
- () => () => {
35421
- teardown();
35422
- },
35423
- [teardown]
35424
- );
35420
+ const commitRef = useRef65(commit);
35421
+ commitRef.current = commit;
35422
+ useEffect44(() => () => commitRef.current(), []);
35425
35423
  return { session, start, commit, cancel };
35426
35424
  }
35427
35425
  function placeCaret(element, at) {
@@ -72647,8 +72645,11 @@ function useDomEditTextCommits({
72647
72645
  refreshDomEditSelectionFromPreview,
72648
72646
  buildDomSelectionFromTarget,
72649
72647
  persistDomEditOperations,
72650
- resolveImportedFontAsset
72648
+ resolveImportedFontAsset,
72649
+ readOnlyPreview
72651
72650
  }) {
72651
+ const latestReadOnlyPreviewRef = useRef140(readOnlyPreview);
72652
+ latestReadOnlyPreviewRef.current = readOnlyPreview;
72652
72653
  const domTextCommitVersionRef = useRef140(/* @__PURE__ */ new Map());
72653
72654
  const domStyleCommitVersionRef = useRef140(/* @__PURE__ */ new Map());
72654
72655
  const {
@@ -72809,6 +72810,10 @@ function useDomEditTextCommits({
72809
72810
  const handleDomRichTextCommit = useCallback119(
72810
72811
  async ({ element, html: html2, previousHtml }) => {
72811
72812
  if (!domEditSelection) return;
72813
+ if (latestReadOnlyPreviewRef.current) {
72814
+ if (element.isConnected && element.innerHTML === html2) element.innerHTML = previousHtml;
72815
+ return;
72816
+ }
72812
72817
  if (!canCommitInlineTextSelection(domEditSelection, element)) return;
72813
72818
  const iframe = previewIframeRef.current;
72814
72819
  const doc = iframe?.contentDocument;
@@ -73819,6 +73824,7 @@ function useDomEditCommits({
73819
73824
  handleDomAddTextField,
73820
73825
  handleDomRemoveTextField
73821
73826
  } = useDomEditTextCommits({
73827
+ readOnlyPreview,
73822
73828
  activeCompPath,
73823
73829
  previewIframeRef,
73824
73830
  domEditSelection,