@waveform-playlist/browser 17.0.0-next.3 → 17.0.0-next.5

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["<define:__INSTALL_SPECS__>","../src/WaveformPlaylistContext.tsx","../src/soundFontSync.ts","../src/hooks/useTimeFormat.ts","../src/hooks/useZoomControls.ts","../src/hooks/useMasterVolume.ts","../src/hooks/useSelectionState.ts","../src/hooks/useLoopState.ts","../src/hooks/useSelectedTrack.ts","../src/hooks/useClipDragHandlers.ts","../src/utils/boundaryTrim.ts","../src/utils/sortedClips.ts","../src/utils/loadedTracks.ts","../src/utils/sameItems.ts","../src/contexts/playlistContexts.ts","../src/hooks/useAnnotationDragHandlers.ts","../src/hooks/useAnnotationsWithPreview.ts","../src/hooks/useDragSensors.ts","../src/hooks/useClipSplitting.ts","../src/hooks/useKeyboardShortcuts.ts","../src/hooks/usePlaybackShortcuts.ts","../src/hooks/usePlayFromSelectionOrCursor.ts","../src/hooks/useAnnotationKeyboardControls.ts","../src/hooks/useAnimationFrameLoop.ts","../src/hooks/useWaveformDataCache.ts","../src/workers/peaksWorker.ts","../src/hooks/useCreateArrangement.ts","../src/hooks/useArrangementTracks.ts","../src/hooks/useArrangementSources.ts","../src/providerInternals/followAnnotations.ts","../src/providerInternals/useAnnotationState.ts","../src/utils/annotationLookup.ts","../src/utils/isDevelopmentBuild.ts","../src/providerInternals/useFrameCallbacks.ts","../src/providerInternals/useScrollFollow.ts","../src/providerInternals/useMergedTheme.ts","../src/hooks/useShallowStable.ts","../src/providerInternals/useTrimPreview.ts","../src/waveformDataLoader.ts","../src/utils/derivePeaks.ts","../src/providerInternals/useEngineLifetime.ts","../src/utils/installCommand.ts","../src/playout/resolvePlayoutAdapter.ts","../src/providerInternals/useArrangementView.ts","../src/utils/placeholderPeaks.ts","../src/utils/timelineDuration.ts","../src/providerInternals/useReadyOnce.ts","../src/providerInternals/useArrangementEditing.ts","../src/components/partWarnings.ts","../src/providerInternals/arrangementIdentity.ts","../src/MediaElementPlaylistContext.tsx","../src/playout/resolveMediaElementPlayout.ts","../src/components/PlaybackControls.tsx","../src/components/ZoomControls.tsx","../src/components/ContextualControls.tsx","../src/components/WaveformRoot.tsx","../src/utils/trackOrderPreview.ts","../src/hooks/useTrailingActive.ts","../src/hooks/useRecordingLayout.ts","../src/hooks/useTrimPreviewView.ts","../src/SpectrogramIntegrationContext.tsx","../src/utils/trackRenderMode.ts","../src/components/visualizationLayout.tsx","../src/components/waveformFrame.tsx","../src/hooks/useSelectionDrag.ts","../src/hooks/useWindowDrag.ts","../src/components/waveformLayoutContext.ts","../src/components/waveformParts.tsx","../src/components/TrackRows.tsx","../src/contexts/ClipInteractionContext.tsx","../src/components/ChannelWithProgress.tsx","../src/components/TrackControlsColumn.tsx","../src/components/DefaultTrackControls.tsx","../src/components/TrackControlPieces.tsx","../src/components/trackContext.ts","../src/hooks/useTrackReorderHandle.ts","../src/utils/dragPopoverHealer.ts","../src/utils/stableTemplate.ts","../src/components/VisualizationOverlays.tsx","../src/components/AnimatedPlayhead.tsx","../src/components/WaveformViewOptions.tsx","../src/components/WaveformAnnotationBoxes.tsx","../src/AnnotationIntegrationContext.tsx","../src/components/AnnotationBoxes.tsx","../src/components/AnnotationList.tsx","../src/components/Waveform.tsx","../src/components/MediaElementWaveformRoot.tsx","../src/components/MediaElementWaveform.tsx","../src/components/KeyboardShortcuts.tsx","../src/hooks/useRecordingSession.ts","../src/components/ClipInteractionProvider.tsx","../src/modifiers/ClipCollisionModifier.ts","../src/modifiers/SnapToGridModifier.ts"],"sourcesContent":["{\"@dawcore/wam\":\"@dawcore/wam@^0.0.5-next.0\",\"@dnd-kit/abstract\":\"@dnd-kit/abstract@^0.5.0\",\"@dnd-kit/dom\":\"@dnd-kit/dom@^0.5.0\",\"@dnd-kit/react\":\"@dnd-kit/react@^0.5.0\",\"@waveform-playlist/annotations\":\"@waveform-playlist/annotations@^14.0.0-next.2\",\"@waveform-playlist/media-element-playout\":\"@waveform-playlist/media-element-playout@^12.4.0-next.1\",\"@waveform-playlist/playout\":\"@waveform-playlist/playout@^13.0.0-next.1\",\"@waveform-playlist/recording\":\"@waveform-playlist/recording@^14.0.0-next.2\",\"react\":\"react@^19.0.0\",\"react-dom\":\"react-dom@^19.0.0\",\"styled-components\":\"styled-components@^6.0.0\",\"tone\":\"tone@^15.0.0\",\"@waveform-playlist/spectrogram\":\"@waveform-playlist/spectrogram@^15.0.0-next.1\"}","import React, {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useCallback,\n useMemo,\n type ReactNode,\n} from 'react';\nimport { ThemeProvider } from 'styled-components';\nimport type {\n EffectsFunction,\n TrackEffectsFunction,\n SoundFontCache,\n} from '@waveform-playlist/playout';\nimport type {\n Arrangement,\n EngineState,\n PlaylistEngine,\n PlayoutAdapter,\n} from '@waveform-playlist/engine';\nimport { type Fade, type MidiNoteData } from '@waveform-playlist/core';\nimport { type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport { syncSoundFontCacheToAdapter } from './soundFontSync';\nimport type { TrackDragPreview } from './utils/trackOrderPreview';\nimport type { PeakData } from '@waveform-playlist/core';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport {\n useTimeFormat,\n useZoomControls,\n useMasterVolume,\n useSelectionState,\n useLoopState,\n useSelectedTrack,\n useAnimationFrameLoop,\n} from './hooks';\nimport { followAnnotations } from './providerInternals/followAnnotations';\nimport {\n useAnnotationState,\n type AnnotationListProp,\n} from './providerInternals/useAnnotationState';\nimport { useFrameCallbacks, type FrameData } from './providerInternals/useFrameCallbacks';\nimport { centrePlayhead, useScrollFollow } from './providerInternals/useScrollFollow';\nimport { useMergedTheme } from './providerInternals/useMergedTheme';\nimport { useTrimPreview } from './providerInternals/useTrimPreview';\nimport { useEngineLifetime } from './providerInternals/useEngineLifetime';\nimport { useArrangementView } from './providerInternals/useArrangementView';\nimport { useReadyOnce } from './providerInternals/useReadyOnce';\nimport { useArrangementEditing } from './providerInternals/useArrangementEditing';\nimport { useArrangementKey } from './providerInternals/arrangementIdentity';\n\n// Types\n/**\n * What one clip is drawn from.\n *\n * `isPlaceholder` is true for the record of a clip whose audio is still loading\n * (`placeholderPeaks`): it is drawn without drag or trim handles, and there is\n * NO clip for it in `usePlaylistTimeline().tracks`, so look it up by `clipId`,\n * never by position. Every other record has it false.\n */\nexport interface ClipPeaks {\n clipId: string;\n trackName: string;\n peaks: PeakData;\n startSample: number;\n durationSamples: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n midiNotes?: MidiNoteData[];\n sampleRate?: number;\n offsetSamples?: number;\n /** The clip's linear gain — drawn into the waveform when\n * `<WaveformTracks gainScaled />` is set. */\n gain?: number;\n isPlaceholder: boolean;\n}\n\nexport type TrackClipPeaks = ClipPeaks[];\n\nexport type { TrackDragPreview };\n\nexport interface TrackState {\n name: string;\n muted: boolean;\n soloed: boolean;\n volume: number;\n pan: number;\n}\n\nimport {\n BLOCKED,\n ActiveAnnotationContext,\n ArrangementContext,\n AnnotationOptionsContext,\n AnnotationsContext,\n CurrentTimeContext,\n EditorControlsContext,\n EngineRefsContext,\n IsPlayingContext,\n LoopContext,\n MediaElementTrackContext,\n PlaybackControlsContext,\n PlaybackRateContext,\n PlaybackRefsContext,\n PlaylistMixerContext,\n PlaylistSettingsContext,\n PlaylistTimelineContext,\n PlaylistViewContext,\n PlaylistZoomContext,\n SelectedTrackIdContext,\n SelectedRowContext,\n SelectionContext,\n TrackReorderPreviewContext,\n TrimPreviewContext,\n RecordingArmContext,\n TrimPreviewPeaksContext,\n UndoRedoContext,\n type ActiveAnnotationContextValue,\n type CurrentTimeContextValue,\n type EditorControlsContextValue,\n type EngineRefsContextValue,\n type IsPlayingContextValue,\n type LoopContextValue,\n type PlaybackControlsContextValue,\n type PlaybackRefsContextValue,\n type PlaylistMixerContextValue,\n type PlaylistSettingsContextValue,\n type PlaylistTimelineContextValue,\n type PlaylistViewContextValue,\n type PlaylistZoomContextValue,\n type SelectedTrackIdContextValue,\n type SelectionContextValue,\n type TrackReorderPreviewContextValue,\n type UndoRedoContextValue,\n} from './contexts/playlistContexts';\n\nexport interface WaveformPlaylistProviderProps {\n /**\n * What the provider plays and draws: the tracks, their mix, the undo\n * history and the loading of their audio (#812). Make it with\n * `useCreateArrangement` and change it through its methods (or\n * `useArrangement()` below the provider); the provider follows it. A new\n * object is a new playlist: everything below the provider mounts again.\n */\n arrangement: Arrangement;\n /**\n * Draw and analyse every track as one channel. A provider option, not a\n * view option: the provider computes the peaks with it.\n */\n mono?: boolean;\n samplesPerPixel?: number;\n zoomLevels?: number[]; // Array of zoom levels in samples per pixel (lower = more zoomed in)\n automaticScroll?: boolean;\n theme?: Partial<WaveformPlaylistTheme>;\n /**\n * The annotations and the three annotation options (`editable`,\n * `linkEndpoints`, `isContinuousPlay`). The provider follows all four: an\n * option takes a new value of its field, and a setter or checkbox changes\n * it in between.\n */\n annotationList?: AnnotationListProp;\n /** Master effects chain (default Tone.js adapter only). A new function builds a new engine. */\n effects?: EffectsFunction;\n /**\n * Returns the effects function of a track by id, or `undefined` for none:\n * pass `getTrackEffectsFunction` from `useTrackDynamicEffects()`. Default\n * Tone.js adapter only; with `createAdapter`, give the same function to your\n * own `createToneAdapter({ trackEffects })`.\n *\n * It is called when a track's audio graph is built, with the function passed\n * on the latest render. A new function identity does not rebuild anything,\n * so an inline arrow is fine; a different result for a track that is already\n * built applies the next time that track is built.\n */\n trackEffects?: (trackId: string) => TrackEffectsFunction | undefined;\n /**\n * Called once per mount, the first time an engine is attached and no source\n * of the arrangement is still pending. Read when it is called: a new\n * function identity builds nothing.\n */\n onReady?: () => void;\n /** Called when the engine or its adapter cannot be built (e.g. a missing\n * optional peer, a throwing `createAdapter`, or an invalid\n * `zoomLevels`/`samplesPerPixel`), and when `onReady` throws. A source that\n * fails to load is not reported here: see `useArrangementSources`. The\n * provider already logs the error; use this to surface it in your UI. */\n onError?: (err: Error) => void;\n /** Callback when annotations are changed (drag, edit, etc.) */\n onAnnotationsChange?: (annotations: AnnotationData[]) => void;\n /** SoundFont cache for sample-based MIDI playback. When provided, MIDI clips\n * use SoundFont samples instead of PolySynth synthesis. */\n soundFontCache?: SoundFontCache;\n /** Disable the automatic stop when the cursor reaches the end of the\n * longest track — the transport rolls until an explicit stop/pause\n * (DAW-style). The multitrack view then draws the timeline as wide as its\n * container, as `<WaveformViewOptions fillViewport>` does. Recording\n * sessions suppress the auto-stop automatically, so most recording UIs\n * don't need this. A provider option, not a view option: the animation\n * loop and `seekTo` follow it. */\n indefinitePlayback?: boolean;\n /** Desired AudioContext sample rate. Creates a cross-browser AudioContext at\n * this rate via standardized-audio-context. Pre-computed peaks (.dat files)\n * render instantly when they match. On mismatch, falls back to worker. */\n sampleRate?: number;\n /** Factory for a custom PlayoutAdapter. When omitted, the Tone.js engine\n * (@waveform-playlist/playout) is dynamically imported — so a custom adapter\n * lets a consumer use neither @waveform-playlist/playout nor tone. Called once\n * per engine build; the provider owns and disposes the returned instance.\n * Read when an engine is built: a new function identity builds nothing. */\n createAdapter?: () => PlayoutAdapter;\n children: ReactNode;\n}\n\nexport const WaveformPlaylistProvider: React.FC<WaveformPlaylistProviderProps> = (props) => {\n // A new arrangement object is a new playlist: everything below mounts again.\n const key = useArrangementKey(props.arrangement);\n return <ProviderOnArrangement key={key} {...props} />;\n};\n\n// Resting (non-playing) cursor positions display the raw time unchanged.\n// Latency compensation (outputLatency + lookAhead) models the gap between\n// the Transport's scheduling position and audible output — a property of\n// *playing*, not of position. A seeked/paused/stopped cursor has no audible\n// counterpart; the commanded position is the truth. During playback the\n// animation loop uses engine.getAudibleTime() instead.\nfunction toVisualTime(rawTime: number): number {\n return Number.isFinite(rawTime) ? Math.max(0, rawTime) : 0;\n}\n\n/** What a new engine is given and how the provider follows it; set after the hooks that own it. */\ninterface EngineFollowers {\n seed: (engine: PlaylistEngine) => void;\n follow: (engine: PlaylistEngine) => void;\n mirror: (state: EngineState) => void;\n}\n\nconst ProviderOnArrangement: React.FC<WaveformPlaylistProviderProps> = ({\n arrangement,\n mono = false,\n samplesPerPixel: initialSamplesPerPixel = 1024,\n zoomLevels,\n automaticScroll = false,\n theme: userThemeProp,\n annotationList,\n effects,\n trackEffects,\n onReady,\n onError,\n onAnnotationsChange,\n soundFontCache,\n indefinitePlayback = false,\n sampleRate: sampleRateProp,\n createAdapter,\n children,\n}) => {\n const mergedTheme = useMergedTheme(userThemeProp);\n\n // Content-stable: an inline array is new on every render. The engine's\n // lifetime compares the levels by content too.\n const stableZoomLevels = useMemo(\n () => zoomLevels,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [zoomLevels?.join(',')]\n );\n\n // Annotations are derived from the prop (single source of truth in the\n // parent). Shared with the MediaElement provider (#769).\n const {\n annotationsRef,\n annotationLookup,\n setAnnotations,\n annotationPreview,\n activeAnnotationId,\n activeAnnotationIdRef,\n setActiveAnnotationId,\n continuousPlay,\n continuousPlayRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationsValue,\n annotationOptionsValue,\n } = useAnnotationState({\n annotationList,\n onAnnotationsChange,\n providerName: 'WaveformPlaylistProvider',\n });\n const {\n scrollContainerRef,\n setScrollContainer,\n isAutomaticScroll,\n isAutomaticScrollRef,\n setAutomaticScroll,\n } = useScrollFollow(automaticScroll);\n // Components register per-frame DOM updates here instead of running their\n // own rAF loops; the single loop below drives them all.\n const { registerFrameCallback, unregisterFrameCallback, runFrameCallbacks } = useFrameCallbacks();\n\n // State\n const [isPlaying, setIsPlaying] = useState(false);\n const [currentTime, setCurrentTime] = useState(0);\n // Bumped after every track-reorder DRAG interaction (committed or not) —\n // see bumpTrackReorderEpoch below for the full rationale.\n const [trackReorderEpoch, setTrackReorderEpoch] = useState(0);\n // Live track-reorder drag preview (view-level only; see the\n // \"Track Reordering\" section of packages/browser/CLAUDE.md). Set by\n // ClipInteractionProvider's onDragOver, cleared on drag end/cancel.\n // The committed order is untouched until drop.\n const [trackDragPreview, setTrackDragPreview] = useState<TrackDragPreview | null>(null);\n\n // Refs\n // Ref for animation loop access (avoids adding the prop to useCallback deps)\n const indefinitePlaybackRef = useRef(indefinitePlayback);\n indefinitePlaybackRef.current = indefinitePlayback;\n const isPlayingRef = useRef<boolean>(false);\n isPlayingRef.current = isPlaying;\n const playStartPositionRef = useRef<number>(0);\n const currentTimeRef = useRef<number>(0);\n // Visually-aligned playback time (see toVisualTime / getAudibleTime). The\n // animation loop updates this per frame. Pause/seek/stop paths sync it\n // explicitly so the static playhead reflects the commanded resting position.\n const visualTimeRef = useRef<number>(0);\n const soundFontCacheRef = useRef(soundFontCache);\n soundFontCacheRef.current = soundFontCache;\n // The adapter keeps ONE lookup for its whole life and calls it whenever it\n // builds a track. It reads the prop through a ref so that a new function\n // identity (an inline arrow) is not a reason to rebuild the engine (#752).\n const trackEffectsRef = useRef(trackEffects);\n trackEffectsRef.current = trackEffects;\n const resolveTrackEffects = useCallback(\n (trackId: string) => trackEffectsRef.current?.(trackId),\n []\n );\n // The latest committed callbacks (QG): read when they are called, so a new\n // identity builds nothing.\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n useLayoutEffect(() => {\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n });\n const playbackStartTimeRef = useRef<number>(0); // context.currentTime when playback started\n const audioStartPositionRef = useRef<number>(0); // Audio position when playback started\n const playbackEndTimeRef = useRef<number | null>(null); // Audio position where playback should stop (for selections)\n // Suppresses the engine 'stop' mirror (below) around provider-initiated\n // engine.stop() calls that immediately seek/restart playback in the same\n // synchronous block (play(), setSelection, reschedulePlayback). Without\n // this, the mirror's ref writes would race the restart's own writes and\n // briefly show the pre-restart position/isPlaying=false. Stop paths that\n // don't restart afterward don't need suppression — see the mirror's own\n // comment for why.\n const suppressEngineStopMirrorRef = useRef(false);\n // Provider-level ref for scroll-position math and animation loop pixel\n // calculation. Distinct from useZoomControls's internal ref (statechange guard).\n const samplesPerPixelRef = useRef<number>(initialSamplesPerPixel);\n // True while the bounded play in progress is the highlighted selection itself\n // (its start and end are the selection's). Set by play(). Selection playback\n // ignores continuous play; anything else, including an annotation clicked\n // while a selection is highlighted elsewhere, follows it.\n const isSelectionPlayRef = useRef(false);\n // Incremented by every play(), stop() and pause(). A play() that has been\n // waiting on engine.init() compares it afterwards: if it moved, the user has\n // since asked for something else and the older play must not start.\n const playRequestIdRef = useRef(0);\n\n const { animationFrameRef, startAnimationFrameLoop, stopAnimationFrameLoop } =\n useAnimationFrameLoop();\n\n // A build that fails while playback shows as running (a rebuild began\n // during playback and queued its resume, which the failure dropped): no\n // engine is coming, so playback shows stopped where it was. Nothing starts\n // by itself after a later build (maintainer, D3).\n const onBuildFailure = useCallback(() => {\n if (!isPlayingRef.current) return;\n setIsPlaying(false);\n stopAnimationFrameLoop();\n visualTimeRef.current = toVisualTime(currentTimeRef.current);\n setCurrentTime(currentTimeRef.current);\n }, [stopAnimationFrameLoop]);\n\n // The engine's own state is mirrored by the hooks below, which need the\n // engine ref first; these three reach them through a ref set after them.\n const followersRef = useRef<EngineFollowers | null>(null);\n const seedEngine = useCallback(\n (engine: PlaylistEngine) => followersRef.current?.seed(engine),\n []\n );\n const onEngine = useCallback(\n (engine: PlaylistEngine) => followersRef.current?.follow(engine),\n []\n );\n const onEngineState = useCallback(\n (state: EngineState) => followersRef.current?.mirror(state),\n []\n );\n\n // The engine around the arrangement: built on mount and when `effects` or\n // the zoom levels change, disposed in every cleanup (#812). A track edit\n // builds nothing.\n const {\n engineRef,\n adapterRef,\n engineEpoch,\n bumpEngineEpoch,\n isEngineAttached,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n sampleRate,\n isSampleRateKnown,\n } = useEngineLifetime({\n arrangement,\n createAdapter,\n effects,\n resolveTrackEffects,\n soundFontCacheRef,\n sampleRateProp,\n zoomLevels,\n samplesPerPixelRef,\n playbackEndTimeRef,\n seedEngine,\n onEngine,\n onEngineState,\n stopAnimationFrameLoop,\n onErrorRef,\n onBuildFailure,\n });\n // For the animation loop and the zoom scroll math, which run outside render.\n const sampleRateRef = useRef(sampleRate);\n sampleRateRef.current = sampleRate;\n\n // Custom hooks — engine-owned state delegated to hooks with onEngineState() pattern\n const { timeFormat, setTimeFormat } = useTimeFormat();\n const zoom = useZoomControls({ engineRef, initialSamplesPerPixel });\n const { samplesPerPixel, onEngineState: onZoomEngineState } = zoom;\n const volume = useMasterVolume({ engineRef, initialVolume: 1.0 });\n const {\n masterVolume,\n setMasterVolume,\n masterVolumeRef,\n onEngineState: onVolumeEngineState,\n } = volume;\n const {\n selectionStart,\n selectionEnd,\n setSelection: setSelectionEngine,\n selectionStartRef,\n selectionEndRef,\n onEngineState: onSelectionEngineState,\n } = useSelectionState({ engineRef });\n const {\n isLoopEnabled,\n loopStart,\n loopEnd,\n setLoopEnabled,\n setLoopRegion,\n clearLoopRegion,\n isLoopEnabledRef,\n loopStartRef,\n loopEndRef,\n onEngineState: onLoopEngineState,\n } = useLoopState({ engineRef });\n const {\n selectedTrackId,\n setSelectedTrackId: setSelectedTrackIdControl,\n onEngineState: onSelectedTrackEngineState,\n selectedTrackIdRef,\n } = useSelectedTrack({ engineRef });\n\n // Everything the provider publishes about the tracks, derived from the\n // arrangement during render and never written back (#812).\n const baseScale = useMemo(\n () => Math.min(...(stableZoomLevels ?? [256, 512, 1024, 2048, 4096, 8192])),\n [stableZoomLevels]\n );\n const view = useArrangementView(arrangement, {\n samplesPerPixel,\n mono,\n baseScale,\n placeholderSampleRate: isSampleRateKnown ? sampleRate : null,\n });\n const { tracks, duration } = view;\n // The animation loop and `seekTo` read the timeline end from here, so that\n // neither changes identity when it moves: `seekTo` and `play` are in the\n // controls value, which must not follow `duration` (#767). Written during\n // render, like `isPlayingRef`, so that a child that calls `seekTo` from a\n // layout effect of the same commit already gets the new end.\n const durationRef = useRef(duration);\n durationRef.current = duration;\n\n const { isReady, refusePlayBeforeFirstReady } = useReadyOnce({\n isEngineAttached,\n arrangement,\n onReadyRef,\n onErrorRef,\n trackCount: tracks.length,\n duration,\n });\n\n // A trim drag in progress (#812): moves go to this source, and only the\n // dragged clip's view follows them. The tracks change once, on release.\n const { trimPreview, trimPreviewPeaks } = useTrimPreview({\n tracks,\n peaksOptions: view.peaksOptions,\n peaksCacheRef: view.peaksCacheRef,\n });\n\n // The mixer setters, reorder, undo, redo and the recording session: all\n // through the arrangement, engine or not.\n const editing = useArrangementEditing(arrangement);\n const { recordingActiveRef } = editing;\n\n // Cross-hook concern: reads selection refs to set loop region\n const setLoopRegionFromSelection = useCallback(() => {\n const start = selectionStartRef.current ?? 0;\n const end = selectionEndRef.current ?? 0;\n if (start !== end && end > start) {\n setLoopRegion(start, end);\n }\n }, [setLoopRegion, selectionStartRef, selectionEndRef]);\n\n // Adjust scroll position proportionally when zoom changes\n useEffect(() => {\n if (!scrollContainerRef.current || duration === 0) return;\n\n const container = scrollContainerRef.current;\n const oldSamplesPerPixel = samplesPerPixelRef.current;\n const newSamplesPerPixel = samplesPerPixel;\n\n if (oldSamplesPerPixel === newSamplesPerPixel) return;\n\n // Calculate the current center time in the viewport\n const containerWidth = container.clientWidth;\n const currentScrollLeft = container.scrollLeft;\n const centerPixel = currentScrollLeft + containerWidth / 2;\n const sr = sampleRateRef.current;\n const centerTime = (centerPixel * oldSamplesPerPixel) / sr;\n\n // Calculate new scroll position to keep the same center time\n const newCenterPixel = (centerTime * sr) / newSamplesPerPixel;\n const newScrollLeft = Math.max(0, newCenterPixel - containerWidth / 2);\n\n container.scrollLeft = newScrollLeft;\n samplesPerPixelRef.current = newSamplesPerPixel;\n }, [samplesPerPixel, duration, scrollContainerRef]);\n\n // Forward late-arriving / swapped SoundFontCache to the live adapter so\n // MIDI tracks upgrade from PolySynth without an engine rebuild. Before the\n // first adapter exists this runs against null, which the helper ignores;\n // the build reads the cache from its ref.\n useEffect(() => {\n syncSoundFontCacheToAdapter(adapterRef.current, soundFontCache);\n }, [soundFontCache, adapterRef]);\n\n // A loaded clip with nothing to draw from is almost always a wiring\n // mistake. A clip still loading is not in `tracks`, so it is never reported.\n useEffect(() => {\n for (const track of tracks) {\n for (const clip of track.clips) {\n if (!clip.audioBuffer && !clip.waveformData && !clip.midiNotes) {\n console.warn(`[waveform-playlist] Clip \"${clip.id}\" has no audio data or waveform data`);\n }\n }\n }\n }, [tracks]);\n\n // Audio clock from the adapter's own AudioContext (#510 — replaces tone's\n // getContext()). Stable; reads a ref so identity never changes.\n const getAudioContextTime = useCallback(\n () => adapterRef.current?.audioContext.currentTime ?? 0,\n [adapterRef]\n );\n\n // Returns current playback time from engine (auto-wraps at loop boundaries).\n // Falls back to manual calculation when engine is unavailable.\n const getPlaybackTimeFallbackWarnedRef = useRef(false);\n const getPlaybackTime = useCallback(() => {\n if (engineRef.current) {\n return engineRef.current.getCurrentTime();\n }\n // Fallback: manual calculation (does not handle loop wrapping)\n if (!getPlaybackTimeFallbackWarnedRef.current) {\n getPlaybackTimeFallbackWarnedRef.current = true;\n console.warn(\n '[waveform-playlist] getPlaybackTime called without engine. ' +\n 'Falling back to manual elapsed time (loop wrapping will not work).'\n );\n }\n const elapsed = getAudioContextTime() - (playbackStartTimeRef.current ?? 0);\n return (audioStartPositionRef.current ?? 0) + elapsed;\n }, [getAudioContextTime, engineRef]);\n\n // Pair-write helper for the dual-ref pattern. Storage stays raw on\n // `currentTimeRef`; display gets the guard-clamped raw version on `visualTimeRef`\n // (compensation happens in the animation loop via engine.getAudibleTime() while playing).\n // Use this at every pause/seek/stop/loop site — never assign one ref alone\n // (browser/CLAUDE.md: \"Display uses visualTimeRef\").\n const setCurrentTimeRefs = useCallback((rawTime: number) => {\n currentTimeRef.current = rawTime;\n visualTimeRef.current = toVisualTime(rawTime);\n }, []);\n\n // Read the engine's scheduler lookahead (Tone adapter ~0.1s, native 0).\n // Exposed through PlaybackRefsContextValue so consumers (e.g., recording\n // live preview) compute audible-latency from the same source as the playhead.\n const getLookAhead = useCallback((): number => {\n return engineRef.current?.lookAhead ?? 0;\n }, [engineRef]);\n\n const getOutputLatency = useCallback((): number => {\n const audioCtx = adapterRef.current?.audioContext;\n return audioCtx && 'outputLatency' in audioCtx ? (audioCtx as AudioContext).outputLatency : 0;\n }, [adapterRef]);\n\n // Engine-initiated stop mirror (final-review CRITICAL 1, #608 follow-up).\n // PlaylistEngine self-stops when a bounded play(start, end) completes on\n // an adapter that reports onPlaybackEnded (Tone) — see engine CLAUDE.md\n // \"onPlaybackEnded hook\". That self-stop rewinds the engine's own current\n // time to playStartPosition BEFORE the rAF loop's own end-of-playback\n // checks (below) can observe it, so the loop's `time >= playbackEndTimeRef`\n // / `time >= duration` comparisons never fire — React isPlaying stays\n // true and the loop spins forever at the rewound position. Mirroring the\n // engine's 'stop' event makes React authoritative-from-engine for ANY\n // engine-initiated stop, closing that race. The engine already rewound\n // its own time (`_currentTime = _playStartPosition`) — we only mirror\n // that into React's refs/state, we never seek() again here.\n //\n // Suppressed via suppressEngineStopMirrorRef around provider-initiated\n // engine.stop() calls that immediately seek/restart playback (play(),\n // setSelection, reschedulePlayback) — those already set the correct target\n // position themselves; an unguarded mirror would clobber it mid-transition\n // with the pre-restart position. Stop paths that terminate playback\n // (stop(), the rAF loop's own annotation/selection/duration-end branches)\n // don't need suppression: they either write the identical value the\n // mirror would (both read _playStartPosition), or run their own\n // setCurrentTimeRefs call synchronously right after this listener, which —\n // as plain refs, not batched state — simply overwrites the mirror's write\n // with no other code observing the transient value in between.\n const mirrorEngineStop = useCallback(\n (engine: PlaylistEngine) => {\n if (suppressEngineStopMirrorRef.current) return;\n setIsPlaying(false);\n stopAnimationFrameLoop();\n // The engine rewound to where its play began. For the selection,\n // return to the selection start instead (see play()): a play that\n // resumed part-way must not leave the cursor inside the selection.\n let stoppedAt = engine.getCurrentTime();\n if (isSelectionPlayRef.current) {\n stoppedAt = playStartPositionRef.current;\n engine.seek(stoppedAt);\n }\n setCurrentTimeRefs(stoppedAt);\n setCurrentTime(stoppedAt);\n },\n [stopAnimationFrameLoop, setCurrentTimeRefs]\n );\n\n // What a new engine is given and how the provider follows it. The engine\n // owns selection, loop, selected track, zoom and master volume; the hooks\n // mirror them from `statechange`. Seeded so that a fresh engine does not\n // put them back to defaults.\n useLayoutEffect(() => {\n const mirror = (state: EngineState) => {\n onSelectionEngineState(state);\n onLoopEngineState(state);\n onSelectedTrackEngineState(state);\n onZoomEngineState(state);\n onVolumeEngineState(state);\n };\n followersRef.current = {\n seed: (engine) => {\n engine.setSelection(selectionStartRef.current ?? 0, selectionEndRef.current ?? 0);\n engine.setLoopRegion(loopStartRef.current ?? 0, loopEndRef.current ?? 0);\n if (isLoopEnabledRef.current) engine.setLoopEnabled(true);\n engine.setMasterVolume(masterVolumeRef.current ?? 1.0);\n if (selectedTrackIdRef.current) engine.selectTrack(selectedTrackIdRef.current);\n },\n follow: (engine) => {\n engine.on('statechange', mirror);\n engine.on('stop', () => mirrorEngineStop(engine));\n },\n mirror,\n };\n });\n\n // Animation loop\n const startAnimationLoop = useCallback(() => {\n const updateTime = () => {\n // Get current time from engine (auto-wraps at loop boundaries via Transport.seconds)\n const time = getPlaybackTime();\n currentTimeRef.current = time;\n\n // Compute visual time once — all visual consumers use this same value.\n // engine.getAudibleTime() subtracts outputLatency (hardware DAC delay)\n // and adapter.lookAhead (Tone.js Transport runs ~100ms ahead of audible),\n // holding at the play-start position during the pre-roll window. Native\n // adapters report lookAhead 0, so this is a near no-op there.\n const visualRaw = engineRef.current ? engineRef.current.getAudibleTime() : time;\n const visualTime = Number.isFinite(visualRaw) ? Math.max(0, visualRaw) : 0;\n visualTimeRef.current = visualTime;\n\n // Drive registered per-frame callbacks BEFORE stop checks so the\n // final frame renders at the correct stop position (not one frame behind).\n const sr = sampleRateRef.current;\n const spp = samplesPerPixelRef.current;\n const frameData: FrameData = {\n time,\n visualTime,\n sampleRate: sr,\n samplesPerPixel: spp,\n };\n runFrameCallbacks(frameData);\n\n // Annotations. Playing the selection takes continuous play out of the\n // picture: playback is not cut at annotation boundaries, whichever way\n // the toggle is set, and the active annotation still follows the\n // playhead. On the frame that reaches a bounded play's end the\n // highlight is held: the end check below stops there, and it must not\n // move on to the next annotation first.\n const activeAnnotationEnded = followAnnotations({\n annotations: annotationsRef.current,\n lookup: annotationLookup,\n time,\n activeId: activeAnnotationIdRef.current,\n followOnly: continuousPlayRef.current || isSelectionPlayRef.current,\n holdHighlight: playbackEndTimeRef.current !== null && time >= playbackEndTimeRef.current,\n setActiveAnnotationId,\n });\n if (activeAnnotationEnded) {\n // Continuous play off: stop at the end of the active annotation and\n // return the cursor to where playback started.\n if (engineRef.current) {\n engineRef.current.stop();\n }\n setIsPlaying(false);\n setCurrentTimeRefs(playStartPositionRef.current);\n setCurrentTime(playStartPositionRef.current);\n return;\n }\n\n // Automatic scroll: the shared visual time, so it lines up with the playhead.\n if (isAutomaticScrollRef.current && scrollContainerRef.current && durationRef.current > 0) {\n centrePlayhead(scrollContainerRef.current, visualTime, sr, spp);\n }\n\n // Check if we've reached the playback end time (for selection playback)\n if (playbackEndTimeRef.current !== null && time >= playbackEndTimeRef.current) {\n // Stop playback at selection end (selection playback is separate from looping)\n if (engineRef.current) {\n engineRef.current.stop();\n }\n setIsPlaying(false);\n // The selection finishing returns the cursor to the selection's start,\n // the same as when the engine ends the play itself (see the stop\n // mirror): which of the two notices the end first is a race on the\n // Tone path, and they must not disagree. Other bounded plays leave the\n // cursor at their end.\n const endCursor = isSelectionPlayRef.current\n ? playStartPositionRef.current\n : playbackEndTimeRef.current;\n setCurrentTimeRefs(endCursor);\n setCurrentTime(endCursor);\n playbackEndTimeRef.current = null; // Clear the end time\n return;\n }\n\n // Loop is handled natively by Tone.js Transport (Transport.loop/loopStart/loopEnd).\n // Transport.seconds auto-wraps at loop boundaries, so getPlaybackTime() returns\n // the correct position without manual detection here.\n\n // Auto-stop at the end of the timeline (player-style default), unless:\n // - indefinitePlayback: the transport rolls until an explicit\n // stop/pause (DAW-style, matching dawcore's indefinite-playback), or\n // - a recording session is active: overdub playback must run past the\n // end of existing material (#589/#590).\n // Explicit ends (selection playback, annotation boundaries) are\n // handled above regardless.\n if (\n time >= durationRef.current &&\n !indefinitePlaybackRef.current &&\n !recordingActiveRef.current\n ) {\n // Stop playback - inline to avoid circular dependency\n if (engineRef.current) {\n engineRef.current.stop();\n }\n setIsPlaying(false);\n setCurrentTimeRefs(playStartPositionRef.current);\n setCurrentTime(playStartPositionRef.current);\n setActiveAnnotationId(null);\n return;\n }\n startAnimationFrameLoop(updateTime);\n };\n startAnimationFrameLoop(updateTime);\n }, [\n setActiveAnnotationId,\n startAnimationFrameLoop,\n getPlaybackTime,\n setCurrentTimeRefs,\n annotationLookup,\n // Refs and a stable function from the shared provider hooks: they never\n // change, and are listed because the linter cannot see that.\n annotationsRef,\n activeAnnotationIdRef,\n continuousPlayRef,\n isAutomaticScrollRef,\n scrollContainerRef,\n runFrameCallbacks,\n engineRef,\n recordingActiveRef,\n ]);\n\n const stopAnimationLoop = stopAnimationFrameLoop;\n\n // Two jobs, during playback only:\n // - restart the animation loop when playback starts and if its closure\n // changes, so the running loop always has current values (its\n // dependencies are stable today; the timeline end is read from\n // `durationRef`, so a duration change does not restart it);\n // - when continuous play is switched ON, reschedule the audio without an end,\n // so it runs past the annotation it was bounded to.\n // The reschedule is tied to that false -> true transition, not to the current\n // value: this effect also runs when playback starts and when the loop is\n // rebuilt, and with continuous play already on those used to stop and restart\n // the audio as well (every Play started twice; a duration change restarted it).\n //\n // While the selection is what is playing, continuous play has no effect at\n // all: the loop does not cut playback at annotation boundaries (see the loop)\n // and switching the toggle reschedules nothing.\n const prevContinuousPlayRef = useRef(continuousPlay);\n useEffect(() => {\n const continuousPlayTurnedOn =\n continuousPlay && !prevContinuousPlayRef.current && !isSelectionPlayRef.current;\n prevContinuousPlayRef.current = continuousPlay;\n\n const reschedulePlayback = async () => {\n if (isPlaying && animationFrameRef.current && engineRef.current) {\n if (continuousPlayTurnedOn) {\n const currentPos = currentTimeRef.current;\n\n // Stop current playout (which may have duration limit + pause callback).\n // Suppressed: this immediately restarts playback below — see\n // suppressEngineStopMirrorRef declaration.\n suppressEngineStopMirrorRef.current = true;\n engineRef.current.stop();\n suppressEngineStopMirrorRef.current = false;\n stopAnimationLoop();\n\n const timeNow = getAudioContextTime();\n playbackStartTimeRef.current = timeNow;\n audioStartPositionRef.current = currentPos;\n\n // What continuous play removes is the end of the annotation being\n // played. Only an end that IS the active annotation's end is dropped\n // (the loop's own end check with it, or it would stop playback there\n // anyway). Any other bounded play, such as a programmatic\n // play(start, duration), keeps its end.\n const boundedEnd = playbackEndTimeRef.current;\n const activeId = activeAnnotationIdRef.current;\n const activeAnnotation = activeId\n ? annotationLookup.byId(annotationsRef.current, activeId)\n : undefined;\n const endsWithAnnotation =\n boundedEnd !== null &&\n activeAnnotation !== undefined &&\n Math.abs(boundedEnd - activeAnnotation.end) < 1e-6;\n const endTime = endsWithAnnotation ? null : boundedEnd;\n playbackEndTimeRef.current = endTime;\n engineRef.current.play(currentPos, endTime ?? undefined);\n startAnimationLoop();\n } else {\n // Nothing about the audio changed: only refresh the loop.\n stopAnimationLoop();\n startAnimationLoop();\n }\n }\n };\n\n reschedulePlayback().catch((err) => {\n console.warn('[waveform-playlist] Failed to reschedule playback:', err);\n setIsPlaying(false);\n stopAnimationLoop();\n });\n }, [\n continuousPlay,\n isPlaying,\n startAnimationLoop,\n stopAnimationLoop,\n animationFrameRef,\n getAudioContextTime,\n annotationLookup,\n annotationsRef,\n activeAnnotationIdRef,\n engineRef,\n ]);\n\n // Start a play that waited for an engine: playback a rebuild interrupted, or a\n // play() asked for while one was being built (#675). Runs when a freshly\n // built engine is assigned (and when play() asks for another run).\n useEffect(() => {\n const resumePlayback = async () => {\n // engineRef is null while a rebuild is in flight — the pending play\n // stays queued until the run triggered by engineEpoch.\n const engine = engineRef.current;\n const request = pendingResumeRef.current;\n if (request && engine) {\n if (!audioInitializedRef.current) {\n // The request STAYS in the slot across this await, so whatever\n // happens meanwhile is unambiguous: stop()/pause()/a newer play()\n // replace or clear it, and if the engine is replaced, the new\n // engine's own run of this effect finds it still waiting.\n await engine.init();\n if (engineRef.current !== engine || pendingResumeRef.current !== request) {\n return;\n }\n audioInitializedRef.current = true;\n }\n\n // Read the request only now: setSelection may have re-pointed it (in\n // place, keeping its identity) while init() was pending.\n const { position, endTime } = request;\n playbackStartTimeRef.current = getAudioContextTime();\n audioStartPositionRef.current = position;\n\n pendingResumeRef.current = null;\n engine.play(position, endTime);\n setIsPlaying(true);\n startAnimationLoop();\n }\n };\n\n resumePlayback().catch((err) => {\n console.warn('[waveform-playlist] Failed to resume playback on the new engine:', err);\n setIsPlaying(false);\n stopAnimationLoop();\n });\n }, [\n engineEpoch,\n startAnimationLoop,\n stopAnimationLoop,\n getAudioContextTime,\n engineRef,\n pendingResumeRef,\n audioInitializedRef,\n ]);\n\n // Playback controls\n const play = useCallback(\n async (startTime?: number, playDuration?: number) => {\n // Before the first ready of this mount nothing plays and nothing is\n // queued (#812): no ref, no request id, no pending resume is touched.\n if (refusePlayBeforeFirstReady()) return;\n const actualStartTime = startTime ?? currentTimeRef.current;\n const endTime = playDuration !== undefined ? actualStartTime + playDuration : undefined;\n\n // Is this the highlighted selection being played?\n const selectionStartNow = selectionStartRef.current ?? 0;\n const selectionEndNow = selectionEndRef.current ?? 0;\n // It may start inside the selection (resuming after a pause) but always\n // runs to the selection's end.\n isSelectionPlayRef.current =\n endTime !== undefined &&\n selectionEndNow > selectionStartNow &&\n actualStartTime >= selectionStartNow - 1e-6 &&\n actualStartTime < selectionEndNow &&\n Math.abs(endTime - selectionEndNow) < 1e-6;\n // Where a Stop (or the play finishing) returns the cursor. For the\n // selection that is its start even when this play resumed part-way in:\n // otherwise the cursor would land back inside the selection and every\n // later Play would repeat only the tail.\n const playStartPosition = isSelectionPlayRef.current ? selectionStartNow : actualStartTime;\n const requestId = ++playRequestIdRef.current;\n\n const engine = engineRef.current;\n if (!engine) {\n // The engine is being built. Queue the play: the\n // resume effect starts it when the new engine is assigned. isPlaying\n // stays false until audio actually starts (#675).\n if (engineBuildInFlightRef.current) {\n playStartPositionRef.current = playStartPosition;\n setCurrentTimeRefs(actualStartTime);\n playbackEndTimeRef.current = endTime ?? null;\n pendingResumeRef.current = { position: actualStartTime, endTime };\n }\n return;\n }\n // A direct play supersedes anything queued for a rebuild.\n pendingResumeRef.current = null;\n\n playStartPositionRef.current = playStartPosition;\n\n // Update currentTimeRef to match the actual start position\n // This ensures the animation loop starts from the correct position\n setCurrentTimeRefs(actualStartTime);\n\n // Stop existing playback and animation loop before restarting.\n // engine.stop() resets engine._currentTime to _playStartPosition (could be 0)\n // and sets _isPlaying=false. AnimatedPlayhead's RAF may fire during this\n // window and call engine.getCurrentTime() which would return 0.\n // The seek() immediately sets _currentTime to the intended start position,\n // preventing the cursor flash.\n // Suppressed: seek()+play() below immediately re-establish the correct\n // position — see suppressEngineStopMirrorRef declaration.\n suppressEngineStopMirrorRef.current = true;\n engine.stop();\n suppressEngineStopMirrorRef.current = false;\n engine.seek(actualStartTime);\n stopAnimationLoop();\n\n // Record timing for accurate position tracking using the adapter's AudioContext\n const startTimeNow = getAudioContextTime();\n playbackStartTimeRef.current = startTimeNow;\n audioStartPositionRef.current = actualStartTime;\n\n // Set playback end time if playing with duration (e.g., selection playback)\n playbackEndTimeRef.current = endTime ?? null;\n\n // Don't set up playback complete callback for annotations\n // The animation loop handles stopping at annotation boundaries\n // This avoids callback timing issues when switching between annotations\n\n // Ensure AudioContext is resumed (requires user gesture, no-op after first call).\n // Guarded by ref so subsequent plays skip the await entirely.\n if (!audioInitializedRef.current) {\n await engine.init();\n if (playRequestIdRef.current !== requestId) {\n // stop(), pause() or a newer play() happened while init() was\n // pending. This request is obsolete — starting it now would play\n // after the user's Stop, or over their newer request.\n return;\n }\n if (engineRef.current !== engine) {\n // A rebuild disposed this engine while init() was pending. Hand the\n // play to its replacement instead of starting a dead engine — if\n // there is one: after a failed build nothing is coming, and a\n // stranded request would fire on some later, unrelated rebuild.\n if (engineRef.current) {\n pendingResumeRef.current = { position: actualStartTime, endTime };\n // Already assigned, so its epoch run has passed — ask for another.\n bumpEngineEpoch();\n } else if (engineBuildInFlightRef.current) {\n pendingResumeRef.current = { position: actualStartTime, endTime };\n }\n return;\n }\n audioInitializedRef.current = true;\n }\n\n try {\n engine.play(actualStartTime, endTime);\n } catch (err) {\n console.warn('[waveform-playlist] Playback failed to start:', err);\n // The play never started, so the UI must not keep saying it is\n // playing. The engine.stop() above is suppressed (the mirror would\n // otherwise clear the flag before the seek that follows it), so\n // nothing else turns isPlaying off on this path: a restart that\n // throws — a seek or an annotation click while playing — would\n // leave the transport showing playback that is not running (#827).\n setIsPlaying(false);\n stopAnimationLoop();\n return;\n }\n setIsPlaying(true);\n startAnimationLoop();\n },\n [\n startAnimationLoop,\n stopAnimationLoop,\n setCurrentTimeRefs,\n getAudioContextTime,\n selectionStartRef,\n selectionEndRef,\n engineRef,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n bumpEngineEpoch,\n refusePlayBeforeFirstReady,\n ]\n );\n\n const pause = useCallback(() => {\n // Cancels a play queued behind an engine rebuild or parked in init().\n pendingResumeRef.current = null;\n playRequestIdRef.current += 1;\n\n // With no engine (a rebuild is in flight) there is nothing to pause, but\n // the UI state must still change: playback that was running when the\n // rebuild began leaves isPlaying true until its resume, which was just\n // cancelled. Hold the cursor where it is.\n const engine = engineRef.current;\n // Get current position from engine (auto-wraps at loop boundaries)\n const pauseTime = engine ? getPlaybackTime() : currentTimeRef.current;\n\n engine?.pause();\n setIsPlaying(false);\n stopAnimationLoop();\n\n // Update to the calculated pause position\n setCurrentTimeRefs(pauseTime);\n setCurrentTime(pauseTime);\n }, [stopAnimationLoop, getPlaybackTime, setCurrentTimeRefs, engineRef, pendingResumeRef]);\n\n const stop = useCallback(() => {\n // Cancels a play queued behind an engine rebuild or parked in init().\n pendingResumeRef.current = null;\n playRequestIdRef.current += 1;\n\n // No engine while a rebuild is in flight — the UI state still resets\n // (see pause()).\n engineRef.current?.stop();\n // The engine rewinds to where ITS play began; for a selection resumed\n // part-way that is not the selection start. Keep the two in step.\n if (isSelectionPlayRef.current) engineRef.current?.seek(playStartPositionRef.current);\n setIsPlaying(false);\n stopAnimationLoop();\n\n // Return cursor to where playback started (Audacity-style)\n setCurrentTimeRefs(playStartPositionRef.current);\n setCurrentTime(playStartPositionRef.current);\n setActiveAnnotationId(null);\n }, [stopAnimationLoop, setActiveAnnotationId, setCurrentTimeRefs, engineRef, pendingResumeRef]);\n\n // Seek to a specific time - works whether playing or stopped\n const seekTo = useCallback(\n (time: number) => {\n // Clamp to the audio. Where the transport may run past its end (an\n // `indefinitePlayback` provider, a recording session) a finite time\n // past the end is a valid position: Skip Backward from 30 s over 10 s\n // of material must land at 25 s, not at 10 s. An infinite one\n // (Fast Forward) still means the end of the audio.\n const pastEndAllowed =\n Number.isFinite(time) && (indefinitePlaybackRef.current || recordingActiveRef.current);\n const upperLimit = pastEndAllowed ? Infinity : durationRef.current;\n const clampedTime = Math.max(0, Math.min(time, upperLimit));\n\n // Update the current time state\n setCurrentTimeRefs(clampedTime);\n setCurrentTime(clampedTime);\n\n // If currently playing, restart at the new position. play() handles\n // stop+seek+restart internally, and with the engine mid-rebuild it\n // re-points the play that is waiting for the new engine (#688: the\n // transport buttons are `seekTo` only, and used to do this themselves).\n if (isPlayingRef.current) {\n play(clampedTime);\n }\n },\n [play, setCurrentTimeRefs, recordingActiveRef]\n );\n\n // @dnd-kit/react's Feedback and OptimisticSortingPlugin sortable plugins\n // perform raw, React-bypassing DOM node moves (insertAdjacentElement /\n // replaceWith) as part of their live drag-preview and collision-commit\n // mechanics — confirmed via MutationObserver instrumentation to physically\n // relocate the React-owned track-controls row during a track-reorder drag,\n // leaving its parent/nextSibling different from what React's fiber tree\n // still believes. That desync is permanent for the session: every LATER\n // React-driven reorder (button OR drag) computes correct data but silently\n // fails to patch the DOM for these rows. `useTrackReorderHandle` already\n // sets `feedback: 'move'` to avoid the placeholder-splice half of this (see\n // its comment), but OptimisticSortingPlugin's own `reorder()` DOM splice\n // fires independently on any drag that commits a real index change and\n // isn't configurable away without losing live index tracking. Bumping this\n // epoch forces the view's track-controls part to re-key (remount) its\n // slots after every track-reorder drag ends — committed or canceled, since\n // corruption can occur before a final index is even decided — discarding\n // any corrupted fiber state so the NEXT reorder (drag or button) starts\n // from a clean DOM. Called from ClipInteractionProvider's onDragEnd.\n const bumpTrackReorderEpoch = useCallback(() => {\n setTrackReorderEpoch((epoch) => epoch + 1);\n }, []);\n\n // Selection — wraps hook setter with playback side-effects (provider concern).\n const setSelection = useCallback(\n (start: number, end: number) => {\n setSelectionEngine(start, end);\n setCurrentTimeRefs(start);\n setCurrentTime(start);\n\n // What playback does from here, if it is running or queued. A new\n // highlighted range is played start to end, as the Play button would\n // (looping on: open-ended, the transport's loop handles the bounds). A\n // plain cursor move carries on open-ended from the new position.\n const playsRange = end > start && !(isLoopEnabledRef.current ?? false);\n const endTime = playsRange ? end : undefined;\n\n // Whatever bounded play was running or queued (a selection, an\n // annotation) is over, so nothing of it may outlive it. Its end stopped\n // playback at once when the new position was past it; its active\n // annotation did the same through the loop's stop-at-annotation-end;\n // and its play-start position is where a later Stop would have\n // returned the cursor.\n const replaceBoundedPlay = () => {\n playbackEndTimeRef.current = endTime ?? null;\n isSelectionPlayRef.current = playsRange;\n playStartPositionRef.current = start;\n if (activeAnnotationIdRef.current !== null) setActiveAnnotationId(null);\n };\n\n // A play queued behind an engine rebuild follows the selection too. The\n // request is changed IN PLACE: a resume parked in init() recognises its\n // request by identity, and a new object would strand it (#675, rule 4).\n const queued = pendingResumeRef.current;\n if (queued) {\n // The queued play will start it; restarting the engine here as well\n // would start it twice.\n queued.position = start;\n queued.endTime = endTime;\n replaceBoundedPlay();\n return;\n }\n\n if (!isPlayingRef.current) {\n // Nothing is playing: whatever play ended earlier no longer says\n // anything about this position. Without this, Stop (Escape) pressed\n // while stopped sent the cursor back to an old play's start.\n isSelectionPlayRef.current = false;\n playStartPositionRef.current = start;\n return;\n }\n\n if (engineRef.current) {\n // Stop + seek before restarting playback from selection start.\n // engine.stop() resets _currentTime and _isPlaying, creating a window\n // where getCurrentTime() returns wrong value. seek() immediately\n // corrects _currentTime so any RAF firing in between reads the\n // intended position. engine.play() then restarts everything.\n // Suppressed: seek()+play() below immediately re-establish the correct\n // position — see suppressEngineStopMirrorRef declaration. Unguarded,\n // the mirror would also flip isPlaying to false with nothing here to\n // set it back true (isPlaying was already true on entry to this branch).\n suppressEngineStopMirrorRef.current = true;\n engineRef.current.stop();\n suppressEngineStopMirrorRef.current = false;\n engineRef.current.seek(start);\n replaceBoundedPlay();\n // This is a new play: say when and where it started, as `play()` does.\n // `useEngineRefs()` hands these two to consumers (a custom readout or\n // playhead), and until 2026-11 they kept describing the play this one\n // replaced.\n playbackStartTimeRef.current = getAudioContextTime();\n audioStartPositionRef.current = start;\n engineRef.current.play(start, endTime);\n }\n },\n [\n setSelectionEngine,\n setCurrentTimeRefs,\n setActiveAnnotationId,\n isLoopEnabledRef,\n activeAnnotationIdRef,\n getAudioContextTime,\n engineRef,\n pendingResumeRef,\n ]\n );\n\n // Context values, grouped by how often their fields change (#768). A\n // subscription is to a whole value, so a field belongs with the fields that\n // change when it does: a component that reads `sampleRate` must not render\n // on every step of a volume slider.\n\n // Changes on play, pause and stop only. Not on a seek: the resting cursor\n // position has its own context (#740).\n const isPlayingValue: IsPlayingContextValue = useMemo(() => ({ isPlaying }), [isPlaying]);\n\n // Refs and stable functions: these two values never change. The first is\n // the part the MediaElement provider has too (#688).\n const refsValue: PlaybackRefsContextValue = useMemo(\n () => ({\n currentTimeRef,\n visualTimeRef,\n registerFrameCallback,\n unregisterFrameCallback,\n }),\n [currentTimeRef, visualTimeRef, registerFrameCallback, unregisterFrameCallback]\n );\n\n const engineRefsValue: EngineRefsContextValue = useMemo(\n () => ({\n playbackStartTimeRef,\n audioStartPositionRef,\n getPlaybackTime,\n getAudioContextTime,\n getLookAhead,\n getOutputLatency,\n playoutRef: engineRef,\n }),\n [\n playbackStartTimeRef,\n audioStartPositionRef,\n getPlaybackTime,\n getAudioContextTime,\n getLookAhead,\n getOutputLatency,\n engineRef,\n ]\n );\n\n const loopValue: LoopContextValue = useMemo(\n () => ({ isLoopEnabled, loopStart, loopEnd }),\n [isLoopEnabled, loopStart, loopEnd]\n );\n\n const selectedTrackIdValue: SelectedTrackIdContextValue = useMemo(\n () => ({ selectedTrackId }),\n [selectedTrackId]\n );\n\n const { canUndo, canRedo } = view;\n const undoRedoValue: UndoRedoContextValue = useMemo(\n () => ({ canUndo, canRedo }),\n [canUndo, canRedo]\n );\n\n // Its own context: these two change on every pointer move of a selection\n // drag, and nothing else in the state value does (#733).\n const selectionValue: SelectionContextValue = useMemo(\n () => ({ selectionStart, selectionEnd }),\n [selectionStart, selectionEnd]\n );\n\n // Their own contexts too (#740): the resting cursor position changes on\n // every seek and on every pointer move of a leftward selection drag; the\n // active annotation changes at every annotation boundary during playback.\n const currentTimeValue: CurrentTimeContextValue = useMemo(() => ({ currentTime }), [currentTime]);\n const activeAnnotationValue: ActiveAnnotationContextValue = useMemo(\n () => ({ activeAnnotationId }),\n [activeAnnotationId]\n );\n\n const setCurrentTimeControl = useCallback(\n (time: number) => {\n setCurrentTimeRefs(time);\n setCurrentTime(time);\n },\n [setCurrentTimeRefs]\n );\n\n // What a click on an annotation does (#686). A play of the annotation's\n // length, so the audio ends on the sample; with continuous play on, an\n // open-ended one. Continuous play is read when the click happens, so the\n // function never changes.\n const playAnnotation = useCallback(\n (annotation: AnnotationData) => {\n // Before the first ready the click does nothing, highlight included.\n if (refusePlayBeforeFirstReady()) return;\n setActiveAnnotationId(annotation.id);\n const playDuration = continuousPlayRef.current\n ? undefined\n : annotation.end - annotation.start;\n play(annotation.start, playDuration).catch((err) => {\n console.warn(\n '[waveform-playlist] Failed to start playback for annotation ' +\n annotation.id +\n ': ' +\n String(err)\n );\n });\n },\n [play, setActiveAnnotationId, continuousPlayRef, refusePlayBeforeFirstReady]\n );\n\n // The actions both providers have (#688). Never changes.\n const controlsValue: PlaybackControlsContextValue = useMemo(\n () => ({\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n setAnnotations,\n annotationPreview,\n setActiveAnnotationId,\n playAnnotation,\n }),\n [\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n setAnnotations,\n annotationPreview,\n setActiveAnnotationId,\n playAnnotation,\n ]\n );\n\n // The actions only the multitrack editor has. Never changes.\n const editorControlsValue: EditorControlsContextValue = useMemo(\n () => ({\n setCurrentTime: setCurrentTimeControl,\n\n // Track controls (the arrangement's mix and order)\n setTrackMute: editing.setTrackMute,\n setTrackSolo: editing.setTrackSolo,\n setTrackVolume: editing.setTrackVolume,\n setTrackPan: editing.setTrackPan,\n reorderTrack: editing.reorderTrack,\n bumpTrackReorderEpoch,\n setTrackDragPreview,\n setSelectedTrackId: setSelectedTrackIdControl,\n\n // Zoom\n zoomIn: zoom.zoomIn,\n zoomOut: zoom.zoomOut,\n\n // Master volume\n setMasterVolume,\n\n // Loop controls\n setLoopEnabled,\n setLoopRegion,\n setLoopRegionFromSelection,\n clearLoopRegion,\n\n // Undo/redo (the arrangement's history)\n undo: editing.undo,\n redo: editing.redo,\n\n // Recording\n setRecordingActive: editing.setRecordingActive,\n }),\n [\n setCurrentTimeControl,\n editing.setTrackMute,\n editing.setTrackSolo,\n editing.setTrackVolume,\n editing.setTrackPan,\n editing.reorderTrack,\n bumpTrackReorderEpoch,\n setTrackDragPreview,\n setSelectedTrackIdControl,\n zoom.zoomIn,\n zoom.zoomOut,\n setMasterVolume,\n setLoopEnabled,\n setLoopRegion,\n setLoopRegionFromSelection,\n clearLoopRegion,\n editing.undo,\n editing.redo,\n editing.setRecordingActive,\n ]\n );\n\n const viewValue: PlaylistViewContextValue = useMemo(\n () => ({\n sampleRate,\n mono,\n indefinitePlayback,\n }),\n [sampleRate, mono, indefinitePlayback]\n );\n\n const settingsValue: PlaylistSettingsContextValue = useMemo(\n () => ({ timeFormat, isAutomaticScroll }),\n [timeFormat, isAutomaticScroll]\n );\n\n const zoomValue: PlaylistZoomContextValue = useMemo(\n () => ({ samplesPerPixel, canZoomIn: zoom.canZoomIn, canZoomOut: zoom.canZoomOut }),\n [samplesPerPixel, zoom.canZoomIn, zoom.canZoomOut]\n );\n\n // Changes on every clip operation (a trim once, on release: its moves are\n // the trim preview, #812), on a zoom (the peaks are computed per zoom\n // level) and when audio arrives for a clip.\n const { peaksDataArray, trackStates } = view;\n const timelineValue: PlaylistTimelineContextValue = useMemo(\n () => ({ tracks, peaksDataArray, duration, isReady }),\n [tracks, peaksDataArray, duration, isReady]\n );\n\n // Changes on every mute, solo, volume or pan change.\n const mixerValue: PlaylistMixerContextValue = useMemo(\n () => ({ trackStates, masterVolume }),\n [trackStates, masterVolume]\n );\n\n // Changes on every drag-over of a track reorder.\n const reorderPreviewValue: TrackReorderPreviewContextValue = useMemo(\n () => ({ trackDragPreview, trackReorderEpoch }),\n [trackDragPreview, trackReorderEpoch]\n );\n\n // Outermost: the values that change least. The order has no effect on\n // behaviour (every value is committed together); it is for reading.\n // The two MediaElement-only contexts are blocked: inside this provider\n // `usePlaybackRate()` must not reach a MediaElement provider further out.\n return (\n <ThemeProvider theme={mergedTheme}>\n <PlaybackRateContext value={BLOCKED}>\n <MediaElementTrackContext value={BLOCKED}>\n <ArrangementContext value={arrangement}>\n <PlaybackRefsContext value={refsValue}>\n <EngineRefsContext value={engineRefsValue}>\n <TrimPreviewContext value={trimPreview}>\n <TrimPreviewPeaksContext value={trimPreviewPeaks}>\n <PlaybackControlsContext value={controlsValue}>\n <EditorControlsContext value={editorControlsValue}>\n <PlaylistViewContext value={viewValue}>\n <PlaylistSettingsContext value={settingsValue}>\n <PlaylistZoomContext value={zoomValue}>\n <UndoRedoContext value={undoRedoValue}>\n <SelectedTrackIdContext value={selectedTrackIdValue}>\n <SelectedRowContext value={selectedTrackIdValue}>\n <LoopContext value={loopValue}>\n <AnnotationOptionsContext value={annotationOptionsValue}>\n <AnnotationsContext value={annotationsValue}>\n <IsPlayingContext value={isPlayingValue}>\n <ActiveAnnotationContext value={activeAnnotationValue}>\n <CurrentTimeContext value={currentTimeValue}>\n <SelectionContext value={selectionValue}>\n <TrackReorderPreviewContext\n value={reorderPreviewValue}\n >\n <PlaylistMixerContext value={mixerValue}>\n <PlaylistTimelineContext\n value={timelineValue}\n >\n <RecordingArmContext\n value={editing.recordingArm}\n >\n {children}\n </RecordingArmContext>\n </PlaylistTimelineContext>\n </PlaylistMixerContext>\n </TrackReorderPreviewContext>\n </SelectionContext>\n </CurrentTimeContext>\n </ActiveAnnotationContext>\n </IsPlayingContext>\n </AnnotationsContext>\n </AnnotationOptionsContext>\n </LoopContext>\n </SelectedRowContext>\n </SelectedTrackIdContext>\n </UndoRedoContext>\n </PlaylistZoomContext>\n </PlaylistSettingsContext>\n </PlaylistViewContext>\n </EditorControlsContext>\n </PlaybackControlsContext>\n </TrimPreviewPeaksContext>\n </TrimPreviewContext>\n </EngineRefsContext>\n </PlaybackRefsContext>\n </ArrangementContext>\n </MediaElementTrackContext>\n </PlaybackRateContext>\n </ThemeProvider>\n );\n};\n","import type { PlayoutAdapter } from '@waveform-playlist/engine';\nimport type { SoundFontCache } from '@waveform-playlist/playout';\n\n/** Adapters that accept a SoundFontCache (e.g. the Tone.js adapter). */\ninterface SoundFontCapableAdapter {\n setSoundFontCache(cache: SoundFontCache | undefined): void;\n}\n\n/**\n * Structural check for soundfont support — avoids a runtime import of\n * `@waveform-playlist/playout`. `isToneAdapter` from playout does the same\n * structural check (via optional chaining); our local `supportsSoundFont`\n * adds an explicit `adapter != null` guard. Keeping it structural lets the\n * core barrel stay engine-free (#510) and works for any custom adapter that\n * exposes `setSoundFontCache`.\n */\nfunction supportsSoundFont(\n adapter: PlayoutAdapter | null\n): adapter is PlayoutAdapter & SoundFontCapableAdapter {\n return (\n adapter != null &&\n typeof (adapter as Partial<SoundFontCapableAdapter>).setSoundFontCache === 'function'\n );\n}\n\n/**\n * Forward a (possibly late-loaded or swapped) SoundFontCache to the live\n * adapter. Safe no-op when the adapter is absent or doesn't support\n * soundfonts. The adapter itself skips MIDI tracks whose routing is\n * unchanged, so redundant calls (e.g. on mount) cause no rebuild churn.\n */\nexport function syncSoundFontCacheToAdapter(\n adapter: PlayoutAdapter | null,\n cache: SoundFontCache | undefined\n): void {\n if (!supportsSoundFont(adapter)) return;\n adapter.setSoundFontCache(cache);\n}\n","import { useCallback, useState } from 'react';\nimport {\n formatTime as formatTimeUtil,\n parseTime as parseTimeUtil,\n type TimeFormat,\n} from '@waveform-playlist/ui-components';\n\nexport interface TimeFormatControls {\n timeFormat: TimeFormat;\n setTimeFormat: (format: TimeFormat) => void;\n formatTime: (seconds: number) => string;\n parseTime: (timeString: string) => number;\n}\n\n/**\n * Hook to manage time format state\n *\n * @example\n * ```tsx\n * const { timeFormat, setTimeFormat, formatTime, parseTime } = useTimeFormat();\n *\n * <TimeFormatSelect\n * value={timeFormat}\n * onChange={setTimeFormat}\n * />\n * <span>{formatTime(currentTime)}</span>\n * <input onChange={(e) => seekTo(parseTime(e.target.value))} />\n * ```\n */\nexport function useTimeFormat(): TimeFormatControls {\n const [timeFormat, setTimeFormat] = useState<TimeFormat>('hh:mm:ss.uuu');\n\n const formatTime = useCallback(\n (seconds: number) => formatTimeUtil(seconds, timeFormat),\n [timeFormat]\n );\n\n const parseTime = useCallback(\n (timeString: string) => parseTimeUtil(timeString, timeFormat),\n [timeFormat]\n );\n\n return {\n timeFormat,\n setTimeFormat,\n formatTime,\n parseTime,\n };\n}\n","import { useState, useCallback, useRef, startTransition, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface ZoomControls {\n samplesPerPixel: number;\n zoomIn: () => void;\n zoomOut: () => void;\n canZoomIn: boolean;\n canZoomOut: boolean;\n}\n\nexport interface UseZoomControlsProps {\n engineRef: RefObject<PlaylistEngine | null>;\n initialSamplesPerPixel: number;\n}\n\n/**\n * Hook for managing zoom controls via PlaylistEngine delegation.\n *\n * zoomIn/zoomOut delegate to the engine. State is mirrored back from\n * the engine via onEngineState(), which the provider's statechange\n * handler calls on every engine event.\n *\n * samplesPerPixel updates use startTransition so React treats them as\n * non-urgent — during playback, animation RAF callbacks interleave\n * with the zoom re-render instead of being blocked.\n */\nexport function useZoomControls({\n engineRef,\n initialSamplesPerPixel,\n}: UseZoomControlsProps): ZoomControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [samplesPerPixel, setSamplesPerPixel] = useState(initialSamplesPerPixel);\n const [canZoomIn, setCanZoomIn] = useState(true);\n const [canZoomOut, setCanZoomOut] = useState(true);\n\n // Internal refs for statechange guards — prevent redundant setState\n // calls during high-frequency engine events (clip drags, play/pause).\n const canZoomInRef = useRef(true);\n const canZoomOutRef = useRef(true);\n const samplesPerPixelRef = useRef(initialSamplesPerPixel);\n\n const zoomIn = useCallback(() => {\n engineRef.current?.zoomIn();\n }, [engineRef]);\n\n const zoomOut = useCallback(() => {\n engineRef.current?.zoomOut();\n }, [engineRef]);\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.samplesPerPixel !== samplesPerPixelRef.current) {\n samplesPerPixelRef.current = state.samplesPerPixel;\n startTransition(() => {\n setSamplesPerPixel(state.samplesPerPixel);\n });\n }\n if (state.canZoomIn !== canZoomInRef.current) {\n canZoomInRef.current = state.canZoomIn;\n setCanZoomIn(state.canZoomIn);\n }\n if (state.canZoomOut !== canZoomOutRef.current) {\n canZoomOutRef.current = state.canZoomOut;\n setCanZoomOut(state.canZoomOut);\n }\n }, []);\n\n return {\n samplesPerPixel,\n zoomIn,\n zoomOut,\n canZoomIn,\n canZoomOut,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseMasterVolumeProps {\n engineRef: RefObject<PlaylistEngine | null>;\n initialVolume?: number; // 0-1.0 (linear gain, consistent with Web Audio API)\n}\n\nexport interface MasterVolumeControls {\n masterVolume: number;\n setMasterVolume: (volume: number) => void;\n /** Ref holding the current masterVolume for seeding a fresh engine. */\n masterVolumeRef: React.RefObject<number>;\n}\n\n/**\n * Hook for managing master volume via PlaylistEngine delegation.\n *\n * setMasterVolume delegates to the engine. State is mirrored back from\n * the engine via onEngineState(), which the provider's statechange\n * handler calls on every engine event.\n */\nexport function useMasterVolume({\n engineRef,\n initialVolume = 1.0,\n}: UseMasterVolumeProps): MasterVolumeControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [masterVolume, setMasterVolumeState] = useState(initialVolume);\n\n // Internal ref for statechange guard + engine seeding on rebuild.\n const masterVolumeRef = useRef(initialVolume);\n\n const setMasterVolume = useCallback(\n (volume: number) => {\n if (engineRef.current) {\n // Engine exists — delegate; statechange will update ref + React state.\n engineRef.current.setMasterVolume(volume);\n } else {\n // No engine yet — persist locally so loadAudio() seeds correctly.\n masterVolumeRef.current = volume;\n setMasterVolumeState(volume);\n }\n },\n [engineRef]\n );\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.masterVolume !== masterVolumeRef.current) {\n masterVolumeRef.current = state.masterVolume;\n setMasterVolumeState(state.masterVolume);\n }\n }, []);\n\n return {\n masterVolume,\n setMasterVolume,\n masterVolumeRef,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseSelectionStateProps {\n engineRef: RefObject<PlaylistEngine | null>;\n}\n\nexport interface SelectionControls {\n selectionStart: number;\n selectionEnd: number;\n setSelection: (start: number, end: number) => void;\n selectionStartRef: React.RefObject<number>;\n selectionEndRef: React.RefObject<number>;\n}\n\n/**\n * Hook for managing selection state via PlaylistEngine delegation.\n *\n * setSelection delegates to the engine. State is mirrored back from\n * the engine via onEngineState(), which the provider's statechange\n * handler calls on every engine event.\n *\n * Note: The provider wraps this setter with playback side-effects\n * (updating currentTime, restarting playback). This hook only handles\n * the engine delegation + state mirroring.\n */\nexport function useSelectionState({ engineRef }: UseSelectionStateProps): SelectionControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [selectionStart, setSelectionStartState] = useState(0);\n const [selectionEnd, setSelectionEndState] = useState(0);\n\n // Internal refs for statechange guard + engine seeding on rebuild.\n const selectionStartRef = useRef(0);\n const selectionEndRef = useRef(0);\n\n const setSelection = useCallback(\n (start: number, end: number) => {\n engineRef.current?.setSelection(start, end);\n },\n [engineRef]\n );\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.selectionStart !== selectionStartRef.current) {\n selectionStartRef.current = state.selectionStart;\n setSelectionStartState(state.selectionStart);\n }\n if (state.selectionEnd !== selectionEndRef.current) {\n selectionEndRef.current = state.selectionEnd;\n setSelectionEndState(state.selectionEnd);\n }\n }, []);\n\n return {\n selectionStart,\n selectionEnd,\n setSelection,\n selectionStartRef,\n selectionEndRef,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseLoopStateProps {\n engineRef: RefObject<PlaylistEngine | null>;\n}\n\nexport interface LoopControls {\n isLoopEnabled: boolean;\n loopStart: number;\n loopEnd: number;\n setLoopEnabled: (value: boolean) => void;\n setLoopRegion: (start: number, end: number) => void;\n clearLoopRegion: () => void;\n isLoopEnabledRef: React.RefObject<boolean>;\n loopStartRef: React.RefObject<number>;\n loopEndRef: React.RefObject<number>;\n}\n\n/**\n * Hook for managing loop state via PlaylistEngine delegation.\n *\n * setLoopEnabled, setLoopRegion, and clearLoopRegion delegate to the\n * engine. State is mirrored back from the engine via onEngineState(),\n * which the provider's statechange handler calls on every engine event.\n */\nexport function useLoopState({ engineRef }: UseLoopStateProps): LoopControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [isLoopEnabled, setIsLoopEnabledState] = useState(false);\n const [loopStart, setLoopStartState] = useState(0);\n const [loopEnd, setLoopEndState] = useState(0);\n\n // Internal refs for statechange guard + animation loop reads.\n const isLoopEnabledRef = useRef(false);\n const loopStartRef = useRef(0);\n const loopEndRef = useRef(0);\n\n const setLoopEnabled = useCallback(\n (value: boolean) => {\n engineRef.current?.setLoopEnabled(value);\n },\n [engineRef]\n );\n\n const setLoopRegion = useCallback(\n (start: number, end: number) => {\n engineRef.current?.setLoopRegion(start, end);\n },\n [engineRef]\n );\n\n const clearLoopRegion = useCallback(() => {\n engineRef.current?.setLoopRegion(0, 0);\n }, [engineRef]);\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.isLoopEnabled !== isLoopEnabledRef.current) {\n isLoopEnabledRef.current = state.isLoopEnabled;\n setIsLoopEnabledState(state.isLoopEnabled);\n }\n if (state.loopStart !== loopStartRef.current) {\n loopStartRef.current = state.loopStart;\n setLoopStartState(state.loopStart);\n }\n if (state.loopEnd !== loopEndRef.current) {\n loopEndRef.current = state.loopEnd;\n setLoopEndState(state.loopEnd);\n }\n }, []);\n\n return {\n isLoopEnabled,\n loopStart,\n loopEnd,\n setLoopEnabled,\n setLoopRegion,\n clearLoopRegion,\n isLoopEnabledRef,\n loopStartRef,\n loopEndRef,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseSelectedTrackProps {\n engineRef: RefObject<PlaylistEngine | null>;\n}\n\nexport interface SelectedTrackControls {\n selectedTrackId: string | null;\n setSelectedTrackId: (trackId: string | null) => void;\n}\n\n/**\n * Hook for managing selected track state via PlaylistEngine delegation.\n *\n * setSelectedTrackId delegates to the engine's selectTrack method.\n * State is mirrored back from the engine via onEngineState(), which\n * the provider's statechange handler calls on every engine event.\n */\nexport function useSelectedTrack({ engineRef }: UseSelectedTrackProps): SelectedTrackControls & {\n onEngineState: (state: EngineState) => void;\n selectedTrackIdRef: React.RefObject<string | null>;\n} {\n const [selectedTrackId, setSelectedTrackIdState] = useState<string | null>(null);\n\n // Internal ref for statechange guard.\n const selectedTrackIdRef = useRef<string | null>(null);\n\n const setSelectedTrackId = useCallback(\n (trackId: string | null) => {\n engineRef.current?.selectTrack(trackId);\n },\n [engineRef]\n );\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.selectedTrackId !== selectedTrackIdRef.current) {\n selectedTrackIdRef.current = state.selectedTrackId;\n setSelectedTrackIdState(state.selectedTrackId);\n }\n }, []);\n\n return {\n selectedTrackId,\n setSelectedTrackId,\n onEngineState,\n selectedTrackIdRef,\n };\n}\n","import React from 'react';\nimport type { DragStartEvent, DragMoveEvent, DragEndEvent } from '@dnd-kit/abstract';\nimport type { AudioClip } from '@waveform-playlist/core';\nimport { calculateBoundaryTrim } from '../utils/boundaryTrim';\nimport { sortedClipsOf } from '../utils/sortedClips';\nimport { loadedClipsOf } from '../utils/loadedTracks';\nimport {\n useArrangement,\n usePlaylistView,\n useTrimPreviewOptional,\n} from '../contexts/playlistContexts';\nimport type { TrimPreview } from '../providerInternals/useTrimPreview';\n\ninterface UseClipDragHandlersOptions {\n samplesPerPixel: number;\n /** Optional function that snaps a sample position to the nearest grid position.\n * Used for boundary trim snapping (move snapping is handled by the SnapToGridModifier). */\n snapSamplePosition?: (samplePosition: number) => number;\n}\n\ntype Boundary = 'left' | 'right';\n\n/** What dnd-kit's source data holds for a clip (see `Clip` in ui-components). */\ninterface ClipDragData {\n kind?: string;\n clipId: string;\n boundary?: Boundary;\n trackIndex: number;\n clipIndex: number;\n}\n\ntype Geometry = Pick<AudioClip, 'startSample' | 'durationSamples' | 'offsetSamples'>;\n\n/** A boundary trim in progress: which clip, and its bounds when the drag started. */\ninterface TrimDrag {\n trackId: string;\n clipId: string;\n boundary: Boundary;\n original: Geometry;\n}\n\n/** A clip move in progress: the track it was picked up on, by id. */\ninterface MoveDrag {\n trackId: string;\n clipId: string;\n}\n\n/** A track's clips in timeline order, and where `clip` sits in it. */\nfunction trimOrderFor(clips: readonly AudioClip[], clip: AudioClip) {\n const sortedClips = sortedClipsOf(clips);\n return { clips, sortedClips, sortedIndex: sortedClips.indexOf(clip) };\n}\n\ntype TrimOrder = ReturnType<typeof trimOrderFor>;\n\n/** Whether every clip except the one with id `clipId` is the same object in both arrays. */\nfunction sameNeighbours(a: readonly AudioClip[], b: readonly AudioClip[], clipId: string): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].id !== clipId && a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/** The geometry of a clip whose `boundary` has moved by `delta` samples. */\nfunction trimmedGeometry(original: Geometry, boundary: Boundary, delta: number): Geometry {\n return boundary === 'left'\n ? {\n startSample: original.startSample + delta,\n durationSamples: original.durationSamples - delta,\n offsetSamples: original.offsetSamples + delta,\n }\n : { ...original, durationSamples: original.durationSamples + delta };\n}\n\ninterface ProposedTrim {\n drag: TrimDrag;\n clip: AudioClip;\n pixelDelta: number;\n samplesPerPixel: number;\n sampleRate: number;\n order: TrimOrder;\n snap: ((samplePosition: number) => number) | undefined;\n}\n\n/**\n * The trim delta, in whole samples, for a pointer `pixelDelta` from where the\n * drag started: constrained by the clip's neighbours and source, then with the\n * moved boundary's absolute position snapped to the grid.\n */\nfunction proposedTrimDelta({\n drag,\n clip,\n pixelDelta,\n samplesPerPixel,\n sampleRate,\n order,\n snap,\n}: ProposedTrim): number {\n const { original, boundary } = drag;\n const trimmed = calculateBoundaryTrim({\n originalClip: original,\n clip,\n pixelDelta,\n samplesPerPixel,\n sampleRate,\n boundary,\n sortedClips: order.sortedClips,\n sortedIndex: order.sortedIndex,\n });\n if (boundary === 'left') {\n const start = snap ? snap(trimmed.startSample) : trimmed.startSample;\n return Math.floor(start - original.startSample);\n }\n const end = trimmed.startSample + trimmed.durationSamples;\n const snappedEnd = snap ? snap(end) : end;\n return Math.floor(snappedEnd - original.startSample - original.durationSamples);\n}\n\n/**\n * Custom hook for handling clip drag operations (movement and trimming)\n *\n * Provides drag handlers for use with @dnd-kit/react DragDropProvider.\n * Handles both clip movement (dragging entire clips) and boundary trimming (adjusting clip edges).\n *\n * Collision detection for clip moves is handled by `ClipCollisionModifier` (passed to DragDropProvider).\n *\n * It changes the provider's arrangement (`useArrangement()`), so it works\n * whether an engine is attached or not, and throws outside\n * `WaveformPlaylistProvider`.\n *\n * **Move:** `onDragStart` notes the clip and its track by id; `onDragEnd`\n * makes one `arrangement.moveClip()` of that clip on that track, also when\n * the tracks were reordered or the row's clips changed meanwhile.\n *\n * **Trim (#812):** each `onDragMove` publishes where the clip would be to the\n * provider's trim preview, which only the dragged clip's view follows; the\n * tracks are not changed. Each move is computed from the clip as it was when\n * the drag started, constrained as the release will be\n * (`arrangement.constrainTrimDelta`), so the preview shows what the release\n * commits. `onDragEnd` makes one `arrangement.trimClip()` with the delta of\n * the last preview and clears the preview in the same render; Escape clears\n * the preview only. Each of `moveClip` and `trimClip` is one undo step.\n *\n * The returned handlers read the tracks from the arrangement when they run,\n * so they keep their identity and are safe to pass straight to\n * `DragDropProvider`.\n *\n * @example\n * ```tsx\n * const { tracks } = usePlaylistTimeline();\n * const { onDragStart, onDragMove, onDragEnd } = useClipDragHandlers({ samplesPerPixel });\n *\n * return (\n * <DragDropProvider\n * onDragStart={onDragStart}\n * onDragMove={onDragMove}\n * onDragEnd={onDragEnd}\n * modifiers={[RestrictToHorizontalAxis, ClipCollisionModifier.configure({ tracks, samplesPerPixel })]}\n * >\n * <WaveformEditor />\n * </DragDropProvider>\n * );\n * ```\n */\nexport function useClipDragHandlers({\n samplesPerPixel,\n snapSamplePosition,\n}: UseClipDragHandlersOptions) {\n const arrangement = useArrangement();\n const { sampleRate } = usePlaylistView();\n // The provider's trim preview; none under another provider or outside one,\n // and then a trim is committed on release without being shown.\n const preview = useTrimPreviewOptional();\n // Store snap function in ref so onDragMove doesn't need it as a dependency\n const snapSamplePositionRef = React.useRef(snapSamplePosition);\n snapSamplePositionRef.current = snapSamplePosition;\n // The trimmed clip's neighbours in timeline order. Collision constraints\n // keep the clip between the same two neighbours, so the order found at drag\n // start holds for the drag and is not re-sorted on every pointer move.\n // `clips` is the array it was computed from: if any OTHER clip of the track\n // has been replaced since (an undo during the drag, a recording landing on\n // the track, audio arriving for it), it is recomputed.\n const trimOrderRef = React.useRef<TrimOrder | null>(null);\n // The trim in progress, with the clip's bounds at drag start (each move is\n // computed from them, never from the previous move).\n const trimDragRef = React.useRef<TrimDrag | null>(null);\n // The delta (samples) of the last published preview: what the release sends.\n const lastBoundaryDeltaRef = React.useRef(0);\n // The move in progress: the clip's track by id, so a reorder before the\n // drop does not move a clip of another track.\n const moveDragRef = React.useRef<MoveDrag | null>(null);\n\n // A drag that never ends (its component unmounts mid-drag) must not leave\n // its preview on screen.\n React.useEffect(() => {\n if (!preview) return;\n return () => {\n if (trimDragRef.current) {\n trimDragRef.current = null;\n preview.publish(null);\n }\n };\n }, [preview]);\n\n const onDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const data = event.operation.source?.data as ClipDragData | undefined;\n if (!data || data.kind === 'track-reorder') return;\n trimDragRef.current = null;\n trimOrderRef.current = null;\n moveDragRef.current = null;\n lastBoundaryDeltaRef.current = 0;\n // The row the drag began on is the arrangement's track at that index.\n const track = arrangement.getTracks()[data.trackIndex];\n if (!track) return;\n // A move needs nothing else until the drop.\n if (!data.boundary) {\n moveDragRef.current = { trackId: track.id, clipId: data.clipId };\n return;\n }\n\n // By id: `clipIndex` is a position in the drawn row, which can hold\n // placeholders that are not loaded clips.\n const clips = loadedClipsOf(track);\n const clip = clips.find((c) => c.id === data.clipId);\n if (!clip) return;\n trimDragRef.current = {\n trackId: track.id,\n clipId: clip.id,\n boundary: data.boundary,\n original: {\n startSample: clip.startSample,\n durationSamples: clip.durationSamples,\n offsetSamples: clip.offsetSamples,\n },\n };\n trimOrderRef.current = trimOrderFor(clips, clip);\n },\n [arrangement]\n );\n\n const onDragMove = React.useCallback(\n (event: DragMoveEvent) => {\n const data = event.operation.source?.data as ClipDragData | undefined;\n const drag = trimDragRef.current;\n if (!data?.boundary || !drag || !trimOrderRef.current) return;\n // By the id captured at drag start: the track's row can move mid-drag\n // (a reorder), and `data.trackIndex` is the row it had then. While the\n // track is gone, a move does nothing.\n const track = arrangement.getTracks().find((t) => t.id === drag.trackId);\n const currentClips = track ? loadedClipsOf(track) : undefined;\n const clip = currentClips?.find((c) => c.id === drag.clipId);\n if (!currentClips || !clip) return;\n if (!sameNeighbours(trimOrderRef.current.clips, currentClips, drag.clipId)) {\n trimOrderRef.current = trimOrderFor(currentClips, clip);\n }\n\n // The dragmove event is dispatched BEFORE position.current is updated (happens\n // in a microtask), so the snapshot's position.current is stale. Use event.to\n // (the pointer's current coordinates from the sensor) for the correct position.\n const currentX = event.to?.x ?? event.operation.position.current.x;\n const proposed = proposedTrimDelta({\n drag,\n clip,\n pixelDelta: currentX - event.operation.position.initial.x,\n samplesPerPixel,\n sampleRate,\n order: trimOrderRef.current,\n snap: snapSamplePositionRef.current,\n });\n // What `trimClip` will apply on release: the clip has not been\n // changed during the drag, so it constrains from the same bounds.\n const delta = arrangement.constrainTrimDelta(\n drag.trackId,\n drag.clipId,\n drag.boundary,\n proposed\n );\n\n lastBoundaryDeltaRef.current = delta;\n const next: TrimPreview = {\n trackId: drag.trackId,\n clipId: drag.clipId,\n ...trimmedGeometry(drag.original, drag.boundary, delta),\n };\n preview?.publish(next);\n },\n [samplesPerPixel, sampleRate, arrangement, preview]\n );\n\n /** Ends a trim: one `trimClip` with the last preview's delta, the preview cleared with it. */\n const commitTrim = React.useCallback(\n (drag: TrimDrag, delta: number) => {\n // No frame shows the clip where it was before the drag: dnd-kit calls\n // this inside `startTransition`, but the view reads both the\n // arrangement and the preview with `useSyncExternalStore`, whose\n // updates React applies at once, together, even inside a transition.\n arrangement.trimClip(drag.trackId, drag.clipId, drag.boundary, delta);\n preview?.publish(null);\n },\n [arrangement, preview]\n );\n\n const onDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n const data = event.operation.source?.data as ClipDragData | undefined;\n if (data?.kind === 'track-reorder') return;\n\n const drag = trimDragRef.current;\n const move = moveDragRef.current;\n const delta = lastBoundaryDeltaRef.current;\n trimDragRef.current = null;\n trimOrderRef.current = null;\n moveDragRef.current = null;\n lastBoundaryDeltaRef.current = 0;\n\n // Canceled (Escape, focus loss, unmount): nothing was changed but the\n // preview. A canceled move needs nothing: the Feedback plugin puts the\n // clip back and the engine was never told.\n if (event.canceled || !data) {\n if (drag) preview?.publish(null);\n return;\n }\n\n // A trim commits the clip captured at drag start (`drag`).\n if (data.boundary) {\n if (drag) commitTrim(drag, delta);\n return;\n }\n\n // Clip move: transform.x is modifier-constrained, cached as a plain\n // object in the snapshot.\n const sampleDelta = event.operation.transform.x * samplesPerPixel;\n const tracks = arrangement.getTracks();\n // The clip and track picked up at drag start, never the clip the drop's\n // data names: the row can have changed under the drag (a clip arriving\n // earlier in it shifts every later clip's position). From the drop's\n // data only when the drag start was not seen (a custom wiring that\n // calls onDragEnd alone).\n const clipId = move ? move.clipId : data.clipId;\n const trackId = move ? move.trackId : tracks[data.trackIndex]?.id;\n const track = trackId === undefined ? undefined : tracks.find((t) => t.id === trackId);\n if (!track) {\n console.warn(\n `[waveform-playlist] The move was dropped: the clip's track is not there ` +\n `(row ${data.trackIndex}). The clip stays where it was.`\n );\n } else if (!loadedClipsOf(track).some((c) => c.id === clipId)) {\n console.warn(\n `[waveform-playlist] The move was dropped: track \"${track.id}\" has no clip \"${clipId}\".`\n );\n } else {\n arrangement.moveClip(track.id, clipId, Math.floor(sampleDelta));\n }\n },\n [samplesPerPixel, arrangement, preview, commitTrim]\n );\n\n return {\n onDragStart,\n onDragMove,\n onDragEnd,\n };\n}\n","import type { AudioClip } from '@waveform-playlist/core';\nimport { constrainBoundaryTrim } from '@waveform-playlist/engine';\n\n/**\n * Result of a boundary trim calculation — the new clip dimensions\n * after dragging a left or right boundary by a given pixel delta.\n */\nexport interface BoundaryTrimResult {\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n}\n\nexport interface CalculateBoundaryTrimParams {\n /** The original clip state captured at drag start */\n originalClip: Pick<AudioClip, 'startSample' | 'durationSamples' | 'offsetSamples'>;\n /** The current clip with full AudioClip shape (used for constraint calculation) */\n clip: AudioClip;\n /** Raw pixel delta from drag start (positive = rightward) */\n pixelDelta: number;\n /** Samples per pixel (zoom level) */\n samplesPerPixel: number;\n /** Audio sample rate (used to compute minimum duration) */\n sampleRate: number;\n /** Which boundary is being dragged */\n boundary: 'left' | 'right';\n /** Clips on the same track, sorted by startSample (for collision detection) */\n sortedClips: AudioClip[];\n /** Index of the clip being trimmed within sortedClips */\n sortedIndex: number;\n}\n\n/**\n * Pure function that calculates new clip dimensions after a boundary trim drag.\n *\n * Converts a pixel delta to sample delta, constrains it via the engine's\n * `constrainBoundaryTrim`, and applies the constrained delta to the original\n * clip snapshot to produce new startSample, durationSamples, and offsetSamples.\n *\n * For left boundary: startSample and offsetSamples increase by the constrained delta,\n * durationSamples decreases by the same amount.\n *\n * For right boundary: only durationSamples changes (increases by the constrained delta).\n */\nexport function calculateBoundaryTrim({\n originalClip,\n clip,\n pixelDelta,\n samplesPerPixel,\n sampleRate,\n boundary,\n sortedClips,\n sortedIndex,\n}: CalculateBoundaryTrimParams): BoundaryTrimResult {\n const sampleDelta = pixelDelta * samplesPerPixel;\n const MIN_DURATION_SAMPLES = Math.floor(0.1 * sampleRate);\n\n // Build a temporary clip with original state for constraint calculation\n const tempClip: AudioClip = {\n ...clip,\n startSample: originalClip.startSample,\n offsetSamples: originalClip.offsetSamples,\n durationSamples: originalClip.durationSamples,\n };\n\n const constrainedDelta = constrainBoundaryTrim(\n tempClip,\n Math.floor(sampleDelta),\n boundary,\n sortedClips,\n sortedIndex,\n MIN_DURATION_SAMPLES\n );\n\n if (boundary === 'left') {\n return {\n startSample: originalClip.startSample + constrainedDelta,\n durationSamples: originalClip.durationSamples - constrainedDelta,\n offsetSamples: originalClip.offsetSamples + constrainedDelta,\n };\n } else {\n return {\n startSample: originalClip.startSample,\n durationSamples: originalClip.durationSamples + constrainedDelta,\n offsetSamples: originalClip.offsetSamples,\n };\n }\n}\n","import type { AudioClip } from '@waveform-playlist/core';\n\nconst cache = new WeakMap<readonly AudioClip[], AudioClip[]>();\n\n/**\n * A track's clips in timeline order.\n *\n * The result is cached per clips array, so calling this on every pointer move\n * of a drag sorts once: tracks are updated immutably, and a clips array that\n * has not been replaced has not changed order. Do not mutate the result.\n */\nexport function sortedClipsOf(clips: readonly AudioClip[]): AudioClip[] {\n let sorted = cache.get(clips);\n if (!sorted) {\n sorted = [...clips].sort((a, b) => a.startSample - b.startSample);\n cache.set(clips, sorted);\n }\n return sorted;\n}\n","/**\n * loadedTracks\n *\n * An arrangement's tracks without their loading clips (#812): what the\n * provider publishes as `usePlaylistTimeline().tracks` and what the engine\n * plays. A clip that is still loading is drawn from its placeholder record\n * (`placeholderPeaks`) and is in no tracks array.\n *\n * Identities are kept as `derivePeaks` keeps them, because they are compared\n * downstream: a track that holds no loading clip is the arrangement's own\n * object; a track that holds one gives the same projection for as long as the\n * arrangement hands back the same track object; and the result is the same\n * array while no element changed. Nothing here writes to the arrangement's\n * objects (they are frozen in development).\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, AudioClip, ClipTrack } from '@waveform-playlist/core';\nimport { sameItems } from './sameItems';\n\nexport interface LoadedTracksCache {\n /** The projection of each arrangement track of the last pass. */\n readonly byTrack: ReadonlyMap<ArrangementTrack, ClipTrack>;\n readonly result: readonly ClipTrack[];\n}\n\nexport const EMPTY_LOADED_TRACKS: LoadedTracksCache = { byTrack: new Map(), result: [] };\n\n// The loaded clips of each arrangement track object. The objects never change\n// (a change replaces them), so one array per object is right for its life.\nconst loadedClipsByTrack = new WeakMap<ArrangementTrack, AudioClip[]>();\n\nfunction cachedLoadedClips(track: ArrangementTrack): AudioClip[] {\n let clips = loadedClipsByTrack.get(track);\n if (!clips) {\n clips = track.clips.filter((clip): clip is AudioClip => !isLoadingClip(clip));\n loadedClipsByTrack.set(track, clips);\n }\n return clips;\n}\n\n/**\n * The clips of `track` that have their audio, in its order: the same array\n * for the same track object. What a drag can pick up and a split can cut.\n */\nexport function loadedClipsOf(track: ArrangementTrack): readonly AudioClip[] {\n return cachedLoadedClips(track);\n}\n\nfunction projection(track: ArrangementTrack, previous: LoadedTracksCache): ClipTrack {\n if (!track.clips.some(isLoadingClip)) {\n // Every clip is loaded: the track is a `ClipTrack` as it is.\n return track as ClipTrack;\n }\n const known = previous.byTrack.get(track);\n if (known) return known;\n return { ...track, clips: cachedLoadedClips(track) };\n}\n\n/**\n * `tracks` without their loading clips, reusing `cache` (the previous pass).\n * Keep the returned cache and pass it to the next call.\n */\nexport function loadedTracks(\n tracks: readonly ArrangementTrack[],\n cache: LoadedTracksCache\n): { tracks: readonly ClipTrack[]; cache: LoadedTracksCache } {\n const byTrack = new Map<ArrangementTrack, ClipTrack>();\n const projected = tracks.map((track) => {\n const loaded = projection(track, cache);\n byTrack.set(track, loaded);\n return loaded;\n });\n const result = sameItems(cache.result, projected) ? cache.result : projected;\n return { tracks: result, cache: { byTrack, result } };\n}\n","/**\n * True when `a` holds the same items as `b`, in the same order, compared by\n * identity. The derivations that keep identities (`derivePeaks`,\n * `loadedTracks`, the view of an arrangement) hand back the previous array\n * when it does.\n */\nexport function sameItems<T>(a: readonly T[] | undefined, b: readonly T[]): a is T[] {\n return a !== undefined && a.length === b.length && a.every((item, i) => item === b[i]);\n}\n","/**\n * The context objects, their value types and their hooks (#688).\n *\n * Both providers render the SAME context objects for the part they share, so\n * a control written against `useIsPlaying()` or `usePlaybackControls()` works\n * under either. What only one provider has is on its own context, and the\n * other provider blocks it (see `BLOCKED`), so that a hook never reaches\n * through one provider to an outer one of the other kind.\n *\n * This file imports no provider and no engine: a MediaElement-only bundle\n * must not pull in the WebAudio provider through it.\n */\nimport { createContext, use } from 'react';\nimport type { ClipTrack, AnnotationData } from '@waveform-playlist/core';\nimport type { Arrangement, PlaylistEngine } from '@waveform-playlist/engine';\nimport type { MediaElementPlayout, FadeConfig } from '@waveform-playlist/media-element-playout';\nimport type { TimeFormat } from '@waveform-playlist/ui-components';\nimport type { AnnotationPreviewHandle } from '../hooks/useAnnotationDragHandlers';\nimport type { FrameData } from '../providerInternals/useFrameCallbacks';\nimport type { TrackDragPreview } from '../utils/trackOrderPreview';\nimport type { TrimPreviewHandle, TrimPreviewPeaksValue } from '../providerInternals/useTrimPreview';\nimport type { TrackClipPeaks, TrackState } from '../WaveformPlaylistContext';\n\nexport type { FrameData };\n\nconst WEB_AUDIO = 'WaveformPlaylistProvider';\nconst MEDIA_ELEMENT = 'MediaElementPlaylistProvider';\n\n/** The id of the one track of a MediaElement player (its row and its clip carry it). */\nexport const MEDIA_ELEMENT_TRACK_ID = 'media-element-track-0';\n\n/**\n * What a provider puts in a context it does not serve. The hook then throws\n * and names the provider that is needed, instead of reading an outer provider\n * of the other kind.\n */\nexport const BLOCKED = Symbol('waveform-playlist.blocked-context');\ntype Blocked = typeof BLOCKED;\ntype Slot<T> = T | Blocked | null;\n\n// ---------------------------------------------------------------------------\n// Shared: rendered by both providers\n// ---------------------------------------------------------------------------\n\n/**\n * Whether playback is running. Its own context (#768): it is the only value of\n * the playback state that changes on play, pause and stop, and a component\n * that needs a ref or a frame callback (`usePlaybackRefs`) must not re-render\n * with it.\n */\nexport interface IsPlayingContextValue {\n isPlaying: boolean;\n}\n\n/**\n * Refs and functions that keep their identity for the life of the provider\n * (#768). Reading this never causes a re-render: read a ref's `.current` in an\n * event handler, an effect or a frame callback, not during render.\n */\nexport interface PlaybackRefsContextValue {\n /** The playback position, in seconds. Advances during playback. */\n currentTimeRef: React.RefObject<number>;\n /**\n * The position to DRAW. Under the WebAudio provider it is the audible\n * position (the raw time less output latency and lookahead while playing);\n * under the MediaElement provider it is `currentTimeRef` itself, because a\n * media element reports the audible position.\n */\n visualTimeRef: React.RefObject<number>;\n /** Register a per-frame callback driven by the provider's one animation loop. */\n registerFrameCallback: (id: string, cb: (data: FrameData) => void) => void;\n /** Unregister a per-frame callback. */\n unregisterFrameCallback: (id: string) => void;\n}\n\n/**\n * The selected time range, in seconds. Apart from the state context because it\n * is the only state that changes on every pointer move of a selection drag\n * (#733). `selectionStart === selectionEnd` means nothing is selected.\n */\nexport interface SelectionContextValue {\n selectionStart: number;\n selectionEnd: number;\n}\n\n/**\n * Where the cursor rests, in seconds: the position playback starts from. It\n * changes on a seek, a pause, a stop (including playback reaching the end) and\n * a selection whose start moves; it does NOT advance during playback (read\n * `currentTimeRef`, or register a frame callback, for that). Apart from the\n * other values so that a component reading `isPlaying` or a ref is not\n * re-rendered by every seek, nor by every pointer move of a leftward selection\n * drag (#740).\n */\nexport interface CurrentTimeContextValue {\n currentTime: number;\n}\n\n/**\n * The annotation that is playing or was last chosen. Its own context because\n * it changes at every annotation boundary during playback (#740).\n */\nexport interface ActiveAnnotationContextValue {\n activeAnnotationId: string | null;\n}\n\n/**\n * The annotations. Changes on an annotation edit; an edge drag changes it\n * once, on release (its moves go through the preview source).\n */\nexport interface AnnotationsContextValue {\n annotations: AnnotationData[];\n}\n\n/**\n * The three annotation options, under both providers (#686): whether\n * annotations can be edited, whether an edge takes the edge it touches along,\n * and whether playback runs on past the end of an annotation. They start from\n * the provider's `annotationList` prop and are set with\n * `setAnnotationsEditable`, `setLinkEndpoints` and `setContinuousPlay` of\n * `usePlaybackControls()`.\n */\nexport interface AnnotationOptionsContextValue {\n editable: boolean;\n linkEndpoints: boolean;\n continuousPlay: boolean;\n}\n\n/**\n * The actions both providers have (#688). The value never changes, so reading\n * it never re-renders.\n */\nexport interface PlaybackControlsContextValue {\n /**\n * Starts playback at `startTime` (default: the cursor). With `playDuration`\n * it stops by itself after that many seconds of audio.\n */\n play: (startTime?: number, playDuration?: number) => Promise<void>;\n pause: () => void;\n /** Ends playback and returns the cursor to where playback started. */\n stop: () => void;\n /** Moves the cursor, clamped to the audio. During playback, playback restarts there. */\n seekTo: (time: number) => void;\n /** Sets the selected range and moves the cursor to its start. During playback, playback\n * restarts: a range is played start to end (open-ended under WaveformPlaylistProvider with\n * looping on), a collapsed one carries on from there. */\n setSelection: (start: number, end: number) => void;\n\n setTimeFormat: (format: TimeFormat) => void;\n\n setAutomaticScroll: (enabled: boolean) => void;\n setScrollContainer: (element: HTMLDivElement | null) => void;\n scrollContainerRef: React.RefObject<HTMLDivElement | null>;\n\n setContinuousPlay: (enabled: boolean) => void;\n setAnnotationsEditable: (enabled: boolean) => void;\n setLinkEndpoints: (enabled: boolean) => void;\n setAnnotations: React.Dispatch<React.SetStateAction<AnnotationData[]>>;\n /**\n * Where an annotation edge drag shows its moves while it is in progress.\n * Pass it to `useAnnotationDragHandlers({ preview })`; read it in a custom\n * annotation renderer with `useAnnotationsWithPreview`. Stable identity.\n */\n annotationPreview: AnnotationPreviewHandle;\n setActiveAnnotationId: (id: string | null) => void;\n /**\n * What a click on an annotation does (its box, or its row in the list): the\n * annotation becomes the active one and is played from its start. With\n * continuous play off, playback ends where the annotation ends. Call it\n * from a box or a row of your own. Each provider plays an annotation its\n * own way: `WaveformPlaylistProvider` starts a play of the annotation's\n * length, `MediaElementPlaylistProvider` starts an open-ended play that its\n * loop ends with the active annotation. Left alone, both end at the\n * annotation's end. They differ when something changes during the play:\n * under MediaElement the play follows an end that is moved, and continuous\n * play switched on lets it run on; under WebAudio the first keeps the end\n * it started with. A start that fails is logged as a warning.\n */\n playAnnotation: (annotation: AnnotationData) => void;\n}\n\n/**\n * What the provider was configured with that a view also reads (#768, #689).\n * Changes on a prop change (and once when the real sample rate is known),\n * never during an interaction.\n *\n * The options that only affect how a view draws (row height, bar style,\n * playhead width, the filled layout) are not here: they are\n * `<WaveformViewOptions>`, and what is drawn reads them from ui-components'\n * `usePlaylistInfo()` inside a root.\n */\nexport interface PlaylistViewContextValue {\n sampleRate: number;\n /**\n * Whether tracks are drawn and analysed as one channel. On the provider\n * because the provider computes the peaks with it. Always false under the\n * MediaElement provider.\n */\n mono: boolean;\n /**\n * Whether playback continues past the end of the audio instead of stopping\n * there. On the provider because its animation loop and `seekTo` follow it;\n * the multitrack root also draws the timeline as wide as its container\n * then. Always false under the MediaElement provider.\n */\n indefinitePlayback: boolean;\n}\n\n/**\n * The two settings a user toggles (#768). Apart from the view value because\n * every clip overlay and the visualization shell read that one: a toggle here\n * renders only the components that show the setting.\n */\nexport interface PlaylistSettingsContextValue {\n timeFormat: TimeFormat;\n isAutomaticScroll: boolean;\n}\n\n/**\n * The zoom level (#768). Changes on a zoom. Under the MediaElement provider\n * the level is fixed: `canZoomIn` and `canZoomOut` are always false.\n */\nexport interface PlaylistZoomContextValue {\n samplesPerPixel: number;\n canZoomIn: boolean;\n canZoomOut: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// WaveformPlaylistProvider only\n// ---------------------------------------------------------------------------\n\n/**\n * The actions only the multitrack editor has (#688). The value never changes.\n */\nexport interface EditorControlsContextValue {\n /**\n * Moves the cursor without touching playback. `seekTo` is the one to use\n * from a control; this is for the view's own press and drag handling.\n */\n setCurrentTime: (time: number) => void;\n\n // Track mixer, by track id (#687; by index until then). An id no track has\n // is ignored. They change the arrangement's mix, also while no engine is\n // attached (#812). Inside a track's control panel, `useTrack()` has the\n // same actions already bound to that track.\n setTrackMute: (trackId: string, muted: boolean) => void;\n setTrackSolo: (trackId: string, soloed: boolean) => void;\n setTrackVolume: (trackId: string, volume: number) => void;\n setTrackPan: (trackId: string, pan: number) => void;\n\n /** Move a track to a new index in the vertical track order. Purely\n * organizational — playback is not interrupted. An undo step of the\n * arrangement (#812). */\n reorderTrack: (trackId: string, toIndex: number) => void;\n\n /** Internal: call after every track-reorder DRAG interaction ends\n * (committed or canceled) to force the view's track-controls part to remount\n * its slots, discarding any @dnd-kit sortable-plugin DOM\n * corruption. Not needed for button-driven reorderTrack calls (they never\n * touch dnd-kit's DOM). See bumpTrackReorderEpoch in the provider. */\n bumpTrackReorderEpoch: () => void;\n\n /** INTERNAL wiring for ClipInteractionProvider: publishes/clears the live\n * track-reorder drag preview. Custom drag integrations may call it, but\n * most consumers only ever READ trackDragPreview from useTrackReorderPreview(). */\n setTrackDragPreview: React.Dispatch<React.SetStateAction<TrackDragPreview | null>>;\n\n setSelectedTrackId: (trackId: string | null) => void;\n\n // Zoom\n zoomIn: () => void;\n zoomOut: () => void;\n\n // Master volume\n setMasterVolume: (volume: number) => void;\n\n // Loop controls\n setLoopEnabled: (enabled: boolean) => void;\n setLoopRegion: (start: number, end: number) => void;\n setLoopRegionFromSelection: () => void;\n clearLoopRegion: () => void;\n\n // Undo/redo: the arrangement's history, engine or not (#812).\n undo: () => void;\n redo: () => void;\n\n // Recording\n /** Mark a recording session active/inactive. While active: (1) the\n * end-of-audio auto-stop is suppressed so overdub playback runs past the\n * end of existing material, and (2) with an `armedTrackId`, that track is\n * muted in the arrangement's mix for the session (#812): punch-in\n * recording replaces whatever the take overlaps (#579), so the doomed\n * material must not play under the overdub. The mixer and the track's Mute\n * button show it muted, the built-in `<TrackMuteButton />` of that track\n * is disabled, and `useTrack().isRecordingArmed` is true for it. The mute\n * from before the session is written back when it ends or the armed track\n * changes, whatever was set in between; nothing is written for a track\n * that is no longer in the arrangement. `useRecordingSession` calls it for\n * the length of a take; overdub flows should also call it eagerly (before\n * `play()`). */\n setRecordingActive: (active: boolean, armedTrackId?: string | null) => void;\n}\n\n/**\n * Refs and functions of the multitrack engine (#688). Like\n * `usePlaybackRefs()`, the value never changes.\n */\nexport interface EngineRefsContextValue {\n // Refs for direct time calculation in animated components (avoids timing drift)\n playbackStartTimeRef: React.RefObject<number>; // context.currentTime when playback started\n audioStartPositionRef: React.RefObject<number>; // Audio position when playback started\n /** Returns raw playback time from engine (auto-wraps at loop boundaries). */\n getPlaybackTime: () => number;\n /** Current time of the adapter's AudioContext, in seconds. */\n getAudioContextTime: () => number;\n /**\n * Returns the current adapter scheduler lookahead (Tone ~0.1s, native 0).\n * Use this for any audible-latency calculation that must match the playhead\n * (e.g., recording live-preview peak slicing).\n */\n getLookAhead: () => number;\n /**\n * Returns the adapter AudioContext's output latency in seconds.\n * Use this for audible-latency calculations (e.g., recording live-preview peak slicing).\n */\n getOutputLatency: () => number;\n /** The engine. `current` is null until the first build and during a rebuild. */\n playoutRef: React.RefObject<PlaylistEngine | null>;\n}\n\n/** Loop region (separate from selection), Audacity-style loop points (#768). */\nexport interface LoopContextValue {\n isLoopEnabled: boolean;\n loopStart: number;\n loopEnd: number;\n}\n\n/** The track selected for editing operations (#768). */\nexport interface SelectedTrackIdContextValue {\n selectedTrackId: string | null;\n}\n\n/** Whether undo and redo are available (#768). Changes after an edit. */\nexport interface UndoRedoContextValue {\n canUndo: boolean;\n canRedo: boolean;\n}\n\n/**\n * What is on the timeline (#768). Changes on every clip operation (a trim\n * once, on release: its moves are a preview only the dragged clip follows,\n * #812) and on a zoom (the peaks are computed per zoom level), so call\n * `usePlaylistTimeline()` only in a component\n * that draws tracks or needs the timeline length during render.\n */\nexport interface PlaylistTimelineContextValue {\n /**\n * The arrangement's tracks without the clips that are still loading\n * (#812): derived from the arrangement, never written back. Change them\n * through `useArrangement()`.\n */\n tracks: readonly ClipTrack[];\n /**\n * One row per track, in the order of `tracks`. A row also holds the\n * placeholder record (`isPlaceholder: true`) of each clip still loading,\n * which `tracks` does not have: find a record by `clipId`, never by position.\n */\n peaksDataArray: TrackClipPeaks[];\n /** The end, in seconds, of the loaded audio. */\n duration: number;\n /**\n * False until an engine is attached and the first sources have settled;\n * then false while a later engine is being built.\n */\n isReady: boolean;\n}\n\n/** Mixer state (#768). Changes on every mute, solo, volume or pan change. */\nexport interface PlaylistMixerContextValue {\n trackStates: TrackState[];\n masterVolume: number;\n}\n\n/** The live track-reorder drag (#768). Changes on every drag-over. */\nexport interface TrackReorderPreviewContextValue {\n /** Non-null while a track-reorder drag is live: the dragged track and the\n * index it would drop at. Both playlist columns derive their display\n * layout from it; a track's panel can read it to mirror the preview in\n * its own UI. */\n trackDragPreview: TrackDragPreview | null;\n /** Internal: incremented after every track-reorder drag interaction ends.\n * The view's track-controls part folds this into each slot's `key` to\n * force a remount, working around @dnd-kit sortable-plugin DOM corruption\n * (see bumpTrackReorderEpoch in EditorControlsContextValue). */\n trackReorderEpoch: number;\n}\n\n/**\n * INTERNAL (the context and its hook are not exported from the package,\n * #812): the track a take is being recorded onto, set by\n * `setRecordingActive(true, trackId)` and cleared when the session ends.\n * Changes when a take starts and ends and when the armed track changes. The\n * track controls read it and give each track's panel `isRecordingArmed`.\n */\nexport interface RecordingArmContextValue {\n armedTrackId: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// MediaElementPlaylistProvider only\n// ---------------------------------------------------------------------------\n\n/** The playback speed and its setter (#688). Changes when the speed does. */\nexport interface PlaybackRateContextValue {\n /** 0.5 to 2. */\n playbackRate: number;\n /** Clamped to 0.5–2. Stable identity. */\n setPlaybackRate: (rate: number) => void;\n}\n\n/**\n * The one track of a MediaElement player (#688). Changes when the track or the\n * zoom level does, and when the player becomes ready.\n */\nexport interface MediaElementTrackContextValue {\n /** The length of the track's audio, from its waveform data. Never 0 for a real track. */\n duration: number;\n /**\n * True once the media element has loaded its metadata, false again while a\n * replaced player loads. Use this, not `duration`, as \"the player can be used\".\n */\n isReady: boolean;\n /** One track with one clip (`[]` when the peak data could not be read). The clip carries the track's fadeIn / fadeOut. */\n peaksDataArray: TrackClipPeaks[];\n fadeIn?: FadeConfig;\n fadeOut?: FadeConfig;\n /** The player. `current` is null until it has been created. */\n playoutRef: React.RefObject<MediaElementPlayout | null>;\n}\n\n// ---------------------------------------------------------------------------\n// The contexts. Each holds fields that change together (#733, #740, #768).\n// ---------------------------------------------------------------------------\n\nconst slot = <T>() => createContext<Slot<T>>(null);\n\n// Shared\nexport const IsPlayingContext = slot<IsPlayingContextValue>();\nexport const PlaybackRefsContext = slot<PlaybackRefsContextValue>();\nexport const SelectionContext = slot<SelectionContextValue>();\nexport const CurrentTimeContext = slot<CurrentTimeContextValue>();\nexport const ActiveAnnotationContext = slot<ActiveAnnotationContextValue>();\nexport const AnnotationsContext = slot<AnnotationsContextValue>();\nexport const AnnotationOptionsContext = slot<AnnotationOptionsContextValue>();\nexport const PlaybackControlsContext = slot<PlaybackControlsContextValue>();\nexport const PlaylistViewContext = slot<PlaylistViewContextValue>();\nexport const PlaylistSettingsContext = slot<PlaylistSettingsContextValue>();\nexport const PlaylistZoomContext = slot<PlaylistZoomContextValue>();\n/**\n * INTERNAL (the context and its hook are not exported from the package): which\n * row the view draws as selected. Both providers serve it, so the tracks part\n * of the view needs no provider-specific hook: the multitrack provider gives\n * the value of `useSelectedTrackId()` (the same object), the MediaElement\n * provider its one track, always.\n */\nexport const SelectedRowContext = slot<SelectedTrackIdContextValue>();\n\n// WaveformPlaylistProvider only\n/** The arrangement the provider was given (#812). Never changes for a mount. */\nexport const ArrangementContext = slot<Arrangement>();\nexport const EditorControlsContext = slot<EditorControlsContextValue>();\nexport const EngineRefsContext = slot<EngineRefsContextValue>();\nexport const LoopContext = slot<LoopContextValue>();\nexport const SelectedTrackIdContext = slot<SelectedTrackIdContextValue>();\nexport const UndoRedoContext = slot<UndoRedoContextValue>();\nexport const PlaylistTimelineContext = slot<PlaylistTimelineContextValue>();\nexport const PlaylistMixerContext = slot<PlaylistMixerContextValue>();\nexport const TrackReorderPreviewContext = slot<TrackReorderPreviewContextValue>();\n/**\n * INTERNAL (neither context is exported from the package, #812): a clip trim\n * drag in progress. The first holds the preview source, which the drag\n * handlers write on every pointer move and clear on release and on cancel;\n * the second the stable function that draws the previewed clip. Both values\n * keep their identity for the life of the provider; only the dragged clip's\n * view and the root (for the width) subscribe to the source.\n */\nexport const TrimPreviewContext = slot<TrimPreviewHandle>();\nexport const TrimPreviewPeaksContext = slot<TrimPreviewPeaksValue>();\n/** INTERNAL (#812): see {@link RecordingArmContextValue}. */\nexport const RecordingArmContext = slot<RecordingArmContextValue>();\n\n// MediaElementPlaylistProvider only\nexport const PlaybackRateContext = slot<PlaybackRateContextValue>();\nexport const MediaElementTrackContext = slot<MediaElementTrackContextValue>();\n\n// ---------------------------------------------------------------------------\n// One hook per context. A component re-renders only when the value of a\n// context it reads changes, so read the smallest group that has the field.\n// ---------------------------------------------------------------------------\n\nfunction useSlot<T>(context: React.Context<Slot<T>>, hookName: string, needs: string): T {\n const value = use(context);\n if (value === BLOCKED) {\n const nearest = needs === WEB_AUDIO ? MEDIA_ELEMENT : WEB_AUDIO;\n throw new Error(\n `${hookName} needs ${needs}, and the nearest playlist provider here is ${nearest}, ` +\n 'which does not provide it'\n );\n }\n if (!value) {\n throw new Error(`${hookName} must be used within ${needs}`);\n }\n return value;\n}\n\nconst EITHER = `${WEB_AUDIO} or ${MEDIA_ELEMENT}`;\n\n/** `{ isPlaying }`. Re-renders on play, pause and stop. */\nexport const useIsPlaying = () => useSlot(IsPlayingContext, 'useIsPlaying', EITHER);\n\n/**\n * Refs and functions that never change identity: `currentTimeRef`,\n * `visualTimeRef`, `registerFrameCallback`, `unregisterFrameCallback`. Calling\n * this never re-renders the component. Read `.current` in a handler, an effect\n * or a frame callback; to re-render when the value behind a ref changes, also\n * call the hook that carries it (`useCurrentTime()`, `useIsPlaying()`).\n */\nexport const usePlaybackRefs = () => useSlot(PlaybackRefsContext, 'usePlaybackRefs', EITHER);\n\n/**\n * The selected time range. A component that calls this re-renders on every\n * pointer move of a selection drag, so call it in the smallest component that\n * shows the selection.\n */\nexport const useSelection = () => useSlot(SelectionContext, 'useSelection', EITHER);\n\n/**\n * Where the cursor rests, in seconds. A component that calls this re-renders\n * on every seek, pause and stop, and on every pointer move of a selection drag\n * to the left. The value does not advance during playback: for a live position\n * read `currentTimeRef` from `usePlaybackRefs()` or register a frame callback\n * there.\n */\nexport const useCurrentTime = () => useSlot(CurrentTimeContext, 'useCurrentTime', EITHER);\n\n/**\n * The id of the annotation that is playing or was last chosen, or `null`. A\n * component that calls this re-renders at every annotation boundary during\n * playback, so call it in the smallest component that shows the active one.\n */\nexport const useActiveAnnotation = () =>\n useSlot(ActiveAnnotationContext, 'useActiveAnnotation', EITHER);\n\n/** `{ annotations }`. Re-renders on an annotation edit. */\nexport const useAnnotations = () => useSlot(AnnotationsContext, 'useAnnotations', EITHER);\n\n/**\n * `{ editable, linkEndpoints, continuousPlay }`: the one home of the three\n * annotation options, under both providers. Re-renders when one is toggled.\n */\nexport const useAnnotationOptions = () =>\n useSlot(AnnotationOptionsContext, 'useAnnotationOptions', EITHER);\n\n/**\n * The actions both providers have: `play`, `pause`, `stop`, `seekTo`,\n * `setSelection`, and the annotation, scroll and time-format setters. The\n * value never changes, so calling this never re-renders.\n */\nexport const usePlaybackControls = () =>\n useSlot(PlaybackControlsContext, 'usePlaybackControls', EITHER);\n\n/**\n * `{ sampleRate, mono, indefinitePlayback }`: what the provider was\n * configured with that a view also reads. Re-renders on a prop change.\n */\nexport const usePlaylistView = () => useSlot(PlaylistViewContext, 'usePlaylistView', EITHER);\n\n/** `{ timeFormat, isAutomaticScroll }`. Re-renders when the user changes either. */\nexport const usePlaylistSettings = () =>\n useSlot(PlaylistSettingsContext, 'usePlaylistSettings', EITHER);\n\n/** `{ samplesPerPixel, canZoomIn, canZoomOut }`. Re-renders on a zoom. */\nexport const usePlaylistZoom = () => useSlot(PlaylistZoomContext, 'usePlaylistZoom', EITHER);\n\n/**\n * The arrangement of the nearest WaveformPlaylistProvider: the owner of the\n * tracks, the mix, the undo history and the loading (#812). Change the tracks\n * through it; the provider and the engine follow. The value never changes,\n * so calling this never re-renders.\n */\nexport const useArrangement = () => useSlot(ArrangementContext, 'useArrangement', WEB_AUDIO);\n\n/**\n * The multitrack editor's actions: track mixer and order, zoom, loop, undo,\n * annotation editing settings, recording. WaveformPlaylistProvider only. The\n * value never changes.\n */\nexport const useEditorControls = () =>\n useSlot(EditorControlsContext, 'useEditorControls', WEB_AUDIO);\n\n/**\n * The multitrack engine's refs and clock functions (`playoutRef`,\n * `getPlaybackTime`, `getLookAhead`, …). WaveformPlaylistProvider only. The\n * value never changes.\n */\nexport const useEngineRefs = () => useSlot(EngineRefsContext, 'useEngineRefs', WEB_AUDIO);\n\n/** `{ isLoopEnabled, loopStart, loopEnd }`. Re-renders on a loop change. */\nexport const useLoop = () => useSlot(LoopContext, 'useLoop', WEB_AUDIO);\n\n/** `{ selectedTrackId }`. Re-renders when another track is selected. */\nexport const useSelectedTrackId = () =>\n useSlot(SelectedTrackIdContext, 'useSelectedTrackId', WEB_AUDIO);\n\n/**\n * INTERNAL (not exported from the package): `{ selectedTrackId }` for the row\n * the view draws as selected, under either provider. Consumers use\n * `useSelectedTrackId()`, which only the multitrack provider serves.\n */\nexport const useSelectedRow = () => useSlot(SelectedRowContext, 'The tracks of the view', EITHER);\n\n/** `{ canUndo, canRedo }`. Re-renders after an edit. */\nexport const useUndoRedo = () => useSlot(UndoRedoContext, 'useUndoRedo', WEB_AUDIO);\n\n/**\n * `{ tracks, peaksDataArray, duration, isReady }`. A component that calls this\n * re-renders on every clip operation (a trim once, on release), on a zoom and\n * when audio arrives for a clip.\n */\nexport const usePlaylistTimeline = () =>\n useSlot(PlaylistTimelineContext, 'usePlaylistTimeline', WEB_AUDIO);\n\n/**\n * `{ trackStates, masterVolume }`. A component that calls this re-renders on\n * every mute, solo, volume or pan change (each step of a slider drag).\n */\nexport const usePlaylistMixer = () => useSlot(PlaylistMixerContext, 'usePlaylistMixer', WEB_AUDIO);\n\n/**\n * `{ trackDragPreview, trackReorderEpoch }`. A component that calls this\n * re-renders on every drag-over of a track reorder.\n */\nexport const useTrackReorderPreview = () =>\n useSlot(TrackReorderPreviewContext, 'useTrackReorderPreview', WEB_AUDIO);\n\n/**\n * INTERNAL (not exported from the package, #812): `{ armedTrackId }`, the\n * track a take is being recorded onto. Re-renders when a take starts or ends.\n */\nexport const useRecordingArm = () => useSlot(RecordingArmContext, 'useRecordingArm', WEB_AUDIO);\n\n/** `{ playbackRate, setPlaybackRate }`. MediaElementPlaylistProvider only. */\nexport const usePlaybackRate = () => useSlot(PlaybackRateContext, 'usePlaybackRate', MEDIA_ELEMENT);\n\n/**\n * `{ duration, isReady, peaksDataArray, fadeIn, fadeOut, playoutRef }`: the\n * one track of a MediaElement player. MediaElementPlaylistProvider only.\n */\nexport const useMediaElementTrack = () =>\n useSlot(MediaElementTrackContext, 'useMediaElementTrack', MEDIA_ELEMENT);\n\n/**\n * INTERNAL (not exported from the package): throws under\n * MediaElementPlaylistProvider, in the name of a hook that reads only shared\n * contexts but is not meant to run there. `usePlaybackShortcuts()` listens on\n * the window; what keys do for the single-track player is not decided yet.\n */\nexport const useWebAudioProviderOnly = (hookName: string): void => {\n useSlot(EditorControlsContext, hookName, WEB_AUDIO);\n};\n\n/**\n * INTERNAL (not exported from the package): the loop state, or `null` where\n * there is none (under the MediaElement provider). For the one hook that\n * starts playback under both providers.\n */\nexport const useLoopOptional = (): LoopContextValue | null => {\n const value = use(LoopContext);\n return value === BLOCKED ? null : value;\n};\nconst orNull = <T>(value: T | typeof BLOCKED | null): T | null =>\n value === BLOCKED ? null : value;\n\n/**\n * INTERNAL (not exported from the package): like {@link usePlaylistView} and\n * {@link usePlaylistZoom} but `null` when there is no provider above. For a\n * hook that may also be called outside one with explicit options.\n */\nexport const usePlaylistViewOptional = () => orNull(use(PlaylistViewContext));\nexport const usePlaylistZoomOptional = () => orNull(use(PlaylistZoomContext));\n\n/**\n * INTERNAL (not exported from the package): the trim preview source and the\n * previewed clip's drawing, or `null` under the MediaElement provider (which\n * blocks both) and outside a provider. The clip rows are shared by both\n * views, so their reads mean \"no preview\" there instead of throwing.\n */\nexport const useTrimPreviewOptional = () => orNull(use(TrimPreviewContext));\nexport const useTrimPreviewPeaksOptional = () => orNull(use(TrimPreviewPeaksContext));\n","import React from 'react';\nimport { flushSync } from 'react-dom';\nimport type { DragStartEvent, DragMoveEvent, DragEndEvent } from '@dnd-kit/abstract';\nimport {\n updateAnnotationBoundaries,\n type AnnotationData,\n type ValueSourceHandle,\n} from '@waveform-playlist/core';\n\n/**\n * Where an annotation edge drag shows its moves while it is in progress:\n * the annotations as the drag would leave them, or `null` when no drag is\n * running. Both providers have one (`annotationPreview` in their controls).\n */\nexport type AnnotationPreviewHandle = ValueSourceHandle<AnnotationData[] | null>;\n\ninterface UseAnnotationDragHandlersOptions {\n annotations: AnnotationData[];\n onAnnotationsChange: (annotations: AnnotationData[]) => void;\n samplesPerPixel: number;\n /** Sample rate for pixel-to-time conversion. Providers pass the real rate from\n * context; defaults to 48000 (the engine default) for out-of-provider usage. */\n sampleRate?: number;\n duration: number;\n linkEndpoints: boolean;\n /**\n * Pass the provider's `annotationPreview` to keep the drag out of your own\n * state: each move is published there (the built-in annotation boxes and\n * list follow it), and `onAnnotationsChange` is called once, on release.\n * Without it `onAnnotationsChange` is called on every move, which\n * re-renders whatever holds the annotations for each one.\n */\n preview?: AnnotationPreviewHandle;\n}\n\n/**\n * Custom hook for handling annotation drag operations (boundary trimming)\n *\n * Provides drag handlers for use with @dnd-kit/react DragDropProvider.\n * Handles annotation boundary resizing with linked endpoints support.\n * A cancelled drag (Escape) puts back every annotation it moved.\n *\n * @example\n * ```tsx\n * const { onDragStart, onDragMove, onDragEnd } = useAnnotationDragHandlers({\n * annotations,\n * onAnnotationsChange: setAnnotations,\n * preview: annotationPreview, // from usePlaybackControls()\n * samplesPerPixel,\n * sampleRate,\n * duration,\n * linkEndpoints,\n * });\n *\n * return (\n * <DragDropProvider\n * onDragStart={onDragStart}\n * onDragMove={onDragMove}\n * onDragEnd={onDragEnd}\n * modifiers={[RestrictToHorizontalAxis]}\n * >\n * {renderAnnotations()}\n * </DragDropProvider>\n * );\n * ```\n */\nexport function useAnnotationDragHandlers({\n annotations,\n onAnnotationsChange,\n samplesPerPixel,\n // Default mirrors the engine default; the providers always pass the real rate from context (#510).\n sampleRate = 48000,\n duration,\n linkEndpoints,\n preview,\n}: UseAnnotationDragHandlersOptions) {\n // `snapshot`: the annotations as they were when the drag began; a cancelled\n // drag restores them. Each move is applied to the result of the previous\n // move, not to the snapshot: that is how, with linked endpoints, an edge\n // dragged into a separated neighbour picks it up and carries it along (#747).\n const dragRef = React.useRef<{\n snapshot: AnnotationData[];\n start: number;\n end: number;\n annotationIndex: number;\n } | null>(null);\n\n // Read through refs so the handlers keep their identity while a drag\n // without a preview replaces `annotations` on every move.\n const annotationsRef = React.useRef(annotations);\n annotationsRef.current = annotations;\n const onAnnotationsChangeRef = React.useRef(onAnnotationsChange);\n onAnnotationsChangeRef.current = onAnnotationsChange;\n\n // A drag that never ends (its component unmounts mid-drag) must not leave\n // its preview on screen.\n React.useEffect(() => {\n if (!preview) return;\n return () => {\n if (dragRef.current) {\n dragRef.current = null;\n preview.publish(null);\n }\n };\n }, [preview]);\n\n const onDragStart = React.useCallback((event: DragStartEvent) => {\n const data = event.operation.source?.data as\n | {\n annotationId: string;\n annotationIndex: number;\n edge: 'start' | 'end';\n }\n | undefined;\n\n const snapshot = annotationsRef.current;\n const annotation =\n data?.annotationIndex === undefined ? undefined : snapshot[data.annotationIndex];\n dragRef.current =\n data && annotation\n ? {\n snapshot,\n start: annotation.start,\n end: annotation.end,\n annotationIndex: data.annotationIndex,\n }\n : null;\n }, []);\n\n const onDragMove = React.useCallback(\n (event: DragMoveEvent) => {\n const drag = dragRef.current;\n if (!drag) {\n return;\n }\n\n const data = event.operation.source?.data as\n | {\n annotationId: string;\n annotationIndex: number;\n edge: 'start' | 'end';\n }\n | undefined;\n\n if (!data) return;\n\n const { edge, annotationIndex } = data;\n\n // The dragmove event is dispatched BEFORE position.current is updated (happens\n // in a microtask), so the snapshot's position.current is stale. Use event.to\n // (the pointer's current coordinates from the sensor) for the correct position.\n const currentX = event.to?.x ?? event.operation.position.current.x;\n const rawDeltaX = currentX - event.operation.position.initial.x;\n const timeDelta = (rawDeltaX * samplesPerPixel) / sampleRate;\n\n const newTime = edge === 'start' ? drag.start + timeDelta : drag.end + timeDelta;\n\n // The boundary logic (linked endpoints, collisions) is core's, shared with\n // dawcore's annotation track.\n const updatedAnnotations = updateAnnotationBoundaries({\n annotationIndex,\n newTime,\n isDraggingStart: edge === 'start',\n annotations: preview\n ? (preview.source.getSnapshot() ?? drag.snapshot)\n : annotationsRef.current,\n duration,\n linkEndpoints,\n });\n\n if (preview) {\n preview.publish(updatedAnnotations);\n } else {\n onAnnotationsChangeRef.current(updatedAnnotations);\n }\n },\n [samplesPerPixel, sampleRate, duration, linkEndpoints, preview]\n );\n\n const onDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n const drag = dragRef.current;\n dragRef.current = null;\n if (!drag) return;\n\n if (!preview) {\n // The moves were reported as they happened; a cancelled drag takes\n // them all back, the neighbours it moved included.\n if (event.canceled && annotationsRef.current !== drag.snapshot) {\n onAnnotationsChangeRef.current(drag.snapshot);\n }\n return;\n }\n\n const result = preview.source.getSnapshot();\n if (result === null) return;\n if (event.canceled) {\n preview.publish(null);\n return;\n }\n // Committed and cleared in one synchronous render, so the boxes never\n // show the old positions between the two.\n flushSync(() => {\n onAnnotationsChangeRef.current(result);\n preview.publish(null);\n });\n },\n [preview]\n );\n\n return {\n onDragStart,\n onDragMove,\n onDragEnd,\n };\n}\n","import { useSyncExternalStore } from 'react';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport type { AnnotationPreviewHandle } from './useAnnotationDragHandlers';\n\n/**\n * The annotations to draw: the provider's, or while an edge is being dragged\n * with a preview (`useAnnotationDragHandlers({ preview })`), the annotations\n * as the drag would leave them.\n *\n * Call it in the component that draws annotations (a custom list or row of\n * boxes), with `annotationPreview` from the provider's controls. Only that\n * component then re-renders per pointer move of the drag.\n */\nexport function useAnnotationsWithPreview(\n annotations: AnnotationData[],\n preview: AnnotationPreviewHandle\n): AnnotationData[] {\n const { subscribe, getSnapshot } = preview.source;\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot) ?? annotations;\n}\n","/**\n * Hook for configuring @dnd-kit sensors for clip dragging\n *\n * Provides consistent drag activation behavior across all examples.\n * Always overrides PointerSensor defaults with custom activation constraints:\n * - Default mode: distance-based activation (1px) for all pointer types\n * - Touch-optimized mode: delay-based activation for touch (250ms),\n * distance-based for mouse/pen\n */\n\nimport { useMemo } from 'react';\nimport { PointerSensor, PointerActivationConstraints } from '@dnd-kit/dom';\nimport type { PluginDescriptor } from '@dnd-kit/abstract';\n\nexport interface DragSensorOptions {\n /**\n * Enable mobile-optimized touch handling with delay-based activation.\n * When true, touch events get delay-based activation while mouse/pen get distance-based.\n * When false (default), all pointer types use distance-based activation (1px).\n */\n touchOptimized?: boolean;\n /**\n * Delay in milliseconds before touch drag activates (only when touchOptimized is true).\n * Default: 250ms - long enough to distinguish from scroll intent\n */\n touchDelay?: number;\n /**\n * Distance tolerance during touch delay (only when touchOptimized is true).\n * If finger moves more than this during delay, drag is cancelled.\n * Default: 5px - allows slight finger movement\n */\n touchTolerance?: number;\n /**\n * Distance in pixels before mouse drag activates.\n * Default: 1px for immediate feedback on desktop\n */\n mouseDistance?: number;\n}\n\n/**\n * Returns configured sensors for @dnd-kit drag operations\n *\n * @param options - Configuration options for drag sensors\n * @returns Array of sensor constructors/descriptors for DragDropProvider's sensors prop\n *\n * @example\n * // Desktop-optimized (default — 1px distance activation for all pointer types)\n * const sensors = useDragSensors();\n *\n * @example\n * // Mobile-optimized with custom touch delay\n * const sensors = useDragSensors({ touchOptimized: true, touchDelay: 300 });\n */\nexport function useDragSensors(\n options: DragSensorOptions = {}\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): (typeof PointerSensor | PluginDescriptor<any, any, any>)[] {\n const {\n touchOptimized = false,\n touchDelay = 250,\n touchTolerance = 5,\n mouseDistance = 1,\n } = options;\n\n return useMemo(() => {\n if (touchOptimized) {\n // Custom activation constraints for touch-optimized mode\n return [\n PointerSensor.configure({\n activationConstraints(event) {\n // Touch events get delay-based activation\n if (event.pointerType === 'touch') {\n return [\n new PointerActivationConstraints.Delay({\n value: touchDelay,\n tolerance: touchTolerance,\n }),\n ];\n }\n // Mouse/pen get distance-based activation\n return [new PointerActivationConstraints.Distance({ value: mouseDistance })];\n },\n }),\n ];\n }\n\n // Default: PointerSensor with distance-based activation\n return [\n PointerSensor.configure({\n activationConstraints: [\n new PointerActivationConstraints.Distance({ value: mouseDistance }),\n ],\n }),\n ];\n }, [touchOptimized, touchDelay, touchTolerance, mouseDistance]);\n}\n","import { useCallback } from 'react';\nimport { calculateSplitPoint, canSplitAt } from '@waveform-playlist/engine';\nimport {\n useArrangement,\n usePlaylistView,\n usePlaybackRefs,\n useSelectedTrackId,\n} from '../contexts/playlistContexts';\nimport { loadedClipsOf } from '../utils/loadedTracks';\n\nexport interface UseClipSplittingOptions {\n samplesPerPixel: number;\n}\n\nexport interface UseClipSplittingResult {\n splitClipAtPlayhead: () => boolean;\n splitClipAt: (trackId: string, clipId: string, splitTime: number) => boolean;\n}\n\n/**\n * Hook for splitting clips at the playhead or at a specific time\n *\n * Splitting is one `arrangement.splitClip()` on the provider's arrangement\n * (`useArrangement()`): an undo step, engine or not; the engine and the view\n * follow the arrangement. Throws outside `WaveformPlaylistProvider`.\n *\n * @param options - Configuration options\n * @returns Object with split functions\n *\n * @example\n * ```tsx\n * const { samplesPerPixel } = usePlaylistZoom();\n * const { splitClipAtPlayhead } = useClipSplitting({ samplesPerPixel });\n *\n * // In keyboard handler\n * const handleKeyPress = (e: KeyboardEvent) => {\n * if (e.key === 's' || e.key === 'S') {\n * splitClipAtPlayhead();\n * }\n * };\n * ```\n */\nexport const useClipSplitting = (options: UseClipSplittingOptions): UseClipSplittingResult => {\n const { samplesPerPixel } = options;\n const arrangement = useArrangement();\n const { sampleRate } = usePlaylistView();\n const { currentTimeRef } = usePlaybackRefs();\n const { selectedTrackId } = useSelectedTrackId();\n\n /**\n * Split a specific clip at a given time\n *\n * @param trackId - Id of the track containing the clip\n * @param clipId - Id of the clip\n * @param splitTime - Timeline position where to split (in seconds)\n * @returns true if pre-validation passed and the arrangement was called, false otherwise\n * (also for a track id or clip id that is not there, or a clip still loading:\n * nothing changes). Note: splitClip() returns void so a true here assumes the\n * arrangement accepted the split (it performs its own canSplitAt check).\n */\n const splitClipAt = useCallback(\n (trackId: string, clipId: string, splitTime: number): boolean => {\n const track = arrangement.getTracks().find((t) => t.id === trackId);\n if (!track) return false;\n\n // A clip still loading cannot be split.\n const clip = loadedClipsOf(track).find((c) => c.id === clipId);\n if (!clip) return false;\n\n // Convert split time to sample position, snapped to pixel boundary\n const splitSample = Math.round(splitTime * sampleRate);\n const snappedSplitSample = calculateSplitPoint(splitSample, samplesPerPixel);\n\n // Pre-flight validation before sending to engine (engine also validates internally).\n // Duplicated here to provide early user feedback via console.warn.\n const MIN_DURATION_SAMPLES = Math.floor(0.1 * sampleRate);\n if (!canSplitAt(clip, snappedSplitSample, MIN_DURATION_SAMPLES)) {\n console.warn('Split point is invalid (outside bounds or too close to edge)');\n return false;\n }\n\n arrangement.splitClip(track.id, clip.id, snappedSplitSample);\n return true;\n },\n [arrangement, samplesPerPixel, sampleRate]\n );\n\n /**\n * Split clip at the current playhead position on the selected track\n * If no track is selected, does nothing\n *\n * @returns true if a clip was split, false otherwise\n */\n const splitClipAtPlayhead = useCallback((): boolean => {\n // If no track is selected, cannot split\n if (!selectedTrackId) {\n console.warn('[waveform-playlist] No track selected — click a clip to select a track first');\n return false;\n }\n\n // Find the selected track\n const track = arrangement.getTracks().find((t) => t.id === selectedTrackId);\n if (!track) {\n console.warn('Selected track not found');\n return false;\n }\n\n // Use ref for real-time position during playback (state updates are throttled)\n const currentTime = currentTimeRef.current ?? 0;\n\n // Find clip at current time on the selected track\n for (const clip of loadedClipsOf(track)) {\n const clipStartTime = clip.startSample / sampleRate;\n const clipEndTime = (clip.startSample + clip.durationSamples) / sampleRate;\n\n // Check if currentTime is within this clip (not at boundaries)\n if (currentTime > clipStartTime && currentTime < clipEndTime) {\n // Found a clip! Split it\n return splitClipAt(track.id, clip.id, currentTime);\n }\n }\n\n console.warn(`[waveform-playlist] No clip found at playhead position on track \"${track.name}\"`);\n return false;\n }, [arrangement, currentTimeRef, selectedTrackId, splitClipAt, sampleRate]);\n\n return {\n splitClipAtPlayhead,\n splitClipAt,\n };\n};\n","import { useEffect, useRef } from 'react';\nimport { handleKeyboardEvent } from '@waveform-playlist/core';\nimport type { KeyboardShortcut } from '@waveform-playlist/core';\n\nexport interface UseKeyboardShortcutsOptions {\n shortcuts: KeyboardShortcut[];\n enabled?: boolean;\n}\n\n/**\n * Hook for managing keyboard shortcuts\n *\n * @param options - Configuration options\n *\n * @example\n * ```tsx\n * useKeyboardShortcuts({\n * shortcuts: [\n * {\n * key: ' ',\n * action: togglePlayPause,\n * description: 'Play/Pause',\n * preventDefault: true,\n * },\n * {\n * key: 's',\n * action: splitClipAtPlayhead,\n * description: 'Split clip at playhead',\n * preventDefault: true,\n * },\n * ],\n * });\n * ```\n */\nexport const useKeyboardShortcuts = (options: UseKeyboardShortcutsOptions): void => {\n const { shortcuts, enabled = true } = options;\n\n // The listener reads the latest shortcuts from a ref. Callers build the array\n // inline, so its identity changes on every render; keyed on it, the window\n // listener was removed and re-added each time.\n const shortcutsRef = useRef(shortcuts);\n useEffect(() => {\n shortcutsRef.current = shortcuts;\n });\n\n useEffect(() => {\n if (!enabled) return;\n\n const handleKeyDown = (event: KeyboardEvent) =>\n handleKeyboardEvent(event, shortcutsRef.current, true);\n window.addEventListener('keydown', handleKeyDown);\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown);\n };\n }, [enabled]);\n};\n","import { useCallback } from 'react';\nimport {\n usePlaybackControls,\n useIsPlaying,\n useWebAudioProviderOnly,\n} from '../contexts/playlistContexts';\nimport { usePlayFromSelectionOrCursor } from './usePlayFromSelectionOrCursor';\nimport type { KeyboardShortcut } from '@waveform-playlist/core';\nimport { useKeyboardShortcuts } from './useKeyboardShortcuts';\n\nexport interface UsePlaybackShortcutsOptions {\n /**\n * Enable the shortcuts. Defaults to true.\n */\n enabled?: boolean;\n /**\n * Additional shortcuts to include alongside the default playback shortcuts.\n */\n additionalShortcuts?: KeyboardShortcut[];\n /**\n * Override default shortcuts. If provided, only these shortcuts will be used.\n */\n shortcuts?: KeyboardShortcut[];\n}\n\nexport interface UsePlaybackShortcutsReturn {\n /** Rewind to the beginning (time = 0) */\n rewindToStart: () => void;\n /** Toggle play/pause */\n togglePlayPause: () => void;\n /** Stop playback and return to start position */\n stopPlayback: () => void;\n /** The list of active keyboard shortcuts */\n shortcuts: KeyboardShortcut[];\n}\n\n/**\n * Hook that provides common playback keyboard shortcuts for the playlist.\n *\n * Default shortcuts:\n * - `Space` - Toggle play/pause\n * - `Escape` - Stop playback\n * - `0` - Rewind to start (seek to time 0)\n *\n * @example\n * ```tsx\n * // Basic usage - enables default shortcuts\n * usePlaybackShortcuts();\n *\n * // With additional custom shortcuts\n * usePlaybackShortcuts({\n * additionalShortcuts: [\n * { key: 's', action: splitClipAtPlayhead, description: 'Split clip' },\n * ],\n * });\n *\n * // Completely override shortcuts\n * usePlaybackShortcuts({\n * shortcuts: [\n * { key: 'Home', action: rewindToStart, description: 'Go to start' },\n * ],\n * });\n * ```\n */\nexport const usePlaybackShortcuts = (\n options: UsePlaybackShortcutsOptions = {}\n): UsePlaybackShortcutsReturn => {\n const { enabled = true, additionalShortcuts = [], shortcuts: overrideShortcuts } = options;\n\n // The keys act on the whole window, so this hook is not for a page that may\n // hold several single-track players (maintainer's decision, #688).\n useWebAudioProviderOnly('usePlaybackShortcuts');\n const { isPlaying } = useIsPlaying();\n const { seekTo, pause, stop } = usePlaybackControls();\n // Space starts playback exactly as the Play button does.\n const playFromSelectionOrCursor = usePlayFromSelectionOrCursor();\n\n /**\n * Toggle between play and pause.\n */\n const togglePlayPause = useCallback(() => {\n if (isPlaying) {\n pause();\n } else {\n playFromSelectionOrCursor().catch((err) => {\n console.warn('[waveform-playlist] Playback failed to start: ' + String(err));\n });\n }\n }, [isPlaying, playFromSelectionOrCursor, pause]);\n\n /**\n * Stop playback and return to start position.\n */\n const stopPlayback = useCallback(() => {\n stop();\n }, [stop]);\n\n /**\n * Rewind to the beginning of the timeline.\n * If playing, stops and restarts playback from the beginning.\n */\n const rewindToStart = useCallback(() => {\n seekTo(0);\n }, [seekTo]);\n\n // Default playback shortcuts\n const defaultShortcuts: KeyboardShortcut[] = [\n {\n key: ' ',\n action: togglePlayPause,\n description: 'Play/Pause',\n preventDefault: true,\n },\n {\n key: 'Escape',\n action: stopPlayback,\n description: 'Stop',\n preventDefault: true,\n },\n {\n key: '0',\n action: rewindToStart,\n description: 'Rewind to start',\n preventDefault: true,\n },\n ];\n\n // Use override shortcuts if provided, otherwise combine defaults with additional\n const activeShortcuts = overrideShortcuts ?? [...defaultShortcuts, ...additionalShortcuts];\n\n // Register the keyboard shortcuts\n useKeyboardShortcuts({\n shortcuts: activeShortcuts,\n enabled,\n });\n\n return {\n rewindToStart,\n togglePlayPause,\n stopPlayback,\n shortcuts: activeShortcuts,\n };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n usePlaybackControls,\n useSelection,\n usePlaybackRefs,\n useLoopOptional,\n} from '../contexts/playlistContexts';\n\n/**\n * The one way playback is started by the built-in controls, so the Play button\n * and the Space shortcut cannot drift apart:\n *\n * - a highlighted selection, with looping off: play the selection, then stop.\n * If the cursor is inside the selection (playback was paused there), resume\n * from the cursor to the selection's end instead of starting over;\n * - otherwise: play from the cursor. With looping on, the transport's own loop\n * handles the boundaries.\n *\n * The returned function keeps its identity; it reads the latest selection and\n * loop state when it is called.\n */\nexport function usePlayFromSelectionOrCursor(): () => Promise<void> {\n const { currentTimeRef } = usePlaybackRefs();\n const { selectionStart, selectionEnd } = useSelection();\n // No loop under the MediaElement provider.\n const isLoopEnabled = useLoopOptional()?.isLoopEnabled ?? false;\n const { play } = usePlaybackControls();\n\n const latest = useRef({ selectionStart, selectionEnd, isLoopEnabled });\n useEffect(() => {\n latest.current = { selectionStart, selectionEnd, isLoopEnabled };\n });\n\n return useCallback(async () => {\n const { selectionStart: start, selectionEnd: end, isLoopEnabled: looping } = latest.current;\n const cursor = currentTimeRef.current ?? 0;\n if (end > start && !looping) {\n // Paused part-way through the selection: carry on from the cursor.\n const from = cursor > start && cursor < end ? cursor : start;\n await play(from, end - from);\n } else {\n await play(cursor);\n }\n }, [play, currentTimeRef]);\n}\n","import { useCallback, useMemo, useEffect } from 'react';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport { usePlaylistViewOptional, usePlaylistZoomOptional } from '../contexts/playlistContexts';\nimport { useKeyboardShortcuts } from './useKeyboardShortcuts';\n\nconst LINK_THRESHOLD = 0.01; // Consider edges \"linked\" if within 10ms\nconst TIME_DELTA = 0.01; // 10ms adjustment per keypress\n\ninterface UseAnnotationKeyboardControlsOptions {\n annotations: AnnotationData[];\n activeAnnotationId: string | null;\n onAnnotationsChange: (annotations: AnnotationData[]) => void;\n /** Callback to set the active annotation ID for selection */\n onActiveAnnotationChange?: (id: string | null) => void;\n duration: number;\n linkEndpoints: boolean;\n /** Whether continuous play is enabled (affects playback duration) */\n continuousPlay?: boolean;\n enabled?: boolean;\n /** Optional: scroll container ref for auto-scrolling to annotation */\n scrollContainerRef?: React.RefObject<HTMLDivElement | null>;\n /** Optional: callback to start playback at a time with optional duration */\n onPlay?: (startTime: number, duration?: number) => void;\n /**\n * Pixels-per-sample for auto-scroll positioning. Falls back to the\n * WaveformPlaylistProvider context when omitted (WebAudio path). Pass\n * explicitly when used outside that provider (e.g. the MediaElement path).\n */\n samplesPerPixel?: number;\n /** Sample rate for auto-scroll positioning. Falls back to context. */\n sampleRate?: number;\n}\n\n/**\n * Hook for keyboard-based annotation navigation and boundary editing\n *\n * Navigation Shortcuts:\n * - ArrowUp / ArrowLeft = Select previous annotation\n * - ArrowDown / ArrowRight = Select next annotation\n * - Home = Select first annotation\n * - End = Select last annotation\n * - Escape = Deselect annotation\n * - Enter = Play selected annotation\n *\n * Boundary Editing Shortcuts (requires active annotation):\n * - [ = Move start boundary earlier (left)\n * - ] = Move start boundary later (right)\n * - Shift+[ = Move end boundary earlier (left)\n * - Shift+] = Move end boundary later (right)\n *\n * Respects linkEndpoints and continuousPlay settings.\n *\n * @example\n * ```tsx\n * useAnnotationKeyboardControls({\n * annotations,\n * activeAnnotationId,\n * onAnnotationsChange: setAnnotations,\n * onActiveAnnotationChange: setActiveAnnotationId,\n * duration,\n * linkEndpoints,\n * });\n * ```\n */\nexport function useAnnotationKeyboardControls({\n annotations,\n activeAnnotationId,\n onAnnotationsChange,\n onActiveAnnotationChange,\n duration,\n linkEndpoints,\n continuousPlay = false,\n enabled = true,\n scrollContainerRef,\n onPlay,\n samplesPerPixel: samplesPerPixelProp,\n sampleRate: sampleRateProp,\n}: UseAnnotationKeyboardControlsOptions) {\n // Auto-scroll positioning needs samplesPerPixel/sampleRate. Prefer explicit\n // props (works in the MediaElement path); otherwise read them from the\n // provider's contexts (either provider renders them). The optional readers\n // return null instead of throwing, so this hook is safe outside a provider.\n const playlistView = usePlaylistViewOptional();\n const playlistZoom = usePlaylistZoomOptional();\n const samplesPerPixel = samplesPerPixelProp ?? playlistZoom?.samplesPerPixel;\n const sampleRate = sampleRateProp ?? playlistView?.sampleRate;\n\n const activeIndex = useMemo(() => {\n if (!activeAnnotationId) return -1;\n return annotations.findIndex((a) => a.id === activeAnnotationId);\n }, [annotations, activeAnnotationId]);\n\n // Scroll waveform to show a specific annotation\n const scrollToAnnotation = useCallback(\n (annotationId: string) => {\n if (!scrollContainerRef?.current || !samplesPerPixel || !sampleRate) return;\n\n const annotation = annotations.find((a) => a.id === annotationId);\n if (!annotation) return;\n\n const container = scrollContainerRef.current;\n const containerWidth = container.clientWidth;\n\n // Calculate pixel positions for annotation start and center\n const startPixel = (annotation.start * sampleRate) / samplesPerPixel;\n const endPixel = (annotation.end * sampleRate) / samplesPerPixel;\n const annotationCenter = (startPixel + endPixel) / 2;\n\n // Check if annotation is currently visible\n const scrollLeft = container.scrollLeft;\n const visibleStart = scrollLeft;\n const visibleEnd = scrollLeft + containerWidth;\n\n // If annotation is not fully visible, scroll to center it\n if (startPixel < visibleStart || endPixel > visibleEnd) {\n const targetScrollLeft = Math.max(0, annotationCenter - containerWidth / 2);\n container.scrollTo({\n left: targetScrollLeft,\n behavior: 'smooth',\n });\n }\n },\n [annotations, scrollContainerRef, samplesPerPixel, sampleRate]\n );\n\n // Auto-scroll when active annotation changes via keyboard navigation\n useEffect(() => {\n if (activeAnnotationId && scrollContainerRef?.current && samplesPerPixel && sampleRate) {\n scrollToAnnotation(activeAnnotationId);\n }\n }, [activeAnnotationId, scrollToAnnotation, scrollContainerRef, samplesPerPixel, sampleRate]);\n\n const moveStartBoundary = useCallback(\n (delta: number) => {\n if (activeIndex < 0) return;\n\n const annotation = annotations[activeIndex];\n const newStart = Math.max(0, Math.min(annotation.end - 0.1, annotation.start + delta));\n const actualDelta = newStart - annotation.start;\n\n const updatedAnnotations = [...annotations];\n updatedAnnotations[activeIndex] = {\n ...annotation,\n start: newStart,\n };\n\n // Handle linked endpoints\n if (linkEndpoints && activeIndex > 0) {\n const prevAnnotation = updatedAnnotations[activeIndex - 1];\n if (Math.abs(prevAnnotation.end - annotation.start) < LINK_THRESHOLD) {\n // Already linked: move previous annotation's end together\n updatedAnnotations[activeIndex - 1] = {\n ...prevAnnotation,\n end: Math.max(prevAnnotation.start + 0.1, prevAnnotation.end + actualDelta),\n };\n }\n } else if (!linkEndpoints && activeIndex > 0) {\n // Non-linked mode: don't overlap previous annotation\n const prevAnnotation = updatedAnnotations[activeIndex - 1];\n if (newStart < prevAnnotation.end) {\n // Push back previous annotation's end\n updatedAnnotations[activeIndex - 1] = {\n ...prevAnnotation,\n end: newStart,\n };\n }\n }\n\n onAnnotationsChange(updatedAnnotations);\n },\n [annotations, activeIndex, linkEndpoints, onAnnotationsChange]\n );\n\n const moveEndBoundary = useCallback(\n (delta: number) => {\n if (activeIndex < 0) return;\n\n const annotation = annotations[activeIndex];\n const newEnd = Math.max(annotation.start + 0.1, Math.min(duration, annotation.end + delta));\n const actualDelta = newEnd - annotation.end;\n\n const updatedAnnotations = [...annotations];\n updatedAnnotations[activeIndex] = {\n ...annotation,\n end: newEnd,\n };\n\n // Handle linked endpoints\n if (linkEndpoints && activeIndex < annotations.length - 1) {\n const nextAnnotation = updatedAnnotations[activeIndex + 1];\n if (Math.abs(nextAnnotation.start - annotation.end) < LINK_THRESHOLD) {\n // Already linked: move next annotation's start together\n const newNextStart = Math.min(\n nextAnnotation.end - 0.1,\n nextAnnotation.start + actualDelta\n );\n updatedAnnotations[activeIndex + 1] = {\n ...nextAnnotation,\n start: newNextStart,\n };\n\n // Cascade linked endpoints\n let currentIndex = activeIndex + 1;\n while (currentIndex < updatedAnnotations.length - 1) {\n const current = updatedAnnotations[currentIndex];\n const next = updatedAnnotations[currentIndex + 1];\n\n if (Math.abs(next.start - annotations[currentIndex].end) < LINK_THRESHOLD) {\n const nextDelta = current.end - annotations[currentIndex].end;\n updatedAnnotations[currentIndex + 1] = {\n ...next,\n start: Math.min(next.end - 0.1, next.start + nextDelta),\n };\n currentIndex++;\n } else {\n break;\n }\n }\n }\n } else if (!linkEndpoints && activeIndex < annotations.length - 1) {\n // Non-linked mode: don't overlap next annotation\n const nextAnnotation = updatedAnnotations[activeIndex + 1];\n if (newEnd > nextAnnotation.start) {\n // Push forward next annotation's start\n updatedAnnotations[activeIndex + 1] = {\n ...nextAnnotation,\n start: newEnd,\n };\n\n // Cascade collisions\n let currentIndex = activeIndex + 1;\n while (currentIndex < updatedAnnotations.length - 1) {\n const current = updatedAnnotations[currentIndex];\n const next = updatedAnnotations[currentIndex + 1];\n\n if (current.end > next.start) {\n updatedAnnotations[currentIndex + 1] = {\n ...next,\n start: current.end,\n };\n currentIndex++;\n } else {\n break;\n }\n }\n }\n }\n\n onAnnotationsChange(updatedAnnotations);\n },\n [annotations, activeIndex, duration, linkEndpoints, onAnnotationsChange]\n );\n\n // Navigation functions\n const selectPrevious = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n\n if (activeIndex <= 0) {\n // If no selection or at first, select last annotation\n onActiveAnnotationChange(annotations[annotations.length - 1].id);\n } else {\n onActiveAnnotationChange(annotations[activeIndex - 1].id);\n }\n }, [annotations, activeIndex, onActiveAnnotationChange]);\n\n const selectNext = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n\n if (activeIndex < 0 || activeIndex >= annotations.length - 1) {\n // If no selection or at last, select first annotation\n onActiveAnnotationChange(annotations[0].id);\n } else {\n onActiveAnnotationChange(annotations[activeIndex + 1].id);\n }\n }, [annotations, activeIndex, onActiveAnnotationChange]);\n\n const selectFirst = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n onActiveAnnotationChange(annotations[0].id);\n }, [annotations, onActiveAnnotationChange]);\n\n const selectLast = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n onActiveAnnotationChange(annotations[annotations.length - 1].id);\n }, [annotations, onActiveAnnotationChange]);\n\n const clearSelection = useCallback(() => {\n if (!onActiveAnnotationChange) return;\n onActiveAnnotationChange(null);\n }, [onActiveAnnotationChange]);\n\n // Play the currently selected annotation\n const playActiveAnnotation = useCallback(() => {\n if (activeIndex < 0 || !onPlay) return;\n\n const annotation = annotations[activeIndex];\n // If continuous play is off, play just this annotation's duration\n const playDuration = !continuousPlay ? annotation.end - annotation.start : undefined;\n onPlay(annotation.start, playDuration);\n }, [annotations, activeIndex, continuousPlay, onPlay]);\n\n // Shortcuts that require an active annotation (boundary editing + playback)\n const activeAnnotationShortcuts = useMemo(\n () => [\n {\n key: '[',\n action: () => moveStartBoundary(-TIME_DELTA),\n description: 'Move annotation start earlier',\n preventDefault: true,\n },\n {\n key: ']',\n action: () => moveStartBoundary(TIME_DELTA),\n description: 'Move annotation start later',\n preventDefault: true,\n },\n {\n key: '{',\n shiftKey: true,\n action: () => moveEndBoundary(-TIME_DELTA),\n description: 'Move annotation end earlier',\n preventDefault: true,\n },\n {\n key: '}',\n shiftKey: true,\n action: () => moveEndBoundary(TIME_DELTA),\n description: 'Move annotation end later',\n preventDefault: true,\n },\n {\n key: 'Enter',\n action: playActiveAnnotation,\n description: 'Play selected annotation',\n preventDefault: true,\n },\n ],\n [moveStartBoundary, moveEndBoundary, playActiveAnnotation]\n );\n\n // Navigation shortcuts (always active when enabled and there are annotations)\n const navigationShortcuts = useMemo(\n () => [\n {\n key: 'ArrowUp',\n action: selectPrevious,\n description: 'Select previous annotation',\n preventDefault: true,\n },\n {\n key: 'ArrowLeft',\n action: selectPrevious,\n description: 'Select previous annotation',\n preventDefault: true,\n },\n {\n key: 'ArrowDown',\n action: selectNext,\n description: 'Select next annotation',\n preventDefault: true,\n },\n {\n key: 'ArrowRight',\n action: selectNext,\n description: 'Select next annotation',\n preventDefault: true,\n },\n {\n key: 'Home',\n action: selectFirst,\n description: 'Select first annotation',\n preventDefault: true,\n },\n {\n key: 'End',\n action: selectLast,\n description: 'Select last annotation',\n preventDefault: true,\n },\n {\n key: 'Escape',\n action: clearSelection,\n description: 'Deselect annotation',\n preventDefault: true,\n },\n ],\n [selectPrevious, selectNext, selectFirst, selectLast, clearSelection]\n );\n\n // Active annotation shortcuts only work when an annotation is selected\n useKeyboardShortcuts({\n shortcuts: activeAnnotationShortcuts,\n enabled: enabled && activeIndex >= 0,\n });\n\n // Navigation shortcuts work whenever there are annotations\n useKeyboardShortcuts({\n shortcuts: navigationShortcuts,\n enabled: enabled && annotations.length > 0 && !!onActiveAnnotationChange,\n });\n\n return {\n moveStartBoundary,\n moveEndBoundary,\n selectPrevious,\n selectNext,\n selectFirst,\n selectLast,\n clearSelection,\n scrollToAnnotation,\n playActiveAnnotation,\n };\n}\n","import { useCallback, useEffect, useRef } from 'react';\n\nexport interface AnimationFrameLoopControls {\n animationFrameRef: React.MutableRefObject<number | null>;\n startAnimationFrameLoop: (callback: () => void) => void;\n stopAnimationFrameLoop: () => void;\n}\n\n/**\n * Shared RAF loop controller used by playlist providers.\n * Always guarantees a single in-flight animation frame.\n */\nexport const useAnimationFrameLoop = (): AnimationFrameLoopControls => {\n const animationFrameRef = useRef<number | null>(null);\n\n const stopAnimationFrameLoop = useCallback(() => {\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n animationFrameRef.current = null;\n }\n }, []);\n\n const startAnimationFrameLoop = useCallback(\n (callback: () => void) => {\n stopAnimationFrameLoop();\n animationFrameRef.current = requestAnimationFrame(callback);\n },\n [stopAnimationFrameLoop]\n );\n\n useEffect(() => {\n return () => {\n stopAnimationFrameLoop();\n };\n }, [stopAnimationFrameLoop]);\n\n return {\n animationFrameRef,\n startAnimationFrameLoop,\n stopAnimationFrameLoop,\n };\n};\n","/**\n * useWaveformDataCache\n *\n * Generates a WaveformData object per unique AudioBuffer in a web worker.\n * These enable near-instant zoom changes via WaveformData.resample() instead\n * of re-scanning raw audio samples.\n *\n * Results are looked up by AudioBuffer during render (`getWaveformData`), so a\n * `tracks` change that only rearranges clips of already-generated buffers\n * causes no state update here (#692). The only state is `version`, bumped when\n * a worker job finishes: depend on it to recompute peaks for the clips that\n * share that buffer.\n *\n * Behavior:\n * - Creates the worker lazily on first clip needing generation\n * - Generates waveform data once per unique AudioBuffer; a job keeps running\n * across `tracks` changes\n * - A failed job is tried again on the next `tracks` change, three attempts\n * per buffer in all\n * - Terminates the worker on unmount\n */\n\nimport { useState, useEffect, useRef, useCallback } from 'react';\nimport type { ClipTrack } from '@waveform-playlist/core';\nimport type WaveformData from 'waveform-data';\nimport { createPeaksWorker, type PeaksWorkerApi } from '../workers/peaksWorker';\n\nexport interface UseWaveformDataCacheReturn {\n /** Worker-generated waveform data for a buffer, once ready. Stable identity. */\n getWaveformData: (audioBuffer: AudioBuffer) => WaveformData | undefined;\n /** Bumped each time a buffer's waveform data becomes available. */\n version: number;\n}\n\n/**\n * Attempts per buffer before giving up. A failed job is tried again on the\n * next `tracks` change (a crashed worker is replaced), but a buffer that can\n * never succeed (a CSP that blocks blob workers) must not be copied and sent\n * again on every change of the tracks.\n */\nconst MAX_GENERATION_ATTEMPTS = 3;\n\nfunction buffersNeedingGeneration(\n tracks: readonly ClipTrack[],\n generated: WeakMap<AudioBuffer, WaveformData>,\n inflight: WeakMap<AudioBuffer, Promise<void>>,\n failures: WeakMap<AudioBuffer, number>\n): Set<AudioBuffer> {\n const buffers = new Set<AudioBuffer>();\n for (const track of tracks) {\n for (const clip of track.clips) {\n // Clips with their own waveformData never need the worker.\n if (!clip.audioBuffer || clip.waveformData) continue;\n if (generated.has(clip.audioBuffer) || inflight.has(clip.audioBuffer)) continue;\n if ((failures.get(clip.audioBuffer) ?? 0) >= MAX_GENERATION_ATTEMPTS) continue;\n buffers.add(clip.audioBuffer);\n }\n }\n return buffers;\n}\n\nexport function useWaveformDataCache(\n tracks: readonly ClipTrack[],\n baseScale: number\n): UseWaveformDataCacheReturn {\n const [version, setVersion] = useState(0);\n\n const workerRef = useRef<PeaksWorkerApi | null>(null);\n const generatedByBufferRef = useRef<WeakMap<AudioBuffer, WaveformData>>(new WeakMap());\n const inflightByBufferRef = useRef<WeakMap<AudioBuffer, Promise<void>>>(new WeakMap());\n const failuresByBufferRef = useRef<WeakMap<AudioBuffer, number>>(new WeakMap());\n // Changes on unmount. A job started in an earlier mount (StrictMode\n // remounts, or a real unmount) must not set state or warn.\n const mountSessionRef = useRef(0);\n\n // Stable callback to get or create the worker.\n // Also replaces a crashed worker (onerror marks it terminated) — reusing\n // it would reject every later generation until the component remounts.\n const getWorker = useCallback(() => {\n if (!workerRef.current || workerRef.current.isTerminated()) {\n workerRef.current = createPeaksWorker();\n }\n return workerRef.current;\n }, []);\n\n const getWaveformData = useCallback(\n (audioBuffer: AudioBuffer) => generatedByBufferRef.current.get(audioBuffer),\n []\n );\n\n useEffect(() => {\n const generatedByBuffer = generatedByBufferRef.current;\n const inflightByBuffer = inflightByBufferRef.current;\n const session = mountSessionRef.current;\n const failuresByBuffer = failuresByBufferRef.current;\n const buffers = buffersNeedingGeneration(\n tracks,\n generatedByBuffer,\n inflightByBuffer,\n failuresByBuffer\n );\n if (buffers.size === 0) return;\n\n const worker = getWorker();\n\n for (const audioBuffer of buffers) {\n // .slice() channel buffers to avoid detaching the original AudioBuffer views\n const channels: ArrayBuffer[] = [];\n for (let c = 0; c < audioBuffer.numberOfChannels; c++) {\n channels.push(audioBuffer.getChannelData(c).slice().buffer as ArrayBuffer);\n }\n\n // Only clear the in-flight marker if it is still this job's: after an\n // unmount the map is replaced and a new job may own the buffer.\n const settle = () => {\n if (inflightByBuffer.get(audioBuffer) === job) {\n inflightByBuffer.delete(audioBuffer);\n }\n };\n\n const id = `buffer-${Math.random().toString(36).slice(2, 11)}`;\n const job: Promise<void> = worker\n .generate({\n id,\n channels,\n length: audioBuffer.length,\n sampleRate: audioBuffer.sampleRate,\n scale: baseScale,\n bits: 16,\n splitChannels: true,\n })\n .then((waveformData) => {\n generatedByBuffer.set(audioBuffer, waveformData);\n settle();\n if (mountSessionRef.current !== session) return;\n setVersion((v) => v + 1);\n })\n .catch((err) => {\n settle();\n // A job rejected by the unmount's terminate() is not a failure of\n // the buffer.\n if (mountSessionRef.current !== session) return;\n const attempts = (failuresByBuffer.get(audioBuffer) ?? 0) + 1;\n failuresByBuffer.set(audioBuffer, attempts);\n console.warn(\n '[waveform-playlist] Worker peak generation failed' +\n (attempts >= MAX_GENERATION_ATTEMPTS\n ? ' ' + attempts + ' times, giving up on this audio buffer: '\n : ': ') +\n String(err)\n );\n });\n\n inflightByBuffer.set(audioBuffer, job);\n }\n }, [tracks, baseScale, getWorker]);\n\n // Terminate worker on unmount. Terminating rejects the jobs still running,\n // so forget them: a remount (StrictMode) starts them again on a new worker.\n useEffect(() => {\n return () => {\n mountSessionRef.current += 1;\n inflightByBufferRef.current = new WeakMap();\n workerRef.current?.terminate();\n workerRef.current = null;\n };\n }, []);\n\n return { getWaveformData, version };\n}\n","/**\n * Inline Web Worker for generating WaveformData binary format from AudioBuffer channels.\n *\n * Uses a Blob URL approach (portable across all bundlers) with the generateWaveformData\n * algorithm adapted from BBC's waveform-data.js (MIT licensed, adapted from Audacity).\n *\n * The worker generates peaks at a base scale (finest zoom level). The main thread\n * then uses WaveformData.resample() for near-instant zoom changes.\n */\n\nimport WaveformData from 'waveform-data';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Worker code (runs inside the Blob URL worker)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Self-contained worker source.\n * Contains the generateWaveformData function from waveform-data.js/src/waveform-generator.js\n * (MIT License, BBC). Pure JS, zero dependencies.\n */\nconst workerSource = `\n\"use strict\";\n\nvar INT8_MAX = 127;\nvar INT8_MIN = -128;\nvar INT16_MAX = 32767;\nvar INT16_MIN = -32768;\n\nfunction calculateWaveformDataLength(audio_sample_count, scale) {\n var data_length = Math.floor(audio_sample_count / scale);\n var samples_remaining = audio_sample_count - (data_length * scale);\n if (samples_remaining > 0) {\n data_length++;\n }\n return data_length;\n}\n\nfunction generateWaveformData(options) {\n var scale = options.scale;\n var amplitude_scale = options.amplitude_scale;\n var split_channels = options.split_channels;\n var length = options.length;\n var sample_rate = options.sample_rate;\n var channels = options.channels.map(function(channel) {\n return new Float32Array(channel);\n });\n var output_channels = split_channels ? channels.length : 1;\n var header_size = 24;\n var data_length = calculateWaveformDataLength(length, scale);\n var bytes_per_sample = options.bits === 8 ? 1 : 2;\n var total_size = header_size + data_length * 2 * bytes_per_sample * output_channels;\n var buffer = new ArrayBuffer(total_size);\n var data_view = new DataView(buffer);\n\n var scale_counter = 0;\n var offset = header_size;\n\n var min_value = new Array(output_channels);\n var max_value = new Array(output_channels);\n\n for (var channel = 0; channel < output_channels; channel++) {\n min_value[channel] = Infinity;\n max_value[channel] = -Infinity;\n }\n\n var range_min = options.bits === 8 ? INT8_MIN : INT16_MIN;\n var range_max = options.bits === 8 ? INT8_MAX : INT16_MAX;\n\n data_view.setInt32(0, 2, true);\n data_view.setUint32(4, options.bits === 8, true);\n data_view.setInt32(8, sample_rate, true);\n data_view.setInt32(12, scale, true);\n data_view.setInt32(16, data_length, true);\n data_view.setInt32(20, output_channels, true);\n\n for (var i = 0; i < length; i++) {\n var sample = 0;\n\n if (output_channels === 1) {\n for (var ch = 0; ch < channels.length; ++ch) {\n sample += channels[ch][i];\n }\n sample = Math.floor(range_max * sample * amplitude_scale / channels.length);\n\n if (sample < min_value[0]) {\n min_value[0] = sample;\n if (min_value[0] < range_min) {\n min_value[0] = range_min;\n }\n }\n if (sample > max_value[0]) {\n max_value[0] = sample;\n if (max_value[0] > range_max) {\n max_value[0] = range_max;\n }\n }\n }\n else {\n for (var ch2 = 0; ch2 < output_channels; ++ch2) {\n sample = Math.floor(range_max * channels[ch2][i] * amplitude_scale);\n\n if (sample < min_value[ch2]) {\n min_value[ch2] = sample;\n if (min_value[ch2] < range_min) {\n min_value[ch2] = range_min;\n }\n }\n if (sample > max_value[ch2]) {\n max_value[ch2] = sample;\n if (max_value[ch2] > range_max) {\n max_value[ch2] = range_max;\n }\n }\n }\n }\n\n if (++scale_counter === scale) {\n for (var ch3 = 0; ch3 < output_channels; ch3++) {\n if (options.bits === 8) {\n data_view.setInt8(offset++, min_value[ch3]);\n data_view.setInt8(offset++, max_value[ch3]);\n }\n else {\n data_view.setInt16(offset, min_value[ch3], true);\n data_view.setInt16(offset + 2, max_value[ch3], true);\n offset += 4;\n }\n min_value[ch3] = Infinity;\n max_value[ch3] = -Infinity;\n }\n scale_counter = 0;\n }\n }\n\n if (scale_counter > 0) {\n for (var ch4 = 0; ch4 < output_channels; ch4++) {\n if (options.bits === 8) {\n data_view.setInt8(offset++, min_value[ch4]);\n data_view.setInt8(offset++, max_value[ch4]);\n }\n else {\n data_view.setInt16(offset, min_value[ch4], true);\n data_view.setInt16(offset + 2, max_value[ch4], true);\n }\n }\n }\n\n return buffer;\n}\n\nself.onmessage = function(e) {\n var msg = e.data;\n try {\n var result = generateWaveformData({\n scale: msg.scale,\n bits: msg.bits,\n amplitude_scale: msg.amplitude_scale,\n split_channels: msg.split_channels,\n length: msg.length,\n sample_rate: msg.sample_rate,\n channels: msg.channels\n });\n self.postMessage({ id: msg.id, buffer: result }, [result]);\n } catch (err) {\n self.postMessage({ id: msg.id, error: err.message || String(err) });\n }\n};\n`;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Promise-based worker API (runs on the main thread)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface PeaksWorkerApi {\n generate(params: {\n id: string;\n channels: ArrayBuffer[];\n length: number;\n sampleRate: number;\n scale: number;\n bits: 8 | 16;\n splitChannels: boolean;\n }): Promise<WaveformData>;\n /** True once the worker has crashed (onerror) or been terminated — every\n * generate() will reject. Callers should discard this instance and create\n * a fresh worker. */\n isTerminated(): boolean;\n terminate(): void;\n}\n\ninterface PendingEntry {\n resolve: (value: WaveformData) => void;\n reject: (reason: unknown) => void;\n}\n\nlet idCounter = 0;\n\nexport function createPeaksWorker(): PeaksWorkerApi {\n let worker: Worker;\n try {\n const blob = new Blob([workerSource], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n worker = new Worker(url);\n URL.revokeObjectURL(url);\n } catch (err) {\n // Worker creation can fail in CSP-restricted environments that block blob: URLs.\n // Return a no-op API that rejects all generate calls gracefully.\n console.warn('[waveform-playlist] Failed to create peaks worker (CSP restriction?):', err);\n return {\n generate() {\n return Promise.reject(new Error('Worker creation failed'));\n },\n // Reports NOT terminated: CSP blocking is permanent for the page, so\n // recreating on every call would just re-attempt (and re-warn about)\n // Worker construction each time.\n isTerminated() {\n return false;\n },\n terminate() {\n /* no-op */\n },\n };\n }\n\n const pending = new Map<string, PendingEntry>();\n let terminated = false;\n\n worker.onmessage = (e: MessageEvent) => {\n const msg = e.data;\n const entry = pending.get(msg.id);\n if (!entry) return;\n pending.delete(msg.id);\n\n if (msg.error) {\n entry.reject(new Error(msg.error));\n } else {\n try {\n const waveformData = WaveformData.create(msg.buffer);\n entry.resolve(waveformData);\n } catch (err) {\n entry.reject(err);\n }\n }\n };\n\n worker.onerror = (e: ErrorEvent) => {\n terminated = true;\n worker.terminate();\n for (const [, entry] of pending) {\n entry.reject(e.error ?? new Error(e.message));\n }\n pending.clear();\n };\n\n return {\n isTerminated() {\n return terminated;\n },\n\n generate(params) {\n if (terminated) return Promise.reject(new Error('Worker terminated'));\n const messageId = String(++idCounter);\n\n return new Promise<WaveformData>((resolve, reject) => {\n pending.set(messageId, { resolve, reject });\n\n worker.postMessage(\n {\n id: messageId,\n scale: params.scale,\n bits: params.bits,\n amplitude_scale: 1.0,\n split_channels: params.splitChannels,\n length: params.length,\n sample_rate: params.sampleRate,\n channels: params.channels,\n },\n params.channels // Transfer ownership\n );\n });\n },\n\n terminate() {\n terminated = true;\n worker.terminate();\n for (const [, entry] of pending) {\n entry.reject(new Error('Worker terminated'));\n }\n pending.clear();\n },\n };\n}\n","import { useState } from 'react';\nimport { createArrangement } from '@waveform-playlist/engine';\nimport type { Arrangement, LoadSource } from '@waveform-playlist/engine';\nimport type { ArrangementTrack } from '@waveform-playlist/core';\n\nexport interface UseCreateArrangementOptions {\n /** How a clip's source is fetched and decoded. Nothing is fetched until a decode context is attached. */\n loadSource?: LoadSource;\n /** How many undo steps the arrangement keeps. */\n undoLimit?: number;\n}\n\n/**\n * Create the `Arrangement` that owns a multitrack editor's tracks, one per\n * component instance. Returns the same arrangement on every render.\n *\n * `init` and `options` are read once, on the first render; a later render\n * with other values changes nothing. An initializer that throws (a track\n * with a wrong kind, a duplicate track id, two clips with one id) throws out\n * of the render, to the nearest error boundary.\n *\n * Under StrictMode React calls the initializer twice and keeps one result;\n * neither arrangement fetches anything, because none has a decode context.\n */\nexport function useCreateArrangement(\n init?: () => readonly ArrangementTrack[],\n options?: UseCreateArrangementOptions\n): Arrangement {\n // Only the two documented options: a stray `tracks` key (plain JS) must not\n // replace what the initializer returns.\n const [arrangement] = useState(() =>\n createArrangement({\n tracks: init?.(),\n loadSource: options?.loadSource,\n undoLimit: options?.undoLimit,\n })\n );\n return arrangement;\n}\n","import { useMemo, useSyncExternalStore } from 'react';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport type { ArrangementTrack } from '@waveform-playlist/core';\n\n/**\n * The tracks of `arrangement`, loaded and loading clips alike. The same\n * array until the tracks change: a mix change (volume, mute, solo, pan)\n * does not re-render. Never write to what it returns.\n */\nexport function useArrangementTracks(arrangement: Arrangement): readonly ArrangementTrack[] {\n const store = useMemo(\n () => ({\n subscribe: (listener: () => void) => arrangement.subscribe(listener),\n getSnapshot: () => arrangement.getTracks(),\n }),\n [arrangement]\n );\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n","import { useMemo, useSyncExternalStore } from 'react';\nimport type { Arrangement, ArrangementSourcesValue } from '@waveform-playlist/engine';\n\n/**\n * The audio sources the clips of `arrangement` name, and whether each is\n * pending, loaded or failed. The same object until a source settles or the\n * set of sources changes.\n */\nexport function useArrangementSources(arrangement: Arrangement): ArrangementSourcesValue {\n const store = useMemo(\n () => ({\n subscribe: (listener: () => void) => arrangement.sources.subscribe(() => listener()),\n getSnapshot: () => arrangement.sources.getSnapshot(),\n }),\n [arrangement]\n );\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n","import type { AnnotationData } from '@waveform-playlist/core';\nimport type { AnnotationLookup } from '../utils/annotationLookup';\n\nexport interface FollowAnnotationsOptions {\n annotations: readonly AnnotationData[];\n lookup: AnnotationLookup<AnnotationData>;\n /** Playback position of this frame, in seconds. */\n time: number;\n activeId: string | null;\n /**\n * True: the highlight follows the playhead and playback is never cut\n * (continuous play). False: playback ends with the active annotation.\n */\n followOnly: boolean;\n /**\n * Leave the highlight where it is this frame. Only read when `followOnly`\n * is true: a bounded play that reaches its end on this frame stops right\n * after, and the highlight must not move on to the next annotation first.\n */\n holdHighlight: boolean;\n setActiveAnnotationId: (id: string | null) => void;\n}\n\n/**\n * The annotation step of a provider's animation loop, once per frame.\n *\n * Returns true when the active annotation has played to its end and playback\n * must stop. What \"stop\" does (where the cursor goes) is the provider's.\n */\nexport function followAnnotations({\n annotations,\n lookup,\n time,\n activeId,\n followOnly,\n holdHighlight,\n setActiveAnnotationId,\n}: FollowAnnotationsOptions): boolean {\n if (annotations.length === 0) return false;\n\n const current = lookup.atTime(annotations, time);\n\n if (followOnly) {\n if (holdHighlight) return false;\n if (current && current.id !== activeId) {\n setActiveAnnotationId(current.id);\n } else if (!current && activeId !== null) {\n // Past the active annotation, in a gap: clear it, keep playing.\n setActiveAnnotationId(null);\n }\n return false;\n }\n\n if (activeId) {\n const active = lookup.byId(annotations, activeId);\n return active !== undefined && time >= active.end;\n }\n // Nothing active yet: adopt the annotation under the playhead.\n if (current) setActiveAnnotationId(current.id);\n return false;\n}\n","import { useCallback, useMemo, useRef, useState } from 'react';\nimport { createValueSource } from '@waveform-playlist/core';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport type { AnnotationPreviewHandle } from '../hooks/useAnnotationDragHandlers';\nimport { createAnnotationLookup, type AnnotationLookup } from '../utils/annotationLookup';\nimport { isDevelopmentBuild } from '../utils/isDevelopmentBuild';\nimport type {\n AnnotationOptionsContextValue,\n AnnotationsContextValue,\n} from '../contexts/playlistContexts';\n\n/**\n * The `annotationList` prop of both providers. The provider holds the three\n * options as state (`useAnnotationOptions()`, and the three setters of\n * `usePlaybackControls()`), and that state follows the prop: when the value\n * of a field changes, the option takes it. Between two changes of the prop a\n * setter (or one of the checkboxes) changes the option; the prop is not told.\n */\nexport interface AnnotationListProp {\n annotations?: AnnotationData[];\n /** Whether annotations can be edited (text, ids, edges). Default: false. */\n editable?: boolean;\n /** Whether a dragged edge takes the edge it touches along. Default: false. */\n linkEndpoints?: boolean;\n /** Whether playback runs on past the end of an annotation. Default: false. */\n isContinuousPlay?: boolean;\n}\n\nexport interface UseAnnotationStateOptions {\n annotationList: AnnotationListProp | undefined;\n onAnnotationsChange: ((annotations: AnnotationData[]) => void) | undefined;\n /** Named in the warning for a `setAnnotations` call with no `onAnnotationsChange`. */\n providerName: string;\n}\n\nexport interface AnnotationState {\n /** From the prop (the parent owns them); `[]` when absent or not parsed. */\n annotations: AnnotationData[];\n /** For the animation loop, so an annotation edit does not restart it. */\n annotationsRef: React.RefObject<AnnotationData[]>;\n /** Cached per-frame lookups. */\n annotationLookup: AnnotationLookup<AnnotationData>;\n setAnnotations: React.Dispatch<React.SetStateAction<AnnotationData[]>>;\n /** Created once: the annotations as an edge drag in progress would leave them. */\n annotationPreview: AnnotationPreviewHandle;\n activeAnnotationId: string | null;\n activeAnnotationIdRef: React.RefObject<string | null>;\n setActiveAnnotationId: (id: string | null) => void;\n continuousPlay: boolean;\n continuousPlayRef: React.RefObject<boolean>;\n setContinuousPlay: (enabled: boolean) => void;\n setAnnotationsEditable: (enabled: boolean) => void;\n setLinkEndpoints: (enabled: boolean) => void;\n /** `{ annotations }`, memoized: the public annotations value. */\n annotationsValue: AnnotationsContextValue;\n /** The three options, memoized: the public options value. */\n annotationOptionsValue: AnnotationOptionsContextValue;\n}\n\n/**\n * A boolean option held as state that follows a prop (#686): it starts from\n * the prop (false when absent), a setter changes it, and when the prop's\n * value changes the option takes the new value. The comparison is made during\n * render against the last prop value seen, kept as state: no effect, so a\n * StrictMode remount or a revealed `<Activity>` does not put an unchanged\n * prop back over a value the user chose. The setter keeps its identity.\n */\nfunction useFollowedOption(prop: boolean | undefined): [boolean, (value: boolean) => void] {\n // A field that is left out says false: leaving it out and writing `false`\n // are the same value, not a change.\n const wanted = prop ?? false;\n const [value, setValue] = useState(wanted);\n const [seen, setSeen] = useState(wanted);\n if (seen !== wanted) {\n setSeen(wanted);\n setValue(wanted);\n return [wanted, setValue];\n }\n return [value, setValue];\n}\n\n/**\n * The annotation state of a provider. The two setters that the animation loop\n * depends on write their ref first and the state second, so a running loop\n * reads the new value on its next frame, before React has rendered. Every\n * function and the preview keep their identity.\n */\nexport function useAnnotationState({\n annotationList,\n onAnnotationsChange,\n providerName,\n}: UseAnnotationStateOptions): AnnotationState {\n // In v6, annotations must be pre-parsed (numeric start/end). Use\n // parseAeneas() from @waveform-playlist/annotations before passing them.\n const annotations = useMemo(() => {\n if (!annotationList?.annotations) return [];\n if (isDevelopmentBuild() && annotationList.annotations.length > 0) {\n const first = annotationList.annotations[0] as unknown as Record<string, unknown>;\n if (typeof first.start !== 'number' || typeof first.end !== 'number') {\n console.error(\n '[waveform-playlist] Annotations must have numeric start/end values. ' +\n 'In v6, use parseAeneas() from @waveform-playlist/annotations before passing annotations. ' +\n 'Received start type: ' +\n typeof first.start\n );\n return [];\n }\n }\n return annotationList.annotations;\n }, [annotationList?.annotations]);\n\n const annotationsRef = useRef<AnnotationData[]>(annotations);\n annotationsRef.current = annotations;\n const [annotationLookup] = useState(() => createAnnotationLookup<AnnotationData>());\n\n const [activeAnnotationId, setActiveAnnotationIdState] = useState<string | null>(null);\n const activeAnnotationIdRef = useRef<string | null>(null);\n const setActiveAnnotationId = useCallback((value: string | null) => {\n activeAnnotationIdRef.current = value;\n setActiveAnnotationIdState(value);\n }, []);\n\n const [continuousPlay, setContinuousPlayState] = useFollowedOption(\n annotationList?.isContinuousPlay\n );\n // Written during render as well as by the setter, so that a value taken\n // from the prop reaches the animation loop too. The setter writes it first:\n // a running loop reads the new value on its next frame, before React has\n // rendered.\n const continuousPlayRef = useRef<boolean>(continuousPlay);\n continuousPlayRef.current = continuousPlay;\n const setContinuousPlay = useCallback(\n (value: boolean) => {\n continuousPlayRef.current = value;\n setContinuousPlayState(value);\n },\n [setContinuousPlayState]\n );\n\n const [editable, setAnnotationsEditable] = useFollowedOption(annotationList?.editable);\n const [linkEndpoints, setLinkEndpoints] = useFollowedOption(annotationList?.linkEndpoints);\n\n const annotationsValue = useMemo(() => ({ annotations }), [annotations]);\n const annotationOptionsValue = useMemo(\n () => ({ editable, linkEndpoints, continuousPlay }),\n [editable, linkEndpoints, continuousPlay]\n );\n\n const [annotationPreview] = useState<AnnotationPreviewHandle>(() =>\n createValueSource<AnnotationData[] | null>(null)\n );\n\n // Read through a ref so that `setAnnotations` keeps its identity.\n const onAnnotationsChangeRef = useRef(onAnnotationsChange);\n onAnnotationsChangeRef.current = onAnnotationsChange;\n\n const setAnnotations: React.Dispatch<React.SetStateAction<AnnotationData[]>> = useCallback(\n (action) => {\n const updated = typeof action === 'function' ? action(annotationsRef.current) : action;\n if (!onAnnotationsChangeRef.current) {\n if (isDevelopmentBuild()) {\n console.warn(\n 'waveform-playlist: setAnnotations was called but no onAnnotationsChange callback is provided. ' +\n 'Annotation edits will not persist. Pass onAnnotationsChange to ' +\n providerName +\n ' to handle annotation updates.'\n );\n }\n return;\n }\n onAnnotationsChangeRef.current(updated);\n },\n [providerName]\n );\n\n return {\n annotations,\n annotationsRef,\n annotationLookup,\n setAnnotations,\n annotationPreview,\n activeAnnotationId,\n activeAnnotationIdRef,\n setActiveAnnotationId,\n continuousPlay,\n continuousPlayRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationsValue,\n annotationOptionsValue,\n };\n}\n","/**\n * Per-frame annotation lookups for the playback animation loops.\n *\n * Both lookups return exactly what the `Array.prototype.find` calls they replace\n * would return; they only avoid scanning the whole list on every frame.\n *\n * The list is treated as immutable: results are cached against the array's\n * identity, so a changed annotation must arrive in a new array (it does: the\n * providers hold annotations in React state).\n */\ninterface TimedAnnotation {\n readonly id: string;\n readonly start: number;\n readonly end: number;\n}\n\nexport interface AnnotationLookup<T extends TimedAnnotation> {\n /** Same result as `annotations.find((a) => time >= a.start && time < a.end)`. */\n atTime(annotations: readonly T[], time: number): T | undefined;\n /** Same result as `annotations.find((a) => a.id === id)`. */\n byId(annotations: readonly T[], id: string): T | undefined;\n}\n\nconst contains = (annotation: TimedAnnotation, time: number): boolean =>\n time >= annotation.start && time < annotation.end;\n\n/**\n * True when every range ends at or before the next one starts. Only then is\n * \"the first annotation containing `time`\" also the only one, which is what\n * lets `atTime` trust a cached hit and binary-search a miss. NaN bounds fail\n * the comparisons and fall back to the linear scan.\n */\nfunction isOrdered(annotations: readonly TimedAnnotation[]): boolean {\n for (let i = 0; i < annotations.length; i++) {\n const current = annotations[i];\n if (!(current.start <= current.end)) return false;\n if (i + 1 < annotations.length && !(current.end <= annotations[i + 1].start)) return false;\n }\n return true;\n}\n\nexport function createAnnotationLookup<T extends TimedAnnotation>(): AnnotationLookup<T> {\n let list: readonly T[] | null = null;\n let ordered = false;\n let lastIndex = -1;\n let lastById: T | undefined;\n\n const sync = (annotations: readonly T[]) => {\n if (annotations === list) return;\n list = annotations;\n ordered = isOrdered(annotations);\n lastIndex = -1;\n lastById = undefined;\n };\n\n return {\n atTime(annotations, time) {\n sync(annotations);\n if (!ordered) return annotations.find((annotation) => contains(annotation, time));\n // NaN compares false both ways and would look like a hit to the search below.\n if (Number.isNaN(time)) return undefined;\n\n // Playback moves forward, so the last hit is nearly always still the answer.\n if (lastIndex >= 0 && contains(annotations[lastIndex], time)) return annotations[lastIndex];\n\n let low = 0;\n let high = annotations.length - 1;\n while (low <= high) {\n const mid = (low + high) >> 1;\n const candidate = annotations[mid];\n if (time < candidate.start) {\n high = mid - 1;\n } else if (time >= candidate.end) {\n low = mid + 1;\n } else {\n lastIndex = mid;\n return candidate;\n }\n }\n return undefined;\n },\n\n byId(annotations, id) {\n sync(annotations);\n if (lastById?.id === id) return lastById;\n // A miss is not cached: the id may be added in a later list.\n lastById = annotations.find((annotation) => annotation.id === id);\n return lastById;\n },\n };\n}\n","/**\n * The one definition of \"development build\" in this package: true unless\n * this is a production build. Bundlers replace `process.env.NODE_ENV` with a\n * literal; where there is no `process` at all (a page that loads the module\n * without a bundler) this is false, so nothing development-only runs and\n * nothing throws. Not exported from the package entry.\n */\nexport function isDevelopmentBuild(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n","import { useCallback, useRef } from 'react';\n\n/** Per-frame data passed to registered animation callbacks. */\nexport interface FrameData {\n /** Raw engine time (for state/logic — NOT for visual positioning). */\n readonly time: number;\n /** Visually-aligned time for DOM positioning: engine.getAudibleTime() while\n * playing (matches speaker output), raw time when resting. */\n readonly visualTime: number;\n readonly sampleRate: number;\n readonly samplesPerPixel: number;\n}\n\nexport type FrameCallback = (data: FrameData) => void;\n\nexport interface FrameCallbacks {\n /** Register a per-frame callback. A second registration under the same id replaces the first. */\n registerFrameCallback: (id: string, cb: FrameCallback) => void;\n unregisterFrameCallback: (id: string) => void;\n /** For the provider's animation loop: call every registered callback. */\n runFrameCallbacks: (data: FrameData) => void;\n}\n\n/**\n * The frame-callback registry of a provider. Components that draw during\n * playback register a callback instead of running their own\n * `requestAnimationFrame` loop; the provider's one loop calls them all with\n * the time it read for that frame. All three functions are stable.\n */\nexport function useFrameCallbacks(): FrameCallbacks {\n const callbacksRef = useRef<Map<string, FrameCallback>>(new Map());\n\n const registerFrameCallback = useCallback((id: string, cb: FrameCallback) => {\n callbacksRef.current.set(id, cb);\n }, []);\n\n const unregisterFrameCallback = useCallback((id: string) => {\n callbacksRef.current.delete(id);\n }, []);\n\n const runFrameCallbacks = useCallback((data: FrameData) => {\n for (const cb of callbacksRef.current.values()) {\n cb(data);\n }\n }, []);\n\n return { registerFrameCallback, unregisterFrameCallback, runFrameCallbacks };\n}\n","import { useCallback, useRef, useState } from 'react';\n\n/**\n * Scrolls so that the playhead is in the middle of the container. Whole\n * pixels: a fractional `scrollLeft` is rounded by the browser anyway, and not\n * always the same way from frame to frame, which shows as jitter.\n */\nexport function centrePlayhead(\n container: HTMLDivElement,\n time: number,\n sampleRate: number,\n samplesPerPixel: number\n): void {\n const pixelPosition = (time * sampleRate) / samplesPerPixel;\n container.scrollLeft = Math.round(Math.max(0, pixelPosition - container.clientWidth / 2));\n}\n\nexport interface ScrollFollow {\n scrollContainerRef: React.RefObject<HTMLDivElement | null>;\n setScrollContainer: (element: HTMLDivElement | null) => void;\n isAutomaticScroll: boolean;\n /** For the animation loop: current without waiting for a render. */\n isAutomaticScrollRef: React.RefObject<boolean>;\n setAutomaticScroll: (enabled: boolean) => void;\n}\n\n/** The scroll container and the automatic-scroll setting of a provider. */\nexport function useScrollFollow(initialAutomaticScroll: boolean): ScrollFollow {\n const scrollContainerRef = useRef<HTMLDivElement | null>(null);\n const [isAutomaticScroll, setIsAutomaticScroll] = useState(initialAutomaticScroll);\n const isAutomaticScrollRef = useRef<boolean>(initialAutomaticScroll);\n\n const setScrollContainer = useCallback((element: HTMLDivElement | null) => {\n scrollContainerRef.current = element;\n }, []);\n\n const setAutomaticScroll = useCallback((enabled: boolean) => {\n isAutomaticScrollRef.current = enabled;\n setIsAutomaticScroll(enabled);\n }, []);\n\n return {\n scrollContainerRef,\n setScrollContainer,\n isAutomaticScroll,\n isAutomaticScrollRef,\n setAutomaticScroll,\n };\n}\n","import { useMemo } from 'react';\nimport { defaultTheme, type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport { useShallowStable } from '../hooks/useShallowStable';\n\n/**\n * The theme both providers hand to styled-components: the `theme` prop merged\n * over `defaultTheme`. An inline object prop (`theme={{ … }}`) gets a new\n * identity on every render of the parent; it keeps the previous one here\n * while its contents are unchanged, so nothing styled is re-rendered.\n *\n * The theme stays on the provider (#689): it is not an option of one view.\n * The transport controls, the checkboxes and the annotation list are drawn\n * outside a root and read it too.\n */\nexport function useMergedTheme(\n themeProp: Partial<WaveformPlaylistTheme> | undefined\n): WaveformPlaylistTheme {\n const userTheme = useShallowStable(themeProp);\n return useMemo(() => ({ ...defaultTheme, ...userTheme }), [userTheme]);\n}\n","import { useRef } from 'react';\n\nfunction shallowEqual(a: object, b: object): boolean {\n if (a === b) return true;\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n const aRecord = a as Record<string, unknown>;\n const bRecord = b as Record<string, unknown>;\n return aKeys.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(bRecord, key) && Object.is(aRecord[key], bRecord[key])\n );\n}\n\n/**\n * Returns the previous object while the new one is shallow-equal to it.\n *\n * Consumers usually pass small config objects as inline literals\n * (`theme={{ playheadColor: 'red' }}`), which have a new identity on every\n * render of the parent. Passing such a prop through this hook before using it\n * as a `useMemo` dependency keeps the memo from being invalidated by a render\n * in which the object's contents did not change.\n */\nexport function useShallowStable<T extends object | undefined>(value: T): T {\n const ref = useRef(value);\n const previous = ref.current;\n if (previous !== value) {\n if (previous === undefined || value === undefined || !shallowEqual(previous, value)) {\n ref.current = value;\n }\n }\n return ref.current;\n}\n","import { useRef, useState } from 'react';\nimport { createValueSource } from '@waveform-playlist/core';\nimport type { ClipTrack, ValueSourceHandle } from '@waveform-playlist/core';\nimport { clipPeaksFor, type DerivePeaksOptions, type PeaksCache } from '../utils/derivePeaks';\nimport type { ClipPeaks } from '../WaveformPlaylistContext';\n\n/**\n * A clip trim drag in progress (#812): where the dragged clip would be if the\n * pointer were released now. View-only: the tracks are not changed until the\n * release, which commits the same geometry through one `engine.trimClip`.\n */\nexport interface TrimPreview {\n trackId: string;\n clipId: string;\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n}\n\n/** The one place a trim drag in progress is kept: written by the drag handlers. */\nexport type TrimPreviewHandle = ValueSourceHandle<TrimPreview | null>;\n\n/**\n * The drawing record of the clip a preview names, with the previewed\n * geometry. A stable object: reading it never re-renders; `peaksFor` reads the\n * provider's latest tracks and peak inputs when it is called.\n */\nexport interface TrimPreviewPeaksValue {\n /** `null` when no track or clip has the preview's ids. */\n peaksFor: (preview: TrimPreview) => ClipPeaks | null;\n}\n\n/** What `peaksFor` derives a previewed clip from: the provider's, as of its last render. */\nexport interface TrimPreviewInputs {\n /** The loaded tracks (no loading clip: a placeholder is never trimmed). */\n tracks: readonly ClipTrack[];\n peaksOptions: DerivePeaksOptions;\n /** The last pass of `derivePeaks`, so an unchanged geometry reuses its record. */\n peaksCacheRef: React.RefObject<PeaksCache>;\n}\n\n/** The previewed clip's record, by the same per-clip step as every other clip. */\nexport function previewedClipPeaks(\n preview: TrimPreview,\n { tracks, peaksOptions, peaksCacheRef }: TrimPreviewInputs\n): ClipPeaks | null {\n const track = tracks.find((t) => t.id === preview.trackId);\n const clip = track?.clips.find((c) => c.id === preview.clipId);\n if (!track || !clip) return null;\n const previewed = {\n ...clip,\n startSample: preview.startSample,\n durationSamples: preview.durationSamples,\n offsetSamples: preview.offsetSamples,\n };\n const previous = peaksCacheRef.current.clips.get(clip.id);\n return clipPeaksFor(previewed, track.name, peaksOptions, previous).clipPeaks;\n}\n\nexport interface TrimPreviewState {\n trimPreview: TrimPreviewHandle;\n trimPreviewPeaks: TrimPreviewPeaksValue;\n}\n\n/**\n * The trim preview of `WaveformPlaylistProvider`: the source, made once, and\n * the stable function that draws a previewed clip. Both are put in internal\n * contexts (`TrimPreviewContext`, `TrimPreviewPeaksContext`), read by\n * `useClipDragHandlers`, the clip view and the root.\n */\nexport function useTrimPreview(inputs: TrimPreviewInputs): TrimPreviewState {\n const [trimPreview] = useState<TrimPreviewHandle>(() =>\n createValueSource<TrimPreview | null>(null)\n );\n // The latest inputs, read when the dragged clip's view asks; a projection\n // of the provider's own values, never written back.\n const inputsRef = useRef(inputs);\n inputsRef.current = inputs;\n const [trimPreviewPeaks] = useState<TrimPreviewPeaksValue>(() => ({\n peaksFor: (preview) => previewedClipPeaks(preview, inputsRef.current),\n }));\n return { trimPreview, trimPreviewPeaks };\n}\n","/**\n * Waveform Data Loader\n *\n * Utilities for loading pre-computed waveform data in waveform-data.js format.\n * Supports both binary (.dat) and JSON formats from BBC's audiowaveform tool.\n */\n\nimport WaveformData from 'waveform-data';\nimport type { PeakData, Peaks } from '@waveform-playlist/core';\n\n/**\n * Load waveform data from a .dat or .json file\n *\n * @param src - URL to waveform data file (.dat or .json)\n * @returns WaveformData instance\n */\nexport async function loadWaveformData(src: string): Promise<WaveformData> {\n const response = await fetch(src);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waveform data: ${response.statusText}`);\n }\n\n // Detect binary format from pathname (ignores query string and fragment)\n const { pathname } = new URL(src, globalThis.location?.href ?? 'http://localhost');\n const isBinary = pathname.toLowerCase().endsWith('.dat');\n\n if (isBinary) {\n const arrayBuffer = await response.arrayBuffer();\n return WaveformData.create(arrayBuffer);\n } else {\n const json = await response.json();\n return WaveformData.create(json);\n }\n}\n\n/**\n * Convert WaveformData to our internal Peaks format\n *\n * @param waveformData - WaveformData instance from waveform-data.js\n * @param channelIndex - Channel index (0 for mono/left, 1 for right)\n * @returns Peaks data with alternating min/max values, preserving original bit depth\n */\nexport function waveformDataToPeaks(\n waveformData: WaveformData,\n channelIndex: number = 0\n): { data: Int8Array | Int16Array; bits: 8 | 16; length: number; sampleRate: number } {\n const channel = waveformData.channel(channelIndex);\n const bits = waveformData.bits as 8 | 16;\n\n // Get the min/max arrays to determine length\n const minArray = channel.min_array();\n const maxArray = channel.max_array();\n const length = minArray.length;\n\n // Use appropriate typed array based on source file bit depth\n // 8-bit: values range from -128 to 127\n // 16-bit: values range from -32768 to 32767\n const peaks = bits === 8 ? new Int8Array(length * 2) : new Int16Array(length * 2);\n\n // Interleave min/max pairs\n for (let i = 0; i < length; i++) {\n peaks[i * 2] = minArray[i];\n peaks[i * 2 + 1] = maxArray[i];\n }\n\n return {\n data: peaks,\n bits,\n length,\n sampleRate: waveformData.sample_rate,\n };\n}\n\n/**\n * Load waveform data file and convert to Peaks format in one step\n *\n * @param src - URL to waveform data file (.dat or .json)\n * @param channelIndex - Channel index (default: 0)\n * @returns Peaks data ready for rendering\n */\nexport async function loadPeaksFromWaveformData(\n src: string,\n channelIndex: number = 0\n): Promise<{ data: Int8Array | Int16Array; bits: 8 | 16; length: number; sampleRate: number }> {\n const waveformData = await loadWaveformData(src);\n return waveformDataToPeaks(waveformData, channelIndex);\n}\n\n/**\n * Get metadata from waveform data file without converting to peaks\n *\n * @param src - URL to waveform data file\n * @returns Metadata (sample rate, channels, duration, bits, etc.)\n */\nexport async function getWaveformDataMetadata(src: string): Promise<{\n sampleRate: number;\n channels: number;\n duration: number;\n samplesPerPixel: number;\n length: number;\n bits: 8 | 16;\n}> {\n const waveformData = await loadWaveformData(src);\n\n return {\n sampleRate: waveformData.sample_rate,\n channels: waveformData.channels,\n duration: waveformData.duration,\n samplesPerPixel: waveformData.scale,\n length: waveformData.length,\n bits: waveformData.bits as 8 | 16,\n };\n}\n\n/**\n * Slice and resample WaveformData with aligned source indices.\n *\n * Handles three cases:\n * 1. Scale differs + offset/duration given → aligned slice then resample\n * 2. Same scale + offset/duration given → direct slice\n * 3. No offset/duration → full-file resample (or identity)\n *\n * @returns Processed WaveformData ready for peak extraction\n */\nfunction sliceAndResample(\n waveformData: WaveformData,\n samplesPerPixel: number,\n offsetSamples?: number,\n durationSamples?: number\n): WaveformData | null {\n let processedData = waveformData;\n\n if (offsetSamples !== undefined && durationSamples !== undefined) {\n if (processedData.scale !== samplesPerPixel) {\n const sourceScale = waveformData.scale;\n const ratio = samplesPerPixel / sourceScale;\n\n // Compute clip's pixel range in target-scale bins\n const targetStart = Math.floor(offsetSamples / samplesPerPixel);\n const targetEnd = Math.ceil((offsetSamples + durationSamples) / samplesPerPixel);\n\n // Convert to source indices using floor/ceil for inclusive slicing.\n // For integer ratios (power-of-two scales), this gives exact alignment.\n // For non-integer ratios, floor/ceil ensures we always include all source\n // bins that contribute to the target bins — never underrepresenting peaks.\n const sourceStart = Math.floor(targetStart * ratio);\n const sourceEnd = Math.min(waveformData.length, Math.ceil(targetEnd * ratio));\n\n if (sourceStart >= sourceEnd) {\n return null; // Clip offset beyond waveform data\n }\n\n processedData = processedData.slice({\n startIndex: sourceStart,\n endIndex: sourceEnd,\n });\n processedData = processedData.resample({ scale: samplesPerPixel });\n } else {\n // No resampling needed — slice directly at base scale\n const startIndex = Math.floor(offsetSamples / samplesPerPixel);\n const endIndex = Math.ceil((offsetSamples + durationSamples) / samplesPerPixel);\n processedData = processedData.slice({ startIndex, endIndex });\n }\n } else if (processedData.scale !== samplesPerPixel) {\n processedData = processedData.resample({ scale: samplesPerPixel });\n }\n\n return processedData;\n}\n\n/**\n * Extract peaks from a WaveformData object at a specific scale (samplesPerPixel)\n * and optionally slice to a sample range.\n *\n * @param waveformData - WaveformData instance from waveform-data.js\n * @param samplesPerPixel - Target samples per pixel (will resample if different)\n * @param channelIndex - Channel index (default: 0)\n * @param offsetSamples - Optional start offset in samples (for clip trimming)\n * @param durationSamples - Optional duration in samples (for clip trimming)\n * @returns Peaks data ready for rendering\n */\nexport function extractPeaksFromWaveformData(\n waveformData: WaveformData,\n samplesPerPixel: number,\n channelIndex: number = 0,\n offsetSamples?: number,\n durationSamples?: number\n): { data: Int8Array | Int16Array; bits: 8 | 16; length: number } {\n const processedData = sliceAndResample(\n waveformData,\n samplesPerPixel,\n offsetSamples,\n durationSamples\n );\n\n if (processedData === null) {\n const bits = waveformData.bits as 8 | 16;\n const emptyPeaks = bits === 8 ? new Int8Array(0) : new Int16Array(0);\n return { data: emptyPeaks, bits, length: 0 };\n }\n\n // Convert to our peaks format\n const channel = processedData.channel(channelIndex);\n const bits = processedData.bits as 8 | 16;\n const minArray = channel.min_array();\n const maxArray = channel.max_array();\n const length = minArray.length;\n\n const peaks = bits === 8 ? new Int8Array(length * 2) : new Int16Array(length * 2);\n\n for (let i = 0; i < length; i++) {\n peaks[i * 2] = minArray[i];\n peaks[i * 2 + 1] = maxArray[i];\n }\n\n return { data: peaks, bits, length };\n}\n\n/**\n * Extract peaks from a WaveformData object, handling ALL channels, mono merging,\n * slicing, and resampling.\n *\n * Bit depth is determined by the WaveformData source — all typed arrays match\n * the source's bit depth for consistent data/metadata.\n *\n * @param waveformData - WaveformData instance (should be generated with split_channels: true)\n * @param samplesPerPixel - Target samples per pixel\n * @param isMono - Whether to merge channels to mono\n * @param offsetSamples - Optional start offset in samples (for clip trimming)\n * @param durationSamples - Optional duration in samples (for clip trimming)\n * @returns PeakData matching the interface from @waveform-playlist/core\n */\nexport function extractPeaksFromWaveformDataFull(\n waveformData: WaveformData,\n samplesPerPixel: number,\n isMono: boolean,\n offsetSamples?: number,\n durationSamples?: number\n): PeakData {\n const processedData = sliceAndResample(\n waveformData,\n samplesPerPixel,\n offsetSamples,\n durationSamples\n );\n\n if (processedData === null) {\n const bits = waveformData.bits as 8 | 16;\n return { length: 0, data: [], bits };\n }\n\n const numChannels = processedData.channels;\n const bits = processedData.bits as 8 | 16;\n\n // Extract peaks for all channels\n const channelPeaks: Peaks[] = [];\n for (let c = 0; c < numChannels; c++) {\n const channel = processedData.channel(c);\n const minArray = channel.min_array();\n const maxArray = channel.max_array();\n const len = minArray.length;\n\n const peaks: Peaks = bits === 8 ? new Int8Array(len * 2) : new Int16Array(len * 2);\n\n for (let i = 0; i < len; i++) {\n peaks[i * 2] = minArray[i];\n peaks[i * 2 + 1] = maxArray[i];\n }\n channelPeaks.push(peaks);\n }\n\n // Handle mono merging (same algorithm as makeMono in webaudio-peaks)\n if (isMono && channelPeaks.length > 1) {\n const weight = 1 / channelPeaks.length;\n const numPeaks = channelPeaks[0].length / 2;\n const monoPeaks: Peaks =\n bits === 8 ? new Int8Array(numPeaks * 2) : new Int16Array(numPeaks * 2);\n\n for (let i = 0; i < numPeaks; i++) {\n let min = 0;\n let max = 0;\n for (let c = 0; c < channelPeaks.length; c++) {\n min += weight * channelPeaks[c][i * 2];\n max += weight * channelPeaks[c][i * 2 + 1];\n }\n monoPeaks[i * 2] = min;\n monoPeaks[i * 2 + 1] = max;\n }\n\n return {\n length: numPeaks,\n data: [monoPeaks],\n bits,\n };\n }\n\n const peakLength = channelPeaks.length > 0 ? channelPeaks[0].length / 2 : 0;\n\n return {\n length: peakLength,\n data: channelPeaks,\n bits,\n };\n}\n","/**\n * derivePeaks\n *\n * Turns `tracks` into the per-track, per-clip peaks the visualization draws,\n * reusing everything from the previous pass that still applies (#692).\n *\n * Three identities are preserved, because three different things are keyed on\n * them downstream:\n * - the typed arrays (`ClipPeaks.peaks`): `Channel` redraws its canvas when\n * they change;\n * - the `ClipPeaks` object: a memoized clip re-renders when it changes;\n * - the per-track array: a memoized track row re-renders when it changes.\n *\n * Peak sources, in priority order:\n * A) `clip.waveformData` — external pre-computed peaks (e.g. BBC audiowaveform)\n * B) worker-generated WaveformData for `clip.audioBuffer`\n * C) empty peaks — the clip is still loading, or is a MIDI clip\n *\n * The function does not mutate `previous`; the caller keeps the returned cache\n * and passes it to the next call.\n */\n\nimport type { AudioClip, ClipTrack, PeakData } from '@waveform-playlist/core';\nimport type WaveformData from 'waveform-data';\nimport { extractPeaksFromWaveformDataFull } from '../waveformDataLoader';\nimport type { ClipPeaks, TrackClipPeaks } from '../WaveformPlaylistContext';\nimport { sameItems } from './sameItems';\n\nexport interface DerivePeaksOptions {\n samplesPerPixel: number;\n mono: boolean;\n /** Worker-generated waveform data for a buffer, when it is ready. */\n getGeneratedWaveformData: (audioBuffer: AudioBuffer) => WaveformData | undefined;\n}\n\n/** What a clip's typed arrays were computed from. */\nexport interface PeakInputs {\n waveformData: WaveformData | undefined;\n /** Compared only when path A is absent or failed (`usesGenerated`). */\n generated: WaveformData | undefined;\n offsetSamples: number;\n durationSamples: number;\n sampleRate: number;\n samplesPerPixel: number;\n mono: boolean;\n /** Channel count used for empty peaks (path C). */\n fallbackChannels: number;\n isMidi: boolean;\n}\n\n/** What `clipPeaksFor` returns: a clip's drawing record and what it was computed from. */\nexport interface ClipPeaksEntry {\n inputs: PeakInputs;\n /** True when path A was absent or failed, so `generated` matters. */\n usesGenerated: boolean;\n peaks: PeakData;\n clipPeaks: ClipPeaks;\n}\n\nexport interface PeaksCache {\n readonly clips: ReadonlyMap<string, ClipPeaksEntry>;\n readonly tracks: ReadonlyMap<string, TrackClipPeaks>;\n readonly result: TrackClipPeaks[];\n}\n\nexport const EMPTY_PEAKS_CACHE: PeaksCache = {\n clips: new Map(),\n tracks: new Map(),\n result: [],\n};\n\n/** The slice rule for a clip drawn from its own pre-computed peaks (path A). */\nexport function extractFromOwnWaveformData(\n clip: Pick<AudioClip, 'sampleRate' | 'offsetSamples' | 'durationSamples'>,\n waveformData: WaveformData,\n samplesPerPixel: number,\n mono: boolean\n): PeakData | undefined {\n // When sample rates match, use clip offsets directly. When they differ (e.g.\n // waveformData at 48000 Hz, clip rebuilt at 44100 Hz after audio decode),\n // convert offsets to the waveformData's sample space and adjust\n // samplesPerPixel so peaks fill the correct container width.\n try {\n const wdRate = waveformData.sample_rate;\n const clipRate = clip.sampleRate;\n let peakOffset = clip.offsetSamples;\n let peakDuration = clip.durationSamples;\n let peakSpp = samplesPerPixel;\n if (wdRate !== clipRate && clipRate > 0 && wdRate > 0) {\n const ratio = wdRate / clipRate;\n peakOffset = Math.round(clip.offsetSamples * ratio);\n peakDuration = Math.round(clip.durationSamples * ratio);\n peakSpp = Math.max(1, Math.round(samplesPerPixel * ratio));\n }\n return extractPeaksFromWaveformDataFull(waveformData, peakSpp, mono, peakOffset, peakDuration);\n } catch (err) {\n console.warn('[waveform-playlist] Failed to extract peaks from waveformData: ' + String(err));\n return undefined;\n }\n}\n\nfunction extractFromGenerated(\n clip: AudioClip,\n generated: WaveformData,\n samplesPerPixel: number,\n mono: boolean\n): PeakData | undefined {\n try {\n return extractPeaksFromWaveformDataFull(\n generated,\n samplesPerPixel,\n mono,\n clip.offsetSamples,\n clip.durationSamples\n );\n } catch (err) {\n console.warn('[waveform-playlist] Failed to extract peaks from cache: ' + String(err));\n return undefined;\n }\n}\n\nfunction emptyPeaks(inputs: PeakInputs): PeakData {\n // MIDI clips: derive pixel width from sample duration so the clip renders at\n // the correct width instead of zero-width. Audio clips keep the buffer's\n // channel count so the track height does not shift when peaks arrive.\n const pixelLength = inputs.isMidi\n ? Math.ceil(inputs.durationSamples / inputs.samplesPerPixel)\n : 0;\n return {\n length: pixelLength,\n data: Array.from({ length: inputs.fallbackChannels }, () => new Int16Array(pixelLength * 2)),\n bits: 16,\n };\n}\n\nfunction sameInputs(a: PeakInputs, b: PeakInputs, usesGenerated: boolean): boolean {\n return (\n a.waveformData === b.waveformData &&\n (!usesGenerated || a.generated === b.generated) &&\n a.offsetSamples === b.offsetSamples &&\n a.durationSamples === b.durationSamples &&\n a.sampleRate === b.sampleRate &&\n a.samplesPerPixel === b.samplesPerPixel &&\n a.mono === b.mono &&\n a.fallbackChannels === b.fallbackChannels &&\n a.isMidi === b.isMidi\n );\n}\n\nfunction computePeaks(\n clip: AudioClip,\n inputs: PeakInputs\n): { peaks: PeakData; usesGenerated: boolean } {\n const { waveformData, generated, samplesPerPixel, mono } = inputs;\n const own = waveformData\n ? extractFromOwnWaveformData(clip, waveformData, samplesPerPixel, mono)\n : undefined;\n if (own) return { peaks: own, usesGenerated: false };\n\n const fromWorker = generated\n ? extractFromGenerated(clip, generated, samplesPerPixel, mono)\n : undefined;\n return { peaks: fromWorker ?? emptyPeaks(inputs), usesGenerated: true };\n}\n\nfunction sameClipPeaks(a: ClipPeaks, clip: AudioClip, trackName: string, peaks: PeakData): boolean {\n return (\n a.peaks === peaks &&\n a.trackName === trackName &&\n a.startSample === clip.startSample &&\n a.durationSamples === clip.durationSamples &&\n a.fadeIn === clip.fadeIn &&\n a.fadeOut === clip.fadeOut &&\n a.midiNotes === clip.midiNotes &&\n a.sampleRate === clip.sampleRate &&\n a.offsetSamples === clip.offsetSamples &&\n a.gain === clip.gain &&\n !a.isPlaceholder\n );\n}\n\n/**\n * One clip's peaks and drawing record, reusing `previous` (the entry of the\n * same clip from the last pass) when nothing it depends on changed. The step\n * `derivePeaks` runs for every clip, exported so that a clip drawn with a\n * trim preview's geometry is computed by the same code (#812).\n */\nexport function clipPeaksFor(\n clip: AudioClip,\n trackName: string,\n options: DerivePeaksOptions,\n previous?: ClipPeaksEntry\n): ClipPeaksEntry {\n const inputs: PeakInputs = {\n waveformData: clip.waveformData as WaveformData | undefined,\n generated: clip.audioBuffer ? options.getGeneratedWaveformData(clip.audioBuffer) : undefined,\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n sampleRate: clip.sampleRate,\n samplesPerPixel: options.samplesPerPixel,\n mono: options.mono,\n fallbackChannels: options.mono ? 1 : (clip.audioBuffer?.numberOfChannels ?? 1),\n isMidi: Boolean(clip.midiNotes),\n };\n\n const reusable = previous && sameInputs(previous.inputs, inputs, previous.usesGenerated);\n const { peaks, usesGenerated } = reusable\n ? { peaks: previous.peaks, usesGenerated: previous.usesGenerated }\n : computePeaks(clip, inputs);\n\n if (previous && reusable && sameClipPeaks(previous.clipPeaks, clip, trackName, peaks)) {\n return previous;\n }\n\n return {\n inputs,\n usesGenerated,\n peaks,\n clipPeaks: {\n clipId: clip.id,\n trackName,\n peaks,\n startSample: clip.startSample,\n durationSamples: clip.durationSamples,\n fadeIn: clip.fadeIn,\n fadeOut: clip.fadeOut,\n midiNotes: clip.midiNotes,\n sampleRate: clip.sampleRate,\n offsetSamples: clip.offsetSamples,\n gain: clip.gain,\n isPlaceholder: false,\n },\n };\n}\n\nexport function derivePeaks(\n tracks: readonly ClipTrack[],\n options: DerivePeaksOptions,\n previous: PeaksCache\n): PeaksCache {\n const clips = new Map<string, ClipPeaksEntry>();\n const trackPeaks = new Map<string, TrackClipPeaks>();\n\n const derived = tracks.map((track) => {\n const clipPeaks = track.clips.map((clip) => {\n const entry = clipPeaksFor(clip, track.name, options, previous.clips.get(clip.id));\n clips.set(clip.id, entry);\n return entry.clipPeaks;\n });\n const before = previous.tracks.get(track.id);\n const stable = sameItems(before, clipPeaks) ? before : clipPeaks;\n trackPeaks.set(track.id, stable);\n return stable;\n });\n\n return {\n clips,\n tracks: trackPeaks,\n result: sameItems(previous.result, derived) ? previous.result : derived,\n };\n}\n","/**\n * useEngineLifetime\n *\n * The engine of `WaveformPlaylistProvider` around an arrangement (#812). The\n * arrangement owns the tracks, the mix, the undo history and the loading, and\n * outlives every engine: this hook builds an engine on it on mount and when\n * `effects` changes identity or `zoomLevels` changes content (QG), disposes\n * it in every cleanup, and gives the arrangement the context it decodes with.\n * A track edit builds nothing: the engine follows the arrangement (#798).\n *\n * It also owns what a play waiting for an engine needs (#675, the six rules of\n * `notes/playback-and-engine.md`, \"Engine Rebuilds vs Playback\"):\n * `pendingResumeRef`, `engineBuildInFlightRef` and `engineEpoch`. The\n * provider's `play`, `pause`, `stop` and resume effect read and write them.\n */\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport {\n attachDecodeContext,\n PlaylistEngine,\n type Arrangement,\n type EngineState,\n type PlayoutAdapter,\n} from '@waveform-playlist/engine';\nimport type {\n EffectsFunction,\n SoundFontCache,\n TrackEffectsFunction,\n} from '@waveform-playlist/playout';\nimport { resolvePlayoutAdapter } from '../playout/resolvePlayoutAdapter';\n\n/** The rate the provider assumes until its first adapter says otherwise. */\nconst PROVISIONAL_SAMPLE_RATE = 48000;\n\n/** A play that must start once the engine being built is assigned. */\nexport interface PendingResume {\n position: number;\n /** Set for duration-limited playback. */\n endTime?: number;\n}\n\nexport interface UseEngineLifetimeOptions {\n arrangement: Arrangement;\n /** Read when an engine is built; a new identity builds nothing. */\n createAdapter?: () => PlayoutAdapter;\n /** Master effects chain (default Tone.js adapter). A new identity rebuilds. */\n effects?: EffectsFunction;\n /** Read when an engine is built; the adapter keeps it for its whole life. */\n resolveTrackEffects: (trackId: string) => TrackEffectsFunction | undefined;\n soundFontCacheRef: React.RefObject<SoundFontCache | undefined>;\n /** The provider's `sampleRate` prop. Read when an engine is built. */\n sampleRateProp?: number;\n /** Compared by content: an inline array with the same levels builds nothing. */\n zoomLevels?: number[];\n samplesPerPixelRef: React.RefObject<number>;\n /** Where a bounded play stops: carried into the resume of a play a rebuild interrupts. */\n playbackEndTimeRef: React.RefObject<number | null>;\n /** Give a new engine the provider's selection, loop, volume and selected track. */\n seedEngine: (engine: PlaylistEngine) => void;\n /** Subscribe to a new engine (`statechange`, `stop`). */\n onEngine: (engine: PlaylistEngine) => void;\n /**\n * A new engine's first state, once, after `onEngine`: an engine built on\n * an arrangement sends its tracks in its constructor and emits no\n * `statechange`, so this is where `canZoomIn` / `canZoomOut` first arrive.\n */\n onEngineState: (state: EngineState) => void;\n stopAnimationFrameLoop: () => void;\n /** The latest committed `onError` (QG). */\n onErrorRef: React.RefObject<((error: Error) => void) | undefined>;\n /**\n * A build that is still current failed: no engine is coming until a later\n * build. Called before `onError`.\n */\n onBuildFailure?: () => void;\n}\n\nexport interface EngineLifetime {\n engineRef: React.RefObject<PlaylistEngine | null>;\n adapterRef: React.RefObject<PlayoutAdapter | null>;\n /** Bumped each time a freshly built engine is assigned. */\n engineEpoch: number;\n /** Ask for another run of what follows `engineEpoch` (a play handed to an engine already assigned). */\n bumpEngineEpoch: () => void;\n /** True while an assigned engine is current: false from the start of each\n * build until its engine is assigned, and after a cleanup disposed it. */\n isEngineAttached: boolean;\n /** True from the start of a build until its engine is assigned, it fails or it is superseded. */\n engineBuildInFlightRef: React.RefObject<boolean>;\n /** The play waiting for the engine being built (#675). */\n pendingResumeRef: React.RefObject<PendingResume | null>;\n /** Whether the current engine's `init()` has run; false for each new engine. */\n audioInitializedRef: React.RefObject<boolean>;\n /** Dispose the engine, leaving nothing reachable; queue a resume if it was playing. */\n disposeEngineKeepingPlayback: () => void;\n /** The `sampleRate` prop or 48000 until the first adapter exists, then the adapter's. */\n sampleRate: number;\n /** True from mount with the `sampleRate` prop, else from the first adapter on. */\n isSampleRateKnown: boolean;\n}\n\ninterface Deferred<T> {\n promise: Promise<T>;\n resolve(value: T): void;\n}\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n const promise = new Promise<T>((done) => {\n resolve = done;\n });\n return { promise, resolve };\n}\n\n/** What one run of the build effect needs; `latest` is read when the build reaches it. */\ninterface BuildContext {\n arrangement: Arrangement;\n effects: EffectsFunction | undefined;\n zoomLevels: number[] | undefined;\n latest: React.RefObject<UseEngineLifetimeOptions>;\n engineRef: React.RefObject<PlaylistEngine | null>;\n adapterRef: React.RefObject<PlayoutAdapter | null>;\n engineBuildInFlightRef: React.RefObject<boolean>;\n pendingResumeRef: React.RefObject<PendingResume | null>;\n audioInitializedRef: React.RefObject<boolean>;\n /** Called with a new engine's adapter once the engine is assigned. */\n onAssigned: (adapter: PlayoutAdapter) => void;\n setSampleRate: (rate: number) => void;\n setIsEngineAttached: (attached: boolean) => void;\n bumpEngineEpoch: () => void;\n}\n\ninterface BuildRun {\n cancelled: boolean;\n}\n\nasync function buildEngine(ctx: BuildContext, run: BuildRun): Promise<void> {\n let engine: PlaylistEngine | null = null;\n try {\n const options = ctx.latest.current;\n // A new adapter needs its AudioContext resumed on the first play.\n ctx.audioInitializedRef.current = false;\n const adapter = await resolvePlayoutAdapter({\n createAdapter: options.createAdapter,\n effects: ctx.effects,\n trackEffects: options.resolveTrackEffects,\n soundFontCache: options.soundFontCacheRef.current,\n sampleRate: options.sampleRateProp,\n });\n if (run.cancelled) {\n // Superseded: the next run owns engineBuildInFlightRef now.\n adapter.dispose();\n return;\n }\n ctx.setSampleRate(adapter.audioContext.sampleRate);\n ctx.adapterRef.current = adapter;\n engine = new PlaylistEngine({\n adapter,\n arrangement: ctx.arrangement,\n // The provider attaches the decode context itself, once per mount.\n attachDecodeContext: false,\n samplesPerPixel: ctx.latest.current.samplesPerPixelRef.current,\n zoomLevels: ctx.zoomLevels,\n });\n const latest = ctx.latest.current;\n latest.seedEngine(engine);\n latest.onEngine(engine);\n latest.onEngineState(engine.getState());\n ctx.engineRef.current = engine;\n ctx.engineBuildInFlightRef.current = false;\n ctx.onAssigned(adapter);\n ctx.setIsEngineAttached(true);\n // Starts any play queued for this engine (the provider's resume effect).\n ctx.bumpEngineEpoch();\n } catch (error) {\n reportBuildFailure(ctx, run, engine, error);\n }\n}\n\n/** A build that failed: nothing it made stays reachable, and no queued play waits for it. */\nfunction reportBuildFailure(\n ctx: BuildContext,\n run: BuildRun,\n engine: PlaylistEngine | null,\n error: unknown\n): void {\n if (ctx.engineRef.current === null) {\n // Made but never assigned: the cleanup cannot reach it. Disposing the\n // engine disposes its adapter and lets go of the arrangement.\n const leftover = engine ?? ctx.adapterRef.current;\n try {\n leftover?.dispose();\n } catch (disposeErr) {\n console.warn(\n '[waveform-playlist] adapter dispose after load failure threw: ' + String(disposeErr)\n );\n }\n ctx.adapterRef.current = null;\n }\n // A build that was superseded or unmounted says nothing, neither to the\n // console nor to `onError`: the build that replaced it speaks for itself\n // (maintainer, C1 = b; on `main` `onError` was called for it too).\n if (run.cancelled) return;\n const onError = ctx.latest.current.onErrorRef.current;\n // No engine is coming: a queued play would otherwise wait forever and fire\n // on some later, unrelated rebuild.\n ctx.engineBuildInFlightRef.current = false;\n ctx.pendingResumeRef.current = null;\n ctx.latest.current.onBuildFailure?.();\n // An error, not a warning: the playlist cannot be played until a later\n // build succeeds.\n const reason = error instanceof Error ? error.message : String(error);\n console.error(\n '[waveform-playlist] The playlist could not be built and stays in its loading ' +\n 'state (it cannot be played). Reason: ' +\n reason +\n (onError ? '' : ' Pass `onError` to WaveformPlaylistProvider to show this in your app.')\n );\n onError?.(error instanceof Error ? error : new Error(String(error)));\n}\n\n/** The provider's rate: the prop or 48000 until an adapter says otherwise (B1b). */\nfunction useKnownSampleRate(sampleRateProp: number | undefined) {\n const [sampleRate, setSampleRateState] = useState(\n () => sampleRateProp ?? PROVISIONAL_SAMPLE_RATE\n );\n const [isSampleRateKnown, setIsSampleRateKnown] = useState(() => sampleRateProp !== undefined);\n const setSampleRate = useCallback((rate: number) => {\n setSampleRateState(rate);\n setIsSampleRateKnown(true);\n }, []);\n return { sampleRate, isSampleRateKnown, setSampleRate };\n}\n\n/**\n * The decode context: attached once per mount (and again after an\n * <Activity> reveal), detached in the cleanup, which aborts the loads in\n * flight. The getter gives the current adapter's context; while there is no\n * adapter it waits for the next engine's (`onAssigned`). It never rejects.\n */\nfunction useDecodeContext(\n arrangement: Arrangement,\n adapterRef: React.RefObject<PlayoutAdapter | null>\n): (adapter: PlayoutAdapter) => void {\n const arrivalRef = useRef<Deferred<BaseAudioContext> | null>(null);\n const getDecodeContext = useCallback(async (): Promise<BaseAudioContext> => {\n const adapter = adapterRef.current;\n if (adapter) return adapter.audioContext;\n arrivalRef.current ??= deferred<BaseAudioContext>();\n return arrivalRef.current.promise;\n }, [adapterRef]);\n useEffect(\n () => attachDecodeContext(arrangement, getDecodeContext),\n [arrangement, getDecodeContext]\n );\n return useCallback((adapter: PlayoutAdapter) => {\n const arrival = arrivalRef.current;\n arrivalRef.current = null;\n arrival?.resolve(adapter.audioContext);\n }, []);\n}\n\n/**\n * Dispose the current engine ahead of a rebuild, leaving nothing reachable\n * through engineRef or adapterRef. If the engine is PLAYING at this moment,\n * queue a resume for its replacement. The engine is asked directly, not\n * React's `isPlaying`, which is only as fresh as the last render (#675).\n */\nfunction useDisposeKeepingPlayback(\n refs: Pick<BuildContext, 'engineRef' | 'adapterRef' | 'pendingResumeRef' | 'latest'>\n): () => void {\n const { engineRef, adapterRef, pendingResumeRef, latest } = refs;\n return useCallback(() => {\n const engine = engineRef.current;\n if (!engine) return;\n if (engine.getState().isPlaying && !pendingResumeRef.current) {\n pendingResumeRef.current = {\n position: engine.getCurrentTime(),\n endTime: latest.current.playbackEndTimeRef.current ?? undefined,\n };\n }\n engine.dispose();\n engineRef.current = null;\n // The adapter went with the engine. Nothing may reach it either: the\n // soundfont sync, the clock and the decode context read it (#811).\n adapterRef.current = null;\n }, [engineRef, adapterRef, pendingResumeRef, latest]);\n}\n\nexport function useEngineLifetime(options: UseEngineLifetimeOptions): EngineLifetime {\n const { arrangement, effects, zoomLevels, sampleRateProp } = options;\n // Callbacks and build-time inputs, as of the latest committed render.\n const latest = useRef(options);\n useLayoutEffect(() => {\n latest.current = options;\n });\n // An inline array (zoomLevels={[256, 512]}) is new on every render; only\n // its content is a reason to rebuild.\n const stableZoomLevels = useMemo(\n () => zoomLevels,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [zoomLevels?.join(',')]\n );\n\n const engineRef = useRef<PlaylistEngine | null>(null);\n const adapterRef = useRef<PlayoutAdapter | null>(null);\n const engineBuildInFlightRef = useRef(false);\n const pendingResumeRef = useRef<PendingResume | null>(null);\n const audioInitializedRef = useRef(false);\n const [engineEpoch, setEngineEpoch] = useState(0);\n const [isEngineAttached, setIsEngineAttached] = useState(false);\n const bumpEngineEpoch = useCallback(() => setEngineEpoch((epoch) => epoch + 1), []);\n const { sampleRate, isSampleRateKnown, setSampleRate } = useKnownSampleRate(sampleRateProp);\n const onAssigned = useDecodeContext(arrangement, adapterRef);\n const disposeEngineKeepingPlayback = useDisposeKeepingPlayback({\n engineRef,\n adapterRef,\n pendingResumeRef,\n latest,\n });\n\n useEffect(() => {\n const run: BuildRun = { cancelled: false };\n engineBuildInFlightRef.current = true;\n setIsEngineAttached(false);\n const ctx: BuildContext = {\n arrangement,\n effects,\n zoomLevels: stableZoomLevels,\n latest,\n engineRef,\n adapterRef,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n onAssigned,\n setSampleRate,\n setIsEngineAttached,\n bumpEngineEpoch,\n };\n void buildEngine(ctx, run);\n return () => {\n run.cancelled = true;\n engineBuildInFlightRef.current = false;\n latest.current.stopAnimationFrameLoop();\n // Never leave a disposed engine reachable (#675).\n disposeEngineKeepingPlayback();\n };\n }, [\n arrangement,\n effects,\n stableZoomLevels,\n onAssigned,\n setSampleRate,\n bumpEngineEpoch,\n disposeEngineKeepingPlayback,\n ]);\n\n return {\n engineRef,\n adapterRef,\n engineEpoch,\n bumpEngineEpoch,\n // The state goes false only when a build starts, so it is still true\n // after a cleanup disposed the engine without a new build yet (an\n // <Activity> hide): a render then must not see an engine. The ref is\n // non-null only between an assignment (followed by the state's true) and\n // the dispose that nulls it, which every dispose does; a render can read\n // a null that is newer than the state, never a stale non-null. Clearing\n // the state in the cleanup instead left published tracks stale after a\n // reveal in the final review's random probe (#812).\n isEngineAttached: isEngineAttached && engineRef.current !== null,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n disposeEngineKeepingPlayback,\n sampleRate,\n isSampleRateKnown,\n };\n}\n","/**\n * The `npm install` command an error message gives for a missing optional\n * package (#884). A bare name installs npm `latest`, which can fail the peer\n * range of this build (a `next` prerelease, or a stable build of an older\n * major), so each name carries the range this package was published with (for\n * spectrogram, which browser does not peer on, a caret on its version).\n *\n * The ranges are written in at build time (`__INSTALL_SPECS__`, from\n * `scripts/build/install-specs.mjs` through `tsup.config.ts`). Code compiled\n * from source without that define (the website and the React examples alias\n * this source) prints the bare name, quoted.\n */\ndeclare const __INSTALL_SPECS__: Readonly<Record<string, string>> | undefined;\n\nconst BUILT_SPECS: Readonly<Record<string, string>> =\n typeof __INSTALL_SPECS__ === 'undefined' ? {} : __INSTALL_SPECS__;\n\n/** `npm install \"<name>@<range>\" …`, quoted: a range can hold `>`, `^` and `||`. */\nexport function formatInstallCommand(\n specs: Readonly<Record<string, string>>,\n names: readonly string[]\n): string {\n return 'npm install ' + names.map((name) => `\"${specs[name] ?? name}\"`).join(' ');\n}\n\n/** The install command for `names`, with the ranges of this build. */\nexport function installCommand(...names: string[]): string {\n return formatInstallCommand(BUILT_SPECS, names);\n}\n","import type { PlayoutAdapter } from '@waveform-playlist/engine';\nimport type {\n EffectsFunction,\n SoundFontCache,\n TrackEffectsFunction,\n} from '@waveform-playlist/playout';\nimport { installCommand } from '../utils/installCommand';\n\n/** Options for {@link resolvePlayoutAdapter}. */\nexport interface ResolvePlayoutAdapterOptions {\n /** Consumer-supplied factory. When present, the default engine is never imported. */\n createAdapter?: () => PlayoutAdapter;\n /** Master effects function — forwarded to the default Tone.js adapter only. */\n effects?: EffectsFunction;\n /** Per-track effects lookup by track id — forwarded to the default Tone.js adapter only. */\n trackEffects?: (trackId: string) => TrackEffectsFunction | undefined;\n /** SoundFont cache — forwarded to the default Tone.js adapter only. */\n soundFontCache?: SoundFontCache;\n /** Desired AudioContext sample rate — configures the global Tone context (default path only). */\n sampleRate?: number;\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst installHint = (): string =>\n '@waveform-playlist/playout (and its peer `tone`) is required for the default WebAudio engine. ' +\n 'Install with: ' +\n installCommand('@waveform-playlist/playout', 'tone') +\n ' — or pass a custom `createAdapter`.';\n\n/**\n * Resolve a {@link PlayoutAdapter}. With `createAdapter`, returns its result and\n * never touches the default engine — so consumers with a custom adapter install\n * neither `@waveform-playlist/playout` nor `tone`. Otherwise dynamically imports\n * the Tone.js engine, rethrowing a friendly install hint (and console.warn-ing the\n * original error) when the optional peer is absent.\n */\nexport async function resolvePlayoutAdapter(\n opts: ResolvePlayoutAdapterOptions\n): Promise<PlayoutAdapter> {\n if (opts.createAdapter) {\n return opts.createAdapter();\n }\n\n let mod: typeof import('@waveform-playlist/playout');\n try {\n mod = await import('@waveform-playlist/playout');\n } catch (originalErr) {\n console.warn(\n '[waveform-playlist] @waveform-playlist/playout dynamic import failed: ' + String(originalErr)\n );\n throw new Error(installHint());\n }\n\n if (opts.sampleRate !== undefined) {\n // Non-fatal: a failed context configuration falls back to the default rate\n // (restores pre-#510 behavior — it was caught in the old mount-time initializer).\n try {\n mod.configureGlobalContext({ sampleRate: opts.sampleRate });\n } catch (ctxErr) {\n console.warn(\n '[waveform-playlist] configureGlobalContext failed (continuing with default rate): ' +\n String(ctxErr)\n );\n }\n }\n return mod.createToneAdapter({\n effects: opts.effects,\n trackEffects: opts.trackEffects,\n soundFontCache: opts.soundFontCache,\n });\n}\n","/**\n * useArrangementView\n *\n * What `WaveformPlaylistProvider` publishes about an arrangement (#812),\n * DERIVED from it during render and never written back: the loaded tracks,\n * one drawing row per track (the loaded clips' records and the placeholder\n * records of the clips still loading, in the arrangement's clip order), the\n * timeline length, `trackStates` from the arrangement's mixer, and the undo\n * state. The arrangement is the one owner of all of it.\n *\n * Every result keeps its identity while nothing it depends on changed: a\n * fader move changes `trackStates` and nothing else; a clip edit changes\n * `tracks` and the rows of the clips it touched, not `trackStates`.\n */\nimport { useMemo, useRef, useSyncExternalStore } from 'react';\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, ClipTrack } from '@waveform-playlist/core';\nimport type { Arrangement, TrackMixerValues } from '@waveform-playlist/engine';\nimport type { ClipPeaks, TrackClipPeaks, TrackState } from '../WaveformPlaylistContext';\nimport { useArrangementTracks } from '../hooks/useArrangementTracks';\nimport { useWaveformDataCache } from '../hooks/useWaveformDataCache';\nimport {\n derivePeaks,\n EMPTY_PEAKS_CACHE,\n type DerivePeaksOptions,\n type PeaksCache,\n} from '../utils/derivePeaks';\nimport { EMPTY_LOADED_TRACKS, loadedTracks, type LoadedTracksCache } from '../utils/loadedTracks';\nimport { placeholderPeaks } from '../utils/placeholderPeaks';\nimport { sameItems } from '../utils/sameItems';\nimport { timelineDuration } from '../utils/timelineDuration';\n\nexport interface ArrangementViewOptions {\n samplesPerPixel: number;\n mono: boolean;\n /** The finest zoom level: the scale the worker generates peaks at. */\n baseScale: number;\n /**\n * The rate placeholder records are built at, or `null` while the provider\n * does not know its real rate yet: then no placeholder record is built\n * (B1b; the provider passes `isSampleRateKnown ? sampleRate : null`).\n */\n placeholderSampleRate: number | null;\n}\n\nexport interface ArrangementView {\n /** The arrangement's tracks without their loading clips. Never write to them. */\n tracks: readonly ClipTrack[];\n /** One row per track, in the arrangement's clip order, placeholders included. */\n peaksDataArray: TrackClipPeaks[];\n /** The end, in seconds, of the loaded audio (placeholders do not count). */\n duration: number;\n /** One entry per track, in order, from the arrangement's mixer. */\n trackStates: TrackState[];\n canUndo: boolean;\n canRedo: boolean;\n /** The last pass of `derivePeaks` (loaded clips): for the trim preview. */\n peaksCacheRef: React.RefObject<PeaksCache>;\n /** What the loaded clips' peaks are derived with: for the trim preview. */\n peaksOptions: DerivePeaksOptions;\n}\n\ninterface RowsCache {\n readonly byTrackId: ReadonlyMap<string, TrackClipPeaks>;\n readonly result: TrackClipPeaks[];\n}\n\ninterface StatesCache {\n readonly byTrackId: ReadonlyMap<string, TrackState>;\n readonly result: TrackState[];\n}\n\nconst EMPTY_ROWS: RowsCache = { byTrackId: new Map(), result: [] };\nconst EMPTY_STATES: StatesCache = { byTrackId: new Map(), result: [] };\nconst DEFAULT_MIX: TrackMixerValues = { volume: 1, muted: false, soloed: false, pan: 0 };\n\ninterface RowInputs {\n loadedPeaks: PeaksCache;\n samplesPerPixel: number;\n mono: boolean;\n placeholderSampleRate: number | null;\n}\n\n/** A track's row: each clip's record by clip id, placeholders where they can be drawn. */\nfunction rowFor(track: ArrangementTrack, index: number, inputs: RowInputs): TrackClipPeaks {\n const loadedRow = inputs.loadedPeaks.result[index];\n if (!track.clips.some(isLoadingClip)) return loadedRow;\n const rate = inputs.placeholderSampleRate;\n const row: ClipPeaks[] = [];\n for (const clip of track.clips) {\n if (!isLoadingClip(clip)) {\n const entry = inputs.loadedPeaks.clips.get(clip.id);\n if (entry) row.push(entry.clipPeaks);\n continue;\n }\n if (rate === null) continue;\n const record = placeholderPeaks(clip, track.name, {\n contextSampleRate: rate,\n samplesPerPixel: inputs.samplesPerPixel,\n mono: inputs.mono,\n });\n if (record) row.push(record);\n }\n return row;\n}\n\nfunction deriveRows(\n tracks: readonly ArrangementTrack[],\n inputs: RowInputs,\n previous: RowsCache\n): RowsCache {\n const byTrackId = new Map<string, TrackClipPeaks>();\n const rows = tracks.map((track, index) => {\n const row = rowFor(track, index, inputs);\n const before = previous.byTrackId.get(track.id);\n const stable = sameItems(before, row) ? before : row;\n byTrackId.set(track.id, stable);\n return stable;\n });\n return { byTrackId, result: sameItems(previous.result, rows) ? previous.result : rows };\n}\n\nfunction sameState(a: TrackState, name: string, mix: TrackMixerValues): boolean {\n return (\n a.name === name &&\n a.volume === mix.volume &&\n a.muted === mix.muted &&\n a.soloed === mix.soloed &&\n a.pan === mix.pan\n );\n}\n\nfunction deriveTrackStates(\n tracks: readonly ArrangementTrack[],\n mixer: ReadonlyMap<string, TrackMixerValues>,\n previous: StatesCache\n): StatesCache {\n const byTrackId = new Map<string, TrackState>();\n const states = tracks.map((track) => {\n // Every track the arrangement holds has a mixer entry; the default is\n // there so that the array never holds `undefined`.\n const mix = mixer.get(track.id) ?? DEFAULT_MIX;\n const before = previous.byTrackId.get(track.id);\n const state =\n before && sameState(before, track.name, mix)\n ? before\n : {\n name: track.name,\n volume: mix.volume,\n muted: mix.muted,\n soloed: mix.soloed,\n pan: mix.pan,\n };\n byTrackId.set(track.id, state);\n return state;\n });\n return { byTrackId, result: sameItems(previous.result, states) ? previous.result : states };\n}\n\n/** A value of the arrangement, read with `useSyncExternalStore` (a primitive or a kept object). */\nfunction useArrangementValue<T>(arrangement: Arrangement, read: (a: Arrangement) => T): T {\n const store = useMemo(\n () => ({\n subscribe: (listener: () => void) => arrangement.subscribe(listener),\n getSnapshot: () => read(arrangement),\n }),\n [arrangement, read]\n );\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n\nconst readMixer = (arrangement: Arrangement) => arrangement.getMixer();\nconst readCanUndo = (arrangement: Arrangement) => arrangement.canUndo;\nconst readCanRedo = (arrangement: Arrangement) => arrangement.canRedo;\n\nexport function useArrangementView(\n arrangement: Arrangement,\n options: ArrangementViewOptions\n): ArrangementView {\n const { samplesPerPixel, mono, baseScale, placeholderSampleRate } = options;\n const arrangementTracks = useArrangementTracks(arrangement);\n const mixer = useArrangementValue(arrangement, readMixer);\n const canUndo = useArrangementValue(arrangement, readCanUndo);\n const canRedo = useArrangementValue(arrangement, readCanRedo);\n\n // The caches below are projections of the arrangement, kept so that each\n // pass can hand back what did not change; nothing reads them as state.\n const loadedCacheRef = useRef<LoadedTracksCache>(EMPTY_LOADED_TRACKS);\n const tracks = useMemo(() => {\n const next = loadedTracks(arrangementTracks, loadedCacheRef.current);\n loadedCacheRef.current = next.cache;\n return next.tracks;\n }, [arrangementTracks]);\n\n const { getWaveformData, version } = useWaveformDataCache(tracks, baseScale);\n const peaksOptions = useMemo<DerivePeaksOptions>(\n () => ({ samplesPerPixel, mono, getGeneratedWaveformData: getWaveformData }),\n [samplesPerPixel, mono, getWaveformData]\n );\n\n const peaksCacheRef = useRef<PeaksCache>(EMPTY_PEAKS_CACHE);\n const loadedPeaks = useMemo(() => {\n const next = derivePeaks(tracks, peaksOptions, peaksCacheRef.current);\n peaksCacheRef.current = next;\n return next;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `version` invalidates the ref-backed lookup\n }, [tracks, peaksOptions, version]);\n\n const rowsCacheRef = useRef<RowsCache>(EMPTY_ROWS);\n const peaksDataArray = useMemo(() => {\n const inputs = { loadedPeaks, samplesPerPixel, mono, placeholderSampleRate };\n const next = deriveRows(arrangementTracks, inputs, rowsCacheRef.current);\n rowsCacheRef.current = next;\n return next.result;\n }, [arrangementTracks, loadedPeaks, samplesPerPixel, mono, placeholderSampleRate]);\n\n const duration = useMemo(() => timelineDuration(tracks), [tracks]);\n\n const statesCacheRef = useRef<StatesCache>(EMPTY_STATES);\n const trackStates = useMemo(() => {\n const next = deriveTrackStates(arrangementTracks, mixer, statesCacheRef.current);\n statesCacheRef.current = next;\n return next.result;\n }, [arrangementTracks, mixer]);\n\n return {\n tracks,\n peaksDataArray,\n duration,\n trackStates,\n canUndo,\n canRedo,\n peaksCacheRef,\n peaksOptions,\n };\n}\n","/**\n * placeholderPeaks\n *\n * The drawing record of a clip whose audio is still loading (#812). It is a\n * `ClipPeaks` with `isPlaceholder: true` and exists nowhere else: no tracks\n * array holds a clip for it. The caller finds it by `clipId`.\n *\n * Drawn from the loading clip's own `waveformData` when it has usable ones,\n * else an empty box as long as its `duration`. `null` when neither gives a\n * length, or when a time is not a usable number. Its sample positions and\n * `sampleRate` are at `contextSampleRate`, whatever the rate of the peaks.\n */\nimport type { LoadingClip } from '@waveform-playlist/core';\nimport type WaveformData from 'waveform-data';\nimport type { ClipPeaks, TrackClipPeaks } from '../WaveformPlaylistContext';\nimport { extractFromOwnWaveformData } from './derivePeaks';\n\nexport interface PlaceholderPeaksOptions {\n contextSampleRate: number;\n samplesPerPixel: number;\n mono: boolean;\n}\n\ninterface MemoEntry {\n trackName: string;\n options: PlaceholderPeaksOptions;\n result: ClipPeaks | null;\n}\n\n// The last result per loading-clip object: the provider asks again on every\n// derivation and a new object would redraw the row.\nconst memo = new WeakMap<LoadingClip, MemoEntry>();\n\nfunction sameOptions(a: PlaceholderPeaksOptions, b: PlaceholderPeaksOptions): boolean {\n return (\n a.contextSampleRate === b.contextSampleRate &&\n a.samplesPerPixel === b.samplesPerPixel &&\n a.mono === b.mono\n );\n}\n\nfunction isTime(value: number | undefined): boolean {\n return value === undefined || (Number.isFinite(value) && value >= 0);\n}\n\nfunction usableWaveformData(clip: LoadingClip): WaveformData | undefined {\n const data = clip.waveformData as WaveformData | undefined;\n if (!data) return undefined;\n const ok =\n Number.isFinite(data.sample_rate) &&\n data.sample_rate > 0 &&\n Number.isFinite(data.duration) &&\n data.duration >= 0;\n return ok ? data : undefined;\n}\n\nfunction build(\n clip: LoadingClip,\n trackName: string,\n options: PlaceholderPeaksOptions\n): ClipPeaks | null {\n const wdata = usableWaveformData(clip);\n // A null duration is \"not given\", as in the engine's resolveLoadingClip: plain\n // JavaScript or JSON input can carry one although the type does not.\n const duration = (clip.duration as number | null | undefined) ?? undefined;\n if (duration === undefined && !wdata) return null;\n if (!isTime(clip.start) || !isTime(clip.offset) || !isTime(duration)) return null;\n // The geometry is at the context's rate, also for peaks at another rate:\n // the audio is decoded at the context's rate, so that is the rate of the\n // loaded clip this record stands in for (B1, #812).\n const rate = options.contextSampleRate;\n if (!(Number.isFinite(rate) && rate > 0)) return null;\n\n const startSample = Math.round((clip.start ?? 0) * rate);\n const offsetSamples = Math.round((clip.offset ?? 0) * rate);\n // With peaks the clip cannot be longer than the file: the same cut as the\n // loaded clip's, the file's length in seconds at the context's rate. An\n // offset at or past the end leaves no samples (`rest` < 1), which gives null\n // below.\n const total = wdata ? Math.ceil(wdata.duration * rate) : undefined;\n const rest = total === undefined ? undefined : total - offsetSamples;\n const wanted = duration === undefined ? rest : Math.round(duration * rate);\n const durationSamples =\n rest === undefined ? (wanted as number) : Math.min(wanted as number, rest);\n if (![startSample, offsetSamples, durationSamples, total ?? 0].every(Number.isSafeInteger)) {\n return null;\n }\n if (durationSamples < 1) return null;\n\n // Converted to the file's own sample positions through the ratio of the two\n // rates, as for a loaded clip drawn from its own peaks.\n const drawn = wdata\n ? extractFromOwnWaveformData(\n { sampleRate: rate, offsetSamples, durationSamples },\n wdata,\n options.samplesPerPixel,\n options.mono\n )\n : undefined;\n const peaks = drawn ?? { length: 0, data: [new Int16Array(0)], bits: 16 as const };\n\n return {\n clipId: clip.id,\n trackName,\n peaks,\n startSample,\n durationSamples,\n offsetSamples,\n sampleRate: rate,\n fadeIn: clip.fadeIn,\n fadeOut: clip.fadeOut,\n gain: clip.gain,\n isPlaceholder: true,\n };\n}\n\nexport function placeholderPeaks(\n clip: LoadingClip,\n trackName: string,\n options: PlaceholderPeaksOptions\n): ClipPeaks | null {\n const hit = memo.get(clip);\n if (hit && hit.trackName === trackName && sameOptions(hit.options, options)) return hit.result;\n const result = build(clip, trackName, options);\n memo.set(clip, { trackName, options: { ...options }, result });\n return result;\n}\n\n/** The end in seconds of the last placeholder record of `rows`, 0 when there is none. */\nexport function placeholdersEnd(rows: readonly TrackClipPeaks[]): number {\n let end = 0;\n for (const row of rows) {\n for (const record of row) {\n if (!record.isPlaceholder || !record.sampleRate) continue;\n end = Math.max(end, (record.startSample + record.durationSamples) / record.sampleRate);\n }\n }\n return end;\n}\n","import type { ClipTrack } from '@waveform-playlist/core';\n\n/**\n * Timeline length in seconds: the end of the last clip across all tracks.\n * Uses each clip's own `sampleRate`, which is always defined (peaks-only clips\n * have no AudioBuffer to ask).\n */\nexport function timelineDuration(tracks: readonly ClipTrack[]): number {\n let maxDuration = 0;\n for (const track of tracks) {\n for (const clip of track.clips) {\n const clipEnd = (clip.startSample + clip.durationSamples) / clip.sampleRate;\n if (clipEnd > maxDuration) maxDuration = clipEnd;\n }\n }\n return maxDuration;\n}\n","/**\n * useReadyOnce\n *\n * \"Ready\" for `WaveformPlaylistProvider` on an arrangement (#812, QE). The\n * provider is the one owner of `isReady` and of \"ready has fired\".\n *\n * - `isReady` is false until an engine is attached and no source of the\n * arrangement is pending, for the first time; from then on it is \"an\n * engine is attached\" (false while a later engine is being built, true\n * again when it is assigned, whatever is still loading then).\n * - `onReady` and the `waveform-playlist:ready` event fire ONCE per mount, at\n * that first time: not again after a rebuild, a StrictMode remount or an\n * `<Activity>` hide and reveal. The event's `trackCount` counts every track\n * of the arrangement, its `duration` the loaded audio (A5).\n * - A failed source counts as settled, and is not reported through `onError`\n * (QB). An `onReady` that throws is the app's own error: it is written to\n * the console and given to `onError`.\n * - Play does nothing before that first time (maintainer, 2026-11-15):\n * `refusePlayBeforeFirstReady()` says so to `play()` at call time, and\n * writes one console warning per mount in a development build (none in a\n * production build). It queues nothing, so Play pressed\n * during the first load never starts by itself.\n */\nimport { useCallback, useEffect, useInsertionEffect, useRef, useState } from 'react';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { useArrangementSources } from '../hooks/useArrangementSources';\nimport { isDevelopmentBuild } from '../utils/isDevelopmentBuild';\n\nconst READY_EVENT = 'waveform-playlist:ready';\n\nconst PLAY_BEFORE_READY_WARNING =\n '[waveform-playlist] play() was called before the playlist was ready and did nothing: ' +\n 'playback starts once the playlist is ready. Wait for `isReady` ' +\n '(usePlaylistTimeline) or the `onReady` callback before calling play().';\n\ninterface ReadyEventDetail {\n trackCount: number;\n duration: number;\n}\n\nexport interface UseReadyOnceOptions {\n /** From `useEngineLifetime`: false from the start of each build until its engine is assigned. */\n isEngineAttached: boolean;\n arrangement: Arrangement;\n /** The latest committed `onReady` (QG). */\n onReadyRef: React.RefObject<(() => void) | undefined>;\n /** The latest committed `onError` (QG). */\n onErrorRef: React.RefObject<((error: Error) => void) | undefined>;\n /** The number of tracks in the arrangement, loaded or not. */\n trackCount: number;\n /** The end, in seconds, of the loaded audio. */\n duration: number;\n}\n\nfunction callOnReady({\n onReadyRef,\n onErrorRef,\n}: Pick<UseReadyOnceOptions, 'onReadyRef' | 'onErrorRef'>): void {\n try {\n onReadyRef.current?.();\n } catch (callbackError) {\n const thrown =\n callbackError instanceof Error ? callbackError : new Error(String(callbackError));\n console.error('[waveform-playlist] The onReady callback threw: ' + thrown.message);\n onErrorRef.current?.(thrown);\n }\n}\n\nexport interface ReadyOnce {\n isReady: boolean;\n /**\n * True when the first ready of this mount has not happened yet, so a play\n * must do nothing; warns the first time per mount, in development builds\n * only. Never changes identity.\n */\n refusePlayBeforeFirstReady: () => boolean;\n}\n\nexport function useReadyOnce(options: UseReadyOnceOptions): ReadyOnce {\n const { isEngineAttached, arrangement, onReadyRef, onErrorRef, trackCount, duration } = options;\n const { pendingCount } = useArrangementSources(arrangement);\n // State, for the render; the ref, so that StrictMode's second run of the\n // effect and an <Activity> reveal do not fire again.\n const [hasBeenReady, setHasBeenReady] = useState(false);\n const firedRef = useRef(false);\n const isReady = isEngineAttached && (hasBeenReady || pendingCount === 0);\n // \"The first ready has happened\", for play() at call time. Written where\n // React commits, so a discarded render cannot leave it true, and never\n // back to false. In an insertion effect: those run in the commit's mutation\n // phase, before every layout effect, ref callback and passive effect of the\n // same commit, so a descendant that calls play() from any of them (or from\n // onReady) on the first `isReady` is not refused. A layout effect here ran\n // after the descendants' layout effects and refused theirs.\n const firstReadyRef = useRef(false);\n const warnedPlayRef = useRef(false);\n useInsertionEffect(() => {\n if (isReady) firstReadyRef.current = true;\n }, [isReady]);\n\n const refusePlayBeforeFirstReady = useCallback(() => {\n if (firstReadyRef.current) return false;\n if (!warnedPlayRef.current && isDevelopmentBuild()) {\n warnedPlayRef.current = true;\n console.warn(PLAY_BEFORE_READY_WARNING);\n }\n return true;\n }, []);\n\n useEffect(() => {\n if (!isReady || firedRef.current) return;\n firedRef.current = true;\n setHasBeenReady(true);\n const detail: ReadyEventDetail = { trackCount, duration };\n window.dispatchEvent(new CustomEvent<ReadyEventDetail>(READY_EVENT, { detail }));\n callOnReady({ onReadyRef, onErrorRef });\n }, [isReady, trackCount, duration, onReadyRef, onErrorRef]);\n\n return { isReady, refusePlayBeforeFirstReady };\n}\n","/**\n * useArrangementEditing\n *\n * The editor actions of `WaveformPlaylistProvider` that change the\n * arrangement (#812): the four mixer setters, `reorderTrack`, `undo`, `redo`\n * and `setRecordingActive`. Each asks the arrangement, which owns the tracks,\n * the mix and the history, and works whether an engine is attached or not;\n * the engine follows the arrangement. Every function keeps its identity for\n * the life of the provider (the arrangement does not change within a mount).\n * Also the value of `RecordingArmContext`: which track is armed for a take.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { createValueSource } from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { warnOnce } from '../components/partWarnings';\nimport type { RecordingArmContextValue } from '../contexts/playlistContexts';\n\ntype MixerSetter = 'setTrackMute' | 'setTrackSolo' | 'setTrackVolume' | 'setTrackPan';\n\n/** A call with anything but a string id is a call from before #687: ignored, once said. */\nfunction isTrackId(setter: MixerSetter, trackId: unknown): trackId is string {\n if (typeof trackId === 'string') return true;\n warnOnce(\n `${setter}() takes a track id since the track controls became parts: ` +\n `${setter}(tracks[index].id, value). A call with anything but a string is ignored.`\n );\n return false;\n}\n\nexport interface ArrangementEditing {\n setTrackMute: (trackId: string, muted: boolean) => void;\n setTrackSolo: (trackId: string, soloed: boolean) => void;\n setTrackVolume: (trackId: string, volume: number) => void;\n setTrackPan: (trackId: string, pan: number) => void;\n reorderTrack: (trackId: string, toIndex: number) => void;\n undo: () => void;\n redo: () => void;\n setRecordingActive: (active: boolean, armedTrackId?: string | null) => void;\n /** True while a recording session is active: the animation loop and `seekTo` read it. */\n recordingActiveRef: React.RefObject<boolean>;\n /** The value of `RecordingArmContext`; a new object only when the armed track changes. */\n recordingArm: RecordingArmContextValue;\n}\n\n/** The armed track and its mute from before the session. */\ninterface ArmedTrack {\n trackId: string;\n prevMuted: boolean;\n}\n\n/**\n * Recording session state. While active:\n * 1. the animation loop's end-of-audio auto-stop is suppressed, so overdub\n * playback runs past the end of existing material (#589/#590);\n * 2. the armed track is muted in the arrangement: punch-in replaces whatever\n * the take overlaps (#579), so that material must not play under the\n * overdub. Its mute from before the session is written back when the\n * session ends or the armed track changes, whatever was set in between\n * (QJ, #812); the arrangement's setter does nothing for a track that is gone.\n * Called by useRecordingSession for the length of a take; overdub flows also\n * call it eagerly before play(), because a render round-trip loses the race\n * against the first animation frame (play() does nothing before the first\n * ready, so a take started during the first load records without playback).\n * The provider also writes the mute from before the session back in its own\n * cleanup (below) when a track is still armed.\n *\n * The armed track is one value source, its owner: the setter reads and\n * writes it synchronously (a start and an end in one handler), and the\n * provider renders from it, so the armed track's panel follows.\n */\nfunction useRecordingActive(arrangement: Arrangement) {\n const recordingActiveRef = useRef(false);\n const [armed] = useState(() => createValueSource<ArmedTrack | null>(null));\n const setRecordingActive = useCallback(\n (active: boolean, armedTrackId?: string | null) => {\n recordingActiveRef.current = active;\n const current = armed.source.getSnapshot();\n if (active && armedTrackId) {\n if (current?.trackId === armedTrackId) return; // already armed\n // Armed track changed mid-session: restore the previous one first.\n if (current) arrangement.setTrackMute(current.trackId, current.prevMuted);\n const prevMuted = arrangement.getMixer().get(armedTrackId)?.muted ?? false;\n armed.publish({ trackId: armedTrackId, prevMuted });\n arrangement.setTrackMute(armedTrackId, true);\n } else if (!active && current) {\n arrangement.setTrackMute(current.trackId, current.prevMuted);\n armed.publish(null);\n }\n },\n [arrangement, armed]\n );\n // The arrangement outlives the provider (maintainer, F1): when the provider\n // goes (unmount, an <Activity> hide, a StrictMode or Fast Refresh remount)\n // with a track still armed, its mute from before the take is written back\n // and the session ends. Nothing happens when the session was already\n // released (by useRecordingSession's own cleanup) or never armed a track;\n // a session armed again after a remount or a reveal works as before.\n useEffect(\n () => () => {\n if (armed.source.getSnapshot()) setRecordingActive(false);\n },\n [armed, setRecordingActive]\n );\n const getArmedTrackId = useCallback(() => armed.source.getSnapshot()?.trackId ?? null, [armed]);\n const armedTrackId = useSyncExternalStore(armed.source.subscribe, getArmedTrackId);\n const recordingArm = useMemo(() => ({ armedTrackId }), [armedTrackId]);\n return { setRecordingActive, recordingActiveRef, recordingArm };\n}\n\nexport function useArrangementEditing(arrangement: Arrangement): ArrangementEditing {\n const setTrackMute = useCallback(\n (trackId: string, muted: boolean) => {\n if (isTrackId('setTrackMute', trackId)) arrangement.setTrackMute(trackId, muted);\n },\n [arrangement]\n );\n const setTrackSolo = useCallback(\n (trackId: string, soloed: boolean) => {\n if (isTrackId('setTrackSolo', trackId)) arrangement.setTrackSolo(trackId, soloed);\n },\n [arrangement]\n );\n const setTrackVolume = useCallback(\n (trackId: string, volume: number) => {\n if (isTrackId('setTrackVolume', trackId)) arrangement.setTrackVolume(trackId, volume);\n },\n [arrangement]\n );\n const setTrackPan = useCallback(\n (trackId: string, pan: number) => {\n if (isTrackId('setTrackPan', trackId)) arrangement.setTrackPan(trackId, pan);\n },\n [arrangement]\n );\n const reorderTrack = useCallback(\n (trackId: string, toIndex: number) => arrangement.reorderTrack(trackId, toIndex),\n [arrangement]\n );\n const undo = useCallback(() => arrangement.undo(), [arrangement]);\n const redo = useCallback(() => arrangement.redo(), [arrangement]);\n const { setRecordingActive, recordingActiveRef, recordingArm } = useRecordingActive(arrangement);\n return {\n setTrackMute,\n setTrackSolo,\n setTrackVolume,\n setTrackPan,\n reorderTrack,\n undo,\n redo,\n setRecordingActive,\n recordingActiveRef,\n recordingArm,\n };\n}\n","/**\n * Development-only warnings, written once per message for the life of the\n * page: for a part of the view that is rendered where it cannot work (#685;\n * it does not throw: it draws nothing, or draws in the wrong place), and for a\n * call with an argument of an older signature (#687).\n */\nimport { isDevelopmentBuild } from '../utils/isDevelopmentBuild';\n\nconst warned = new Set<string>();\n\nexport function warnOnce(message: string): void {\n if (!isDevelopmentBuild()) return;\n if (warned.has(message)) return;\n warned.add(message);\n console.warn('[waveform-playlist] ' + message);\n}\n\n/** A part of the view that is not where it can work. */\nexport const warnMisplacedPart = warnOnce;\n\n/** For tests: forget what has been warned, so each test sees its own warning. */\nexport function resetPartWarnings(): void {\n warned.clear();\n}\n","/**\n * arrangementIdentity\n *\n * Which arrangement object `WaveformPlaylistProvider` was given (#812). The\n * provider keys its body with the arrangement's number, so a new object is a\n * new mount of everything below it, and it says so once in development.\n *\n * Only numbers are kept: the map is weak, and the component remembers the\n * number of the first arrangement, not the object, so an arrangement the app\n * has let go of (its tracks, its decoded audio) can be collected.\n */\nimport { useEffect, useRef } from 'react';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { isDevelopmentBuild } from '../utils/isDevelopmentBuild';\n\nconst arrangementKeys = new WeakMap<Arrangement, number>();\nlet lastArrangementKey = 0;\n\nconst MISSING_ARRANGEMENT_ERROR =\n '[waveform-playlist] WaveformPlaylistProvider needs an `arrangement` prop: an ' +\n 'arrangement made with `useCreateArrangement`, which owns the tracks. The `tracks` and ' +\n '`onTracksChange` props were removed. See ' +\n 'https://naomiaro.github.io/waveform-playlist/docs/react/upgrading';\n\n/**\n * The arrangement's own number: the same for the same object, new for another\n * one. Anything that is not an object (plain JavaScript, or code that still\n * passes only `tracks`) throws: the provider cannot run without one.\n */\nexport function keyOf(arrangement: Arrangement): number {\n if (typeof arrangement !== 'object' || arrangement === null) {\n throw new Error(MISSING_ARRANGEMENT_ERROR);\n }\n let key = arrangementKeys.get(arrangement);\n if (key === undefined) {\n lastArrangementKey += 1;\n key = lastArrangementKey;\n arrangementKeys.set(arrangement, key);\n }\n return key;\n}\n\nconst NEW_ARRANGEMENT_WARNING =\n '[waveform-playlist] WaveformPlaylistProvider was given a new `arrangement` prop: ' +\n 'everything below it mounts again (a new engine, the view and its state). Keep one ' +\n 'arrangement for the life of the playlist (`useCreateArrangement`) and change it ' +\n 'through its methods.';\n\n/**\n * The key of the provider's body for `arrangement`. The first time it differs\n * from the key of the mount's first arrangement, says so in development.\n */\nexport function useArrangementKey(arrangement: Arrangement): number {\n const key = keyOf(arrangement);\n const firstKeyRef = useRef(key);\n const warnedRef = useRef(false);\n useEffect(() => {\n if (key === firstKeyRef.current || warnedRef.current) return;\n warnedRef.current = true;\n if (isDevelopmentBuild()) console.warn(NEW_ARRANGEMENT_WARNING);\n }, [key]);\n return key;\n}\n","import React, {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useCallback,\n useMemo,\n type ReactNode,\n} from 'react';\nimport { ThemeProvider } from 'styled-components';\nimport type { MediaElementPlayout, FadeConfig } from '@waveform-playlist/media-element-playout';\nimport { resolveMediaElementPlayout } from './playout/resolveMediaElementPlayout';\nimport { type WaveformDataObject } from '@waveform-playlist/core';\nimport type { WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport { extractPeaksFromWaveformData } from './waveformDataLoader';\nimport type WaveformData from 'waveform-data';\nimport type { PeakData } from '@waveform-playlist/core';\nimport type { ClipPeaks, TrackClipPeaks } from './WaveformPlaylistContext';\nimport { useAnimationFrameLoop } from './hooks/useAnimationFrameLoop';\nimport { followAnnotations } from './providerInternals/followAnnotations';\nimport {\n useAnnotationState,\n type AnnotationListProp,\n} from './providerInternals/useAnnotationState';\nimport { useFrameCallbacks } from './providerInternals/useFrameCallbacks';\nimport { centrePlayhead, useScrollFollow } from './providerInternals/useScrollFollow';\nimport { useMergedTheme } from './providerInternals/useMergedTheme';\nimport { useTimeFormat } from './hooks/useTimeFormat';\nimport { useShallowStable } from './hooks/useShallowStable';\nimport {\n BLOCKED,\n ActiveAnnotationContext,\n ArrangementContext,\n AnnotationOptionsContext,\n AnnotationsContext,\n CurrentTimeContext,\n EditorControlsContext,\n EngineRefsContext,\n IsPlayingContext,\n LoopContext,\n MediaElementTrackContext,\n PlaybackControlsContext,\n PlaybackRateContext,\n PlaybackRefsContext,\n PlaylistMixerContext,\n PlaylistSettingsContext,\n PlaylistTimelineContext,\n PlaylistViewContext,\n PlaylistZoomContext,\n SelectedTrackIdContext,\n SelectedRowContext,\n MEDIA_ELEMENT_TRACK_ID,\n SelectionContext,\n TrackReorderPreviewContext,\n TrimPreviewContext,\n RecordingArmContext,\n TrimPreviewPeaksContext,\n UndoRedoContext,\n type ActiveAnnotationContextValue,\n type CurrentTimeContextValue,\n type IsPlayingContextValue,\n type MediaElementTrackContextValue,\n type PlaybackControlsContextValue,\n type PlaybackRateContextValue,\n type PlaybackRefsContextValue,\n type PlaylistSettingsContextValue,\n type PlaylistViewContextValue,\n type PlaylistZoomContextValue,\n type SelectionContextValue,\n} from './contexts/playlistContexts';\n\n// The one row of the view is always drawn as selected. One object, so the\n// context value never changes.\nconst ONLY_ROW_SELECTED = { selectedTrackId: MEDIA_ELEMENT_TRACK_ID };\n\n// Configuration for a single media element track\nexport interface MediaElementTrackConfig {\n /** Audio source URL or Blob URL */\n source: string;\n /** Pre-computed waveform data (required for visualization) */\n waveformData: WaveformDataObject;\n /** Track name for display */\n name?: string;\n /** Fade in configuration (requires audioContext on provider) */\n fadeIn?: FadeConfig;\n /** Fade out configuration (requires audioContext on provider) */\n fadeOut?: FadeConfig;\n}\n\nexport interface MediaElementPlaylistProviderProps {\n /** Single track configuration with source URL and waveform data */\n track: MediaElementTrackConfig;\n /** Initial samples per pixel (zoom level) */\n samplesPerPixel?: number;\n /** Playback rate (default 1). Not clamped by the provider: the bundled\n * engine is created at it as given, while `setPlaybackRate` clamps to\n * 0.5–2. The user's `setPlaybackRate` overrides it; a later change of this\n * prop overrides that, until they choose again. */\n playbackRate?: number;\n /** Whether to preserve pitch when changing playback rate (default: true).\n * Set to false when using an external pitch processor like SoundTouch. */\n preservesPitch?: boolean;\n /** Enable automatic scroll to keep playhead centered */\n automaticScroll?: boolean;\n /** Theme configuration */\n theme?: Partial<WaveformPlaylistTheme>;\n /**\n * The annotations and the three annotation options (`editable`,\n * `linkEndpoints`, `isContinuousPlay`). The provider follows all four: an\n * option takes a new value of its field, and a setter or checkbox changes\n * it in between.\n */\n annotationList?: AnnotationListProp;\n /** Callback when annotations are changed (drag, edit, etc.) */\n onAnnotationsChange?: (annotations: AnnotationData[]) => void;\n /**\n * AudioContext for Web Audio routing (fades, effects).\n * When provided, audio routes through Web Audio nodes:\n * HTMLAudioElement → MediaElementSourceNode → fadeGain → volumeGain → destination\n *\n * Without this, playback uses HTMLAudioElement directly (no fades or effects).\n * Each provider instance should use its own AudioContext or share one —\n * createMediaElementSource() is called once per audio element.\n */\n audioContext?: AudioContext;\n /** Called when the media element has loaded its metadata (it knows its\n * length and can be played and seeked), once per player. */\n onReady?: () => void;\n /** Called when playout initialization fails (e.g. a missing optional peer,\n * a throwing `createPlayout`, or an `addTrack` error) and when the media\n * element reports an error (a source that cannot be loaded or decoded).\n * The provider already logs the error; use this to surface it in your UI. */\n onError?: (err: Error) => void;\n /** Factory for a custom MediaElement playout. When omitted, the bundled engine\n * (@waveform-playlist/media-element-playout) is dynamically imported. A\n * custom playout must implement `on()` and emit `loadedmetadata`: the\n * provider is not ready until it does. */\n createPlayout?: () => MediaElementPlayout;\n children: ReactNode;\n}\n\n/**\n * MediaElementPlaylistProvider\n *\n * A simplified playlist provider for single-track playback using HTMLAudioElement.\n * Key features:\n * - Pitch-preserving playback rate (0.5x - 2.0x)\n * - Pre-computed peaks visualization (no AudioBuffer needed)\n * - Simpler API than full WaveformPlaylistProvider\n *\n * Use this for:\n * - Language learning apps (speed control)\n * - Podcast players\n * - Single-track audio viewers\n *\n * For multi-track editing, use WaveformPlaylistProvider instead.\n */\nexport const MediaElementPlaylistProvider: React.FC<MediaElementPlaylistProviderProps> = ({\n track,\n samplesPerPixel: initialSamplesPerPixel = 1024,\n playbackRate: initialPlaybackRate = 1,\n preservesPitch = true,\n automaticScroll = false,\n theme: userThemeProp,\n annotationList,\n audioContext,\n onAnnotationsChange,\n onReady,\n onError,\n createPlayout,\n children,\n}) => {\n const mergedTheme = useMergedTheme(userThemeProp);\n\n // State\n const [isPlaying, setIsPlayingState] = useState(false);\n // Read by `seekTo` and `setSelection`, which must know at call time whether\n // playback is running; written together with the state, never by a render.\n const isPlayingRef = useRef(false);\n const setIsPlaying = useCallback((playing: boolean) => {\n isPlayingRef.current = playing;\n setIsPlayingState(playing);\n }, []);\n const [currentTime, setCurrentTime] = useState(0);\n const [isReady, setIsReady] = useState(false);\n const [playbackRate, setPlaybackRateState] = useState(initialPlaybackRate);\n // The latest instruction wins: the `playbackRate` prop when it changes, or\n // what the user chose with `setPlaybackRate` since. A changed prop becomes\n // the state here, during render (the \"derive state from a prop\" pattern),\n // so the speed select never shows a speed other than the one playing.\n const [ratePropSeen, setRatePropSeen] = useState(initialPlaybackRate);\n // `Object.is`: a NaN prop (a failed parse in the consumer) must compare\n // equal to itself, or this would set state on every render.\n if (!Object.is(ratePropSeen, initialPlaybackRate)) {\n setRatePropSeen(initialPlaybackRate);\n setPlaybackRateState(initialPlaybackRate);\n }\n // The same speed for a player that arrives later (see the init effect).\n // Written by `setPlaybackRate`, and by the layout effect below for a prop\n // VALUE it has not applied yet. Not on every run: the effect also runs\n // again with the same prop (a StrictMode remount, a revealed `<Activity>`),\n // and it runs after a child's layout effect of the same commit; none of\n // those is a new instruction, and each would put the prop's speed back\n // over one that was chosen since. A layout effect, for two reasons: a\n // render React discards leaves nothing here that never committed, and it\n // runs before any child's passive effect of the same commit, so a child\n // that sets a speed in answer to a prop change (restoring a saved one) is\n // the later instruction and wins.\n const playbackRateRef = useRef(initialPlaybackRate);\n const ratePropAppliedRef = useRef(initialPlaybackRate);\n useLayoutEffect(() => {\n if (Object.is(ratePropAppliedRef.current, initialPlaybackRate)) return;\n ratePropAppliedRef.current = initialPlaybackRate;\n playbackRateRef.current = initialPlaybackRate;\n }, [initialPlaybackRate]);\n // Annotations are derived from the prop (single source of truth in the\n // parent). Shared with the WebAudio provider (#769).\n const {\n annotationsRef,\n annotationLookup,\n setAnnotations,\n annotationPreview,\n activeAnnotationId,\n activeAnnotationIdRef,\n setActiveAnnotationId,\n continuousPlayRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationsValue,\n annotationOptionsValue,\n } = useAnnotationState({\n annotationList,\n onAnnotationsChange,\n providerName: 'MediaElementPlaylistProvider',\n });\n const {\n scrollContainerRef,\n setScrollContainer,\n isAutomaticScroll,\n isAutomaticScrollRef,\n setAutomaticScroll,\n } = useScrollFollow(automaticScroll);\n // The playhead, the progress overlay and `AudioPosition` register here; the\n // one loop below draws them.\n const { registerFrameCallback, unregisterFrameCallback, runFrameCallbacks } = useFrameCallbacks();\n\n // The time selection. Setting it moves the cursor to its start, and Play\n // plays it (see `setSelection` and `play` below), as under the WebAudio\n // provider (#688).\n const [selection, setSelectionState] = useState<SelectionContextValue>({\n selectionStart: 0,\n selectionEnd: 0,\n });\n const selectionRef = useRef(selection);\n\n const [samplesPerPixel] = useState(initialSamplesPerPixel);\n const { timeFormat, setTimeFormat } = useTimeFormat();\n\n // Refs\n const playoutRef = useRef<MediaElementPlayout | null>(null);\n const currentTimeRef = useRef<number>(0);\n const samplesPerPixelRef = useRef<number>(initialSamplesPerPixel);\n const { startAnimationFrameLoop, stopAnimationFrameLoop } = useAnimationFrameLoop();\n\n // What the play that is running (or queued) is, in the WebAudio provider's\n // terms (#688):\n // - where Stop, the end of the audio and the end of an annotation return\n // the cursor (for the selection: its start, even when resumed part-way);\n // - where a bounded play ends (null: it runs on);\n // - whether it is the highlighted selection that is playing. Then\n // continuous play is out of the picture: annotation ends do not stop it.\n const playStartPositionRef = useRef(0);\n const playbackEndTimeRef = useRef<number | null>(null);\n const isSelectionPlayRef = useRef(false);\n // Where a queued play ends is `playbackEndTimeRef`, as for a running one.\n // A play asked for while there is no player (the first one is loading, or\n // one is being replaced). Started by the init effect when the player\n // arrives; cleared by Stop, Pause, new audio and a failed init.\n const pendingPlayRef = useRef<{ position: number } | null>(null);\n // False only after an init failed: otherwise there is a player, or one on\n // its way, for a play to start on or wait for. It starts true: a child's\n // mount effect runs before this provider's init effect, and a `play()`\n // there must be queued like any other. The init's cleanup sets it true\n // again for the same reason (cleanups run before any effect of the commit).\n const playoutInFlightRef = useRef(true);\n\n // Get sample rate from waveform data\n const sampleRate = track.waveformData.sample_rate;\n // The length of the audio is known from the waveform data: it does not wait\n // for the player (#688). \"The player can be used\" is `isReady`.\n const duration = track.waveformData.duration;\n\n // Peaks are derived during render, so the waveform is drawn on first paint.\n const trackName = track.name;\n const trackWaveformData = track.waveformData;\n // The peaks alone first: a new name or new fades must not extract them again.\n const trackPeaks = useMemo<{ peaks: PeakData; durationSamples: number } | null>(() => {\n try {\n const durationSamples = Math.ceil(trackWaveformData.duration * sampleRate);\n const extractedPeaks = extractPeaksFromWaveformData(\n trackWaveformData as WaveformData,\n samplesPerPixel,\n 0, // channel index\n 0, // offset\n durationSamples\n );\n return {\n peaks: {\n length: extractedPeaks.length,\n data: [extractedPeaks.data],\n bits: extractedPeaks.bits,\n } as PeakData,\n durationSamples,\n };\n } catch (err) {\n console.warn(\n '[waveform-playlist] Failed to extract peaks from waveform data: ' + String(err)\n );\n return null;\n }\n }, [trackWaveformData, samplesPerPixel, sampleRate]);\n\n // The one clip of the one track. It carries the track's fades, so the view\n // draws them as it draws any clip's (#685).\n // Compared by value: a fade written inline (`fadeIn: { duration: 1 }` in a\n // `track` that is not memoized) is a new object on every render of the\n // parent, and must neither build a new clip nor a new player (below).\n const trackFadeIn = useShallowStable(track.fadeIn);\n const trackFadeOut = useShallowStable(track.fadeOut);\n const peaksDataArray = useMemo<TrackClipPeaks[]>(() => {\n if (!trackPeaks) return [];\n const clipPeaks: ClipPeaks = {\n clipId: 'media-element-clip',\n trackName: trackName ?? 'Track',\n peaks: trackPeaks.peaks,\n startSample: 0,\n durationSamples: trackPeaks.durationSamples,\n fadeIn: trackFadeIn,\n fadeOut: trackFadeOut,\n isPlaceholder: false,\n };\n return [[clipPeaks]];\n }, [trackPeaks, trackName, trackFadeIn, trackFadeOut]);\n\n // The audio of the latest COMMITTED render, read by two things that must not\n // wait for a render or an effect of their own:\n // - the cleanup below, to tell \"new audio\" from \"the same audio in a new\n // player\" (a new name, fades, the pitch setting, a callback's identity);\n // - `seekTo`, which clamps to the length of this audio. The `duration`\n // state cannot serve: it is 0 until the first player is ready and still\n // the previous file's length while the next one loads (and inside\n // `onReady`), so a saved position restored for a longer file was cut off\n // at the old length. Reading a ref also keeps `seekTo`'s identity (#767).\n // Written in a layout effect, not during render: a render React discards\n // (a transition, Suspense) must not leave audio here that never committed.\n // Layout effects run before the passive cleanups of the same commit.\n const latestAudioRef = useRef({ source: track.source, waveformData: track.waveformData });\n useLayoutEffect(() => {\n latestAudioRef.current = { source: track.source, waveformData: track.waveformData };\n }, [track.source, track.waveformData]);\n\n // Ends playback with the cursor resting at `cursor`. The player is paused\n // and moved there too (not `stop()`, which rewinds the element to 0): its\n // own time must agree with the cursor, because the element reports its\n // position back (`timeupdate` writes `currentTimeRef`).\n const restAt = useCallback(\n (cursor: number) => {\n const playout = playoutRef.current;\n if (playout) {\n playout.pause();\n playout.seekTo(cursor);\n }\n stopAnimationFrameLoop();\n setIsPlaying(false);\n playbackEndTimeRef.current = null;\n currentTimeRef.current = cursor;\n setCurrentTime(cursor);\n // Where playback came to rest is where the next one starts from: a Stop\n // pressed while stopped must not move the cursor (to the start of a\n // range that has played out, say). A pause is not a rest.\n playStartPositionRef.current = cursor;\n },\n [stopAnimationFrameLoop, setIsPlaying]\n );\n\n // The init effect starts a queued play when its player arrives, long after\n // the render that created the effect: it reads the loop starter from here.\n const startAnimationLoopRef = useRef<() => void>(() => {});\n // Likewise the step that ends playback, for the engine's `timeupdate`.\n const endPlaybackIfDueRef = useRef<(time: number) => boolean>(() => false);\n\n // Initialize playout and load track\n useEffect(() => {\n let cancelled = false;\n let createdPlayout: MediaElementPlayout | null = null;\n // The audio this run's player is for.\n const source = track.source;\n const waveformData = track.waveformData;\n playoutInFlightRef.current = true;\n\n (async () => {\n try {\n const playout = await resolveMediaElementPlayout({\n createPlayout,\n playbackRate: initialPlaybackRate,\n preservesPitch,\n });\n if (cancelled) {\n playout.dispose();\n return;\n }\n createdPlayout = playout;\n\n // Subscribed before the track exists: the engine attaches the\n // listeners when it creates the media element, so neither event can\n // be missed. \"Ready\" is the element having its metadata (#688), not\n // this object existing; a source that cannot be loaded never is.\n playout.on('loadedmetadata', () => {\n if (cancelled) return;\n setIsReady(true);\n onReady?.();\n });\n // The URL is left out of the message on purpose: it may carry a\n // token, and consumers show `error.message` in their UI.\n playout.on('error', (mediaError) => {\n if (cancelled) return;\n const detail = mediaError\n ? ' (code ' +\n mediaError.code +\n (mediaError.message ? ': ' + mediaError.message : '') +\n ')'\n : '';\n const error = new Error('Media failed to load' + detail);\n console.warn('[waveform-playlist] ' + error.message);\n // Nothing is audible any more: do not go on showing \"playing\".\n if (isPlayingRef.current) restAt(currentTimeRef.current);\n onError?.(error);\n });\n // The browser refused to start playback (no user gesture, most often\n // for a play that was queued and started here, outside the click).\n playout.on('playrejected', () => {\n if (cancelled) return;\n if (isPlayingRef.current) restAt(currentTimeRef.current);\n });\n\n playout.addTrack({\n source: track.source,\n peaks: track.waveformData,\n name: track.name,\n audioContext,\n fadeIn: trackFadeIn,\n fadeOut: trackFadeOut,\n });\n\n // The media element reports its position about four times a second,\n // also while the tab is hidden and animation frames are not running.\n // It keeps the cursor current, and it is the fallback that ends a\n // range or an annotation in a hidden tab (up to a quarter of a second\n // late); in a visible tab the animation loop sees the end first.\n playout.on('timeupdate', (time) => {\n if (cancelled) return;\n currentTimeRef.current = time;\n if (isPlayingRef.current) endPlaybackIfDueRef.current(time);\n });\n\n // The audio played to its end. The cursor returns to where playback\n // started, as on Stop. A bounded play that is not the selection rests\n // at its own end instead: the loop below does the same when it sees\n // the end first, and which of the two does is a race.\n playout.setOnPlaybackComplete(() => {\n // The element's `ended` also arrives after the loop or `timeupdate`\n // has already ended a range that reaches the end of the audio;\n // that rest stands.\n if (cancelled || !isPlayingRef.current) return;\n const boundedEnd = playbackEndTimeRef.current;\n if (boundedEnd !== null && !isSelectionPlayRef.current) {\n restAt(Math.min(boundedEnd, waveformData.duration));\n return;\n }\n restAt(playStartPositionRef.current);\n setActiveAnnotationId(null);\n });\n\n playoutRef.current = playout;\n // The speed the provider shows (`usePlaybackRate()`, the speed\n // select) is the prop's, or the one chosen since the prop last\n // changed. The bundled engine was created at the prop's speed, as\n // given: it is told only a speed that differs (its setter clamps,\n // its constructor does not, so repeating the prop could change it).\n // A custom `createPlayout` is not given the speed: it is always told.\n const speed = playbackRateRef.current;\n if (createPlayout || !Object.is(speed, initialPlaybackRate)) {\n playout.setPlaybackRate(speed);\n }\n // The cursor may not be at 0: a position kept across a same-audio\n // replacement, or one stored by `seekTo` while there was no player (a\n // restore for this file). Move the new player there now, so its own\n // time agrees with the cursor before Play is pressed (`pause()` reads\n // it, and the media element reports it).\n if (currentTimeRef.current > 0) {\n playout.seekTo(currentTimeRef.current);\n }\n // A play asked for while there was no player starts now. The media\n // element accepts play() before its metadata has loaded.\n const queued = pendingPlayRef.current;\n if (queued) {\n pendingPlayRef.current = null;\n currentTimeRef.current = queued.position;\n playout.play(undefined, queued.position);\n setIsPlaying(true);\n startAnimationLoopRef.current();\n }\n } catch (err) {\n if (!cancelled) {\n // Nothing will arrive for a queued play to wait for.\n playoutInFlightRef.current = false;\n pendingPlayRef.current = null;\n // A play that was queued moved the cursor ref to its start; show it.\n setCurrentTime(currentTimeRef.current);\n }\n console.warn('[waveform-playlist] MediaElement playout init failed: ' + String(err));\n onError?.(err instanceof Error ? err : new Error(String(err)));\n }\n })();\n\n return () => {\n cancelled = true;\n stopAnimationFrameLoop();\n // The player that was playing is about to be disposed: playback has\n // stopped, whatever replaces it. Left true, the UI showed \"playing\"\n // with no audio and no loop, and the playhead and progress overlay\n // (drawn at rest only while not playing) stopped following seeks.\n setIsPlaying(false);\n // Whatever replaces this player has its own metadata to load.\n setIsReady(false);\n // A player is on its way again, also after an init that failed.\n playoutInFlightRef.current = true;\n const latest = latestAudioRef.current;\n if (latest.source !== source || latest.waveformData !== waveformData) {\n // New audio: the old position and the old active annotation mean\n // nothing in it. Done here, in the cleanup, and not when the next\n // player is set up: React runs every cleanup of a commit before any\n // effect, so an effect of a child that restores a saved position for\n // the new audio (`seekTo`, `setActiveAnnotationId`) runs after this\n // and is kept.\n currentTimeRef.current = 0;\n setCurrentTime(0);\n setActiveAnnotationId(null);\n // A play queued for the old audio, and where a Stop would return to\n // in it, mean nothing either. (A play queued AFTER this cleanup, for\n // the new audio, is kept: the cleanup has already run by then.)\n pendingPlayRef.current = null;\n playStartPositionRef.current = 0;\n isSelectionPlayRef.current = false;\n } else {\n // The same audio (or an unmount): keep the listener's place, and\n // bring the state up to it. During playback only the ref advances.\n // That place is also where a Stop leaves the cursor from now on.\n setCurrentTime(currentTimeRef.current);\n // Not while a play is queued: it has set its own play start (the\n // selection's start for a resumed selection), and it is kept.\n if (pendingPlayRef.current === null) {\n playStartPositionRef.current = currentTimeRef.current;\n }\n }\n if (createdPlayout) {\n createdPlayout.dispose();\n }\n playoutRef.current = null;\n };\n }, [\n track.source,\n track.waveformData,\n track.name,\n trackFadeIn,\n trackFadeOut,\n audioContext,\n initialPlaybackRate,\n preservesPitch,\n onReady,\n onError,\n stopAnimationFrameLoop,\n setActiveAnnotationId,\n setIsPlaying,\n restAt,\n createPlayout,\n ]);\n\n // The step that follows the annotations and ends playback when it is due.\n // Returns true when it ended playback. Run by the animation loop on every\n // frame and by the engine's `timeupdate` (see the init effect), so it must\n // give the same result when it runs twice for one position.\n const endPlaybackIfDue = useCallback(\n (time: number): boolean => {\n const activeAnnotationEnded = followAnnotations({\n annotations: annotationsRef.current,\n lookup: annotationLookup,\n time,\n activeId: activeAnnotationIdRef.current,\n // Playing the selection takes continuous play out of the picture,\n // and on the frame that reaches a bounded play's end the highlight\n // is held (the end check below stops there). As in the WebAudio loop.\n followOnly: continuousPlayRef.current || isSelectionPlayRef.current,\n holdHighlight: playbackEndTimeRef.current !== null && time >= playbackEndTimeRef.current,\n setActiveAnnotationId,\n });\n if (activeAnnotationEnded) {\n // Continuous play off: stop at the end of the active annotation and\n // return the cursor to where playback started.\n restAt(playStartPositionRef.current);\n return true;\n }\n\n // A bounded play (`play(start, duration)`, the selection) has reached\n // its end. The selection returns the cursor to its start; any other\n // range leaves it at the end.\n const endTime = playbackEndTimeRef.current;\n if (endTime !== null && time >= endTime) {\n restAt(isSelectionPlayRef.current ? playStartPositionRef.current : endTime);\n return true;\n }\n return false;\n },\n [\n annotationsRef,\n annotationLookup,\n activeAnnotationIdRef,\n continuousPlayRef,\n setActiveAnnotationId,\n restAt,\n ]\n );\n\n // Animation loop\n const startAnimationLoop = useCallback(() => {\n const updateTime = () => {\n const time = playoutRef.current?.getCurrentTime() ?? 0;\n currentTimeRef.current = time;\n\n // The media element reports the audible position: one time for logic\n // and for drawing.\n runFrameCallbacks({\n time,\n visualTime: time,\n sampleRate,\n samplesPerPixel: samplesPerPixelRef.current,\n });\n\n if (endPlaybackIfDue(time)) return;\n\n if (isAutomaticScrollRef.current && scrollContainerRef.current) {\n centrePlayhead(scrollContainerRef.current, time, sampleRate, samplesPerPixelRef.current);\n }\n\n startAnimationFrameLoop(updateTime);\n };\n\n startAnimationFrameLoop(updateTime);\n }, [\n sampleRate,\n startAnimationFrameLoop,\n isAutomaticScrollRef,\n scrollContainerRef,\n runFrameCallbacks,\n endPlaybackIfDue,\n ]);\n useLayoutEffect(() => {\n startAnimationLoopRef.current = startAnimationLoop;\n endPlaybackIfDueRef.current = endPlaybackIfDue;\n }, [startAnimationLoop, endPlaybackIfDue]);\n\n const stopAnimationLoop = stopAnimationFrameLoop;\n\n // Playback controls. The rules are the WebAudio provider's (#688), so that\n // one Play, Stop or seek control means the same under either provider.\n const play = useCallback(\n async (startTime?: number, playDuration?: number) => {\n const actualStartTime = startTime ?? currentTimeRef.current;\n const endTime = playDuration !== undefined ? actualStartTime + playDuration : undefined;\n\n const playout = playoutRef.current;\n // No player and none on its way (the init failed): nothing to do.\n if (!playout && !playoutInFlightRef.current) return;\n\n // Is this the highlighted selection being played? It may start inside\n // the selection (resuming after a pause) but always runs to its end.\n const { selectionStart, selectionEnd } = selectionRef.current;\n isSelectionPlayRef.current =\n endTime !== undefined &&\n selectionEnd > selectionStart &&\n actualStartTime >= selectionStart - 1e-6 &&\n actualStartTime < selectionEnd &&\n Math.abs(endTime - selectionEnd) < 1e-6;\n // Where a Stop (or the play finishing) returns the cursor. For the\n // selection that is its start even when this play resumed part-way in.\n playStartPositionRef.current = isSelectionPlayRef.current ? selectionStart : actualStartTime;\n playbackEndTimeRef.current = endTime ?? null;\n currentTimeRef.current = actualStartTime;\n\n if (!playout) {\n // The player is loading or being replaced: the init effect starts\n // this when it arrives. `isPlaying` stays false until audio starts.\n pendingPlayRef.current = { position: actualStartTime };\n return;\n }\n pendingPlayRef.current = null;\n\n // The engine schedules the track's fades in `play()`, relative to the\n // start position; the end is watched by the loop, not by the engine\n // (its own duration timer does not follow a pause or a rate change).\n playout.play(undefined, actualStartTime);\n setIsPlaying(true);\n startAnimationLoop();\n },\n [startAnimationLoop, setIsPlaying]\n );\n\n const pause = useCallback(() => {\n // Cancels a play queued for a player that has not arrived.\n pendingPlayRef.current = null;\n if (!playoutRef.current) {\n // The play it cancelled moved the cursor ref to its start; show it.\n setCurrentTime(currentTimeRef.current);\n return;\n }\n\n playoutRef.current.pause();\n setIsPlaying(false);\n stopAnimationLoop();\n setCurrentTime(playoutRef.current.getCurrentTime());\n }, [stopAnimationLoop, setIsPlaying]);\n\n const stop = useCallback(() => {\n // Cancels a play queued for a player that has not arrived.\n pendingPlayRef.current = null;\n // Return the cursor to where playback started (Audacity-style), with or\n // without a player.\n restAt(playStartPositionRef.current);\n setActiveAnnotationId(null);\n }, [restAt, setActiveAnnotationId]);\n\n const seekTo = useCallback((time: number) => {\n // NaN is not a position: it would go into the time ref, into the state\n // and into the player, and nothing would come back. It is ignored.\n // Infinity is a position — the end of the audio (Fast Forward asks for\n // it, and the clamp below turns it into the track's duration) — so only\n // NaN is rejected here.\n if (Number.isNaN(time)) return;\n const trackDuration = latestAudioRef.current.waveformData.duration;\n const clampedTime = Math.max(0, Math.min(time, trackDuration));\n currentTimeRef.current = clampedTime;\n setCurrentTime(clampedTime);\n\n // Whatever play was running or queued started somewhere else and may\n // have had an end: from here on this position is where playback began.\n playStartPositionRef.current = clampedTime;\n playbackEndTimeRef.current = null;\n isSelectionPlayRef.current = false;\n const queued = pendingPlayRef.current;\n if (queued) {\n queued.position = clampedTime;\n return;\n }\n\n const playout = playoutRef.current;\n if (!playout) return;\n if (isPlayingRef.current) {\n // Restart at the new position instead of moving the element under\n // the running play: the engine schedules fades in `play()`, so a bare\n // seek would land mid-fade at the wrong gain.\n playout.play(undefined, clampedTime);\n } else {\n playout.seekTo(clampedTime);\n }\n }, []);\n\n // Selection. As under the WebAudio provider: the cursor moves to its start,\n // a range set during playback is played start to end, and a collapsed one\n // (a cursor move) carries on open-ended from there.\n const setSelection = useCallback(\n (requestedStart: number, requestedEnd: number) => {\n // Ordered and inside the audio, whoever asks: the highlight, the cursor\n // and what Play plays must be one range (typed times can be reversed\n // or past the end; the multitrack engine orders its pair too).\n const length = latestAudioRef.current.waveformData.duration;\n const clamp = (time: number) => Math.max(0, Math.min(time, length));\n const start = clamp(Math.min(requestedStart, requestedEnd));\n const end = clamp(Math.max(requestedStart, requestedEnd));\n const previous = selectionRef.current;\n if (previous.selectionStart !== start || previous.selectionEnd !== end) {\n selectionRef.current = { selectionStart: start, selectionEnd: end };\n setSelectionState(selectionRef.current);\n }\n const cursorMoved = currentTimeRef.current !== start;\n currentTimeRef.current = start;\n setCurrentTime(start);\n\n const playsRange = end > start;\n const endTime = playsRange ? end : undefined;\n // Whatever bounded play was running or queued is over: its end, its\n // start and its active annotation must not outlive it.\n const replaceBoundedPlay = () => {\n playbackEndTimeRef.current = endTime ?? null;\n isSelectionPlayRef.current = playsRange;\n playStartPositionRef.current = start;\n if (activeAnnotationIdRef.current !== null) setActiveAnnotationId(null);\n };\n\n const queued = pendingPlayRef.current;\n if (queued) {\n queued.position = start;\n replaceBoundedPlay();\n return;\n }\n\n const playout = playoutRef.current;\n if (!isPlayingRef.current) {\n // Nothing is playing: an earlier play no longer says anything about\n // this position.\n playStartPositionRef.current = start;\n // Only when the start moved: a rightward drag keeps its start, and\n // must not seek the media element on every pointer move.\n if (playout && cursorMoved) playout.seekTo(start);\n return;\n }\n\n if (playout) {\n replaceBoundedPlay();\n playout.play(undefined, start);\n }\n },\n [activeAnnotationIdRef, setActiveAnnotationId]\n );\n\n const setPlaybackRate = useCallback((rate: number) => {\n // NaN is not a speed: it would go into the ref, into the state and into\n // the player, and the clamp below would pass it on unchanged (every\n // comparison with NaN is false). It is ignored. An infinite rate is\n // clamped to the upper bound by the same clamp as any other speed.\n if (Number.isNaN(rate)) return;\n const clampedRate = Math.max(0.5, Math.min(2.0, rate));\n playbackRateRef.current = clampedRate;\n setPlaybackRateState(clampedRate);\n if (playoutRef.current) {\n playoutRef.current.setPlaybackRate(clampedRate);\n }\n }, []);\n\n // Context values. The shared ones are the same context objects the\n // WebAudio provider renders (#688), each holding fields that change together.\n const isPlayingValue: IsPlayingContextValue = useMemo(() => ({ isPlaying }), [isPlaying]);\n const currentTimeValue: CurrentTimeContextValue = useMemo(() => ({ currentTime }), [currentTime]);\n const activeAnnotationValue: ActiveAnnotationContextValue = useMemo(\n () => ({ activeAnnotationId }),\n [activeAnnotationId]\n );\n const settingsValue: PlaylistSettingsContextValue = useMemo(\n () => ({ timeFormat, isAutomaticScroll }),\n [timeFormat, isAutomaticScroll]\n );\n\n // Never changes. A media element reports the audible position, so the\n // position to draw is the playback position itself.\n const refsValue: PlaybackRefsContextValue = useMemo(\n () => ({\n currentTimeRef,\n visualTimeRef: currentTimeRef,\n registerFrameCallback,\n unregisterFrameCallback,\n }),\n [registerFrameCallback, unregisterFrameCallback]\n );\n\n // What a click on an annotation does (#686). An open-ended play: where it\n // ends (the annotation's end, or not at all with continuous play) is the\n // animation loop's job, which follows the option and the annotation as they\n // are at that moment. Never changes.\n const playAnnotation = useCallback(\n (annotation: AnnotationData) => {\n setActiveAnnotationId(annotation.id);\n play(annotation.start).catch((err) => {\n console.warn(\n '[waveform-playlist] Failed to start playback for annotation ' +\n annotation.id +\n ': ' +\n String(err)\n );\n });\n },\n [play, setActiveAnnotationId]\n );\n\n // Never changes.\n const controlsValue: PlaybackControlsContextValue = useMemo(\n () => ({\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n setAnnotations,\n annotationPreview,\n setActiveAnnotationId,\n playAnnotation,\n }),\n [\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n setAnnotations,\n annotationPreview,\n setActiveAnnotationId,\n playAnnotation,\n ]\n );\n\n // A single track at a fixed zoom level: the two provider modes and both\n // zoom directions are always off.\n const viewValue: PlaylistViewContextValue = useMemo(\n () => ({ sampleRate, mono: false, indefinitePlayback: false }),\n [sampleRate]\n );\n const zoomValue: PlaylistZoomContextValue = useMemo(\n () => ({ samplesPerPixel, canZoomIn: false, canZoomOut: false }),\n [samplesPerPixel]\n );\n\n const playbackRateValue: PlaybackRateContextValue = useMemo(\n () => ({ playbackRate, setPlaybackRate }),\n [playbackRate, setPlaybackRate]\n );\n\n const trackValue: MediaElementTrackContextValue = useMemo(\n () => ({\n duration,\n isReady,\n peaksDataArray,\n fadeIn: trackFadeIn,\n fadeOut: trackFadeOut,\n playoutRef,\n }),\n [duration, isReady, peaksDataArray, trackFadeIn, trackFadeOut]\n );\n\n // The twelve contexts only the WebAudio provider serves are blocked, so that\n // inside this provider `useLoop()` (say) throws instead of reading a\n // WebAudio provider further out. Outermost: what changes least.\n return (\n <ThemeProvider theme={mergedTheme}>\n <ArrangementContext value={BLOCKED}>\n <EditorControlsContext value={BLOCKED}>\n <EngineRefsContext value={BLOCKED}>\n <AnnotationOptionsContext value={annotationOptionsValue}>\n <LoopContext value={BLOCKED}>\n <SelectedTrackIdContext value={BLOCKED}>\n <UndoRedoContext value={BLOCKED}>\n <PlaylistTimelineContext value={BLOCKED}>\n <PlaylistMixerContext value={BLOCKED}>\n <TrackReorderPreviewContext value={BLOCKED}>\n <TrimPreviewContext value={BLOCKED}>\n <TrimPreviewPeaksContext value={BLOCKED}>\n <PlaybackRefsContext value={refsValue}>\n <PlaybackControlsContext value={controlsValue}>\n <PlaylistViewContext value={viewValue}>\n <PlaylistZoomContext value={zoomValue}>\n <PlaylistSettingsContext value={settingsValue}>\n <MediaElementTrackContext value={trackValue}>\n <PlaybackRateContext value={playbackRateValue}>\n <AnnotationsContext value={annotationsValue}>\n <IsPlayingContext value={isPlayingValue}>\n <ActiveAnnotationContext\n value={activeAnnotationValue}\n >\n <CurrentTimeContext value={currentTimeValue}>\n <SelectionContext value={selection}>\n <SelectedRowContext value={ONLY_ROW_SELECTED}>\n <RecordingArmContext value={BLOCKED}>\n {children}\n </RecordingArmContext>\n </SelectedRowContext>\n </SelectionContext>\n </CurrentTimeContext>\n </ActiveAnnotationContext>\n </IsPlayingContext>\n </AnnotationsContext>\n </PlaybackRateContext>\n </MediaElementTrackContext>\n </PlaylistSettingsContext>\n </PlaylistZoomContext>\n </PlaylistViewContext>\n </PlaybackControlsContext>\n </PlaybackRefsContext>\n </TrimPreviewPeaksContext>\n </TrimPreviewContext>\n </TrackReorderPreviewContext>\n </PlaylistMixerContext>\n </PlaylistTimelineContext>\n </UndoRedoContext>\n </SelectedTrackIdContext>\n </LoopContext>\n </AnnotationOptionsContext>\n </EngineRefsContext>\n </EditorControlsContext>\n </ArrangementContext>\n </ThemeProvider>\n );\n};\n","import type { MediaElementPlayout } from '@waveform-playlist/media-element-playout';\nimport { installCommand } from '../utils/installCommand';\n\n/** Options for {@link resolveMediaElementPlayout}. */\nexport interface ResolveMediaElementPlayoutOptions {\n /** Consumer-supplied factory. When present, the default engine is never imported. */\n createPlayout?: () => MediaElementPlayout;\n /** Initial playback rate forwarded to the default engine. */\n playbackRate?: number;\n /** Whether to preserve pitch on rate change (default engine only). */\n preservesPitch?: boolean;\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst installHint = (): string =>\n '@waveform-playlist/media-element-playout is required for the default MediaElement engine. ' +\n 'Install with: ' +\n installCommand('@waveform-playlist/media-element-playout') +\n ' — or pass a custom `createPlayout`.';\n\n/**\n * Resolve a MediaElement playout. With `createPlayout`, returns its result and\n * never imports the default engine. Otherwise dynamically imports\n * `@waveform-playlist/media-element-playout`, rethrowing a friendly install hint\n * (and console.warn-ing the original error) when the optional peer is absent.\n */\nexport async function resolveMediaElementPlayout(\n opts: ResolveMediaElementPlayoutOptions\n): Promise<MediaElementPlayout> {\n if (opts.createPlayout) {\n return opts.createPlayout();\n }\n\n let mod: typeof import('@waveform-playlist/media-element-playout');\n try {\n mod = await import('@waveform-playlist/media-element-playout');\n } catch (originalErr) {\n console.warn(\n '[waveform-playlist] @waveform-playlist/media-element-playout dynamic import failed: ' +\n String(originalErr)\n );\n throw new Error(installHint());\n }\n\n return new mod.MediaElementPlayout({\n playbackRate: opts.playbackRate,\n preservesPitch: opts.preservesPitch,\n });\n}\n","import React, { useCallback } from 'react';\nimport { BaseControlButton } from '@waveform-playlist/ui-components';\nimport {\n useSelection,\n usePlaybackControls,\n useEditorControls,\n usePlaylistTimeline,\n usePlaybackRefs,\n usePlaylistView,\n useLoop,\n useIsPlaying,\n} from '../contexts/playlistContexts';\nimport { usePlayFromSelectionOrCursor } from '../hooks/usePlayFromSelectionOrCursor';\n\n// Play, Pause, Stop, Rewind, Fast Forward and the two skips read only what\n// both providers have (#688), so they work under WaveformPlaylistProvider and\n// under MediaElementPlaylistProvider. The loop buttons below are\n// WaveformPlaylistProvider only.\n\nexport const PlayButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isPlaying } = useIsPlaying();\n // Shared with the Space shortcut: the selection if one is highlighted, else the cursor.\n const handleClick = usePlayFromSelectionOrCursor();\n\n return (\n <BaseControlButton onClick={handleClick} disabled={isPlaying} className={className}>\n Play\n </BaseControlButton>\n );\n};\n\nexport const PauseButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isPlaying } = useIsPlaying();\n const { pause } = usePlaybackControls();\n\n return (\n <BaseControlButton onClick={pause} disabled={!isPlaying} className={className}>\n Pause\n </BaseControlButton>\n );\n};\n\nexport const StopButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isPlaying } = useIsPlaying();\n const { stop } = usePlaybackControls();\n\n return (\n <BaseControlButton onClick={stop} disabled={!isPlaying} className={className}>\n Stop\n </BaseControlButton>\n );\n};\n\n// The four below move the cursor with `seekTo`, which clamps to the audio and\n// restarts playback at the new position when it is running.\n\nexport const RewindButton: React.FC<{ className?: string }> = ({ className }) => {\n const { seekTo } = usePlaybackControls();\n const handleClick = () => seekTo(0);\n\n return (\n <BaseControlButton onClick={handleClick} className={className}>\n Rewind\n </BaseControlButton>\n );\n};\n\nexport const FastForwardButton: React.FC<{ className?: string }> = ({ className }) => {\n const { seekTo } = usePlaybackControls();\n // A provider with `indefinitePlayback` has no end to go to: its transport\n // runs on past the audio (never set under the MediaElement provider).\n const { indefinitePlayback } = usePlaylistView();\n // An infinite time is the end of the audio.\n const handleClick = () => seekTo(Infinity);\n\n return (\n <BaseControlButton onClick={handleClick} disabled={indefinitePlayback} className={className}>\n Fast Forward\n </BaseControlButton>\n );\n};\n\nexport const SkipBackwardButton: React.FC<{ skipAmount?: number; className?: string }> = ({\n skipAmount = 5,\n className,\n}) => {\n const { currentTimeRef } = usePlaybackRefs();\n const { seekTo } = usePlaybackControls();\n const handleClick = () => seekTo((currentTimeRef.current ?? 0) - skipAmount);\n\n return (\n <BaseControlButton onClick={handleClick} className={className}>\n Skip Backward\n </BaseControlButton>\n );\n};\n\nexport const SkipForwardButton: React.FC<{ skipAmount?: number; className?: string }> = ({\n skipAmount = 5,\n className,\n}) => {\n const { currentTimeRef } = usePlaybackRefs();\n const { seekTo } = usePlaybackControls();\n const handleClick = () => seekTo((currentTimeRef.current ?? 0) + skipAmount);\n\n return (\n <BaseControlButton onClick={handleClick} className={className}>\n Skip Forward\n </BaseControlButton>\n );\n};\n\nexport const LoopButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isLoopEnabled, loopStart, loopEnd } = useLoop();\n const { setLoopEnabled, setLoopRegion } = useEditorControls();\n const { duration } = usePlaylistTimeline();\n\n const hasValidLoopRegion = loopStart !== loopEnd && loopEnd > loopStart;\n\n const handleClick = () => {\n if (!isLoopEnabled && !hasValidLoopRegion) {\n // Create a default loop region when enabling loop without one\n // Default to first 10 seconds or 25% of duration, whichever is smaller\n const defaultEnd = Math.min(10, duration * 0.25);\n setLoopRegion(0, Math.max(1, defaultEnd)); // At least 1 second\n }\n setLoopEnabled(!isLoopEnabled);\n };\n\n return (\n <BaseControlButton\n onClick={handleClick}\n className={className}\n title={isLoopEnabled ? 'Disable loop' : 'Enable loop'}\n >\n {isLoopEnabled ? 'Loop On' : 'Loop Off'}\n </BaseControlButton>\n );\n};\n\nexport const SetLoopRegionButton: React.FC<{ className?: string }> = ({ className }) => {\n const { selectionStart, selectionEnd } = useSelection();\n const { loopStart, loopEnd } = useLoop();\n const { setLoopRegionFromSelection, clearLoopRegion } = useEditorControls();\n\n const hasValidSelection = selectionStart !== selectionEnd && selectionEnd > selectionStart;\n const hasLoopRegion = loopStart !== loopEnd && loopEnd > loopStart;\n\n const handleClick = () => {\n if (hasLoopRegion) {\n clearLoopRegion();\n } else {\n setLoopRegionFromSelection();\n }\n };\n\n return (\n <BaseControlButton\n onClick={handleClick}\n disabled={!hasValidSelection && !hasLoopRegion}\n className={className}\n title={\n hasLoopRegion\n ? 'Clear loop region'\n : hasValidSelection\n ? 'Set loop region from selection'\n : 'Create a selection first'\n }\n >\n {hasLoopRegion ? 'Clear Loop' : 'Set Loop'}\n </BaseControlButton>\n );\n};\n\nexport interface ClearAllButtonProps {\n onClearAll: () => void;\n label?: string;\n className?: string;\n}\n\nexport const ClearAllButton: React.FC<ClearAllButtonProps> = ({\n onClearAll,\n label = 'Clear All',\n className,\n}) => {\n const { stop } = usePlaybackControls();\n\n const handleClick = useCallback(() => {\n stop();\n onClearAll();\n }, [stop, onClearAll]);\n\n return (\n <BaseControlButton onClick={handleClick} className={className} title=\"Remove all tracks\">\n {label}\n </BaseControlButton>\n );\n};\n","import React from 'react';\nimport { BaseControlButton } from '@waveform-playlist/ui-components';\nimport { useEditorControls, usePlaylistZoom } from '../contexts/playlistContexts';\n\nexport const ZoomInButton: React.FC<{ className?: string; disabled?: boolean }> = ({\n className,\n disabled,\n}) => {\n const { zoomIn } = useEditorControls();\n const { canZoomIn } = usePlaylistZoom();\n\n return (\n <BaseControlButton onClick={zoomIn} disabled={disabled || !canZoomIn} className={className}>\n Zoom In\n </BaseControlButton>\n );\n};\n\nexport const ZoomOutButton: React.FC<{ className?: string; disabled?: boolean }> = ({\n className,\n disabled,\n}) => {\n const { zoomOut } = useEditorControls();\n const { canZoomOut } = usePlaylistZoom();\n\n return (\n <BaseControlButton onClick={zoomOut} disabled={disabled || !canZoomOut} className={className}>\n Zoom Out\n </BaseControlButton>\n );\n};\n","import React, { useRef, useEffect, useId } from 'react';\nimport {\n MasterVolumeControl as BaseMasterVolumeControl,\n TimeFormatSelect as BaseTimeFormatSelect,\n PlaybackRateSelect as BasePlaybackRateSelect,\n AutomaticScrollCheckbox as BaseAutomaticScrollCheckbox,\n SelectionTimeInputs as BaseSelectionTimeInputs,\n formatTime,\n} from '@waveform-playlist/ui-components';\nimport styled from 'styled-components';\nimport {\n useCurrentTime,\n useSelection,\n usePlaybackControls,\n useEditorControls,\n usePlaybackRate,\n usePlaylistSettings,\n usePlaylistMixer,\n usePlaybackRefs,\n useIsPlaying,\n} from '../contexts/playlistContexts';\n\n/**\n * Master volume control that uses the playlist context\n */\nexport const MasterVolumeControl: React.FC<{ className?: string }> = ({ className }) => {\n const { masterVolume } = usePlaylistMixer();\n const { setMasterVolume } = useEditorControls();\n\n return (\n <BaseMasterVolumeControl\n volume={masterVolume}\n onChange={setMasterVolume}\n className={className}\n />\n );\n};\n\n/**\n * Time format selector that uses the playlist context\n */\nexport const TimeFormatSelect: React.FC<{ className?: string }> = ({ className }) => {\n const { timeFormat } = usePlaylistSettings();\n const { setTimeFormat } = usePlaybackControls();\n\n return <BaseTimeFormatSelect value={timeFormat} onChange={setTimeFormat} className={className} />;\n};\n\nconst PositionDisplay = styled.span`\n font-family: 'Courier New', Monaco, monospace;\n font-size: 1rem;\n font-weight: 600;\n color: ${(props) => props.theme?.textColor || '#333'};\n user-select: none;\n`;\n\n/**\n * Audio position display that uses the playlist context.\n * Updates via the shared animation frame registry — no own rAF loop.\n * Direct DOM manipulation avoids React re-renders.\n */\nexport const AudioPosition: React.FC<{ className?: string }> = ({ className }) => {\n const timeRef = useRef<HTMLSpanElement>(null);\n const { currentTimeRef, registerFrameCallback, unregisterFrameCallback } = usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only: what is shown comes from the ref.\n useCurrentTime();\n const { timeFormat: format } = usePlaylistSettings();\n\n // Its own id in the frame registry: under a shared one, a second readout\n // under the same provider replaced the first one's callback.\n const id = useId();\n\n // Register per-frame callback during playback — uses raw time for display\n useEffect(() => {\n if (isPlaying) {\n registerFrameCallback(id, ({ time }) => {\n if (timeRef.current) {\n timeRef.current.textContent = formatTime(time, format);\n }\n });\n }\n return () => unregisterFrameCallback(id);\n }, [id, isPlaying, format, registerFrameCallback, unregisterFrameCallback]);\n\n // Update when stopped (for seeks)\n useEffect(() => {\n if (!isPlaying && timeRef.current) {\n timeRef.current.textContent = formatTime(currentTimeRef.current ?? 0, format);\n }\n });\n\n return (\n <PositionDisplay ref={timeRef} className={className} aria-label=\"Audio position\">\n {formatTime(currentTimeRef.current ?? 0, format)}\n </PositionDisplay>\n );\n};\n\n/**\n * Playback speed dropdown. MediaElementPlaylistProvider only (#688).\n * `rates` lists the speeds to offer (default 0.5× to 2×).\n */\nexport const PlaybackRateSelect: React.FC<{ rates?: readonly number[]; className?: string }> = ({\n rates,\n className,\n}) => {\n const { playbackRate, setPlaybackRate } = usePlaybackRate();\n return (\n <BasePlaybackRateSelect\n value={playbackRate}\n onChange={setPlaybackRate}\n rates={rates}\n className={className}\n />\n );\n};\n\n/**\n * Selection time inputs bound to the provider: its selection, and its time\n * format (the one `TimeFormatSelect` and `setTimeFormat()` set).\n */\nexport const SelectionTimeInputs: React.FC<{ className?: string }> = ({ className }) => {\n const { selectionStart, selectionEnd } = useSelection();\n const { timeFormat } = usePlaylistSettings();\n const { setSelection } = usePlaybackControls();\n\n return (\n <BaseSelectionTimeInputs\n selectionStart={selectionStart}\n selectionEnd={selectionEnd}\n onSelectionChange={setSelection}\n format={timeFormat}\n className={className}\n />\n );\n};\n\n/**\n * Automatic scroll checkbox that uses the playlist context\n * Uses split contexts to avoid re-rendering during animation\n */\nexport const AutomaticScrollCheckbox: React.FC<{ className?: string }> = ({ className }) => {\n const { isAutomaticScroll } = usePlaylistSettings();\n const { setAutomaticScroll } = usePlaybackControls();\n\n return (\n <BaseAutomaticScrollCheckbox\n checked={isAutomaticScroll}\n onChange={setAutomaticScroll}\n className={className}\n />\n );\n};\n","import React, {\n use,\n useLayoutEffect,\n useRef,\n useState,\n useMemo,\n type ReactNode,\n useCallback,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { DevicePixelRatioProvider, CLIP_HEADER_HEIGHT } from '@waveform-playlist/ui-components';\nimport {\n usePlaylistView,\n usePlaylistZoom,\n usePlaylistTimeline,\n useTrackReorderPreview,\n useEditorControls,\n} from '../contexts/playlistContexts';\nimport {\n applyTrackOrderPreview,\n computeTrackLayout,\n trackIdAtOffset,\n} from '../utils/trackOrderPreview';\nimport { useTrailingActive } from '../hooks/useTrailingActive';\nimport { useRecordingLayout } from '../hooks/useRecordingLayout';\nimport { useTrimPreviewExtent } from '../hooks/useTrimPreviewView';\nimport { trackKind, type RenderMode, type SpectrogramConfig } from '@waveform-playlist/core';\nimport { SpectrogramIntegrationContext } from '../SpectrogramIntegrationContext';\nimport { trackRenderMode } from '../utils/trackRenderMode';\nimport { placeholdersEnd } from '../utils/placeholderPeaks';\nimport type { SpectrogramTrackHelpers } from './TrackRows';\nimport { getTrackChannelCount } from './visualizationLayout';\nimport type { WaveformRow, WaveformRowsValue } from './waveformLayoutContext';\nimport { useWaveformFrame, useWaveformParts } from './waveformFrame';\nimport { useResolvedViewOptions } from './WaveformViewOptions';\n\n// Default duration in seconds for empty tracks (used for recording workflow)\nconst DEFAULT_EMPTY_TRACK_DURATION = 60;\n\n// Passed to the spectrogram settings modal when no config exists at any level.\n// A module constant, so the prop keeps its identity across renders.\nconst EMPTY_SPECTROGRAM_CONFIG: SpectrogramConfig = {};\n\nexport interface WaveformRootProps {\n className?: string;\n /** The parts (see waveformParts.tsx), and anything else to draw over the tracks. */\n children?: ReactNode;\n}\n\n/**\n * The root of the multitrack view (#685), exported from the package.\n *\n * It owns what the parts share and nothing they draw: the size of the\n * timeline, the vertical layout of the rows (one layout for the tracks and\n * the controls column, so they cannot disagree), what a press on the tracks\n * does beyond the selection drag, and the spectrogram settings modal. The\n * scrolling frame (`Playlist`), the selection drag and the context for the\n * drawing primitives are shared with the MediaElement root: `useWaveformFrame`.\n *\n * It renders on its own state (a drag in progress, the settings modal, the\n * measured container width), on play and stop (its selection drag reads\n * `isPlaying`), on every change of the timeline, the zoom, the view settings,\n * the reorder preview, the spectrogram integration and the theme, on a\n * recording layout step, on a 10-second step of a trim dragged past the end\n * of the timeline, and whenever the component that composes it renders.\n * None of that renders a part by itself: the\n * parts are `children`, whose elements are the same as on the previous render\n * unless the component that composed them rendered too, and each part follows\n * the two layout values below and the provider contexts it reads. Keep it so:\n * both values are memoized, and everything in them must keep its identity\n * across a render that did not change it.\n */\nexport const WaveformRoot: React.FC<WaveformRootProps> = ({ className, children }) => {\n const { setSelectedTrackId, setCurrentTime } = useEditorControls();\n const { sampleRate, mono, indefinitePlayback } = usePlaylistView();\n const viewOptions = useResolvedViewOptions();\n const { waveHeight, fillViewport } = viewOptions;\n const { samplesPerPixel } = usePlaylistZoom();\n const { peaksDataArray, tracks, duration, isReady } = usePlaylistTimeline();\n const { trackDragPreview } = useTrackReorderPreview();\n\n // Optional spectrogram integration (only available when SpectrogramProvider is present)\n const spectrogram = use(SpectrogramIntegrationContext);\n\n // The parts by place, and what the tracks part was given.\n const parts = useWaveformParts(children);\n const { showClipHeaders, recordingState } = parts.tracksOptions;\n\n // Per-track spectrogram rendering helpers (memoized) — only computed when spectrogram is available\n const spectrogramHelpersById = useMemo(() => {\n const helpers = new Map<string, SpectrogramTrackHelpers>();\n if (!spectrogram) return helpers;\n tracks.forEach((track) => {\n const mode = trackRenderMode(\n track,\n spectrogram.trackSpectrogramOverrides.get(track.id)?.renderMode\n );\n if (mode === 'waveform') return;\n const overrides = spectrogram.trackSpectrogramOverrides.get(track.id);\n const cm =\n overrides?.colorMap ??\n track.spectrogramColorMap ??\n spectrogram.spectrogramColorMap ??\n 'viridis';\n const cfg = overrides?.config ?? track.spectrogramConfig ?? spectrogram.spectrogramConfig;\n helpers.set(track.id, {\n colorLUT: spectrogram.getColorMap(cm),\n frequencyScaleFn: spectrogram.getFrequencyScale(cfg?.frequencyScale ?? 'mel'),\n config: cfg,\n });\n });\n return helpers;\n }, [tracks, spectrogram]);\n\n // Render mode per track (see trackRenderMode): an audio track takes a\n // spectrogram override, else its own mode, else a waveform. A MIDI track is\n // drawn as a piano roll from its kind and has no render mode.\n const renderModeById = useMemo(() => {\n const modes = new Map<string, RenderMode>();\n tracks.forEach((track) => {\n modes.set(\n track.id,\n trackRenderMode(track, spectrogram?.trackSpectrogramOverrides.get(track.id)?.renderMode)\n );\n });\n return modes;\n }, [tracks, spectrogram]);\n\n // The recording, reduced to what the layout depends on: numbers that change\n // rarely, read through selectors. `recordingState` itself is usually a new\n // object literal on every render of the consumer.\n const recordingProgress = recordingState?.isRecording ? recordingState.progress : undefined;\n const recordingLayout = useRecordingLayout(\n recordingProgress,\n recordingState?.startSample ?? 0,\n sampleRate\n );\n const recordingTrackId = recordingState?.isRecording ? recordingState.trackId : null;\n // A trim dragged past the end of the timeline: its end, in 10-second steps (#812).\n const trimPreviewEnd = useTrimPreviewExtent(sampleRate, duration);\n const recordingChannelCount = recordingProgress ? (mono ? 1 : recordingLayout.channelCount) : 0;\n\n // State for spectrogram settings modal\n const [settingsModalTrackId, setSettingsModalTrackId] = useState<string | null>(null);\n const closeSettingsModal = useCallback(() => setSettingsModalTrackId(null), []);\n\n // The frame hands over the scroll container (a state setter: stable).\n const [scrollContainerElement, setScrollContainerElement] = useState<HTMLDivElement | null>(null);\n\n // Fill the visible scroll container when requested — indefinitePlayback\n // implies it (endless playback needs an endless-looking timeline);\n // fillViewport requests the layout alone.\n const fillsContainer = indefinitePlayback || fillViewport;\n\n // The container's width is state, measured in a layout effect (so the first\n // paint already fills it) and kept current by a ResizeObserver. Reading\n // clientWidth in the render body instead forced layout on every render while\n // recording, was 0 on the first render and never followed a container resize.\n const [scrollContainerWidth, setScrollContainerWidth] = useState(0);\n useLayoutEffect(() => {\n if (!fillsContainer || !scrollContainerElement) return;\n const measure = () => setScrollContainerWidth(scrollContainerElement.clientWidth);\n measure();\n if (typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(scrollContainerElement);\n return () => observer.disconnect();\n }, [fillsContainer, scrollContainerElement]);\n\n // Calculate dimensions. `duration` is derived from `tracks` in the provider,\n // so it is already current in this render. It is the loaded audio; a clip\n // still loading is drawn as a placeholder, and the view is as wide as the\n // last one (#812).\n const placeholdersEndSeconds = useMemo(() => placeholdersEnd(peaksDataArray), [peaksDataArray]);\n let displayDuration = Math.max(\n duration > 0 ? duration : DEFAULT_EMPTY_TRACK_DURATION,\n placeholdersEndSeconds\n );\n\n if (fillsContainer) {\n const minContainerDuration = (scrollContainerWidth * samplesPerPixel) / sampleRate;\n displayDuration = Math.max(displayDuration, minContainerDuration);\n }\n\n if (recordingProgress) {\n // Grows in steps, not with every frame of the take (#695).\n displayDuration = Math.max(displayDuration, recordingLayout.displayEndSeconds);\n }\n\n displayDuration = Math.max(displayDuration, trimPreviewEnd);\n\n // Reads `tracks` through a ref so its identity survives `tracks` changes: it\n // is a prop of every memoized clip and control panel.\n const tracksRef = useRef(tracks);\n tracksRef.current = tracks;\n const selectTrack = useCallback(\n (trackIndex: number) => {\n const track = tracksRef.current[trackIndex];\n if (track) {\n setSelectedTrackId(track.id);\n }\n },\n [setSelectedTrackId]\n );\n\n // Shared vertical layout for BOTH columns (waveform rows + control slots).\n // Heights use the existing slot formula; order applies the live drag\n // preview so both columns slide together. Worked out here, once, so the two\n // columns can never disagree.\n const trackHeightById = useMemo(() => {\n const m = new Map<string, number>();\n peaksDataArray.forEach((trackClipPeaks, trackIndex) => {\n const track = tracks[trackIndex];\n if (!track) return;\n const maxChannels = getTrackChannelCount(\n trackClipPeaks,\n track.id === recordingTrackId ? recordingChannelCount : 0\n );\n m.set(track.id, waveHeight * maxChannels + (showClipHeaders ? CLIP_HEADER_HEIGHT : 0));\n });\n return m;\n }, [\n peaksDataArray,\n tracks,\n recordingTrackId,\n recordingChannelCount,\n waveHeight,\n showClipHeaders,\n ]);\n\n const displayOrderIds = useMemo(\n () => applyTrackOrderPreview(tracks, trackDragPreview).map((t) => t.id),\n [tracks, trackDragPreview]\n );\n\n const trackLayout = useMemo(\n () => computeTrackLayout(displayOrderIds, trackHeightById),\n [displayOrderIds, trackHeightById]\n );\n\n const animateTrackLayout = useTrailingActive(trackDragPreview !== null, 200);\n\n // What the parts need to know of each track. Changes with `tracks`, as the\n // peaks beside it do.\n const rowList = useMemo<WaveformRow[]>(\n () => tracks.map((track) => ({ id: track.id, kind: trackKind(track) })),\n [tracks]\n );\n const dragSourceTrackId = trackDragPreview?.trackId ?? null;\n\n const rows = useMemo<WaveformRowsValue>(\n () => ({\n rows: rowList,\n peaksDataArray,\n showClipHeaders,\n trackHeightById,\n trackLayout,\n animateTrackLayout,\n renderModeById,\n spectrogramHelpersById,\n selectTrack,\n setSettingsModalTrackId,\n recordingChannelCount,\n dragSourceTrackId,\n }),\n [\n rowList,\n peaksDataArray,\n showClipHeaders,\n trackHeightById,\n trackLayout,\n animateTrackLayout,\n renderModeById,\n spectrogramHelpersById,\n selectTrack,\n recordingChannelCount,\n dragSourceTrackId,\n ]\n );\n\n // The frame, with the multitrack extras of the selection drag: a press\n // selects the row under the pointer, and a click while stopped moves the\n // cursor only (the selection the press collapsed stays).\n const frame = useWaveformFrame({\n className,\n viewOptions,\n parts,\n displayDuration,\n rows,\n playlistState: isReady ? 'ready' : 'loading',\n controlsWidth: parts.controlsWidth,\n onScrollContainer: setScrollContainerElement,\n onPress: ({ offsetY }) => {\n // The row under the pointer, from the layout the rows are positioned with.\n const clickedTrackId = trackIdAtOffset(\n displayOrderIds,\n trackLayout,\n trackHeightById,\n offsetY\n );\n if (clickedTrackId !== null) {\n setSelectedTrackId(clickedTrackId);\n }\n },\n onClickWhileStopped: setCurrentTime,\n });\n\n return (\n <DevicePixelRatioProvider>\n {frame}\n {spectrogram?.SettingsModal &&\n typeof document !== 'undefined' &&\n createPortal(\n <spectrogram.SettingsModal\n open={settingsModalTrackId !== null}\n onClose={closeSettingsModal}\n config={\n settingsModalTrackId !== null\n ? (spectrogram.trackSpectrogramOverrides.get(settingsModalTrackId)?.config ??\n tracks.find((t) => t.id === settingsModalTrackId)?.spectrogramConfig ??\n spectrogram.spectrogramConfig ??\n EMPTY_SPECTROGRAM_CONFIG)\n : EMPTY_SPECTROGRAM_CONFIG\n }\n colorMap={\n settingsModalTrackId !== null\n ? (spectrogram.trackSpectrogramOverrides.get(settingsModalTrackId)?.colorMap ??\n tracks.find((t) => t.id === settingsModalTrackId)?.spectrogramColorMap ??\n spectrogram.spectrogramColorMap ??\n 'viridis')\n : 'viridis'\n }\n onApply={(newConfig, newColorMap) => {\n if (settingsModalTrackId !== null) {\n spectrogram.setTrackSpectrogramConfig(settingsModalTrackId, newConfig, newColorMap);\n }\n }}\n />,\n document.body\n )}\n </DevicePixelRatioProvider>\n );\n};\n","/**\n * Pure helpers for the track-reorder drag preview.\n *\n * The preview is view-level only: it produces a DISPLAY order/geometry while\n * the engine's committed `tracks` order stays untouched until drop.\n */\n\nexport interface TrackDragPreview {\n trackId: string;\n toIndex: number;\n}\n\n/**\n * Returns the display order with the previewed track moved to `toIndex`.\n * Identity (same reference) when there is nothing to do — null preview,\n * unknown id, or an index that doesn't change the order.\n */\nexport function applyTrackOrderPreview<T extends { id: string }>(\n tracks: readonly T[],\n preview: TrackDragPreview | null\n): readonly T[] {\n if (!preview) return tracks;\n const fromIndex = tracks.findIndex((t) => t.id === preview.trackId);\n if (fromIndex === -1) return tracks;\n const toIndex = Math.max(0, Math.min(tracks.length - 1, preview.toIndex));\n if (toIndex === fromIndex) return tracks;\n const next = tracks.slice();\n const [moved] = next.splice(fromIndex, 1);\n next.splice(toIndex, 0, moved);\n return next;\n}\n\nexport interface TrackLayout {\n topById: Map<string, number>;\n totalHeight: number;\n}\n\n/**\n * Cumulative vertical layout for absolutely-positioned track rows. Both the\n * waveform column and the controls column render from the SAME layout so they\n * can never drift apart mid-preview. Ids missing from `heightById` contribute\n * height 0 (defensive; should not happen in practice).\n */\nexport function computeTrackLayout(\n orderedIds: readonly string[],\n heightById: ReadonlyMap<string, number>\n): TrackLayout {\n const topById = new Map<string, number>();\n let top = 0;\n for (const id of orderedIds) {\n topById.set(id, top);\n top += heightById.get(id) ?? 0;\n }\n return { topById, totalHeight: top };\n}\n\n/**\n * The track whose row contains the vertical offset `y` (measured from the top\n * of the first row), or null when `y` is above the first row or below the\n * last. Reads the SAME layout the rows are positioned with, so a press always\n * lands on the row that is drawn there (#762: the press handler once added up\n * row heights of its own, and counted a 'both' track twice as tall).\n */\nexport function trackIdAtOffset(\n orderedIds: readonly string[],\n layout: TrackLayout,\n heightById: ReadonlyMap<string, number>,\n y: number\n): string | null {\n for (const id of orderedIds) {\n const top = layout.topById.get(id);\n if (top === undefined) continue;\n const height = heightById.get(id) ?? 0;\n if (y >= top && y < top + height) return id;\n }\n return null;\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * True while `active` is true and for `trailingMs` after it turns false.\n * Used to keep the track-reorder transform transition enabled through the\n * cancel-revert animation (the drag ends but the layout still needs to\n * animate back) without animating unrelated layout changes outside a drag.\n */\nexport function useTrailingActive(active: boolean, trailingMs: number): boolean {\n const [trailing, setTrailing] = useState(active);\n useEffect(() => {\n if (active) {\n setTrailing(true);\n return undefined;\n }\n const timer = setTimeout(() => setTrailing(false), trailingMs);\n return () => clearTimeout(timer);\n }, [active, trailingMs]);\n return trailing || active;\n}\n","import { useCallback, useSyncExternalStore } from 'react';\nimport type { RecordingProgressSource } from '@waveform-playlist/core';\n\n/** How far the displayed timeline is extended at a time while a take runs (and a trim is dragged past the end). */\nexport const RECORDING_EXTENT_STEP_SECONDS = 10;\n\n/**\n * Where the displayed timeline should end for a take that currently ends at\n * `takeEndSeconds`: between 10 and 20 seconds further on, moving in 10-second\n * steps. A value that followed the take exactly would change on every\n * animation frame, and with it the width of every track row.\n */\nexport function recordingDisplayEnd(takeEndSeconds: number): number {\n const step = RECORDING_EXTENT_STEP_SECONDS;\n return (Math.floor(Math.max(0, takeEndSeconds) / step) + 2) * step;\n}\n\nconst subscribeToNothing = () => () => {};\n\nexport interface RecordingLayout {\n /** Channels in the take's preview (0 when not recording). */\n channelCount: number;\n /** End of the timeline the take needs, in seconds (0 when not recording). */\n displayEndSeconds: number;\n}\n\n/**\n * The two things the visualization's layout needs from a recording in\n * progress. Both are read through selectors that return numbers, so the\n * calling component re-renders when a number changes (a channel appears, the\n * take crosses a 10-second step) and not on every frame of progress.\n */\nexport function useRecordingLayout(\n progress: RecordingProgressSource | undefined,\n startSample: number,\n sampleRate: number\n): RecordingLayout {\n // Called as a method (not detached), so a source written as a class works.\n const subscribe = useCallback(\n (onChange: () => void) => (progress ? progress.subscribe(onChange) : subscribeToNothing()),\n [progress]\n );\n\n const getChannelCount = useCallback(\n () => (progress ? progress.getSnapshot().peaks.length : 0),\n [progress]\n );\n const getDisplayEnd = useCallback(\n () =>\n progress && sampleRate > 0\n ? recordingDisplayEnd(startSample / sampleRate + progress.getSnapshot().duration)\n : 0,\n [progress, startSample, sampleRate]\n );\n\n const channelCount = useSyncExternalStore(subscribe, getChannelCount, getChannelCount);\n const displayEndSeconds = useSyncExternalStore(subscribe, getDisplayEnd, getDisplayEnd);\n return { channelCount, displayEndSeconds };\n}\n","import { useCallback, useMemo, useSyncExternalStore } from 'react';\nimport type { ValueSource } from '@waveform-playlist/core';\nimport { useTrimPreviewOptional, useTrimPreviewPeaksOptional } from '../contexts/playlistContexts';\nimport type { TrimPreview } from '../providerInternals/useTrimPreview';\nimport type { ClipPeaks } from '../WaveformPlaylistContext';\nimport { RECORDING_EXTENT_STEP_SECONDS } from './useRecordingLayout';\n\n/**\n * How far the view is extended at a time while a trim is dragged past the\n * end of the timeline: the previewed end rounded UP to the next multiple (0 to\n * 10 seconds spare; not the recording layout's 10 to 20).\n */\nconst TRIM_EXTENT_STEP_SECONDS = RECORDING_EXTENT_STEP_SECONDS;\n\nconst NO_UNSUBSCRIBE = () => {};\n/** Where there is no preview source: subscribed to nothing. */\nconst subscribeToNothing = () => NO_UNSUBSCRIBE;\n\n/** `subscribe` for `useSyncExternalStore` over the trim preview, or over nothing. */\nfunction useSubscribe(source: ValueSource<TrimPreview | null> | undefined) {\n // Called as a method (not detached), so a source written as a class works.\n return useMemo(\n () => (source ? (onChange: () => void) => source.subscribe(onChange) : subscribeToNothing),\n [source]\n );\n}\n\n/**\n * The clip to draw: `clip`, or while a trim of this clip is dragged, its\n * record for the previewed geometry (computed by `clipPeaksFor`, as every\n * clip's is). The snapshot is `null` unless the preview names this clip, so a\n * move renders the dragged clip's view and no other. Under the MediaElement\n * provider, or outside a provider, there is no preview and `clip` is drawn.\n */\nexport function usePreviewedClipPeaks(clip: ClipPeaks, trackId: string): ClipPeaks {\n const source = useTrimPreviewOptional()?.source;\n const peaks = useTrimPreviewPeaksOptional();\n const subscribe = useSubscribe(source);\n const clipId = clip.clipId;\n const getSnapshot = useCallback(() => {\n const preview = source?.getSnapshot() ?? null;\n return preview !== null && preview.clipId === clipId && preview.trackId === trackId\n ? preview\n : null;\n }, [source, clipId, trackId]);\n const preview = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n // One record per preview object (and per committed record: a zoom or new\n // peaks during the drag change `clip`).\n return useMemo(\n () => (preview && peaks ? (peaks.peaksFor(preview) ?? clip) : clip),\n [preview, peaks, clip]\n );\n}\n\n/**\n * Where the view must end for a trim dragged past the end of the timeline, in\n * seconds: the previewed end rounded up to the next 10 seconds, or 0 when no\n * trim is dragged or it ends within `durationSeconds`. A selector that returns\n * the stepped number, so the caller renders once per step and not per move.\n */\nexport function useTrimPreviewExtent(sampleRate: number, durationSeconds: number): number {\n const source = useTrimPreviewOptional()?.source;\n const subscribe = useSubscribe(source);\n const getSnapshot = useCallback(() => {\n const preview = source?.getSnapshot() ?? null;\n if (preview === null || !(sampleRate > 0)) return 0;\n const endSeconds = (preview.startSample + preview.durationSamples) / sampleRate;\n if (endSeconds <= durationSeconds) return 0;\n return Math.ceil(endSeconds / TRIM_EXTENT_STEP_SECONDS) * TRIM_EXTENT_STEP_SECONDS;\n }, [source, sampleRate, durationSeconds]);\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","import { createContext, use } from 'react';\nimport { installCommand } from './utils/installCommand';\nimport type {\n SpectrogramConfig,\n ColorMapValue,\n RenderMode,\n TrackSpectrogramOverrides,\n SpectrogramCanvasRegistration,\n} from '@waveform-playlist/core';\nimport type { TrackMenuItem } from '@waveform-playlist/ui-components';\n\nexport interface SpectrogramIntegration {\n trackSpectrogramOverrides: Map<string, TrackSpectrogramOverrides>;\n spectrogramConfig?: SpectrogramConfig;\n spectrogramColorMap?: ColorMapValue;\n setTrackRenderMode: (trackId: string, mode: RenderMode) => void;\n setTrackSpectrogramConfig: (\n trackId: string,\n config: SpectrogramConfig,\n colorMap?: ColorMapValue\n ) => void;\n /** Single-canvas registration. OffscreenCanvas is non-transferable — call once per canvas. */\n registerSpectrogramCanvas: (reg: SpectrogramCanvasRegistration) => void;\n unregisterSpectrogramCanvas: (canvasId: string) => void;\n /** Render spectrogram menu items for a track's context menu */\n renderMenuItems?: (props: {\n renderMode: string;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n }) => TrackMenuItem[];\n /** Settings modal component provided by the spectrogram package */\n SettingsModal?: React.ComponentType<{\n open: boolean;\n onClose: () => void;\n config: SpectrogramConfig;\n colorMap: ColorMapValue;\n onApply: (config: SpectrogramConfig, colorMap: ColorMapValue) => void;\n }>;\n /** Get color lookup table for a color map name */\n getColorMap: (name: ColorMapValue) => Uint8Array;\n /** Get frequency scale function for a scale name */\n getFrequencyScale: (name: string) => (f: number, minF: number, maxF: number) => number;\n}\n\nexport const SpectrogramIntegrationContext = createContext<SpectrogramIntegration | null>(null);\n\nexport const SpectrogramIntegrationProvider = SpectrogramIntegrationContext.Provider;\n\n/**\n * Hook to access spectrogram integration provided by @waveform-playlist/spectrogram.\n * Throws if used without <SpectrogramProvider> wrapping the component tree.\n *\n * Follows the Kent C. Dodds pattern:\n * https://kentcdodds.com/blog/how-to-use-react-context-effectively\n */\nexport function useSpectrogramIntegration(): SpectrogramIntegration {\n const context = use(SpectrogramIntegrationContext);\n if (!context) {\n throw new Error(\n 'useSpectrogramIntegration must be used within <SpectrogramProvider>. ' +\n 'Install @waveform-playlist/spectrogram (' +\n installCommand('@waveform-playlist/spectrogram') +\n ') and wrap your app with <SpectrogramProvider>.'\n );\n }\n return context;\n}\n","import { trackKind } from '@waveform-playlist/core';\nimport type { ClipTrack, RenderMode } from '@waveform-playlist/core';\n\n/**\n * The render mode of a track: the spectrogram override for it, else its own\n * `renderMode`, else a waveform. Render modes are for audio tracks. A MIDI\n * track is drawn as a piano roll from its kind (#756), so it always gets\n * `'waveform'` here, which keeps the spectrogram machinery away from it.\n */\nexport function trackRenderMode(\n track: Pick<ClipTrack, 'kind' | 'renderMode'>,\n override?: RenderMode\n): RenderMode {\n if (trackKind(track) === 'midi') return 'waveform';\n return override ?? track.renderMode ?? 'waveform';\n}\n","import styled from 'styled-components';\nimport type { RecordingProgressSource } from '@waveform-playlist/core';\nimport type { ClipPeaks } from '../WaveformPlaylistContext';\n\n/** Live recording state for the real-time waveform preview. */\nexport interface WaveformRecordingState {\n isRecording: boolean;\n /** Which track is being recorded into. */\n trackId: string;\n /** Where on the timeline the take started. */\n startSample: number;\n /**\n * The take's elapsed time and per-channel preview peaks, from\n * `useRecording` / `useIntegratedRecording`. A source, not values: only the\n * preview clip follows it frame by frame, so the component that renders\n * `<Waveform>` does not re-render while recording.\n */\n progress: RecordingProgressSource;\n /** Bit depth of the peak values. */\n bits: 8 | 16;\n /**\n * Latency offset (seconds) to skip in the live preview. Absolute replacement\n * for the auto-computed outputLatency + lookAhead value. Pass the same value\n * given to useIntegratedRecording so preview and finalized clip match.\n */\n latencyOffset?: number;\n}\n\ninterface PositionedRowProps {\n readonly $top: number;\n readonly $animate: boolean;\n}\n\n/**\n * Shared relative container for absolutely-positioned track rows. Explicit\n * height because absolute children don't size their parent.\n */\nexport const TracksLayout = styled.div.attrs<{ $height: number }>((props) => ({\n style: { height: `${props.$height}px` },\n}))<{ $height: number }>`\n position: relative;\n`;\n\n/**\n * Positions one waveform track row from the shared layout map. Positioned\n * via `top`, NOT `translateY` — a transform (even translateY(0)) creates a\n * stacking context on every row, which flattens the clips' z-index: 105\n * beneath the ClickOverlay (z-index: 1) and blocks all clip interactions\n * (header drag, boundary trim, split). `top` moves the row without a\n * stacking context, so clip z-indexes keep competing globally as before.\n * Transition only while a track drag is active (+trailing window) so\n * unrelated layout changes stay instant.\n */\nexport const TrackRowPositioner = styled.div.attrs<PositionedRowProps>((props) => ({\n style: { top: `${props.$top}px` },\n}))<PositionedRowProps>`\n position: absolute;\n left: 0;\n right: 0;\n ${(props) => props.$animate && 'transition: top 150ms ease;'}\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\ninterface ControlSlotProps {\n readonly $height: number;\n readonly $top: number;\n readonly $animate: boolean;\n readonly $isSelected?: boolean;\n}\n\n/**\n * Height-synced container for each track's controls in the ControlsColumn.\n * Uses the same height formula as Track: waveHeight * numChannels + clipHeaderHeight.\n */\nexport const ControlSlot = styled.div.attrs<ControlSlotProps>((props) => ({\n style: {\n height: `${props.$height}px`,\n top: `${props.$top}px`,\n },\n}))<ControlSlotProps>`\n position: absolute;\n left: 0;\n right: 0;\n overflow: hidden;\n pointer-events: auto;\n background: ${(props) => props.theme.surfaceColor};\n transition: background 0.15s ease-in-out;\n ${(props) => props.$animate && 'transition: top 150ms ease, background 0.15s ease-in-out;'}\n @media (prefers-reduced-motion: reduce) {\n transition: background 0.15s ease-in-out;\n }\n ${(props) => props.$isSelected && `background: ${props.theme.selectedTrackControlsBackground};`}\n`;\n\n/**\n * The maximum channel count for a track, considering both clip peaks and a\n * live recording. `recordingChannels` is the channel count of the recording\n * into THIS track, 0 when it is not being recorded into. It is a number, not\n * the recording state object, so that track heights do not change identity on\n * every recording frame.\n */\nexport function getTrackChannelCount(\n trackClipPeaks: ClipPeaks[],\n recordingChannels: number\n): number {\n const clipChannels =\n trackClipPeaks.length > 0\n ? Math.max(1, ...trackClipPeaks.map((clip) => clip.peaks.data.length))\n : 1;\n return Math.max(clipChannels, recordingChannels);\n}\n","/**\n * What the two roots of the view share (#685): `WaveformRoot` (multitrack) and\n * `MediaElementWaveformRoot`. Internal: not exported from the package.\n *\n * A hook and not a component, so that it adds no component to either tree: a\n * root calls `useWaveformParts` on its children, works out what only its\n * provider knows (how long the timeline is, which rows there are and how tall),\n * and hands that to `useWaveformFrame`, which returns the scrolling frame with\n * the parts in their places.\n *\n * The frame reads shared hooks only (the view settings, the zoom, the playback\n * controls), so it runs under either provider.\n */\nimport React, {\n createElement,\n Fragment,\n useCallback,\n useMemo,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport {\n Playlist,\n PlaylistInfoContext,\n useTheme,\n waveformColorToCss,\n type PlaylistInfo,\n type WaveformPlaylistTheme,\n} from '@waveform-playlist/ui-components';\nimport {\n usePlaybackControls,\n usePlaylistView,\n usePlaylistZoom,\n} from '../contexts/playlistContexts';\nimport {\n useSelectionDrag,\n AutomaticScrollFlag,\n SelectionPreviewContext,\n type UseSelectionDragOptions,\n} from '../hooks/useSelectionDrag';\nimport {\n WaveformExtentContext,\n RootSeesRecordingPreviewContext,\n WaveformPartPlaceContext,\n WaveformRowsContext,\n type WaveformExtentValue,\n type WaveformRowsValue,\n} from './waveformLayoutContext';\nimport { sortWaveformParts, WaveformTimescale } from './waveformParts';\n\n/**\n * The parts of the timescale strip, each under a key made of its kind and\n * its number among that kind, so that one coming or going\n * (`{flag && <WaveformTimescale />}`) does not remount the others. The part\n * elements themselves are passed on untouched.\n */\nfunction keyedByKind(parts: ReactNode[]): ReactElement[] {\n const seen = { timescale: 0, loop: 0 };\n return parts.map((part) => {\n const kind =\n React.isValidElement(part) && part.type === WaveformTimescale ? 'timescale' : 'loop';\n return createElement(Fragment, { key: `${kind}-${seen[kind]++}` }, part);\n });\n}\nimport type { TracksMarkers } from './TrackRows';\nimport type { ResolvedViewOptions } from './WaveformViewOptions';\n\nexport interface WaveformPartsByPlace {\n /** The parts of the timescale strip in one element, or null when there is none. */\n timescale: ReactElement | null;\n /** The parts of the controls column, or undefined when there is none. */\n controls: ReactNode[] | undefined;\n /** Everything drawn in the scrolling tracks area, in order. */\n content: ReactElement;\n /** The per-clip parts the tracks part was given (all off without one). */\n tracksOptions: TracksMarkers;\n /** Width of the controls column the controls part asks for; 0 without one. */\n controlsWidth: number;\n /** Height of the timescale strip the timescale part asks for; 0 without a strip. */\n timescaleHeight: number;\n}\n\n/**\n * The root's children by place. The part elements are passed on as they were\n * given, never cloned: that is what lets React skip every part when the root\n * renders alone (same element, nothing to do). The memo only saves sorting\n * them again.\n */\nexport function useWaveformParts(children: ReactNode): WaveformPartsByPlace {\n return useMemo(() => {\n const sorted = sortWaveformParts(children);\n return {\n // One element per place. The tracks-area and controls parts are its\n // positional children (they carry no keys); the strip's parts are keyed\n // by kind (`keyedByKind`).\n timescale:\n sorted.timescale.length > 0 ? (\n <WaveformPartPlaceContext value=\"timescale\">\n {keyedByKind(sorted.timescale)}\n </WaveformPartPlaceContext>\n ) : null,\n controls:\n sorted.controls.length > 0\n ? [\n <WaveformPartPlaceContext key=\"controls\" value=\"controls\">\n {createElement(Fragment, null, ...sorted.controls)}\n </WaveformPartPlaceContext>,\n ]\n : undefined,\n content: createElement(Fragment, null, ...sorted.content),\n tracksOptions: sorted.tracksOptions,\n controlsWidth: sorted.controlsWidth,\n timescaleHeight: sorted.timescaleHeight,\n };\n }, [children]);\n}\n\nexport interface WaveformFrameOptions {\n className: string | undefined;\n /** From `useResolvedViewOptions()`; published here, memoized on its values, for everything drawn. */\n viewOptions: ResolvedViewOptions;\n parts: WaveformPartsByPlace;\n /** Length of the drawn timeline in seconds. */\n displayDuration: number;\n /** Memoized by the root: the tracks part and the controls part follow it. */\n rows: WaveformRowsValue;\n playlistState: 'ready' | 'loading';\n /** Width of the controls column in pixels; 0 draws none. */\n controlsWidth: number;\n /** Also told the scroll container (the frame registers it with the provider itself). Must be stable. */\n onScrollContainer?: (element: HTMLDivElement | null) => void;\n /** See `useSelectionDrag`. */\n onPress?: UseSelectionDragOptions['onPress'];\n onClickWhileStopped: UseSelectionDragOptions['onClickWhileStopped'];\n}\n\n/**\n * The scrolling frame with the parts in their places, the two layout values\n * and the selection drag. Returns two sibling elements in a fragment; the root\n * wraps them in its `DevicePixelRatioProvider`.\n *\n * It makes the calling root render on its own state (a drag in progress) and\n * on play and stop (the drag reads `isPlaying`), on a zoom and on a change of\n * the view settings or the theme. None of that renders a part by itself: both\n * layout values are memoized, and the part elements are the root's children.\n */\nexport function useWaveformFrame({\n className,\n viewOptions,\n parts,\n displayDuration,\n rows,\n playlistState,\n controlsWidth,\n onScrollContainer,\n onPress,\n onClickWhileStopped,\n}: WaveformFrameOptions): ReactElement {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { setScrollContainer } = usePlaybackControls();\n const { sampleRate } = usePlaylistView();\n const { waveHeight, barWidth, barGap, roundedBars, progressBarWidth } = viewOptions;\n // The strip exists when a part is drawn in it: rendering the timescale (or\n // the loop region) is the one switch, and the timescale part says how tall.\n const timeScaleHeight = parts.timescaleHeight;\n const { samplesPerPixel } = usePlaylistZoom();\n\n const handleScrollContainerRef = useCallback(\n (element: HTMLDivElement | null) => {\n onScrollContainer?.(element);\n setScrollContainer(element);\n },\n [onScrollContainer, setScrollContainer]\n );\n\n const tracksFullWidth = Math.floor((displayDuration * sampleRate) / samplesPerPixel);\n\n const {\n isSelecting,\n handleMouseDown,\n preview: selectionPreview,\n automaticScrollRef,\n } = useSelectionDrag({ samplesPerPixel, sampleRate, onPress, onClickWhileStopped });\n\n // The one publication of what a view draws with (#689): the options of\n // `<WaveformViewOptions>`, resolved by the root, with the zoom, the sample\n // rate and the strip height. Memoized so that its readers (every channel,\n // the timescale, the playhead) are not re-rendered by a render of the root\n // that changed none of it.\n const playlistInfo = useMemo<PlaylistInfo>(\n () => ({\n samplesPerPixel,\n sampleRate,\n waveHeight,\n timeScaleHeight,\n barWidth,\n barGap,\n roundedBars,\n progressBarWidth,\n }),\n [\n samplesPerPixel,\n sampleRate,\n waveHeight,\n timeScaleHeight,\n barWidth,\n barGap,\n roundedBars,\n progressBarWidth,\n ]\n );\n\n const extent = useMemo<WaveformExtentValue>(\n () => ({ displayDuration, tracksFullWidth }),\n [displayDuration, tracksFullWidth]\n );\n\n return (\n <>\n <AutomaticScrollFlag flagRef={automaticScrollRef} />\n <PlaylistInfoContext value={playlistInfo}>\n <WaveformExtentContext value={extent}>\n <WaveformRowsContext value={rows}>\n <RootSeesRecordingPreviewContext\n value={parts.tracksOptions.recordingState !== undefined}\n >\n <SelectionPreviewContext value={selectionPreview}>\n <Playlist\n className={className}\n theme={theme}\n backgroundColor={\n theme.playlistBackgroundColor || waveformColorToCss(theme.waveOutlineColor)\n }\n timescaleBackgroundColor={theme.timescaleBackgroundColor}\n timescaleWidth={tracksFullWidth}\n tracksWidth={tracksFullWidth}\n controlsWidth={controlsWidth}\n onTracksMouseDown={handleMouseDown}\n scrollContainerRef={handleScrollContainerRef}\n isSelecting={isSelecting}\n data-playlist-state={playlistState}\n trackControlsSlots={parts.controls}\n timescaleGapHeight={timeScaleHeight > 0 ? timeScaleHeight + 1 : 0}\n timescale={parts.timescale ?? undefined}\n >\n {parts.content}\n </Playlist>\n </SelectionPreviewContext>\n </RootSeesRecordingPreviewContext>\n </WaveformRowsContext>\n </WaveformExtentContext>\n </PlaylistInfoContext>\n </>\n );\n}\n","import { createContext, memo, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { createValueSource, type ValueSource } from '@waveform-playlist/core';\nimport {\n useIsPlaying,\n usePlaybackControls,\n usePlaylistSettings,\n} from '../contexts/playlistContexts';\nimport { useWindowDrag, clampedOffsetX } from './useWindowDrag';\n\n/** A time range in seconds, `start` before `end`. */\nexport interface SelectionRange {\n start: number;\n end: number;\n}\n\n/**\n * The range being drawn by a drag DURING PLAYBACK, or `null`. It is not the\n * selection yet: it becomes one when the button is released. Published by the\n * view that owns the drag (`useSelectionDrag`) and read by the selection\n * highlight, which shows it in place of the selection while it is set.\n *\n * A source and not state: it changes on every pointer move, and only the\n * highlight should follow it. Internal: not exported from the package.\n */\nexport const SelectionPreviewContext = createContext<ValueSource<SelectionRange | null> | null>(\n null\n);\n\n/** A range shorter than this, in seconds, is a click. */\nconst MIN_RANGE_SECONDS = 0.1;\n\nexport interface UseSelectionDragOptions {\n samplesPerPixel: number;\n sampleRate: number;\n /**\n * Called for every primary-button press, before the drag begins, with the\n * time under the pointer, the pointer's offset from the top of the pressed\n * element, and whether playback is running.\n */\n onPress?: (press: { time: number; offsetY: number; isPlaying: boolean }) => void;\n /** What a click (no drag) does with its time while playback is stopped. */\n onClickWhileStopped: (time: number) => void;\n}\n\nexport interface SelectionDrag {\n /** True from the press to the release. */\n isSelecting: boolean;\n /** For the `mousedown` of the element the drag starts on (the click overlay). */\n handleMouseDown: (event: React.MouseEvent<HTMLDivElement>) => void;\n /** For `<SelectionPreviewContext value>`. The same object for the life of the component. */\n preview: ValueSource<SelectionRange | null>;\n /** For `<AutomaticScrollFlag flagRef>`, which the caller must render (`useWaveformFrame` does). */\n automaticScrollRef: React.RefObject<boolean>;\n}\n\n/**\n * Keeps `flagRef` equal to the provider's automatic-scroll setting. Renders\n * nothing.\n *\n * The drag needs the setting only when an event arrives. Read with\n * `usePlaylistSettings()` in a root of the view, a toggle of the setting would\n * render that root and its frame for a value they never draw. This component\n * is the one that follows the setting; the frame renders it and nothing else\n * changes.\n * A layout effect: only a committed value, and in place before any event that\n * follows the commit. Memoized: its one prop is a ref that never changes, so a\n * render of the view does not render it.\n */\nexport const AutomaticScrollFlag = memo(function AutomaticScrollFlag({\n flagRef,\n}: {\n flagRef: React.RefObject<boolean>;\n}) {\n const { isAutomaticScroll } = usePlaylistSettings();\n useLayoutEffect(() => {\n flagRef.current = isAutomaticScroll;\n });\n return null;\n});\n\n/**\n * The selection drag of a waveform view, the same under either provider.\n *\n * **While playback is stopped** the selection follows the pointer: the press\n * collapses it at the pressed time, every move sets the ordered range from\n * the press to the pointer, and the release leaves that range (or, for a\n * click, calls `onClickWhileStopped`).\n *\n * **While playback is running nothing is committed before the release.**\n * `setSelection` restarts a running play, so writing the selection on the\n * press and on each move would restart playback under the pointer; until\n * 2026-11 the press did exactly that, moves were ignored, and no range could\n * be drawn during playback. Now the press changes nothing and the release\n * calls `setSelection` once. What the release commits depends on the\n * automatic scroll (maintainer's rules, 2026-11-12):\n *\n * - **Automatic scroll off:** the moves publish the range to `preview` (the\n * highlight shows it, playback carries on). The release sets that range,\n * which the provider plays from its start to its end (open-ended under the\n * multitrack provider with looping on); a range shorter than 0.1 s is not\n * previewed and is a click: playback moves to where the press landed.\n * - **Automatic scroll on:** no range can be drawn. The view scrolls to keep\n * the playhead in sight, so the audio moves under a still pointer and the\n * time under it at the release is not the time at the press. A press and\n * its release are one seek, to the time captured at the press, however far\n * the pointer travelled; moves are ignored.\n *\n * The drag is followed on the window (`useWindowDrag`): the pointer may leave\n * the element and the button may be released anywhere; positions outside it\n * clamp to its ends. When the drag ends with no release (the window lost\n * focus, or the `mouseup` was lost), a preview is dropped and playback is untouched; while stopped the\n * selection stays as the last move left it.\n *\n * A press made while playing whose release comes after playback has stopped\n * follows the stopped rules at the release. With the pointer under 0.1 s from\n * the press it is a click that collapses the selection at the press (the\n * press itself did not, because playback was running); further away, the\n * range becomes the selection, unplayed.\n */\nexport function useSelectionDrag({\n samplesPerPixel,\n sampleRate,\n onPress,\n onClickWhileStopped,\n}: UseSelectionDragOptions): SelectionDrag {\n const { isPlaying } = useIsPlaying();\n const { setSelection } = usePlaybackControls();\n const [isSelecting, setIsSelecting] = useState(false);\n // Kept current by <AutomaticScrollFlag>, read only inside the handlers.\n const automaticScrollRef = useRef(false);\n\n const previewHandle = useMemo(() => createValueSource<SelectionRange | null>(null), []);\n // The time under the pointer where the drag began.\n const pressTimeRef = useRef(0);\n // This drag has written the selection (the press while stopped, or a move\n // while stopped). False for a drag that has so far only run during playback.\n const wroteSelectionRef = useRef(false);\n // The element the drag began on, for pointer positions while the pointer is\n // somewhere else.\n const dragElementRef = useRef<HTMLDivElement | null>(null);\n\n const timeAt = (clientX: number): number | null => {\n const element = dragElementRef.current;\n const x = element ? clampedOffsetX(element, clientX) : null;\n return x === null ? null : (x * samplesPerPixel) / sampleRate;\n };\n\n /** From where the press landed to `time`, in order. The anchor is the press,\n * never the selection's start: that stops being the anchor as soon as the\n * pointer passes to the left of it (#733). */\n const rangeTo = (time: number): SelectionRange => ({\n start: Math.min(pressTimeRef.current, time),\n end: Math.max(pressTimeRef.current, time),\n });\n\n const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {\n // Primary button only: a right-click opens the context menu and its\n // release may never be delivered.\n if (event.button !== 0) return;\n const rect = event.currentTarget.getBoundingClientRect();\n // Never before the start of the timeline, whatever the event says.\n const time = Math.max(0, ((event.clientX - rect.left) * samplesPerPixel) / sampleRate);\n\n onPress?.({ time, offsetY: event.clientY - rect.top, isPlaying });\n\n pressTimeRef.current = time;\n dragElementRef.current = event.currentTarget;\n setIsSelecting(true);\n wroteSelectionRef.current = !isPlaying;\n if (!isPlaying) setSelection(time, time);\n };\n\n const handleDragMove = (event: MouseEvent) => {\n if (isPlaying && automaticScrollRef.current) {\n // Also when the setting was switched on under a drag that had already\n // drawn a range: it is withdrawn.\n previewHandle.publish(null);\n return;\n }\n const moveTime = timeAt(event.clientX);\n if (moveTime === null) return;\n const range = rangeTo(moveTime);\n\n if (isPlaying) {\n previewHandle.publish(range.end - range.start < MIN_RANGE_SECONDS ? null : range);\n return;\n }\n\n // Stopped. Also reached when playback stopped (or ended) under a drag\n // that began while it ran: from here it is an ordinary drag.\n previewHandle.publish(null);\n wroteSelectionRef.current = true;\n setSelection(range.start, range.end);\n };\n\n const handleDragEnd = (event: MouseEvent | null) => {\n setIsSelecting(false);\n previewHandle.publish(null);\n\n // The window lost focus mid-drag: there is no release position.\n if (event === null) return;\n\n // Where the press landed: what a click during playback seeks to.\n const pressTime = pressTimeRef.current;\n\n if (isPlaying && automaticScrollRef.current) {\n setSelection(pressTime, pressTime);\n return;\n }\n\n const endTime = timeAt(event.clientX);\n if (endTime === null) return;\n const range = rangeTo(endTime);\n const isClick = range.end - range.start < MIN_RANGE_SECONDS;\n\n if (isPlaying) {\n if (isClick) setSelection(pressTime, pressTime);\n else setSelection(range.start, range.end);\n return;\n }\n\n if (!isClick) {\n setSelection(range.start, range.end);\n } else if (wroteSelectionRef.current) {\n onClickWhileStopped(range.start);\n } else {\n // Pressed while playing, and playback has stopped since: the press did\n // not collapse the selection, so the click does (an older highlighted\n // range would otherwise stay selected, and Play would play it).\n setSelection(pressTime, pressTime);\n }\n };\n\n useWindowDrag(isSelecting, handleDragMove, handleDragEnd);\n\n return { isSelecting, handleMouseDown, preview: previewHandle.source, automaticScrollRef };\n}\n","import { useEffect, useLayoutEffect, useRef } from 'react';\n\n// Page text selection is switched off while any drag is active. Counted, so\n// that two components dragging at once cannot restore each other's 'none'.\nlet activeDrags = 0;\nlet userSelectBeforeDrags = '';\n// Safari only knows the prefixed property.\nlet webkitUserSelectBeforeDrags = '';\n\nfunction suspendTextSelection(): () => void {\n const root = document.documentElement;\n if (activeDrags === 0) {\n userSelectBeforeDrags = root.style.userSelect;\n webkitUserSelectBeforeDrags = root.style.webkitUserSelect;\n root.style.userSelect = 'none';\n root.style.webkitUserSelect = 'none';\n }\n activeDrags++;\n return () => {\n activeDrags--;\n if (activeDrags === 0) {\n root.style.userSelect = userSelectBeforeDrags;\n root.style.webkitUserSelect = webkitUserSelectBeforeDrags;\n }\n };\n}\n\n/**\n * Follows a mouse drag that began on an element for as long as the primary\n * button is held, wherever the pointer goes.\n *\n * An element's own `mousemove` / `mouseup` handlers stop running when the\n * pointer leaves it, so a drag tracked with them stalls outside the element\n * and, after a release outside, stays \"active\" with no button held. While\n * `active`, this listens on the window instead (capture phase, so a\n * `stopPropagation()` elsewhere on the page cannot hide the release):\n *\n * - `onMove` for every `mousemove` with the primary button held;\n * - `onEnd` for the primary button's `mouseup`, with the event;\n * - `onEnd(null)` when the drag ended without a release position: the window\n * lost focus (`blur`: the `mouseup` goes to another application), or a move\n * arrives with the primary button no longer held (the `mouseup` was lost).\n *\n * Text selection on the page is switched off while `active`.\n *\n * The caller starts the drag in its `onMouseDown` (primary button only) and\n * sets `active` false in `onEnd`. The latest callbacks are called; changing\n * them does not re-subscribe.\n */\nexport function useWindowDrag(\n active: boolean,\n onMove: (event: MouseEvent) => void,\n onEnd: (event: MouseEvent | null) => void\n): void {\n const callbacksRef = useRef({ onMove, onEnd });\n // Layout effect: the callbacks of a render are in place before any event\n // that follows its commit.\n useLayoutEffect(() => {\n callbacksRef.current = { onMove, onEnd };\n });\n\n useEffect(() => {\n if (!active) return;\n const move = (event: MouseEvent) => {\n if ((event.buttons & 1) === 0) {\n callbacksRef.current.onEnd(null);\n return;\n }\n callbacksRef.current.onMove(event);\n };\n const up = (event: MouseEvent) => {\n // Another button released while the primary one is still held.\n if (event.button !== 0) return;\n callbacksRef.current.onEnd(event);\n };\n const blur = () => callbacksRef.current.onEnd(null);\n // The press began on the element, so the browser would extend a text\n // selection across the page as the pointer travels over it. Switched off\n // for the length of the drag only (not with `preventDefault` on the press,\n // which would also stop the press from taking focus off a focused control).\n const resumeTextSelection = suspendTextSelection();\n window.addEventListener('mousemove', move, true);\n window.addEventListener('mouseup', up, true);\n window.addEventListener('blur', blur);\n return () => {\n resumeTextSelection();\n window.removeEventListener('mousemove', move, true);\n window.removeEventListener('mouseup', up, true);\n window.removeEventListener('blur', blur);\n };\n }, [active]);\n}\n\n/**\n * The horizontal position of a pointer inside `element`, in pixels from its\n * left edge, clamped to the element: a pointer to the left of it gives 0, one\n * to the right gives its width. `null` when the element is no longer in the\n * document (its rectangle would be all zeros).\n */\nexport function clampedOffsetX(element: Element, clientX: number): number | null {\n if (!element.isConnected) return null;\n const rect = element.getBoundingClientRect();\n return Math.min(Math.max(clientX - rect.left, 0), rect.width);\n}\n","/**\n * What a root of the view works out once and its parts read\n * (#685). Internal: not exported from the package.\n *\n * Two values, by what changes them. The extent changes with the timeline's\n * length and the zoom; the rows value changes with every clip edit (it holds\n * one `{ id, kind }` per track and their peaks, and the row heights follow from them). The timescale, the loop region and the\n * annotation row read the extent only, so a trim that leaves the length alone\n * does not render them.\n */\nimport { createContext, use } from 'react';\nimport type { RenderMode, TrackKind } from '@waveform-playlist/core';\nimport type { TrackClipPeaks } from '../WaveformPlaylistContext';\nimport type { TrackLayout } from '../utils/trackOrderPreview';\nimport type { SpectrogramTrackHelpers } from './TrackRows';\n\nexport interface WaveformExtentValue {\n /** Length of the drawn timeline in seconds (at least the audio's). */\n displayDuration: number;\n /** The same length in pixels at the current zoom. */\n tracksFullWidth: number;\n}\n\n/** What the view needs to know of a track to draw its row. */\nexport interface WaveformRow {\n id: string;\n kind: TrackKind;\n}\n\nexport interface WaveformRowsValue {\n /**\n * One entry per row, in timeline order, and the peaks of each (same index),\n * as the root read them from its provider. The parts take them from here and\n * do not read a provider's track value themselves: the multitrack timeline\n * value also changes with things no part draws (`isReady`), and a part that\n * read it would render for those too;\n * and no part then needs a hook only one provider serves.\n */\n rows: ReadonlyArray<WaveformRow>;\n peaksDataArray: TrackClipPeaks[];\n showClipHeaders: boolean;\n trackHeightById: ReadonlyMap<string, number>;\n trackLayout: TrackLayout;\n animateTrackLayout: boolean;\n /** Render mode per track id (spectrogram override, else the track's own). */\n renderModeById: ReadonlyMap<string, RenderMode>;\n spectrogramHelpersById: ReadonlyMap<string, SpectrogramTrackHelpers>;\n /** Stable: reads the tracks through a ref. */\n selectTrack: (trackIndex: number) => void;\n /** Opens the spectrogram settings of a track (the modal is the root's). */\n setSettingsModalTrackId: (id: string | null) => void;\n /** Channels of the take being recorded (already 1 when `mono`), else 0. */\n recordingChannelCount: number;\n /** The row being dragged to a new position, else null. */\n dragSourceTrackId: string | null;\n}\n\n/**\n * Where in the root a part is being rendered: the timescale strip, the\n * controls column, or the scrolling tracks area (the default: everything the\n * root does not recognise lands there). Read only for the development\n * warning of a part that ended up in the wrong place, which happens when it\n * is wrapped in another component: the root sorts its children by type.\n */\nexport type WaveformPartPlace = 'timescale' | 'controls' | 'tracks';\nexport const WaveformPartPlaceContext = createContext<WaveformPartPlace>('tracks');\n\n/**\n * Whether the root found a recording-preview marker in its tracks part. Read\n * by the tracks part alone, for the development warning of a tracks part the\n * root cannot see into (one wrapped in another component). A value of its own\n * and not a field of the rows value: the controls part reads that one, and\n * must not render because the marker came or went.\n */\nexport const RootSeesRecordingPreviewContext = createContext(false);\n\nexport const WaveformExtentContext = createContext<WaveformExtentValue | null>(null);\nexport const WaveformRowsContext = createContext<WaveformRowsValue | null>(null);\n\nfunction required<T>(value: T | null, part: string): T {\n if (value === null) {\n throw new Error(`${part} must be rendered inside the waveform root`);\n }\n return value;\n}\n\nexport const useWaveformExtent = (part: string) => required(use(WaveformExtentContext), part);\nexport const useWaveformRows = (part: string) => required(use(WaveformRowsContext), part);\n","/**\n * The parts of the view (#685), exported from the package: a consumer\n * composes them inside `WaveformRoot` (or, the ones its provider can serve,\n * inside `MediaElementWaveformRoot`). `Waveform`, `WaveformEditor` and\n * `MediaElementWaveform` are ready-made compositions of them.\n *\n * A part reads what it draws from the provider's contexts and from the root's\n * two layout values (waveformLayoutContext.ts); its props are the options of\n * that part alone. The root sorts its children into the three places a\n * playlist has (the timescale strip, the controls column, the scrolling\n * tracks area) by part type, see `sortWaveformParts`.\n *\n * A part is the component that draws, not a wrapper that forwards to one:\n * the tracks part is in TrackRows.tsx, the controls in\n * TrackControlsColumn.tsx, the overlays in VisualizationOverlays.tsx. The\n * parts with no children are memoized, except the playhead: the component\n * that composes them usually re-renders with the tracks (it holds them), and\n * a part whose props did not change should not follow.\n */\nimport React, { use, type ReactNode } from 'react';\nimport { SmartScale } from '@waveform-playlist/ui-components';\nimport {\n WaveformTracks,\n scanTracksParts,\n type TracksMarkers,\n type WaveformTracksProps,\n} from './TrackRows';\nimport {\n DEFAULT_TRACK_CONTROLS_WIDTH,\n WaveformTrackControls,\n type WaveformTrackControlsProps,\n} from './TrackControlsColumn';\nimport { WaveformLoopRegion } from './VisualizationOverlays';\nimport { useWaveformExtent, WaveformPartPlaceContext } from './waveformLayoutContext';\nimport { warnMisplacedPart } from './partWarnings';\nimport { WaveformViewOptions } from './WaveformViewOptions';\n\nexport {\n WaveformTracks,\n WaveformClipHeaders,\n WaveformFades,\n WaveformRecordingPreview,\n scanTracksParts,\n} from './TrackRows';\nexport { WaveformTrackControls } from './TrackControlsColumn';\n\nexport interface WaveformTimescaleProps {\n /** Custom tick label. `label` is already formatted for the scale mode. */\n renderTick?: (label: string, pixelPosition: number) => ReactNode;\n /**\n * Height in pixels of the timescale strip. The root reads it from the\n * element, as it reads the width of the controls part: the strip is the\n * root's own, above the scrolling area. Default: 30\n */\n height?: number;\n}\n\n/** Height in pixels of the timescale strip when the timescale part gives none. */\nexport const DEFAULT_TIMESCALE_HEIGHT = 30;\n\n/** The time ruler, as long as the root's timeline. */\nexport const WaveformTimescale = React.memo(function WaveformTimescale({\n renderTick,\n}: WaveformTimescaleProps) {\n // `height` is read by the root (`sortWaveformParts`), which draws the strip.\n const { displayDuration } = useWaveformExtent('The timescale');\n if (use(WaveformPartPlaceContext) !== 'timescale') {\n warnMisplacedPart(\n '<WaveformTimescale> is drawn among the tracks, not in the timescale strip: the root ' +\n 'recognises a part by its element type, so it must be a child of the root (a fragment ' +\n 'is fine), not wrapped in another component.'\n );\n }\n return <SmartScale durationMs={displayDuration * 1000} renderTick={renderTick} />;\n});\n\nexport { WaveformLoopRegion, WaveformPlayhead, WaveformSelection } from './VisualizationOverlays';\n\nexport interface SortedWaveformParts {\n /** Drawn in the timescale strip, in order. */\n timescale: ReactNode[];\n /** Drawn in the controls column, in order. */\n controls: ReactNode[];\n /**\n * Drawn in the scrolling tracks area, in order: one entry per child, `null`\n * for a child that is drawn elsewhere or not at all.\n */\n content: ReactNode[];\n /** The per-clip parts of the tracks part (all off when there is none). */\n tracksOptions: TracksMarkers;\n /** Width of the controls column in pixels, from the controls part; 0 without one. */\n controlsWidth: number;\n /** Height of the timescale strip in pixels, from the timescale part; 0 without a strip. */\n timescaleHeight: number;\n}\n\nconst TIMESCALE_PARTS: ReadonlySet<unknown> = new Set([WaveformTimescale, WaveformLoopRegion]);\nconst CONTROLS_PARTS: ReadonlySet<unknown> = new Set([WaveformTrackControls]);\n\n/**\n * Sorts the root's children into the places a playlist has. Fragments are\n * looked through; anything that is not a known part (the consumer's own\n * element, or a part wrapped in another component) goes to the tracks area.\n *\n * The elements are returned as they were given (no clone, no new key), so a\n * render of the root that received the same children hands React the same\n * elements and the parts are skipped. Call it from a `useMemo` on `children`.\n * The elements have no keys of their own: render the tracks-area and controls\n * lists as the children of one element (spread, not an array), and give the\n * strip's parts a key by kind (`useWaveformParts` does both).\n */\nexport function sortWaveformParts(children: ReactNode): SortedWaveformParts {\n const sorted: SortedWaveformParts = {\n timescale: [],\n controls: [],\n content: [],\n tracksOptions: { showClipHeaders: false, showFades: false, recordingState: undefined },\n controlsWidth: 0,\n timescaleHeight: 0,\n };\n let timescaleHeightGiven = false;\n let tracksParts = 0;\n const visit = (node: ReactNode) => {\n React.Children.forEach(node, (child) => {\n if (React.isValidElement(child)) {\n if (child.type === React.Fragment) {\n visit((child.props as { children?: ReactNode }).children);\n return;\n }\n if (TIMESCALE_PARTS.has(child.type)) {\n // The first timescale part says how tall the strip is; a strip that\n // holds only a loop region is the default height.\n if (child.type === WaveformTimescale && !timescaleHeightGiven) {\n timescaleHeightGiven = true;\n const { height } = child.props as WaveformTimescaleProps;\n // `null` (plain JavaScript) means \"not given\", like `undefined`.\n const given = height !== undefined && height !== null;\n if (given && !(height > 0)) {\n warnMisplacedPart(\n '<WaveformTimescale height> must be a positive number of pixels: ' +\n String(height) +\n ' is replaced by ' +\n DEFAULT_TIMESCALE_HEIGHT +\n '. Leave the part out to have no timescale.'\n );\n }\n sorted.timescaleHeight = given && height > 0 ? height : DEFAULT_TIMESCALE_HEIGHT;\n } else if (sorted.timescaleHeight === 0) {\n sorted.timescaleHeight = DEFAULT_TIMESCALE_HEIGHT;\n }\n sorted.timescale.push(child);\n sorted.content.push(null);\n return;\n }\n if (CONTROLS_PARTS.has(child.type)) {\n // The first controls part says how wide the column is.\n if (sorted.controls.length === 0) {\n const { width } = child.props as WaveformTrackControlsProps;\n // `null` (plain JavaScript) means \"not given\", like `undefined`.\n const given = width !== undefined && width !== null;\n if (given && !(width > 0)) {\n warnMisplacedPart(\n '<WaveformTrackControls width> must be a positive number of pixels: with ' +\n String(width) +\n ' no controls column is drawn. Leave the part out to have none.'\n );\n }\n // Not a positive number: no column, and 0 for whoever reads the width.\n sorted.controlsWidth = !given ? DEFAULT_TRACK_CONTROLS_WIDTH : width > 0 ? width : 0;\n }\n sorted.controls.push(child);\n sorted.content.push(null);\n return;\n }\n if (child.type === WaveformViewOptions) {\n // A root reads the options above itself: these do nothing for it,\n // and the parts inside them are wrapped, so not recognised either.\n warnMisplacedPart(\n '<WaveformViewOptions> inside a waveform root does nothing for that root: a root ' +\n 'reads the options above it. Put <WaveformViewOptions> around the root.'\n );\n }\n if (child.type === WaveformTracks) {\n tracksParts++;\n sorted.tracksOptions = scanTracksParts((child.props as WaveformTracksProps).children);\n }\n }\n // Every child keeps one position in the tracks area, also one that is\n // drawn elsewhere or not at all (`{flag && <Part />}`): the parts after\n // it are then not remounted when it comes or goes.\n // (`Children.forEach` already hands over `null` for `false` and `undefined`.)\n sorted.content.push(child);\n });\n };\n visit(children);\n if (sorted.controls.length > 1) {\n warnMisplacedPart(\n 'A waveform root has more than one <WaveformTrackControls>: each draws a panel for every ' +\n 'track in the one controls column, which is as wide as the first says.'\n );\n }\n if (tracksParts > 1) {\n warnMisplacedPart(\n 'A waveform root has more than one <WaveformTracks>: each draws every row, and the row ' +\n 'heights follow the per-clip parts of the last one.'\n );\n }\n return sorted;\n}\n","import React, {\n createContext,\n useCallback,\n use,\n useMemo,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { warnMisplacedPart } from './partWarnings';\nimport {\n Track as TrackComponent,\n Clip,\n ClipPlaceholderBody,\n SpectrogramLabels,\n useTheme,\n usePlaylistInfo,\n waveformColorToCss,\n type WaveformPlaylistTheme,\n} from '@waveform-playlist/ui-components';\nimport {\n resolveRecordingOffsetSamples,\n type Peaks,\n type RenderMode,\n type TrackKind,\n type SpectrogramConfig,\n} from '@waveform-playlist/core';\nimport { type ClipPeaks, type TrackClipPeaks } from '../WaveformPlaylistContext';\nimport {\n useEngineRefs,\n usePlaylistView,\n usePlaylistZoom,\n useSelectedRow,\n} from '../contexts/playlistContexts';\nimport {\n SpectrogramIntegrationContext,\n type SpectrogramIntegration,\n} from '../SpectrogramIntegrationContext';\nimport {\n RootSeesRecordingPreviewContext,\n useWaveformExtent,\n useWaveformRows,\n} from './waveformLayoutContext';\nimport { useClipInteraction } from '../contexts/ClipInteractionContext';\nimport { usePreviewedClipPeaks } from '../hooks/useTrimPreviewView';\nimport { ChannelWithProgress } from './ChannelWithProgress';\nimport {\n TrackRowPositioner,\n TracksLayout,\n getTrackChannelCount,\n type WaveformRecordingState,\n} from './visualizationLayout';\n\ntype FrequencyScaleFn = (f: number, minF: number, maxF: number) => number;\n\n/**\n * What every clip of the view is drawn with and no row uses: set once by the\n * tracks part, read by each clip (#685). A context and not props, so the\n * options do not travel through the row. The value changes only when one of\n * its fields does (a per-clip part comes or goes, the spectrogram integration\n * changes), and then every clip renders, as it must.\n */\ninterface ClipDisplayValue {\n gainScaledWaveforms: boolean;\n showFades: boolean;\n selectTrack: (trackIndex: number) => void;\n registerSpectrogramCanvas: SpectrogramIntegration['registerSpectrogramCanvas'] | undefined;\n unregisterSpectrogramCanvas: SpectrogramIntegration['unregisterSpectrogramCanvas'] | undefined;\n}\n\nconst ClipDisplayContext = createContext<ClipDisplayValue | null>(null);\n\n/** What a row uses itself and hands each of its clips. */\ninterface RowDisplayOptions {\n samplesPerPixel: number;\n sampleRate: number;\n showClipHeaders: boolean;\n}\n\ninterface ClipViewProps extends RowDisplayOptions {\n clip: ClipPeaks;\n trackId: string;\n trackIndex: number;\n clipIndex: number;\n isSelected: boolean;\n renderMode: RenderMode;\n}\n\n/**\n * One clip with its channels.\n *\n * Memoized (#693): `clip` keeps its identity while nothing about the clip\n * changed (see utils/derivePeaks.ts) and everything else is a primitive or a\n * stable callback, so an edit to one clip re-renders that clip only. Each\n * `Clip` runs three `useDraggable` hooks, which is what made re-rendering all\n * of them per pointer move expensive. While a trim of this clip is dragged it\n * also follows the trim preview, and draws the previewed geometry (#812); a\n * move of that drag renders this clip's view and no other. Its spectrogram\n * canvases register with the range drawn, so the spectrogram follows too.\n */\nconst ClipView = React.memo(function ClipView({\n clip: committedClip,\n trackId,\n trackIndex,\n clipIndex,\n isSelected,\n renderMode,\n samplesPerPixel,\n sampleRate,\n showClipHeaders,\n}: ClipViewProps) {\n // Always present: a clip is only ever rendered by the tracks part.\n const {\n gainScaledWaveforms,\n showFades,\n selectTrack,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n } = use(ClipDisplayContext) as ClipDisplayValue;\n // The one source of both options (#690): set by `ClipInteractionProvider`\n // or `ClipInteractionOptions` above, never passed down as props.\n const { enabled: interactiveClips, touchOptimized } = useClipInteraction();\n const clip = usePreviewedClipPeaks(committedClip, trackId);\n const peaksData = clip.peaks;\n const width = peaksData.length;\n // A placeholder with no peaks (only its duration is known) has nothing\n // for its channels to draw: its body shows the clip's extent, also in a\n // view without clip headers. A placeholder drawn from peaks gets none.\n const drawsBody = clip.isPlaceholder && width === 0;\n\n // Pressing a clip selects its track, except when the press starts a drag.\n const handleMouseDown = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n const target = e.target as HTMLElement;\n if (target.closest('[role=\"button\"][aria-roledescription=\"draggable\"]')) {\n return;\n }\n selectTrack(trackIndex);\n },\n [selectTrack, trackIndex]\n );\n\n return (\n <Clip\n clipId={clip.clipId}\n trackIndex={trackIndex}\n clipIndex={clipIndex}\n trackName={clip.trackName}\n startSample={clip.startSample}\n durationSamples={clip.durationSamples}\n samplesPerPixel={samplesPerPixel}\n showHeader={showClipHeaders}\n disableHeaderDrag={!interactiveClips}\n isPlaceholder={clip.isPlaceholder}\n isSelected={isSelected}\n trackId={trackId}\n fadeIn={clip.fadeIn}\n fadeOut={clip.fadeOut}\n sampleRate={sampleRate}\n showFades={showFades}\n touchOptimized={touchOptimized}\n onMouseDown={handleMouseDown}\n >\n {drawsBody && <ClipPlaceholderBody isSelected={isSelected} />}\n {peaksData.data.map((channelPeaks: Peaks, channelIndex: number) => (\n <ChannelWithProgress\n key={`${clip.clipId}-${channelIndex}`}\n index={channelIndex}\n data={channelPeaks}\n bits={peaksData.bits}\n length={width}\n isSelected={isSelected}\n gain={gainScaledWaveforms ? (clip.gain ?? 1) : 1}\n clipStartSample={clip.startSample}\n clipDurationSamples={clip.durationSamples}\n renderMode={renderMode}\n midiNotes={clip.midiNotes}\n clipSampleRate={clip.sampleRate}\n clipOffsetSeconds={\n clip.offsetSamples != null ? clip.offsetSamples / (clip.sampleRate || sampleRate) : 0\n }\n samplesPerPixel={samplesPerPixel}\n spectrogramClipId={clip.clipId}\n spectrogramOnCanvasRegister={registerSpectrogramCanvas}\n spectrogramOnCanvasUnregister={unregisterSpectrogramCanvas}\n // The range this clip is drawn for (the preview's while a trim of\n // it is dragged): its spectrogram canvases register with it.\n spectrogramOffsetSamples={clip.offsetSamples}\n spectrogramDurationSamples={clip.durationSamples}\n />\n ))}\n </Clip>\n );\n});\n\ninterface RecordingPreviewClipProps {\n recordingState: WaveformRecordingState;\n trackId: string;\n trackIndex: number;\n clipIndex: number;\n isSelected: boolean;\n samplesPerPixel: number;\n sampleRate: number;\n showClipHeaders: boolean;\n mono: boolean;\n}\n\n/**\n * The live preview of the take being recorded into a track.\n *\n * Strips leading-silence peaks so the visible preview matches audible content.\n * The recorder runs at real time, but the user's first reaction lands\n * ~outputLatency+lookAhead seconds into the buffer (they hadn't heard the\n * backing track yet). Without this, the playhead — which uses audible time —\n * would appear behind the right edge of the recorded waveform. Mirrors\n * useIntegratedRecording's finalization compensation (shared\n * `resolveRecordingOffsetSamples`) and dawcore's preview-skip pattern.\n * `getLookAhead()` reads from the same engine the playhead's animation loop\n * uses — keeps the two in lockstep.\n */\nconst RecordingPreviewClip: React.FC<RecordingPreviewClipProps> = ({\n recordingState,\n trackId,\n trackIndex,\n clipIndex,\n isSelected,\n samplesPerPixel,\n sampleRate,\n showClipHeaders,\n mono,\n}) => {\n const { getLookAhead, getOutputLatency } = useEngineRefs();\n // The one place that follows the take frame by frame (#695).\n // Called as methods (not destructured), so a source written as a class works.\n const source = recordingState.progress;\n const subscribe = useCallback((onChange: () => void) => source.subscribe(onChange), [source]);\n const getSnapshot = useCallback(() => source.getSnapshot(), [source]);\n const progress = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const durationSamples = Math.floor(progress.duration * sampleRate);\n\n const latencyOffsetSamples = resolveRecordingOffsetSamples({\n overrideSeconds: recordingState.latencyOffset,\n outputLatency: getOutputLatency(),\n lookAhead: getLookAhead(),\n sampleRate,\n });\n const latencyPixels = Math.floor(latencyOffsetSamples / samplesPerPixel);\n const skipPeakElements = latencyPixels * 2; // each pixel is a min/max pair\n const previewDuration = Math.max(0, durationSamples - latencyOffsetSamples);\n const previewChannels = (mono ? progress.peaks.slice(0, 1) : progress.peaks).map(\n (channelPeaks) =>\n skipPeakElements > 0 && skipPeakElements < channelPeaks.length\n ? channelPeaks.subarray(skipPeakElements)\n : channelPeaks\n );\n\n // Nothing to draw until the first peaks arrive.\n if (!(progress.peaks[0]?.length > 0)) return null;\n\n return (\n <Clip\n clipId=\"recording-preview\"\n trackIndex={trackIndex}\n clipIndex={clipIndex}\n trackName=\"Recording...\"\n startSample={recordingState.startSample}\n durationSamples={previewDuration}\n samplesPerPixel={samplesPerPixel}\n showHeader={showClipHeaders}\n disableHeaderDrag={true}\n isSelected={isSelected}\n trackId={trackId}\n >\n {previewChannels.map((channelPeaks, chIdx) => (\n <ChannelWithProgress\n key={`${trackId}-recording-${chIdx}`}\n index={chIdx}\n data={channelPeaks}\n bits={recordingState.bits}\n length={Math.floor(channelPeaks.length / 2)}\n isSelected={isSelected}\n clipStartSample={recordingState.startSample}\n clipDurationSamples={previewDuration}\n />\n ))}\n </Clip>\n );\n};\n\ninterface TrackRowProps extends RowDisplayOptions {\n trackId: string;\n trackIndex: number;\n trackClipPeaks: TrackClipPeaks;\n top: number;\n animate: boolean;\n width: number;\n isSelected: boolean;\n isDragSource: boolean;\n /** Audio or MIDI: a MIDI track is drawn as a piano roll. */\n kind: TrackKind;\n renderMode: RenderMode;\n numChannels: number;\n waveHeight: number;\n mono: boolean;\n /** Set only on the track being recorded into. */\n recordingState: WaveformRecordingState | undefined;\n /** Set only for a spectrogram track whose config asks for labels. */\n spectrogramConfig: SpectrogramConfig | undefined;\n frequencyScaleFn: FrequencyScaleFn | undefined;\n}\n\n/**\n * One track row: its background, spectrogram labels, clips and (while\n * recording into it) the live preview.\n *\n * Memoized (#693): `trackClipPeaks` keeps its identity while no clip of the\n * track changed, and the rest are primitives and stable callbacks.\n */\nconst TrackRow = React.memo(function TrackRow({\n trackId,\n trackIndex,\n trackClipPeaks,\n top,\n animate,\n width,\n isSelected,\n isDragSource,\n kind,\n renderMode,\n numChannels,\n waveHeight,\n mono,\n recordingState,\n spectrogramConfig,\n frequencyScaleFn,\n samplesPerPixel,\n sampleRate,\n showClipHeaders,\n}: TrackRowProps) {\n const theme = useTheme() as WaveformPlaylistTheme;\n\n return (\n <TrackRowPositioner\n $top={top}\n $animate={animate}\n data-track-row=\"\"\n data-track-id={trackId}\n data-track-kind={kind}\n data-selected={isSelected ? 'true' : undefined}\n data-track-drag-source={isDragSource ? 'true' : undefined}\n >\n <TrackComponent\n numChannels={numChannels}\n backgroundColor={\n kind === 'midi'\n ? theme.pianoRollBackgroundColor || '#1a1a2e'\n : waveformColorToCss(theme.waveOutlineColor)\n }\n offset={0}\n width={width}\n hasClipHeaders={showClipHeaders}\n trackId={trackId}\n isSelected={isSelected}\n >\n {renderMode !== 'waveform' && spectrogramConfig?.labels && frequencyScaleFn && (\n <SpectrogramLabels\n waveHeight={waveHeight}\n numChannels={numChannels}\n frequencyScaleFn={frequencyScaleFn}\n minFrequency={spectrogramConfig.minFrequency ?? 0}\n maxFrequency={spectrogramConfig.maxFrequency ?? sampleRate / 2}\n labelsColor={spectrogramConfig.labelsColor}\n labelsBackground={spectrogramConfig.labelsBackground}\n renderMode={renderMode as 'spectrogram' | 'both'}\n hasClipHeaders={showClipHeaders}\n />\n )}\n {trackClipPeaks.map((clip, clipIndex) => (\n <ClipView\n key={clip.clipId}\n clip={clip}\n trackId={trackId}\n trackIndex={trackIndex}\n clipIndex={clipIndex}\n isSelected={isSelected}\n renderMode={renderMode}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n showClipHeaders={showClipHeaders}\n />\n ))}\n {recordingState?.isRecording && (\n <RecordingPreviewClip\n key={`${trackId}-recording`}\n recordingState={recordingState}\n trackId={trackId}\n trackIndex={trackIndex}\n clipIndex={trackClipPeaks.length}\n isSelected={isSelected}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n showClipHeaders={showClipHeaders}\n mono={mono}\n />\n )}\n </TrackComponent>\n </TrackRowPositioner>\n );\n});\n\nexport interface SpectrogramTrackHelpers {\n colorLUT: Uint8Array;\n frequencyScaleFn: FrequencyScaleFn;\n config: SpectrogramConfig | undefined;\n}\n\nconst MARKER_OUTSIDE_TRACKS = (name: string) =>\n `<${name}> does nothing here: it must be a child of <WaveformTracks> (a fragment is fine), ` +\n 'not wrapped in another component and not a child of the root.';\n\n/**\n * Marker: clips get a header. With clip interaction enabled the header is also\n * what a clip is dragged by, and the trim handles come with it. It adds to the\n * height of every row, which is why the root must know of it before anything\n * is drawn: it renders nothing itself.\n */\nexport const WaveformClipHeaders: React.FC = () => {\n // A marker is read from the children of the tracks part and never rendered\n // there: when this runs, it was put somewhere else.\n warnMisplacedPart(MARKER_OUTSIDE_TRACKS('WaveformClipHeaders'));\n return null;\n};\n\n/** Marker: clips show their fade-in and fade-out curves. Renders nothing itself. */\nexport const WaveformFades: React.FC = () => {\n warnMisplacedPart(MARKER_OUTSIDE_TRACKS('WaveformFades'));\n return null;\n};\n\nexport interface WaveformRecordingPreviewProps {\n recordingState: WaveformRecordingState;\n}\n\n/**\n * Marker: the take being recorded is drawn into its track as it grows. The\n * preview clip is drawn by that track's row; this renders nothing itself.\n */\nexport const WaveformRecordingPreview: React.FC<WaveformRecordingPreviewProps> = () => {\n warnMisplacedPart(MARKER_OUTSIDE_TRACKS('WaveformRecordingPreview'));\n return null;\n};\n\nexport interface TracksMarkers {\n showClipHeaders: boolean;\n showFades: boolean;\n recordingState: WaveformRecordingState | undefined;\n}\n\n/**\n * Which per-clip parts are among the children of the tracks part. Looks\n * through fragments; a part wrapped in another component is not seen.\n */\nexport function scanTracksParts(children: ReactNode): TracksMarkers {\n const found: TracksMarkers = {\n showClipHeaders: false,\n showFades: false,\n recordingState: undefined,\n };\n const visit = (node: ReactNode) => {\n React.Children.forEach(node, (child) => {\n if (!React.isValidElement(child)) return;\n if (child.type === WaveformClipHeaders) found.showClipHeaders = true;\n else if (child.type === WaveformFades) found.showFades = true;\n else if (child.type === WaveformRecordingPreview) {\n found.recordingState = (child.props as WaveformRecordingPreviewProps).recordingState;\n } else if (child.type === React.Fragment) {\n visit((child.props as { children?: ReactNode }).children);\n } else {\n warnMisplacedPart(\n '<WaveformTracks> ignores a child that is not <WaveformClipHeaders>, <WaveformFades> or ' +\n '<WaveformRecordingPreview>. A marker wrapped in another component is not seen: ' +\n 'render it directly (a fragment is fine).'\n );\n }\n });\n };\n visit(children);\n return found;\n}\n\nexport interface WaveformTracksProps {\n /** Draw each clip's waveform scaled by its gain. */\n gainScaled?: boolean;\n /**\n * `WaveformClipHeaders`, `WaveformFades`, `WaveformRecordingPreview`: markers that\n * switch a per-clip part on. Nothing else is rendered from here.\n */\n children?: ReactNode;\n}\n\n/**\n * All track rows: the tracks part of the view (#685).\n *\n * It takes the rows, their peaks and the layout from the root's rows value\n * (not from a provider's track value, see waveformLayoutContext.ts) and the\n * selected row from a context both providers serve (`useSelectedRow`), so it\n * draws under either provider. It is\n * deliberately free of the time selection, the cursor and the annotation\n * state: those change on every pointer move of a selection drag and\n * throughout playback, and nothing in a track row depends on them. Read one\n * of them here and every row is back on that path (#693).\n *\n * It is not memoized: its children are new elements whenever the component\n * that composes the view renders. That costs this component's own render; the\n * rows below are memoized and get primitives, stable callbacks and the\n * identity-stable pieces of the peaks.\n */\nexport const WaveformTracks: React.FC<WaveformTracksProps> = ({ gainScaled = false, children }) => {\n const rows = useWaveformRows('The tracks');\n const { tracksFullWidth: width } = useWaveformExtent('The tracks');\n const { selectedTrackId } = useSelectedRow();\n const { sampleRate, mono } = usePlaylistView();\n // Published by the root from `<WaveformViewOptions>` (#689).\n const { waveHeight } = usePlaylistInfo();\n const { samplesPerPixel } = usePlaylistZoom();\n const spectrogram = use(SpectrogramIntegrationContext);\n const rootSeesRecordingPreview = use(RootSeesRecordingPreviewContext);\n const scanned = scanTracksParts(children);\n const { showFades, recordingState } = scanned;\n const {\n rows: rowList,\n peaksDataArray,\n dragSourceTrackId,\n trackLayout,\n renderModeById,\n spectrogramHelpersById,\n recordingChannelCount,\n } = rows;\n\n if (scanned.showClipHeaders !== rows.showClipHeaders) {\n warnMisplacedPart(\n '<WaveformTracks> and its root disagree about <WaveformClipHeaders>, so the rows have the ' +\n 'wrong height: the root reads the per-clip parts from a <WaveformTracks> that is its ' +\n 'own child (a fragment is fine), not one wrapped in another component, and from the ' +\n 'last one when there are several.'\n );\n }\n if ((recordingState !== undefined) !== rootSeesRecordingPreview) {\n warnMisplacedPart(\n '<WaveformTracks> and its root disagree about <WaveformRecordingPreview>, so the timeline ' +\n 'does not grow with the take: the root reads the per-clip parts from a <WaveformTracks> ' +\n 'that is its own child (a fragment is fine), not one wrapped in another component, and ' +\n 'from the last one when there are several.'\n );\n }\n const { selectTrack } = rows;\n const registerSpectrogramCanvas = spectrogram?.registerSpectrogramCanvas;\n const unregisterSpectrogramCanvas = spectrogram?.unregisterSpectrogramCanvas;\n const clipDisplay = useMemo<ClipDisplayValue>(\n () => ({\n gainScaledWaveforms: gainScaled,\n showFades,\n selectTrack,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n }),\n [gainScaled, showFades, selectTrack, registerSpectrogramCanvas, unregisterSpectrogramCanvas]\n );\n\n return (\n <ClipDisplayContext value={clipDisplay}>\n <TracksLayout $height={trackLayout.totalHeight}>\n {peaksDataArray.map((trackClipPeaks, trackIndex) => {\n const track = rowList[trackIndex];\n if (!track) return null;\n\n const isArmed =\n recordingState?.isRecording === true && recordingState.trackId === track.id;\n const recordingChannels = isArmed ? recordingChannelCount : 0;\n const helpers = spectrogramHelpersById.get(track.id);\n\n return (\n <TrackRow\n key={track.id}\n trackId={track.id}\n trackIndex={trackIndex}\n trackClipPeaks={trackClipPeaks}\n top={trackLayout.topById.get(track.id) ?? 0}\n animate={rows.animateTrackLayout}\n width={width}\n isSelected={track.id === selectedTrackId}\n isDragSource={track.id === dragSourceTrackId}\n kind={track.kind}\n renderMode={renderModeById.get(track.id) ?? 'waveform'}\n numChannels={getTrackChannelCount(trackClipPeaks, recordingChannels)}\n waveHeight={waveHeight}\n mono={mono}\n recordingState={isArmed ? recordingState : undefined}\n spectrogramConfig={helpers?.config}\n frequencyScaleFn={helpers?.frequencyScaleFn}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n showClipHeaders={rows.showClipHeaders}\n />\n );\n })}\n </TracksLayout>\n </ClipDisplayContext>\n );\n};\n","import React, { createContext, use, useMemo } from 'react';\n\n/** What the clips below are told about interaction. */\nexport interface ClipInteractionContextValue {\n /** Clips can be dragged and trimmed. */\n enabled: boolean;\n /**\n * Touch handling below: clips widen their trim handles, and a touch on an\n * annotation edge must be held (250 ms) before it drags.\n */\n touchOptimized: boolean;\n}\n\nconst NO_CLIP_INTERACTION: ClipInteractionContextValue = { enabled: false, touchOptimized: false };\n\nconst ClipInteractionContext = createContext<ClipInteractionContextValue>(NO_CLIP_INTERACTION);\n\nexport interface ClipInteractionOptionsProps {\n /** Clips below can be dragged and trimmed. Left out: inherited (false at the top). */\n enabled?: boolean;\n /**\n * Touch handling below: clips get wider trim handles, and a touch on an\n * annotation edge must be held (250 ms) before it drags, so a swipe is not\n * taken for a drag. Left out: inherited (false at the top).\n */\n touchOptimized?: boolean;\n children: React.ReactNode;\n}\n\n/**\n * The one source of the clip interaction options (#690). Every clip below\n * reads them from here; `<Waveform>` takes neither as a prop.\n *\n * `ClipInteractionProvider` renders this for you. Use it directly when you\n * wire up your own `DragDropProvider`, or nested inside a\n * `ClipInteractionProvider` to change one option for part of the tree: an\n * option you leave out keeps the value from above.\n */\nexport const ClipInteractionOptions: React.FC<ClipInteractionOptionsProps> = ({\n enabled: enabledProp,\n touchOptimized: touchOptimizedProp,\n children,\n}) => {\n const inherited = use(ClipInteractionContext);\n const enabled = enabledProp ?? inherited.enabled;\n const touchOptimized = touchOptimizedProp ?? inherited.touchOptimized;\n // Two booleans in, one object out: the value changes only when one of them\n // does, however often the parent renders.\n const value = useMemo(() => ({ enabled, touchOptimized }), [enabled, touchOptimized]);\n return <ClipInteractionContext value={value}>{children}</ClipInteractionContext>;\n};\n\n/** The options for the clip that calls it. */\nexport function useClipInteraction(): ClipInteractionContextValue {\n return use(ClipInteractionContext);\n}\n\n/** True when clips here can be dragged and trimmed. */\nexport function useClipInteractionEnabled(): boolean {\n return use(ClipInteractionContext).enabled;\n}\n","import React, { useId, useRef, useEffect } from 'react';\nimport styled from 'styled-components';\nimport {\n clipPixelWidth as computeClipPixelWidth,\n type MidiNoteData,\n} from '@waveform-playlist/core';\nimport {\n SmartChannel,\n type SmartChannelProps,\n useTheme,\n usePlaylistInfo,\n type WaveformPlaylistTheme,\n waveformColorToCss,\n} from '@waveform-playlist/ui-components';\nimport {\n useCurrentTime,\n usePlaylistView,\n usePlaylistZoom,\n usePlaybackRefs,\n useIsPlaying,\n} from '../contexts/playlistContexts';\n\nconst ChannelWrapper = styled.div`\n position: relative;\n`;\n\ninterface BackgroundProps {\n readonly $color: string;\n readonly $height: number;\n readonly $top: number;\n readonly $width: number;\n}\n\nconst Background = styled.div.attrs<BackgroundProps>((props) => ({\n style: {\n top: `${props.$top}px`,\n width: `${props.$width}px`,\n height: `${props.$height}px`,\n background: props.$color,\n },\n}))<BackgroundProps>`\n position: absolute;\n left: 0;\n z-index: 0;\n /* Force GPU compositing layer to prevent gradient flickering during scroll */\n transform: translateZ(0);\n backface-visibility: hidden;\n`;\n\ninterface ProgressOverlayProps {\n readonly $color: string;\n readonly $height: number;\n readonly $top: number;\n readonly $width: number;\n}\n\nconst ProgressOverlay = styled.div.attrs<ProgressOverlayProps>((props) => ({\n style: {\n top: `${props.$top}px`,\n height: `${props.$height}px`,\n width: `${props.$width}px`,\n background: props.$color,\n transform: 'scaleX(0)',\n },\n}))<ProgressOverlayProps>`\n position: absolute;\n left: 0;\n pointer-events: none;\n z-index: 1;\n transform-origin: left;\n /* scaleX changes are composite-only (GPU) — no layout reflow per frame */\n will-change: transform;\n`;\n\nconst ChannelContainer = styled.div`\n position: relative;\n z-index: 2;\n`;\n\nexport interface ChannelWithProgressProps extends SmartChannelProps {\n /** Start sample of the clip containing this channel (for progress calculation) */\n clipStartSample: number;\n /** Duration in samples of the clip */\n clipDurationSamples: number;\n /** MIDI note data for piano-roll rendering */\n midiNotes?: MidiNoteData[];\n /** Sample rate of the clip (for MIDI note positioning) */\n clipSampleRate?: number;\n /** Clip offset in seconds (for MIDI note positioning) */\n clipOffsetSeconds?: number;\n}\n\ninterface ClipProgressProps {\n clipStartSample: number;\n clipDurationSamples: number;\n color: string;\n height: number;\n top: number;\n}\n\n/** Fraction of the clip that lies before `time`, 0 to 1. */\nfunction playedRatio(\n time: number,\n sampleRate: number,\n clipStartSample: number,\n clipDurationSamples: number\n): number {\n const currentSample = time * sampleRate;\n if (currentSample <= clipStartSample) return 0;\n if (currentSample >= clipStartSample + clipDurationSamples) return 1;\n return (currentSample - clipStartSample) / clipDurationSamples;\n}\n\n/**\n * The played-portion overlay of one channel. It is the only part of a channel\n * that follows the cursor, so it alone subscribes to the provider's contexts\n * (#693): a seek, or a selection whose start moves, re-renders these\n * small overlays and not the channels (and their canvases' React trees) around\n * them. It reads shared hooks only, so it works under either provider (#688).\n */\nconst ClipProgress: React.FC<ClipProgressProps> = ({\n clipStartSample,\n clipDurationSamples,\n color,\n height,\n top,\n}) => {\n const progressRef = useRef<HTMLDivElement>(null);\n const callbackId = useId();\n const { currentTimeRef, visualTimeRef, registerFrameCallback, unregisterFrameCallback } =\n usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only: the effect below reads the refs.\n useCurrentTime();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n\n // Use shared helper to compute clip pixel width (must match Clip.tsx sizing)\n // peaksData.length may be shorter than the clip when audio is shorter than configured duration\n const clipPixelWidth = computeClipPixelWidth(\n clipStartSample,\n clipDurationSamples,\n samplesPerPixel\n );\n\n // Register per-frame callback during playback — no own rAF loop\n useEffect(() => {\n if (isPlaying) {\n registerFrameCallback(callbackId, ({ visualTime, sampleRate: sr }) => {\n if (progressRef.current) {\n const ratio = playedRatio(visualTime, sr, clipStartSample, clipDurationSamples);\n // scaleX is composite-only — no layout reflow, GPU-accelerated\n progressRef.current.style.transform = `scaleX(${ratio})`;\n }\n });\n }\n return () => unregisterFrameCallback(callbackId);\n }, [\n isPlaying,\n clipStartSample,\n clipDurationSamples,\n callbackId,\n registerFrameCallback,\n unregisterFrameCallback,\n ]);\n\n // Also update when not playing (for seeks, stops, etc.). Reads visualTimeRef\n // so the static progress fill matches the playhead's audible position. No\n // dependency array on purpose: `useCurrentTime()` re-renders this component\n // whenever the resting position changes.\n useEffect(() => {\n if (!isPlaying && progressRef.current) {\n const currentTime = visualTimeRef.current ?? currentTimeRef.current ?? 0;\n const ratio = playedRatio(currentTime, sampleRate, clipStartSample, clipDurationSamples);\n progressRef.current.style.transform = `scaleX(${ratio})`;\n }\n });\n\n return (\n <ProgressOverlay\n ref={progressRef}\n $color={color}\n $height={height}\n $top={top}\n $width={clipPixelWidth}\n />\n );\n};\n\n/**\n * SmartChannel wrapper that adds an animated progress overlay showing the\n * played portion of the waveform. Used under either provider: the rows of\n * the tracks part render it in both views. The channel itself reads no\n * playback state; its `ClipProgress` child does.\n */\nexport const ChannelWithProgress: React.FC<ChannelWithProgressProps> = ({\n clipStartSample,\n clipDurationSamples,\n midiNotes,\n clipSampleRate,\n clipOffsetSeconds,\n ...smartChannelProps\n}) => {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { waveHeight } = usePlaylistInfo();\n\n const progressColor = theme?.waveProgressColor || 'rgba(0, 0, 0, 0.1)';\n\n // Get the draw mode from theme (defaults to 'inverted')\n const drawMode = theme?.waveformDrawMode || 'inverted';\n\n // A selected channel without a selected colour in the theme falls back to\n // the unselected one. (The MediaElement view's one row is always the\n // selected one.)\n const selected = smartChannelProps.isSelected;\n const backgroundColor =\n drawMode === 'inverted'\n ? (selected && theme?.selectedWaveFillColor) || theme?.waveFillColor || 'white'\n : (selected && theme?.selectedWaveOutlineColor) || theme?.waveOutlineColor || 'grey';\n\n // A clip with notes is a MIDI clip and is drawn as a piano roll; the render\n // mode applies to audio clips only (black background for a spectrogram).\n const isPianoRollMode = midiNotes != null;\n const isSpectrogramMode =\n !isPianoRollMode &&\n (smartChannelProps.renderMode === 'spectrogram' || smartChannelProps.renderMode === 'both');\n const isBothMode = !isPianoRollMode && smartChannelProps.renderMode === 'both';\n const spectrogramBackground = theme?.spectrogramBackgroundColor ?? '#000';\n const backgroundCss = isSpectrogramMode\n ? spectrogramBackground\n : isPianoRollMode\n ? theme?.pianoRollBackgroundColor || '#1a1a2e'\n : waveformColorToCss(backgroundColor);\n\n // In \"both\" mode each half (spectrogram + waveform) is waveHeight/2 so the track\n // container stays the same height as a single-mode track.\n const halfHeight = Math.floor(waveHeight / 2);\n const effectiveHeight = waveHeight;\n const effectiveTop = isBothMode\n ? smartChannelProps.index * waveHeight\n : smartChannelProps.index * waveHeight;\n\n // In \"both\" mode, the waveform portion needs its own (non-black) background\n const waveformBackgroundCss = waveformColorToCss(backgroundColor);\n\n return (\n <ChannelWrapper>\n {/* Background layer - color depends on draw mode */}\n {isBothMode ? (\n <>\n {/* Spectrogram portion: the theme's spectrogram background */}\n <Background\n $color={spectrogramBackground}\n $height={halfHeight}\n $top={effectiveTop}\n $width={smartChannelProps.length}\n />\n {/* Waveform portion: themed background */}\n <Background\n $color={waveformBackgroundCss}\n $height={halfHeight}\n $top={effectiveTop + halfHeight}\n $width={smartChannelProps.length}\n />\n </>\n ) : (\n <Background\n $color={backgroundCss}\n $height={effectiveHeight}\n $top={effectiveTop}\n $width={smartChannelProps.length}\n />\n )}\n {/* Progress overlay - shows played portion with progress color (skip for piano-roll) */}\n {!isPianoRollMode && (\n <ClipProgress\n clipStartSample={clipStartSample}\n clipDurationSamples={clipDurationSamples}\n color={progressColor}\n height={effectiveHeight}\n top={effectiveTop}\n />\n )}\n {/* Waveform canvas with transparent background */}\n <ChannelContainer>\n <SmartChannel\n {...smartChannelProps}\n transparentBackground\n midiNotes={midiNotes}\n sampleRate={clipSampleRate}\n clipOffsetSeconds={clipOffsetSeconds}\n />\n </ChannelContainer>\n </ChannelWrapper>\n );\n};\n","import React, { use, useMemo, useRef, useState, type ReactNode } from 'react';\nimport type { RenderMode, TrackKind } from '@waveform-playlist/core';\nimport { useTheme, type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport { warnMisplacedPart } from './partWarnings';\nimport {\n usePlaylistMixer,\n useEditorControls,\n useRecordingArm,\n useSelectedTrackId,\n useTrackReorderPreview,\n} from '../contexts/playlistContexts';\nimport { SpectrogramIntegrationContext } from '../SpectrogramIntegrationContext';\nimport { useWaveformRows, WaveformPartPlaceContext } from './waveformLayoutContext';\nimport { DefaultTrackControls } from './DefaultTrackControls';\nimport { ControlSlot, TracksLayout } from './visualizationLayout';\nimport { useStableTemplate } from '../utils/stableTemplate';\nimport {\n TrackContext,\n TrackControlsSharedContext,\n TrackSlotWiringContext,\n type TrackContextValue,\n type TrackControlsShared,\n type TrackSlotWiring,\n} from './trackContext';\n\n/** Width of the controls column when the part does not say. */\nexport const DEFAULT_TRACK_CONTROLS_WIDTH = 200;\n\nexport interface WaveformTrackControlsProps {\n /**\n * Width of the controls column in pixels. Default 200. The root reads it\n * from the element (the column is its own, beside the scrolling area), so it\n * must be on the part itself.\n */\n width?: number;\n /**\n * The control panel of a track, as a template: it is rendered once per\n * track, inside that track's context, which `useTrack()` and the built-in\n * pieces (`<TrackName />`, `<TrackMuteButton />`, …) read. Default:\n * `<DefaultTrackControls />`.\n */\n children?: ReactNode;\n}\n\n/** What the part renders for a track when it has no children. */\nconst DEFAULT_TEMPLATE = <DefaultTrackControls />;\n\n/** Drop-shadow for the floating (fully opaque) drag-source controls row. */\nconst DRAG_SOURCE_SHADOW = '0 4px 12px rgba(0, 0, 0, 0.35)';\n\n/** Fills the slot; the element a reorder drag moves. */\nconst SLOT_BODY_STYLE = { height: '100%' } as const;\n\ninterface TrackControlsSlotProps {\n trackId: string;\n index: number;\n kind: TrackKind;\n name: string;\n muted: boolean;\n soloed: boolean;\n volume: number;\n pan: number;\n isSelected: boolean;\n isFirst: boolean;\n isLast: boolean;\n renderMode: RenderMode;\n hasSpectrogram: boolean;\n isRecordingArmed: boolean;\n height: number;\n top: number;\n animate: boolean;\n template: ReactNode;\n}\n\n/**\n * One track's slot in the controls column: the height-synced box, the track's\n * context around the template, and the click that selects the track.\n *\n * Memoized, and every prop is a primitive or the template: the column renders\n * on each mixer change (it reads the mixer state), and only the slot whose\n * track changed renders with it. The template is the same object for every\n * slot and across renders (see `useStableTemplate`), so inside a slot that\n * does render React skips every element of it and only the components that\n * read the track's context follow.\n */\nfunction TrackControlsSlotImpl({\n trackId,\n index,\n kind,\n name,\n muted,\n soloed,\n volume,\n pan,\n isSelected,\n isFirst,\n isLast,\n renderMode,\n hasSpectrogram,\n isRecordingArmed,\n height,\n top,\n animate,\n template,\n}: TrackControlsSlotProps) {\n const {\n setTrackMute,\n setTrackSolo,\n setTrackVolume,\n setTrackPan,\n reorderTrack,\n setSelectedTrackId,\n } = useEditorControls();\n const theme = useTheme() as WaveformPlaylistTheme;\n const shared = use(TrackControlsSharedContext);\n\n // The position is read when an action runs, so the actions do not change\n // with it.\n const indexRef = useRef(index);\n indexRef.current = index;\n\n const actions = useMemo(\n () => ({\n setMuted: (value: boolean) => setTrackMute(trackId, value),\n setSoloed: (value: boolean) => setTrackSolo(trackId, value),\n setVolume: (value: number) => setTrackVolume(trackId, value),\n setPan: (value: number) => setTrackPan(trackId, value),\n select: () => setSelectedTrackId(trackId),\n // The engine clamps the target and ignores a move to the same place.\n moveUp: () => reorderTrack(trackId, indexRef.current - 1),\n moveDown: () => reorderTrack(trackId, indexRef.current + 1),\n setRenderMode: (mode: RenderMode) => shared?.setTrackRenderMode(trackId, mode),\n openSpectrogramSettings: () => shared?.openSpectrogramSettings(trackId),\n }),\n [\n trackId,\n setTrackMute,\n setTrackSolo,\n setTrackVolume,\n setTrackPan,\n setSelectedTrackId,\n reorderTrack,\n shared,\n ]\n );\n\n const value = useMemo<TrackContextValue>(\n () => ({\n id: trackId,\n kind,\n index,\n name: name || `Track ${index + 1}`,\n muted,\n soloed,\n volume,\n pan,\n renderMode,\n isSelected,\n isFirst,\n isLast,\n hasSpectrogram,\n isRecordingArmed,\n ...actions,\n }),\n [\n trackId,\n kind,\n index,\n name,\n muted,\n soloed,\n volume,\n pan,\n renderMode,\n isSelected,\n isFirst,\n isLast,\n hasSpectrogram,\n isRecordingArmed,\n actions,\n ]\n );\n\n // For a reorder handle inside the panel (`useTrackReorderHandle`).\n const elementRef = useRef<HTMLDivElement | null>(null);\n const [isDragSource, setDragSource] = useState(false);\n const wiring = useMemo<TrackSlotWiring>(\n () => ({ elementRef, setDragSource, handleCount: { current: 0 } }),\n []\n );\n\n return (\n <ControlSlot\n $height={height}\n $top={top}\n $animate={animate}\n $isSelected={isSelected}\n onClick={actions.select}\n >\n <div\n ref={elementRef}\n data-track-controls={trackId}\n style={\n isDragSource\n ? {\n ...SLOT_BODY_STYLE,\n boxShadow: DRAG_SOURCE_SHADOW,\n // Opaque background for the floating (top-layer, popover-based)\n // drag-source row — without it the row underneath shows through.\n // onDragStart selects the dragged track, so its slot always shows\n // the selected-track background while lifted.\n background: theme.selectedTrackControlsBackground,\n }\n : SLOT_BODY_STYLE\n }\n >\n <TrackSlotWiringContext value={wiring}>\n <TrackContext value={value}>{template}</TrackContext>\n </TrackSlotWiringContext>\n </div>\n </ControlSlot>\n );\n}\n\nconst TrackControlsSlot = React.memo(TrackControlsSlotImpl);\n\n/**\n * The control panels of all tracks, one height-synced slot per track, for the\n * ControlsColumn outside the scroll area: the track-controls part of the view\n * (#685). Its children are the panel of ONE track, a template it renders once\n * per track inside that track's context (#687); without children the panel is\n * `<DefaultTrackControls />`.\n *\n * Memoized (#693): it takes the rows and the layout from the root's rows\n * value, reads the selected track itself, and no time selection, cursor or\n * annotation state, so a selection drag or an active-annotation change during\n * playback does not re-render the panels. It reads the mixer state itself\n * (#768), so a volume or pan step renders this column, the slot of that track\n * and the pieces of that track, and not the root above it.\n */\nfunction WaveformTrackControlsImpl({ children }: WaveformTrackControlsProps) {\n const {\n rows: tracks,\n renderModeById,\n trackLayout,\n trackHeightById,\n animateTrackLayout,\n setSettingsModalTrackId,\n } = useWaveformRows('The track controls');\n if (use(WaveformPartPlaceContext) !== 'controls') {\n warnMisplacedPart(\n '<WaveformTrackControls> is drawn among the tracks, not in the controls column: the root ' +\n 'recognises a part by its element type, so it must be a child of the root (a fragment ' +\n 'is fine), not wrapped in another component.'\n );\n }\n const { selectedTrackId } = useSelectedTrackId();\n // The track a take is recorded onto (#812): its slot alone renders when a take starts or ends.\n const { armedTrackId } = useRecordingArm();\n const { trackReorderEpoch } = useTrackReorderPreview();\n const spectrogram = use(SpectrogramIntegrationContext);\n const { trackStates } = usePlaylistMixer();\n\n // `null` and `undefined` both mean \"not given\".\n const template = useStableTemplate(children ?? DEFAULT_TEMPLATE);\n\n // The spectrogram integration's value changes with every per-track\n // override; the slots and the pieces get functions that read the latest\n // one, in a value that changes only when a menu comes or goes.\n const spectrogramRef = useRef(spectrogram);\n spectrogramRef.current = spectrogram;\n const menuAvailable = Boolean(spectrogram?.renderMenuItems);\n const shared = useMemo<TrackControlsShared>(\n () => ({\n menuAvailable,\n menuItems: (args) => spectrogramRef.current?.renderMenuItems?.(args) ?? [],\n setTrackRenderMode: (trackId, mode) =>\n spectrogramRef.current?.setTrackRenderMode(trackId, mode),\n openSpectrogramSettings: (trackId) => {\n if (spectrogramRef.current) setSettingsModalTrackId(trackId);\n },\n }),\n [menuAvailable, setSettingsModalTrackId]\n );\n\n return (\n <TrackControlsSharedContext value={shared}>\n <TracksLayout $height={trackLayout.totalHeight}>\n {tracks.map((track, trackIndex) => {\n // One entry per track, also while its audio loads (#812): a\n // change made then is kept.\n const state = trackStates[trackIndex];\n return (\n // key includes trackReorderEpoch: forces a remount after every\n // track-reorder drag, discarding @dnd-kit sortable-plugin DOM\n // corruption (see bumpTrackReorderEpoch's doc comment in\n // WaveformPlaylistContext). Stays at `-0` — a no-op suffix — for\n // consumers that never render a reorder handle.\n <TrackControlsSlot\n key={`${track.id}-${trackReorderEpoch}`}\n trackId={track.id}\n index={trackIndex}\n kind={track.kind}\n name={state.name}\n muted={state.muted}\n soloed={state.soloed}\n volume={state.volume}\n pan={state.pan}\n isSelected={track.id === selectedTrackId}\n isFirst={trackIndex === 0}\n isLast={trackIndex === tracks.length - 1}\n renderMode={renderModeById.get(track.id) ?? 'waveform'}\n hasSpectrogram={spectrogram !== null && track.kind !== 'midi'}\n isRecordingArmed={track.id === armedTrackId}\n height={trackHeightById.get(track.id) ?? 0}\n top={trackLayout.topById.get(track.id) ?? 0}\n animate={animateTrackLayout}\n template={template}\n />\n );\n })}\n </TracksLayout>\n </TrackControlsSharedContext>\n );\n}\n\nexport const WaveformTrackControls = React.memo(WaveformTrackControlsImpl);\n","import React, { type ReactNode } from 'react';\nimport styled from 'styled-components';\nimport { ButtonGroup, Controls, Header } from '@waveform-playlist/ui-components';\nimport {\n TrackMenuButton,\n TrackMuteButton,\n TrackName,\n TrackPanSlider,\n TrackSoloButton,\n TrackVolumeSlider,\n} from './TrackControlPieces';\n\n/**\n * The frame of the default panel. It makes room on both sides when a\n * `<TrackReorderGrip />` is rendered beside it (the grip sits at the right\n * edge of the slot, over the panel).\n */\nconst Frame = styled(Controls)`\n *:has(> [data-track-reorder-grip]) > & {\n padding-left: 18px;\n padding-right: 18px;\n }\n`;\n\nconst HEADER_STYLE = { justifyContent: 'center', position: 'relative' } as const;\nconst MENU_ANCHOR_STYLE = { position: 'absolute', right: 0, top: 0 } as const;\n\n/**\n * The default control panel of a track: its name, the track menu (under a\n * `<SpectrogramProvider>`, for an audio track), mute, solo, volume and pan.\n * It is what `<WaveformTrackControls />` renders when it has no children\n * (#687). It has no remove button and no reorder grip: render\n * `<TrackRemoveButton />` or `<TrackReorderGrip />` beside it for those (both\n * place themselves at an edge of the slot), or compose a panel from the\n * pieces.\n *\n * Its children are drawn inside the panel, below the pan slider: the place\n * for one more control of your own. An element rendered BESIDE the panel is\n * outside it, and the panel fills the slot, so that element is only visible\n * when it positions itself, as the remove button and the grip do.\n *\n * It reads no context itself: the pieces read the track.\n */\nexport interface DefaultTrackControlsProps {\n /** Drawn inside the panel, below the pan slider. */\n children?: ReactNode;\n}\n\nfunction DefaultTrackControlsImpl({ children }: DefaultTrackControlsProps) {\n return (\n <Frame>\n <Header style={HEADER_STYLE}>\n <TrackName />\n <span style={MENU_ANCHOR_STYLE}>\n <TrackMenuButton />\n </span>\n </Header>\n <ButtonGroup>\n <TrackMuteButton />\n <TrackSoloButton />\n </ButtonGroup>\n <TrackVolumeSlider />\n <TrackPanSlider />\n {children}\n </Frame>\n );\n}\n\nexport const DefaultTrackControls = React.memo(DefaultTrackControlsImpl);\n","/**\n * The pieces of a track's control panel (#687). Each is bound to the track\n * whose panel it is rendered in (`useTrack()`), takes no prop for the track,\n * and is drawn by being rendered among the children of\n * `<WaveformTrackControls>`.\n */\nimport React, { use } from 'react';\nimport {\n Button,\n CloseButton,\n ReorderRail,\n Slider,\n SliderWrapper,\n TrackMenu,\n VolumeDownIcon,\n VolumeUpIcon,\n} from '@waveform-playlist/ui-components';\nimport { TrackControlsSharedContext, useTrack } from './trackContext';\nimport { useTrackReorderHandle } from '../hooks/useTrackReorderHandle';\n\nconst NAME_STYLE = {\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n // Room for a remove button on the left and the track menu on the right.\n padding: '0 24px',\n display: 'block',\n} as const;\n\n/** The track's name, on one line, cut off with an ellipsis. */\nexport const TrackName: React.FC = () => {\n const { name } = useTrack();\n return (\n <span data-track-name=\"\" style={NAME_STYLE}>\n {name}\n </span>\n );\n};\n\n/**\n * Mutes and unmutes the track. Disabled while a take is recorded onto the\n * track (`useTrack().isRecordingArmed`): the track is muted for the take and\n * its mute from before is written back when the take ends (#812).\n */\nexport const TrackMuteButton: React.FC = () => {\n const { muted, setMuted, isRecordingArmed } = useTrack();\n return (\n <Button\n $variant={muted ? 'danger' : 'outline'}\n aria-pressed={muted}\n disabled={isRecordingArmed}\n onClick={() => setMuted(!muted)}\n >\n Mute\n </Button>\n );\n};\n\n/** Solos and unsolos the track. */\nexport const TrackSoloButton: React.FC = () => {\n const { soloed, setSoloed } = useTrack();\n return (\n <Button\n $variant={soloed ? 'info' : 'outline'}\n aria-pressed={soloed}\n onClick={() => setSoloed(!soloed)}\n >\n Solo\n </Button>\n );\n};\n\n/** The track's volume, 0 to 1. */\nexport const TrackVolumeSlider: React.FC = () => {\n const { volume, setVolume } = useTrack();\n return (\n <SliderWrapper>\n <VolumeDownIcon />\n <Slider\n min=\"0\"\n max=\"1\"\n step=\"0.01\"\n value={volume}\n aria-label=\"Volume\"\n onChange={(e) => setVolume(parseFloat(e.target.value))}\n />\n <VolumeUpIcon />\n </SliderWrapper>\n );\n};\n\n/** The track's pan, -1 (left) to 1 (right). */\nexport const TrackPanSlider: React.FC = () => {\n const { pan, setPan } = useTrack();\n return (\n <SliderWrapper>\n <span>L</span>\n <Slider\n min=\"-1\"\n max=\"1\"\n step=\"0.01\"\n value={pan}\n aria-label=\"Pan\"\n onChange={(e) => setPan(parseFloat(e.target.value))}\n />\n <span>R</span>\n </SliderWrapper>\n );\n};\n\n/**\n * The track's menu: how the track is drawn (waveform, spectrogram, both) and\n * its spectrogram settings. Draws nothing without a `<SpectrogramProvider>`\n * and nothing for a MIDI track, which is always a piano roll.\n */\nexport const TrackMenuButton: React.FC = () => {\n const { renderMode, hasSpectrogram, setRenderMode, openSpectrogramSettings } = useTrack();\n const shared = use(TrackControlsSharedContext);\n if (!shared || !shared.menuAvailable || !hasSpectrogram) return null;\n return (\n <TrackMenu\n items={(onClose) =>\n shared.menuItems({\n renderMode,\n onRenderModeChange: setRenderMode,\n onOpenSettings: openSpectrogramSettings,\n onClose,\n })\n }\n />\n );\n};\n\nexport interface TrackRemoveButtonProps {\n /** Called with the track's id. Removing the track from your `tracks` is yours to do. */\n onRemove: (trackId: string) => void;\n}\n\n// The primitive is absolutely positioned at its container's top left corner.\n// One pixel in, where it sat inside the bordered default panel.\nconst REMOVE_ANCHOR_STYLE = { position: 'absolute', left: 1, top: 1 } as const;\n\n/**\n * A close button at the top left corner of the track's slot. A click calls\n * `onRemove` with the track's id and does not select the track.\n */\nexport const TrackRemoveButton: React.FC<TrackRemoveButtonProps> = ({ onRemove }) => {\n const { id } = useTrack();\n return (\n <span style={REMOVE_ANCHOR_STYLE}>\n <CloseButton\n onClick={(e) => {\n e.stopPropagation();\n onRemove(id);\n }}\n />\n </span>\n );\n};\n\nconst GRIP_ANCHOR_STYLE = {\n position: 'absolute',\n right: 3,\n top: '50%',\n transform: 'translateY(-50%)',\n} as const;\n\n/**\n * A drag grip with a move-up and a move-down button, at the right edge of the\n * track's slot. The buttons work with no other setup; dragging needs a\n * `ClipInteractionProvider` above the view. The default panel makes room for\n * it. Neither the grip nor the buttons select the track.\n */\nexport const TrackReorderGrip: React.FC = () => {\n const { isFirst, isLast, moveUp, moveDown } = useTrack();\n const { handleRef } = useTrackReorderHandle();\n return (\n <span data-track-reorder-grip=\"\" style={GRIP_ANCHOR_STYLE}>\n <ReorderRail\n gripRef={handleRef as React.Ref<HTMLButtonElement>}\n onGripClick={(e) => e.stopPropagation()}\n upDisabled={isFirst}\n downDisabled={isLast}\n onMoveUp={(e) => {\n e.stopPropagation();\n moveUp();\n }}\n onMoveDown={(e) => {\n e.stopPropagation();\n moveDown();\n }}\n />\n </span>\n );\n};\n","/**\n * The per-track context of the track controls (#687).\n *\n * `<WaveformTrackControls>` renders its children once per track; around each\n * copy it provides that track's value, which `useTrack()` reads. A value\n * changes only when something about ITS track changes, so a volume step on one\n * track renders the pieces of that track and of no other.\n *\n * This file imports no provider and no engine.\n */\nimport { createContext, use, type RefObject } from 'react';\nimport type { RenderMode, TrackKind } from '@waveform-playlist/core';\nimport type { TrackMenuItem } from '@waveform-playlist/ui-components';\n\n/** What `useTrack()` returns: one track's identity, mixer state and bound actions. */\nexport interface TrackContextValue {\n /** The track's id. */\n id: string;\n /** `'audio'` or `'midi'`. */\n kind: TrackKind;\n /** The track's position in the list of tracks, from 0. Changes on a reorder. */\n index: number;\n\n /** The track's name, or \"Track N\" (N is the position, from 1) when it has none and while it is loading. */\n name: string;\n muted: boolean;\n soloed: boolean;\n /** 0 to 1. */\n volume: number;\n /** -1 (left) to 1 (right). */\n pan: number;\n /** How the track is drawn. Always `'waveform'` for a MIDI track. */\n renderMode: RenderMode;\n\n /** Whether this is the selected track. */\n isSelected: boolean;\n isFirst: boolean;\n isLast: boolean;\n /**\n * True for an audio track under a `<SpectrogramProvider>`: `setRenderMode`\n * and `openSpectrogramSettings` then do something.\n */\n hasSpectrogram: boolean;\n /**\n * True while a take is being recorded onto this track (`setRecordingActive`,\n * `useRecordingSession`). The track is muted for the take and its mute from\n * before is written back when the take ends, so a change made meanwhile does\n * not stay: the built-in `<TrackMuteButton />` is disabled while this is\n * true, and an app's own mute control can do the same.\n */\n isRecordingArmed: boolean;\n\n // Actions. Each keeps its identity while the track's slot is mounted and a\n // track menu neither becomes available nor stops being so.\n setMuted: (muted: boolean) => void;\n setSoloed: (soloed: boolean) => void;\n setVolume: (volume: number) => void;\n setPan: (pan: number) => void;\n /** Makes this the selected track. */\n select: () => void;\n /** Moves the track one position up. Nothing happens for the first track. */\n moveUp: () => void;\n /** Moves the track one position down. Nothing happens for the last track. */\n moveDown: () => void;\n /** Nothing happens without a `<SpectrogramProvider>`. */\n setRenderMode: (mode: RenderMode) => void;\n /** Opens the spectrogram settings of this track. Nothing happens without a `<SpectrogramProvider>`. */\n openSpectrogramSettings: () => void;\n}\n\nexport const TrackContext = createContext<TrackContextValue | null>(null);\n\n/**\n * The track whose control panel the calling component is part of. For the\n * children of `<WaveformTrackControls>`, which renders them once per track.\n */\nexport function useTrack(): TrackContextValue {\n const value = use(TrackContext);\n if (value === null) {\n throw new Error(\n 'useTrack must be used within <WaveformTrackControls>: it reads the track whose control ' +\n 'panel is being drawn, so the component that calls it (a built-in piece such as ' +\n '<TrackMuteButton />, or your own) must be among the children of ' +\n '<WaveformTrackControls>. Elsewhere, use usePlaylistMixer() and the setters of ' +\n 'useEditorControls(), which take a track id.'\n );\n }\n return value;\n}\n\n/** What the items of a track menu are built from (the spectrogram integration's). */\nexport interface TrackMenuItemsArgs {\n renderMode: RenderMode;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n}\n\n/**\n * Internal: what the controls part hands every slot and piece. The functions\n * read the spectrogram integration through a ref, so the value changes only\n * when a menu becomes available or stops being so.\n */\nexport interface TrackControlsShared {\n /** Whether the spectrogram integration offers menu items. */\n menuAvailable: boolean;\n menuItems: (args: TrackMenuItemsArgs) => TrackMenuItem[];\n setTrackRenderMode: (trackId: string, mode: RenderMode) => void;\n openSpectrogramSettings: (trackId: string) => void;\n}\n\nexport const TrackControlsSharedContext = createContext<TrackControlsShared | null>(null);\n\n/**\n * Internal: the wiring between a slot and the reorder handle inside it. The\n * slot's element is the item that is dragged; the handle says when it is.\n * Stable for the life of the slot.\n */\nexport interface TrackSlotWiring {\n elementRef: RefObject<HTMLDivElement | null>;\n setDragSource: (isDragSource: boolean) => void;\n /** How many reorder handles are mounted in the slot (one is right). */\n handleCount: { current: number };\n}\n\nexport const TrackSlotWiringContext = createContext<TrackSlotWiring | null>(null);\n","import { use, useEffect } from 'react';\nimport { useSortable } from '@dnd-kit/react/sortable';\nimport { RestrictToVerticalAxis } from '@dnd-kit/abstract/modifiers';\nimport { Feedback } from '@dnd-kit/dom';\nimport type { Plugins } from '@dnd-kit/abstract';\nimport { createDragPopoverHealer } from '../utils/dragPopoverHealer';\nimport { warnOnce } from '../components/partWarnings';\nimport { TrackSlotWiringContext, useTrack } from '../components/trackContext';\n\nexport interface TrackReorderHandle {\n /** Attach to the element the track is dragged by (a grip). */\n handleRef: (element: Element | null) => void;\n /** True while this track is the one being dragged. */\n isDragSource: boolean;\n}\n\nconst MOVE_FEEDBACK = Feedback.configure({ feedback: 'move' });\nconst withMoveFeedback = (defaults: Plugins): Plugins => [...defaults, MOVE_FEEDBACK];\n\n/**\n * Makes the track whose control panel the caller is part of a vertical\n * sortable item in the ambient `DragDropProvider` (`ClipInteractionProvider`),\n * dragged by the element `handleRef` is attached to (#687; it replaces\n * `SortableTrackControls`). `<TrackReorderGrip />` is this hook with the\n * built-in grip; call it yourself for a grip of your own. Once per panel: two\n * calls for one track register the same sortable id twice.\n *\n * The item that moves is the slot `<WaveformTrackControls>` draws around the\n * panel, not an element of the caller. The per-source modifiers REPLACE the\n * provider's clip modifiers for this operation, so track drags are\n * vertical-only and skip clip collision and snap. Data kind 'track-reorder'\n * is the discriminator the shared drag handlers branch on.\n */\nexport function useTrackReorderHandle(): TrackReorderHandle {\n const { id, index } = useTrack();\n const wiring = use(TrackSlotWiringContext);\n const { ref, handleRef, isDragSource } = useSortable({\n id: `track-reorder-${id}`,\n index,\n group: 'playlist-tracks',\n type: 'track',\n accept: ['track'],\n data: { kind: 'track-reorder', trackId: id },\n modifiers: [RestrictToVerticalAxis],\n // Per-entity Feedback config (@dnd-kit 0.5+ moved `feedback` out of the\n // hook options into `plugins`). The FUNCTION form extends the sortable's\n // default plugins — a bare array would silently drop\n // OptimisticSortingPlugin, which drives the live `sortable.index` that\n // drag-commit reads (covered by trackReorderHandleFeedbackPlugins.test).\n //\n // feedback: 'move' (NOT 'none' — see below) disables the Feedback\n // plugin's placeholder/clone splicing for this sortable while KEEPING its\n // dragOperation.shape computation alive. That plugin does raw,\n // React-bypassing DOM surgery on ANY pointer movement during an activated\n // drag (insertAdjacentElement to splice in a placeholder, then\n // `placeholder.replaceWith(element)` on drop) — confirmed via\n // MutationObserver instrumentation to relocate the React-owned row 6\n // times during a single one-slot drag, leaving its final parent/sibling\n // different from what React's fiber tree still believes. That desync is\n // permanent for the session: every later React-driven reorder (button OR\n // drag) computes the correct data but silently fails to update the DOM\n // for these rows. The placeholder splice is created only when\n // `feedback !== 'move'` (@dnd-kit/dom Feedback.ts) — 'move' keeps the\n // dragged element in the live DOM (no clone/placeholder) while still\n // running the *unconditional* `dragOperation.shape = ...` assignment.\n // `feedback: 'none'` looked like the boundary-trim precedent (Clip.tsx /\n // AnnotationBox.tsx) but is wrong here: 'none' bails out of Feedback's\n // render function BEFORE dragOperation.shape is ever set, and shape is\n // the ONLY input CollisionObserver.computeCollisions() checks — with\n // 'none', collision (and therefore sortable.index) never updates, so\n // drag-based reordering silently never commits. Boundary trims don't hit\n // this because they're plain useDraggable (no collision-based commit) —\n // sortables need shape. `isDragSource` is a reactive signal, unaffected\n // either way. See browser/CLAUDE.md \"Track Reordering\".\n plugins: withMoveFeedback,\n });\n\n // The sortable item is the slot's element, which the part owns: it is\n // handed to dnd-kit here, after the commit that mounted it. Not in a layout\n // effect: a child's layout effects run before React attaches its parent's\n // ref, so the slot's element would still be null on the first mount (tried:\n // no drag started at all).\n useEffect(() => {\n if (!wiring) return undefined;\n ref(wiring.elementRef.current);\n return () => ref(null);\n }, [ref, wiring]);\n\n // One handle per panel: a second one registers the same sortable id again.\n useEffect(() => {\n if (!wiring) return undefined;\n const { handleCount } = wiring;\n handleCount.current += 1;\n if (handleCount.current > 1) {\n warnOnce(\n 'A track control panel has more than one reorder handle (<TrackReorderGrip /> or ' +\n 'useTrackReorderHandle()): each registers the track as the same sortable item. ' +\n 'Render one per panel.'\n );\n }\n return () => {\n handleCount.current -= 1;\n };\n }, [wiring]);\n\n // The slot draws itself lifted (opaque, with a shadow) while it is dragged.\n useEffect(() => {\n if (!wiring) return undefined;\n wiring.setDragSource(isDragSource);\n return () => wiring.setDragSource(false);\n }, [isDragSource, wiring]);\n\n // `feedback: 'move'` opts out of dnd-kit's placeholder — and with it the\n // plugin's own popover-recovery MutationObserver, which is only created\n // when a placeholder exists. OptimisticSortingPlugin's mid-drag\n // insertAdjacentElement splices force-dismiss the top-layer popover\n // (eventlessly, per spec), leaving the dragged row UA-hidden\n // (`[popover]:not(:popover-open) { display: none }`) for the rest of the\n // drag. Run our own healer while this row is the drag source.\n useEffect(() => {\n const element = wiring?.elementRef.current;\n if (!isDragSource || !element) return undefined;\n return createDragPopoverHealer(element);\n }, [isDragSource, wiring]);\n\n return { handleRef, isDragSource };\n}\n","/**\n * Keeps a dnd-kit drag-feedback element visible for the duration of a drag.\n *\n * @dnd-kit/dom's Feedback plugin promotes the dragged element into the\n * browser top layer via the Popover API (`popover=\"manual\"` + showPopover()).\n * During a sortable drag, OptimisticSortingPlugin reorders rows with\n * `insertAdjacentElement` — a remove + reinsert that force-dismisses the\n * popover with NO toggle events (per spec, removal-dismissal fires none).\n * A dismissed `[popover]` element falls under the UA rule\n * `[popover]:not(:popover-open) { display: none }`, so the dragged row\n * vanishes the moment it crosses a collision boundary. dnd-kit's own\n * recovery MutationObserver is only created when a placeholder exists\n * (`feedback !== 'move'`), so `feedback: 'move'` sortables never recover.\n *\n * This observer mirrors that upstream recovery for the 'move' case: on any\n * childList mutation, if the element is connected but its popover was\n * dismissed, re-show it. MutationObserver callbacks run as microtasks, so\n * the heal lands in the same frame as the splice — no visible flicker.\n */\nexport function createDragPopoverHealer(element: HTMLElement): () => void {\n if (typeof element.showPopover !== 'function') {\n // Browser without the Popover API: dnd-kit falls back to plain\n // fixed-position feedback, which DOM splices cannot dismiss.\n return () => {};\n }\n const heal = () => {\n if (!element.isConnected || !element.hasAttribute('popover')) return;\n let open = false;\n try {\n open = element.matches(':popover-open');\n } catch {\n // Selector unsupported (older engines): treat as closed and let\n // showPopover's own InvalidStateError guard below settle it.\n }\n if (open) return;\n try {\n element.showPopover();\n } catch {\n // InvalidStateError (already open / mid-toggle) — nothing to heal.\n }\n };\n const observer = new MutationObserver(heal);\n observer.observe(element.ownerDocument.body, {\n childList: true,\n subtree: true,\n });\n return () => observer.disconnect();\n}\n","/**\n * Keeps a template of React elements while a new one says the same thing\n * (#687).\n *\n * `<WaveformTrackControls>` renders its children once per track. Children\n * written inline are new element objects on every render of the component\n * that composes the view, which usually holds the tracks and renders on every\n * move of a trim: handed on as they are, they rendered every piece of every\n * track each time (measured with a prototype on the multi-clip example: 237 components per\n * trim move against 83). Two elements describe the same thing when their\n * type, key and props are equal, so the previous template can stand in for an\n * equal new one, and React then skips everything below it.\n */\nimport { isValidElement, useRef, type ReactNode } from 'react';\n\nfunction sameStyle(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n const one = a as Record<string, unknown>;\n const other = b as Record<string, unknown>;\n const keys = Object.keys(one);\n return (\n keys.length === Object.keys(other).length && keys.every((k) => Object.is(one[k], other[k]))\n );\n}\n\n/**\n * Whether two templates describe the same elements: the same types and keys,\n * and props that are identical (`Object.is`), except `children` (compared the\n * same way, recursively) and `style` (compared one level deep, because a\n * style object is usually written inline). A function or an object written\n * inline as any other prop makes the templates differ.\n */\nexport function sameTemplate(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => sameTemplate(item, b[index]));\n }\n if (isValidElement(a) && isValidElement(b)) {\n if (a.type !== b.type || a.key !== b.key) return false;\n const one = a.props as Record<string, unknown>;\n const other = b.props as Record<string, unknown>;\n const keys = Object.keys(one);\n if (keys.length !== Object.keys(other).length) return false;\n return keys.every((key) => {\n if (!(key in other)) return false;\n if (key === 'children') return sameTemplate(one[key], other[key]);\n if (key === 'style') return sameStyle(one[key], other[key]);\n return Object.is(one[key], other[key]);\n });\n }\n return false;\n}\n\n/**\n * The template to render: the previous one while `template` is equal to it by\n * `sameTemplate`, else `template`.\n *\n * The ref is written during render. That is safe here: whatever it holds is a\n * template some render was given, and it is only ever used in place of one\n * that is equal to it.\n */\nexport function useStableTemplate(template: ReactNode): ReactNode {\n const kept = useRef(template);\n if (!sameTemplate(kept.current, template)) {\n kept.current = template;\n }\n return kept.current;\n}\n","/**\n * The parts of the visualization that follow selection, cursor, loop and\n * annotation state. They are small siblings of the track rows (#693): these\n * re-render on every pointer move of a selection drag and on every\n * active-annotation change during playback, and the rows do not.\n *\n * `WaveformSelection` and `WaveformPlayhead` read shared hooks only and are\n * rendered under both providers (#688). The loop region is multitrack only.\n * (The annotation boxes are `WaveformAnnotationBoxes.tsx`, for both providers.)\n */\nimport React, { use, useSyncExternalStore } from 'react';\nimport {\n Selection,\n TimescaleLoopRegion,\n useTheme,\n type RenderPlayheadFunction,\n type WaveformPlaylistTheme,\n} from '@waveform-playlist/ui-components';\nimport {\n useCurrentTime,\n useSelection,\n usePlaylistView,\n usePlaylistZoom,\n usePlaybackRefs,\n useLoop,\n useIsPlaying,\n useEditorControls,\n} from '../contexts/playlistContexts';\nimport { AnimatedPlayhead } from './AnimatedPlayhead';\nimport { useWaveformExtent, WaveformPartPlaceContext } from './waveformLayoutContext';\nimport { warnMisplacedPart } from './partWarnings';\nimport { SelectionPreviewContext, type SelectionRange } from '../hooks/useSelectionDrag';\n\nconst subscribeToNothing = () => () => {};\nconst noPreview = (): SelectionRange | null => null;\n\n/**\n * The highlighted selection range. Renders nothing for a collapsed selection.\n * While a drag is drawing a range during playback it shows that range.\n * Memoized (it takes no props): a render of the view around it (play, pause,\n * a press) is not its concern, only the selection, the zoom, the view settings\n * and the theme are.\n */\nexport const WaveformSelection: React.FC = React.memo(function WaveformSelection() {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { selectionStart, selectionEnd } = useSelection();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n // The range a drag is drawing during playback (see useSelectionDrag). It is\n // not the selection yet, and it is shown in its place until the release.\n // Called as methods (not detached), so a source written as a class works.\n const previewSource = use(SelectionPreviewContext);\n const preview = useSyncExternalStore(\n previewSource ? (onChange) => previewSource.subscribe(onChange) : subscribeToNothing,\n previewSource ? () => previewSource.getSnapshot() : noPreview,\n previewSource ? () => previewSource.getSnapshot() : noPreview\n );\n\n const start = preview ? preview.start : Math.min(selectionStart, selectionEnd);\n const end = preview ? preview.end : Math.max(selectionStart, selectionEnd);\n if (start === end) return null;\n\n return (\n <Selection\n startPosition={(start * sampleRate) / samplesPerPixel}\n endPosition={(end * sampleRate) / samplesPerPixel}\n color={theme.selectionColor}\n />\n );\n});\n\n/**\n * Wrapper that isolates the custom playhead's hooks from its parent.\n * Calling renderPlayhead() directly would merge its hooks into the parent,\n * causing \"Rendered more hooks\" errors if renderPlayhead is conditionally provided.\n * It reads shared hooks only, so it serves both providers.\n */\nconst CustomPlayhead: React.FC<{\n renderPlayhead: RenderPlayheadFunction;\n color: string;\n samplesPerPixel: number;\n sampleRate: number;\n}> = ({ renderPlayhead, color, samplesPerPixel, sampleRate }) => {\n const { currentTimeRef, visualTimeRef } = usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only, so a seek while stopped moves a custom\n // playhead: the position below comes from the refs.\n useCurrentTime();\n\n // Use visualTimeRef so the initial position matches the audible output\n // (the default playhead and the progress fill are drawn from it too).\n const visualTime = visualTimeRef.current ?? currentTimeRef.current ?? 0;\n\n return renderPlayhead({\n position: (visualTime * sampleRate) / samplesPerPixel,\n color,\n isPlaying,\n currentTimeRef,\n visualTimeRef,\n samplesPerPixel,\n sampleRate,\n }) as React.ReactElement;\n};\n\nexport interface WaveformPlayheadProps {\n /** Custom playhead render function. Receives position (pixels) and color from theme. */\n renderPlayhead?: RenderPlayheadFunction;\n}\n\n/**\n * The playhead: shown while playing, and at rest when no range is selected.\n * The same under either provider.\n */\nexport const WaveformPlayhead: React.FC<WaveformPlayheadProps> = ({ renderPlayhead }) => {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { isPlaying } = useIsPlaying();\n const { selectionStart, selectionEnd } = useSelection();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n\n if (!isPlaying && selectionStart !== selectionEnd) return null;\n\n return renderPlayhead ? (\n <CustomPlayhead\n renderPlayhead={renderPlayhead}\n color={theme.playheadColor}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n />\n ) : (\n <AnimatedPlayhead color={theme.playheadColor} />\n );\n};\n\n/**\n * The draggable loop region in the timescale, bounded by the root's timeline.\n * Renders nothing while looping is off. Memoized: it takes no props.\n */\nexport const WaveformLoopRegion = React.memo(function WaveformLoopRegion() {\n const { tracksFullWidth: maxPosition } = useWaveformExtent('The loop region');\n if (use(WaveformPartPlaceContext) !== 'timescale') {\n warnMisplacedPart(\n '<WaveformLoopRegion> is drawn among the tracks, not in the timescale strip: the root ' +\n 'recognises a part by its element type, so it must be a child of the root (a fragment ' +\n 'is fine), not wrapped in another component.'\n );\n }\n const theme = useTheme() as WaveformPlaylistTheme;\n const { isLoopEnabled, loopStart, loopEnd } = useLoop();\n const { setLoopRegion } = useEditorControls();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n\n if (!isLoopEnabled) return null;\n\n return (\n <TimescaleLoopRegion\n startPosition={(Math.min(loopStart, loopEnd) * sampleRate) / samplesPerPixel}\n endPosition={(Math.max(loopStart, loopEnd) * sampleRate) / samplesPerPixel}\n markerColor={theme.loopMarkerColor}\n regionColor={theme.loopRegionColor}\n minPosition={0}\n maxPosition={maxPosition}\n onLoopRegionChange={(startPixels, endPixels) => {\n const startSeconds = (startPixels * samplesPerPixel) / sampleRate;\n const endSeconds = (endPixels * samplesPerPixel) / sampleRate;\n setLoopRegion(startSeconds, endSeconds);\n }}\n />\n );\n});\n","import React, { useRef, useEffect, useId } from 'react';\nimport styled from 'styled-components';\nimport { usePlaylistInfo } from '@waveform-playlist/ui-components';\nimport {\n useCurrentTime,\n usePlaylistView,\n usePlaylistZoom,\n usePlaybackRefs,\n useIsPlaying,\n} from '../contexts/playlistContexts';\n\nconst PlayheadLine = styled.div.attrs<{ $color: string; $width: number }>((props) => ({\n style: {\n width: `${props.$width}px`,\n background: props.$color,\n },\n}))<{ $color: string; $width: number }>`\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n z-index: 100; /* Below sticky controls (z-index: 101) so playhead is hidden when scrolled behind controls */\n pointer-events: none;\n will-change: transform;\n`;\n\ninterface AnimatedPlayheadProps {\n color?: string;\n}\n\n/**\n * The default playhead, under either provider. During playback the provider's\n * animation loop moves it (a registered frame callback, no loop of its own);\n * at rest it is placed after each render.\n */\nexport const AnimatedPlayhead: React.FC<AnimatedPlayheadProps> = ({ color = '#ff0000' }) => {\n const playheadRef = useRef<HTMLDivElement>(null);\n // Per instance: two visualizations under one provider each have a playhead,\n // and the registry keeps one callback per id.\n const frameCallbackId = useId();\n\n const { currentTimeRef, visualTimeRef, registerFrameCallback, unregisterFrameCallback } =\n usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only: the resting-position effect below\n // reads the refs.\n useCurrentTime();\n const { sampleRate } = usePlaylistView();\n // The view option, published by the root (#689).\n const { progressBarWidth } = usePlaylistInfo();\n const { samplesPerPixel } = usePlaylistZoom();\n\n // Register per-frame callback during playback\n useEffect(() => {\n if (isPlaying) {\n registerFrameCallback(\n frameCallbackId,\n ({ visualTime, sampleRate: sr, samplesPerPixel: spp }) => {\n if (playheadRef.current) {\n const px = (visualTime * sr) / spp;\n playheadRef.current.style.transform = `translate3d(${px}px, 0, 0)`;\n }\n }\n );\n }\n return () => unregisterFrameCallback(frameCallbackId);\n }, [isPlaying, frameCallbackId, registerFrameCallback, unregisterFrameCallback]);\n\n // Update position when not playing (seeks, stops, etc.) — no rAF needed.\n // Reads visualTimeRef so the static playhead lines up with audible output\n // (the pause/seek paths sync visualTimeRef when they update currentTimeRef).\n useEffect(() => {\n if (!isPlaying && playheadRef.current) {\n const time = visualTimeRef.current ?? currentTimeRef.current ?? 0;\n const position = (time * sampleRate) / samplesPerPixel;\n playheadRef.current.style.transform = `translate3d(${position}px, 0, 0)`;\n }\n });\n\n return <PlayheadLine ref={playheadRef} $color={color} $width={progressBarWidth} data-playhead />;\n};\n","/**\n * The options that only affect how a view draws (#689): row height, bar\n * style, playhead width, and whether a multitrack timeline fills its\n * container. One home for them, read by the root of each view below.\n *\n * It is a context and not props of a root or a part because several\n * components draw with these values (the root lays the rows out, the channels\n * draw the bars, the playhead takes its width) and because one set of options\n * often serves several views: ten players on a page, each under its own\n * provider, are styled by one `<WaveformViewOptions>` above them all.\n */\nimport React, { createContext, use, useMemo, type ReactNode } from 'react';\nimport {\n DEFAULT_BAR_GAP,\n DEFAULT_BAR_WIDTH,\n DEFAULT_WAVE_HEIGHT,\n} from '@waveform-playlist/ui-components';\nimport { warnOnce } from './partWarnings';\n\nexport interface WaveformViewOptionsValue {\n /** Height in pixels of one channel of a track. Default: 80 */\n waveHeight?: number;\n /** Width in pixels of a waveform bar. Default: 1 */\n barWidth?: number;\n /** Space in pixels between two bars. Default: 0 */\n barGap?: number;\n /** Draw bars with rounded caps (radius `barWidth / 2`). Default: false */\n roundedBars?: boolean;\n /** Width in pixels of the playhead line. Default: `barWidth + barGap` */\n progressBarWidth?: number;\n /**\n * Draw the timeline at least as wide as its scroll container when the audio\n * is shorter. `WaveformRoot` only: a MediaElement timeline is as long as\n * its audio. Default: false\n */\n fillViewport?: boolean;\n}\n\nexport interface WaveformViewOptionsProps extends WaveformViewOptionsValue {\n children?: ReactNode;\n}\n\nconst NO_OPTIONS: WaveformViewOptionsValue = {};\n\n/** INTERNAL: what the nearest `<WaveformViewOptions>` says, inherited props included. */\nconst WaveformViewOptionsContext = createContext<WaveformViewOptionsValue>(NO_OPTIONS);\n\n/**\n * Sets view options for every waveform root below it, under either provider.\n * It may sit above the provider, and above several.\n *\n * A prop that is left out is taken from the `<WaveformViewOptions>` above\n * (`??`, so `0` and `false` are values), and from the defaults when there is\n * none: nest one to change a single option for part of the tree. A nested one\n * cannot return an option to its default: write the value.\n *\n * It goes ABOVE a root. A root reads the options above itself, so one written\n * among a root's children does nothing for that root (and warns).\n */\nexport const WaveformViewOptions: React.FC<WaveformViewOptionsProps> = ({\n children,\n waveHeight: ownWaveHeight,\n barWidth: ownBarWidth,\n barGap: ownBarGap,\n roundedBars: ownRoundedBars,\n progressBarWidth: ownProgressBarWidth,\n fillViewport: ownFillViewport,\n}) => {\n const above = use(WaveformViewOptionsContext);\n const waveHeight = ownWaveHeight ?? above.waveHeight;\n const barWidth = ownBarWidth ?? above.barWidth;\n const barGap = ownBarGap ?? above.barGap;\n const roundedBars = ownRoundedBars ?? above.roundedBars;\n const progressBarWidth = ownProgressBarWidth ?? above.progressBarWidth;\n const fillViewport = ownFillViewport ?? above.fillViewport;\n // Memoized on the six values: the component that renders this usually\n // holds the tracks and renders whenever they change.\n const value = useMemo<WaveformViewOptionsValue>(\n () => ({ waveHeight, barWidth, barGap, roundedBars, progressBarWidth, fillViewport }),\n [waveHeight, barWidth, barGap, roundedBars, progressBarWidth, fillViewport]\n );\n return <WaveformViewOptionsContext value={value}>{children}</WaveformViewOptionsContext>;\n};\n\n/** INTERNAL: every option with a value, as a root draws with them. */\nexport interface ResolvedViewOptions {\n waveHeight: number;\n barWidth: number;\n barGap: number;\n roundedBars: boolean;\n progressBarWidth: number;\n fillViewport: boolean;\n}\n\nconst isPositive = (value: number) => value > 0;\n\n/**\n * INTERNAL: the options a root draws with. Called by the two roots only; what\n * is drawn below a root reads the resolved values from ui-components'\n * `PlaylistInfoContext`, where the root publishes them once (memoized there).\n *\n * Values that cannot be drawn are replaced, with one development warning per\n * message: a row height or a bar width that is not above 0 becomes the\n * default, a gap that is no number becomes the default, a gap that would put\n * the next bar less than one pixel on is raised until the step is one pixel,\n * and a playhead width that is not above 0 becomes the bar and its gap.\n */\nexport function useResolvedViewOptions(): ResolvedViewOptions {\n const options = use(WaveformViewOptionsContext);\n let waveHeight = options.waveHeight ?? DEFAULT_WAVE_HEIGHT;\n let barWidth = options.barWidth ?? DEFAULT_BAR_WIDTH;\n let barGap = options.barGap ?? DEFAULT_BAR_GAP;\n const roundedBars = options.roundedBars ?? false;\n const fillViewport = options.fillViewport ?? false;\n\n if (!isPositive(waveHeight)) {\n warnOnce(\n `<WaveformViewOptions waveHeight> must be a positive number of pixels: ${String(waveHeight)} ` +\n `is replaced by ${DEFAULT_WAVE_HEIGHT}.`\n );\n waveHeight = DEFAULT_WAVE_HEIGHT;\n }\n if (!isPositive(barWidth)) {\n warnOnce(\n `<WaveformViewOptions barWidth> must be a positive number of pixels: ${String(barWidth)} ` +\n `is replaced by ${DEFAULT_BAR_WIDTH}.`\n );\n barWidth = DEFAULT_BAR_WIDTH;\n }\n if (Number.isNaN(barGap)) {\n warnOnce(\n `<WaveformViewOptions barGap> must be a number of pixels: ${String(barGap)} is replaced by ` +\n `${DEFAULT_BAR_GAP}.`\n );\n barGap = DEFAULT_BAR_GAP;\n }\n if (!(barWidth + barGap >= 1)) {\n const raised = 1 - barWidth;\n warnOnce(\n `<WaveformViewOptions barGap> of ${String(barGap)} with a bar ${barWidth} px wide puts the ` +\n `next bar less than one pixel on, which cannot be drawn: the gap is ${raised}.`\n );\n barGap = raised;\n }\n // As wide as a bar and its gap unless a width is given.\n let progressBarWidth = options.progressBarWidth ?? barWidth + barGap;\n if (!isPositive(progressBarWidth)) {\n warnOnce(\n `<WaveformViewOptions progressBarWidth> must be a positive number of pixels: ` +\n `${String(progressBarWidth)} is replaced by the bar and its gap, ${barWidth + barGap}. ` +\n 'Leave <WaveformPlayhead> out to draw no playhead.'\n );\n progressBarWidth = barWidth + barGap;\n }\n\n // A new object on every call: the roots read its fields, and the frame\n // memoizes what it publishes on those values, so nothing follows its identity.\n return { waveHeight, barWidth, barGap, roundedBars, progressBarWidth, fillViewport };\n}\n","import React, { use } from 'react';\nimport { DragDropProvider } from '@dnd-kit/react';\nimport { RestrictToHorizontalAxis } from '@dnd-kit/abstract/modifiers';\nimport { useTheme, type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport {\n useActiveAnnotation,\n useAnnotationOptions,\n useAnnotations,\n usePlaybackControls,\n usePlaylistView,\n usePlaylistZoom,\n} from '../contexts/playlistContexts';\nimport { AnnotationIntegrationContext } from '../AnnotationIntegrationContext';\nimport { useClipInteraction } from '../contexts/ClipInteractionContext';\nimport { useAnnotationDragHandlers } from '../hooks/useAnnotationDragHandlers';\nimport { useAnnotationsWithPreview } from '../hooks/useAnnotationsWithPreview';\nimport { useDragSensors } from '../hooks/useDragSensors';\nimport type { GetAnnotationBoxLabelFn } from '../types/annotations';\nimport { AnnotationBoxes } from './AnnotationBoxes';\nimport { useWaveformExtent } from './waveformLayoutContext';\n\n/** An edge moves along time only. */\nconst HORIZONTAL_ONLY = [RestrictToHorizontalAxis];\n\n/** Height in pixels of the row of annotation boxes when `height` is not given. */\nexport const DEFAULT_ANNOTATION_BOXES_HEIGHT = 30;\n\nexport interface WaveformAnnotationBoxesProps {\n /**\n * The label of a box, from the annotation and its index. Default: the\n * annotation's id. Pass a function that keeps its identity (defined outside\n * the component, or memoized): a new one renders every box.\n */\n getLabel?: GetAnnotationBoxLabelFn;\n /** Height of the row in pixels. Default: 30. */\n height?: number;\n}\n\n/**\n * The row of annotation boxes: a part of either root (`WaveformRoot`,\n * `MediaElementWaveformRoot`), as wide as the root's timeline. Needs the\n * annotation integration (`<AnnotationProvider>`); draws nothing without it\n * or without annotations.\n *\n * It wires the drag of a box's edges itself (#686): its own\n * `DragDropProvider` around the row, the moves shown through the provider's\n * preview, one `onAnnotationsChange` on release. The edges can be dragged\n * while the provider's `editable` option is on; `linkEndpoints` and\n * `continuousPlay` come from the same place (`useAnnotationOptions()`). The\n * touch setting of the drag is `ClipInteractionOptions`' `touchOptimized`.\n * The box colour is the theme's `annotationBoxBorder`.\n *\n * It is the one part of the view that reads the annotations and the active\n * annotation, so an annotation boundary during playback renders this and not\n * the waveform (#744). Memoized: a render of the component that composes the\n * view does not render it while its props keep their identity.\n */\nexport const WaveformAnnotationBoxes = React.memo(function WaveformAnnotationBoxes({\n getLabel,\n height = DEFAULT_ANNOTATION_BOXES_HEIGHT,\n}: WaveformAnnotationBoxesProps) {\n // An edge can be dragged as far as the timeline is drawn, not only as far as\n // there is audio: annotations may mark what is not recorded yet (chords, a\n // lyric sheet), on an empty timeline or past the end of a take (maintainer's\n // choice, #686). Under the MediaElement root the two lengths are the same.\n const { tracksFullWidth: width, displayDuration } = useWaveformExtent('The annotation boxes');\n const integration = use(AnnotationIntegrationContext);\n const { annotations } = useAnnotations();\n const { editable, linkEndpoints } = useAnnotationOptions();\n const { activeAnnotationId } = useActiveAnnotation();\n const { setAnnotations, annotationPreview, playAnnotation } = usePlaybackControls();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n const { touchOptimized } = useClipInteraction();\n const theme = useTheme() as Partial<WaveformPlaylistTheme>;\n // While an edge is dragged, the boxes follow the drag.\n const shownAnnotations = useAnnotationsWithPreview(annotations, annotationPreview);\n const sensors = useDragSensors({ touchOptimized });\n\n const { onDragStart, onDragMove, onDragEnd } = useAnnotationDragHandlers({\n annotations,\n onAnnotationsChange: setAnnotations,\n preview: annotationPreview,\n samplesPerPixel,\n sampleRate,\n duration: displayDuration,\n linkEndpoints,\n });\n\n // Nothing to draw: mount no drag provider either.\n if (annotations.length === 0 || !integration) return null;\n\n return (\n <DragDropProvider\n sensors={sensors}\n onDragStart={onDragStart}\n onDragMove={onDragMove}\n onDragEnd={onDragEnd}\n modifiers={HORIZONTAL_ONLY}\n >\n <AnnotationBoxes\n annotations={shownAnnotations}\n activeAnnotationId={activeAnnotationId}\n editable={editable}\n width={width}\n height={height}\n color={theme.annotationBoxBorder}\n sampleRate={sampleRate}\n samplesPerPixel={samplesPerPixel}\n getLabel={getLabel}\n onSelect={playAnnotation}\n />\n </DragDropProvider>\n );\n});\n","import { createContext, use } from 'react';\nimport { installCommand } from './utils/installCommand';\nimport type {\n AnnotationData,\n AnnotationAction,\n AnnotationActionOptions,\n RenderAnnotationItemProps,\n} from '@waveform-playlist/core';\n\n/**\n * Props the browser package passes to the AnnotationText component.\n * Mirrors what `AnnotationList` actually uses.\n */\nexport interface AnnotationTextIntegrationProps {\n annotations: AnnotationData[];\n activeAnnotationId?: string;\n shouldScrollToActive?: boolean;\n scrollActivePosition?: ScrollLogicalPosition;\n scrollActiveContainer?: 'nearest' | 'all';\n editable?: boolean;\n controls?: AnnotationAction[];\n annotationListConfig?: AnnotationActionOptions;\n height?: number;\n /** A click on a row (not in a field being edited, not on an action button). */\n onAnnotationClick?: (annotation: AnnotationData) => void;\n onAnnotationUpdate?: (updatedAnnotations: AnnotationData[]) => void;\n renderAnnotationItem?: (props: RenderAnnotationItemProps) => React.ReactNode;\n}\n\n/**\n * Props the browser package passes to the AnnotationBox component.\n * Mirrors what `WaveformAnnotationBoxes` actually uses.\n */\nexport interface AnnotationBoxIntegrationProps {\n annotationId: string;\n annotationIndex: number;\n startPosition: number;\n endPosition: number;\n label?: string;\n color?: string;\n isActive?: boolean;\n onClick?: () => void;\n editable?: boolean;\n}\n\n/**\n * Props the browser package passes to the AnnotationBoxesWrapper component.\n * Mirrors what `WaveformAnnotationBoxes` actually uses.\n */\nexport interface AnnotationBoxesWrapperIntegrationProps {\n children?: React.ReactNode;\n height?: number;\n width?: number;\n}\n\n/**\n * Interface for annotation integration provided by @waveform-playlist/annotations.\n *\n * The browser package defines what its views need, and the optional annotations\n * package provides it via <AnnotationProvider>.\n */\nexport interface AnnotationIntegration {\n // Parser functions\n parseAeneas: (data: unknown) => AnnotationData;\n serializeAeneas: (annotation: AnnotationData) => unknown;\n\n // The components browser's own views draw (typed with the props it passes).\n // The checkboxes and the download button are not here: the app renders\n // those itself, from @waveform-playlist/annotations.\n AnnotationText: React.ComponentType<AnnotationTextIntegrationProps>;\n AnnotationBox: React.ComponentType<AnnotationBoxIntegrationProps>;\n AnnotationBoxesWrapper: React.ComponentType<AnnotationBoxesWrapperIntegrationProps>;\n}\n\nexport const AnnotationIntegrationContext = createContext<AnnotationIntegration | null>(null);\n\nexport const AnnotationIntegrationProvider = AnnotationIntegrationContext.Provider;\n\n/**\n * Hook to access annotation integration provided by @waveform-playlist/annotations.\n * Throws if used without <AnnotationProvider> wrapping the component tree.\n *\n * Follows the Kent C. Dodds pattern:\n * https://kentcdodds.com/blog/how-to-use-react-context-effectively\n */\nexport function useAnnotationIntegration(): AnnotationIntegration {\n const context = use(AnnotationIntegrationContext);\n if (!context) {\n throw new Error(\n 'useAnnotationIntegration must be used within <AnnotationProvider>. ' +\n 'Install @waveform-playlist/annotations (' +\n installCommand('@waveform-playlist/annotations') +\n ') and wrap your app with <AnnotationProvider>. ' +\n 'See: https://naomiaro.github.io/waveform-playlist/docs/react/guides/annotations'\n );\n }\n return context;\n}\n","import React, { use } from 'react';\nimport {\n AnnotationIntegrationContext,\n type AnnotationBoxIntegrationProps,\n} from '../AnnotationIntegrationContext';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport type { GetAnnotationBoxLabelFn } from '../types/annotations';\n\ninterface AnnotationBoxItemProps {\n AnnotationBox: React.ComponentType<AnnotationBoxIntegrationProps>;\n annotation: AnnotationData;\n index: number;\n startPosition: number;\n endPosition: number;\n label: string;\n color: string | undefined;\n isActive: boolean;\n editable: boolean;\n onSelect: (annotation: AnnotationData) => void;\n}\n\n/**\n * One annotation box. Memoized: the active annotation changes at every\n * annotation boundary during playback, and only the box that stops being\n * active and the box that becomes active have a changed prop (#740).\n */\nconst AnnotationBoxItem = React.memo(function AnnotationBoxItem({\n AnnotationBox,\n annotation,\n index,\n startPosition,\n endPosition,\n label,\n color,\n isActive,\n editable,\n onSelect,\n}: AnnotationBoxItemProps) {\n return (\n <AnnotationBox\n annotationId={annotation.id}\n annotationIndex={index}\n startPosition={startPosition}\n endPosition={endPosition}\n label={label}\n color={color}\n isActive={isActive}\n onClick={() => onSelect(annotation)}\n editable={editable}\n />\n );\n});\n\nexport interface AnnotationBoxesProps {\n annotations: AnnotationData[];\n activeAnnotationId: string | null;\n /** Whether the box edges can be dragged. */\n editable: boolean;\n /** Width of the row in pixels (the full timeline width). */\n width: number;\n /** Height of the row in pixels. */\n height: number;\n /** Border colour of a box that is not active. Without it, the box's own default. */\n color: string | undefined;\n sampleRate: number;\n samplesPerPixel: number;\n /** Label for a box. Default: the annotation's id. */\n getLabel?: GetAnnotationBoxLabelFn;\n /**\n * Called with the annotation of a clicked box. It is a prop of every\n * memoized box, so it must keep its identity across renders in which only\n * the active annotation changed.\n */\n onSelect: (annotation: AnnotationData) => void;\n}\n\n/**\n * The row of annotation boxes under the waveform (#744). The caller\n * (`WaveformAnnotationBoxes`) reads the provider and passes the values in;\n * drag-and-drop (`DragDropProvider`) is the caller's too. Renders nothing without the\n * annotation integration or without annotations.\n */\nexport const AnnotationBoxes: React.FC<AnnotationBoxesProps> = ({\n annotations,\n activeAnnotationId,\n editable,\n width,\n height,\n color,\n sampleRate,\n samplesPerPixel,\n getLabel,\n onSelect,\n}) => {\n const annotationIntegration = use(AnnotationIntegrationContext);\n\n if (annotations.length === 0 || !annotationIntegration) return null;\n\n const { AnnotationBox, AnnotationBoxesWrapper } = annotationIntegration;\n\n return (\n <AnnotationBoxesWrapper height={height} width={width}>\n {annotations.map((annotation, index) => (\n <AnnotationBoxItem\n key={annotation.id}\n AnnotationBox={AnnotationBox}\n annotation={annotation}\n index={index}\n startPosition={(annotation.start * sampleRate) / samplesPerPixel}\n endPosition={(annotation.end * sampleRate) / samplesPerPixel}\n label={getLabel ? getLabel(annotation, index) : annotation.id}\n color={color}\n isActive={annotation.id === activeAnnotationId}\n editable={editable}\n onSelect={onSelect}\n />\n ))}\n </AnnotationBoxesWrapper>\n );\n};\n","import React, { use, useMemo } from 'react';\nimport type { AnnotationAction, RenderAnnotationItemProps } from '@waveform-playlist/core';\nimport { AnnotationIntegrationContext } from '../AnnotationIntegrationContext';\nimport {\n useActiveAnnotation,\n useAnnotationOptions,\n useAnnotations,\n usePlaybackControls,\n} from '../contexts/playlistContexts';\nimport { useAnnotationsWithPreview } from '../hooks/useAnnotationsWithPreview';\nimport { warnOnce } from './partWarnings';\nimport { installCommand } from '../utils/installCommand';\n\nexport interface AnnotationListProps {\n /** Height of the list in pixels. Without it the list is at most 200 px high. */\n height?: number;\n /**\n * Buttons shown on each row while the provider's `editable` option is on\n * (delete, split, …). An action is called with the annotation, its index,\n * the annotations and `{ linkEndpoints, continuousPlay }` as the provider\n * has them. Pass an array that keeps its identity: a new one renders every\n * row.\n */\n actions?: AnnotationAction[];\n /**\n * Where the active annotation is put when the list scrolls to it during\n * playback, or `'none'` for a list that does not follow. Default: `'center'`.\n */\n scrollActivePosition?: ScrollLogicalPosition | 'none';\n /** Which containers scroll: only the list (`'nearest'`), or the page too (`'all'`). Default: `'nearest'`. */\n scrollActiveContainer?: 'nearest' | 'all';\n /**\n * Draws a row, in place of the default one: called with\n * `{ annotation, index, isActive, onClick, formatTime }`. Define the\n * function outside the component (or memoize it): one written inline is a\n * new function on every render of your component and renders every row.\n */\n children?: (item: RenderAnnotationItemProps) => React.ReactNode;\n}\n\n/**\n * The annotation text list, for both providers (#686). Render it anywhere\n * under the provider: below the view, in a sidebar, more than once. It reads\n * everything from the provider (the annotations, the active one, the\n * `editable` / `linkEndpoints` / `continuousPlay` options) and reports edits\n * through the provider's `onAnnotationsChange`. A click on a row plays the\n * annotation, as a click on its box does.\n *\n * Needs the annotation integration (`<AnnotationProvider>` from\n * `@waveform-playlist/annotations`). Without it, and without annotations, it\n * draws nothing.\n *\n * It renders at every annotation boundary during playback, and the rows are\n * memoized, so everything it hands down except the active annotation keeps\n * its identity across such a render.\n */\nexport const AnnotationList: React.FC<AnnotationListProps> = ({\n height,\n actions,\n scrollActivePosition = 'center',\n scrollActiveContainer = 'nearest',\n children,\n}) => {\n const integration = use(AnnotationIntegrationContext);\n const { annotations } = useAnnotations();\n const { editable, linkEndpoints, continuousPlay } = useAnnotationOptions();\n const { activeAnnotationId } = useActiveAnnotation();\n const { setAnnotations, annotationPreview, playAnnotation } = usePlaybackControls();\n // While an edge is dragged, the times in the list follow it.\n const shownAnnotations = useAnnotationsWithPreview(annotations, annotationPreview);\n\n // The fourth argument of an action. Memoized: it is a dependency of a\n // handler given to every memoized row.\n const actionOptions = useMemo(\n () => ({ linkEndpoints, continuousPlay }),\n [linkEndpoints, continuousPlay]\n );\n\n if (annotations.length === 0) return null;\n\n if (!integration) {\n warnOnce(\n '<AnnotationList> draws nothing without the annotation components: ' +\n 'install @waveform-playlist/annotations (' +\n installCommand('@waveform-playlist/annotations') +\n ') and render <AnnotationProvider> above it. ' +\n 'See: https://naomiaro.github.io/waveform-playlist/docs/react/guides/annotations'\n );\n return null;\n }\n\n const { AnnotationText } = integration;\n const follows = scrollActivePosition !== 'none';\n\n return (\n <AnnotationText\n annotations={shownAnnotations}\n activeAnnotationId={activeAnnotationId ?? undefined}\n shouldScrollToActive={follows}\n scrollActivePosition={follows ? scrollActivePosition : undefined}\n scrollActiveContainer={scrollActiveContainer}\n editable={editable}\n controls={editable ? actions : undefined}\n annotationListConfig={actionOptions}\n height={height}\n onAnnotationClick={playAnnotation}\n onAnnotationUpdate={setAnnotations}\n renderAnnotationItem={children}\n />\n );\n};\n","import React from 'react';\nimport { WaveformRoot } from './WaveformRoot';\nimport {\n WaveformClipHeaders,\n WaveformFades,\n WaveformLoopRegion,\n WaveformPlayhead,\n WaveformSelection,\n WaveformTimescale,\n WaveformTrackControls,\n WaveformTracks,\n} from './waveformParts';\nimport { WaveformAnnotationBoxes } from './WaveformAnnotationBoxes';\nimport { AnnotationList } from './AnnotationList';\n\n/**\n * The props of the two ready-made multitrack views: `className`. What the\n * view is made of is not an option here, and neither are the options of its\n * parts (#686 moved the annotation ones onto `WaveformAnnotationBoxes` and\n * `AnnotationList`). For anything else, compose the parts inside\n * `WaveformRoot`.\n */\nexport interface WaveformProps {\n className?: string;\n}\n\nexport type WaveformEditorProps = WaveformProps;\n\n// The parts that take no option are the same elements on every render: a\n// render of the composition then hands the root children it has seen, and\n// React skips every one of them (the tracks part included, which is not\n// memoized because a consumer's children usually are new).\nconst TIMESCALE = <WaveformTimescale />;\nconst LOOP_REGION = <WaveformLoopRegion />;\nconst TRACK_CONTROLS = <WaveformTrackControls />;\nconst TRACKS = <WaveformTracks />;\nconst TRACKS_WITH_HEADERS_AND_FADES = (\n <WaveformTracks>\n <WaveformClipHeaders />\n <WaveformFades />\n </WaveformTracks>\n);\nconst SELECTION = <WaveformSelection />;\nconst PLAYHEAD = <WaveformPlayhead />;\nconst ANNOTATION_BOXES = <WaveformAnnotationBoxes />;\n// Draws nothing while there are no annotations.\nconst ANNOTATION_LIST = <AnnotationList />;\n\ninterface CompositionProps extends WaveformProps {\n tracks: React.ReactElement;\n}\n\n/** Not a component: called by the two below, so neither gains a layer. */\nfunction composeWaveform({ tracks, className }: CompositionProps) {\n return (\n <>\n <WaveformRoot className={className}>\n {TIMESCALE}\n {LOOP_REGION}\n {TRACK_CONTROLS}\n {tracks}\n {ANNOTATION_BOXES}\n {SELECTION}\n {PLAYHEAD}\n </WaveformRoot>\n {ANNOTATION_LIST}\n </>\n );\n}\n\n/**\n * The multitrack view, ready-made: the timescale, the loop region, the track\n * controls (200 px), the tracks, the annotation boxes, the selection and the\n * playhead, with the annotation text list below when there are annotations.\n *\n * It is a composition of the public parts with no options for them. To leave\n * a part out, give one an option (`renderTick`, a column width, a label for\n * the annotation boxes, a height or actions for the annotation list), compose the\n * panel of a track (a remove button, a reorder grip, your own control) or\n * add your own element, write the composition yourself:\n *\n * ```tsx\n * <WaveformRoot>\n * <WaveformTimescale />\n * <WaveformLoopRegion />\n * <WaveformTrackControls />\n * <WaveformTracks />\n * <WaveformAnnotationBoxes />\n * <WaveformSelection />\n * <WaveformPlayhead />\n * </WaveformRoot>\n * <AnnotationList />\n * ```\n */\nexport const Waveform: React.FC<WaveformProps> = (props) =>\n composeWaveform({ ...props, tracks: TRACKS });\n\n/**\n * `Waveform` with clip headers and fade curves: `<WaveformTracks>` holds\n * `<WaveformClipHeaders />` and `<WaveformFades />`. Inside a\n * `ClipInteractionProvider` the header is what a clip is dragged by, and the\n * trim handles come with it.\n */\nexport const WaveformEditor: React.FC<WaveformEditorProps> = (props) =>\n composeWaveform({ ...props, tracks: TRACKS_WITH_HEADERS_AND_FADES });\n","import React, { useCallback, useMemo, type ReactNode } from 'react';\nimport { DevicePixelRatioProvider, CLIP_HEADER_HEIGHT } from '@waveform-playlist/ui-components';\nimport type { RenderMode } from '@waveform-playlist/core';\nimport {\n MEDIA_ELEMENT_TRACK_ID,\n useMediaElementTrack,\n usePlaybackControls,\n} from '../contexts/playlistContexts';\nimport { computeTrackLayout } from '../utils/trackOrderPreview';\nimport type { TrackClipPeaks } from '../WaveformPlaylistContext';\nimport type { SpectrogramTrackHelpers } from './TrackRows';\nimport { getTrackChannelCount } from './visualizationLayout';\nimport type { WaveformRow, WaveformRowsValue } from './waveformLayoutContext';\nimport { useWaveformFrame, useWaveformParts } from './waveformFrame';\nimport { useResolvedViewOptions } from './WaveformViewOptions';\nimport { warnMisplacedPart } from './partWarnings';\n\n// A MediaElement player has one audio track and nothing a row can be asked to\n// do: module constants, so the rows value changes only with the peaks, the\n// wave height and the clip-headers marker.\nconst ONE_ROW: ReadonlyArray<WaveformRow> = [{ id: MEDIA_ELEMENT_TRACK_ID, kind: 'audio' }];\n// The peaks of a row with no clip: what is drawn when the provider has none.\nconst ONE_EMPTY_ROW: TrackClipPeaks[] = [[]];\nconst NO_RENDER_MODES: ReadonlyMap<string, RenderMode> = new Map();\nconst NO_SPECTROGRAM_HELPERS: ReadonlyMap<string, SpectrogramTrackHelpers> = new Map();\nconst nothing = () => {};\n\nexport interface MediaElementWaveformRootProps {\n className?: string;\n /** The parts, and anything else to draw over the track. */\n children?: ReactNode;\n}\n\n/**\n * The root of the MediaElement view (#685), exported from the package.\n *\n * The counterpart of `WaveformRoot` for `MediaElementPlaylistProvider`: it\n * works out what only this provider knows (the timeline is as long as the\n * audio; there is one row, empty when its peaks could not be extracted) and hands it to\n * the shared frame. The parts are the multitrack view's.\n *\n * It renders on what the frame follows (a drag in progress, play and stop, a\n * zoom, the view settings, the theme), when the track or its peaks change, when the\n * player becomes ready, and whenever the component that composes it renders.\n * The root's render never renders a part; a part renders when a value it\n * reads changes. See `WaveformRoot`.\n *\n * No controls column is drawn: there is no controls part for this provider.\n */\nexport const MediaElementWaveformRoot: React.FC<MediaElementWaveformRootProps> = ({\n className,\n children,\n}) => {\n const { setSelection } = usePlaybackControls();\n const { duration, peaksDataArray } = useMediaElementTrack();\n // `fillViewport` is not read here: this timeline is as long as its audio.\n const viewOptions = useResolvedViewOptions();\n const { waveHeight } = viewOptions;\n\n const parts = useWaveformParts(children);\n if (parts.controls) {\n warnMisplacedPart(\n '<WaveformTrackControls> draws nothing inside <MediaElementWaveformRoot>: a MediaElement ' +\n 'player has one track and no mixer. Remove it.'\n );\n }\n const { showClipHeaders } = parts.tracksOptions;\n\n const rows = useMemo<WaveformRowsValue>(() => {\n // No peaks: they could not be extracted (the provider logged it). The row\n // is drawn all the same, one channel tall and with no clip in it, so the\n // timeline keeps its height and can be clicked.\n const rowList = ONE_ROW;\n const rowPeaks = peaksDataArray.length > 0 ? peaksDataArray : ONE_EMPTY_ROW;\n const trackHeightById = new Map<string, number>();\n rowList.forEach((row, index) => {\n const channels = getTrackChannelCount(rowPeaks[index], 0);\n trackHeightById.set(\n row.id,\n waveHeight * channels + (showClipHeaders ? CLIP_HEADER_HEIGHT : 0)\n );\n });\n return {\n rows: rowList,\n peaksDataArray: rowPeaks,\n showClipHeaders,\n trackHeightById,\n trackLayout: computeTrackLayout(\n rowList.map((row) => row.id),\n trackHeightById\n ),\n animateTrackLayout: false,\n renderModeById: NO_RENDER_MODES,\n spectrogramHelpersById: NO_SPECTROGRAM_HELPERS,\n selectTrack: nothing,\n setSettingsModalTrackId: nothing,\n recordingChannelCount: 0,\n dragSourceTrackId: null,\n };\n }, [peaksDataArray, waveHeight, showClipHeaders]);\n\n // A click while stopped collapses the selection at its time, which moves\n // the cursor.\n const collapseSelectionAt = useCallback(\n (time: number) => setSelection(time, time),\n [setSelection]\n );\n\n const frame = useWaveformFrame({\n className,\n viewOptions,\n parts,\n displayDuration: duration,\n rows,\n // The waveform is drawn from the provider's first render: it does not\n // wait for the player (`useMediaElementTrack().isReady` is that).\n playlistState: 'ready',\n controlsWidth: 0,\n onClickWhileStopped: collapseSelectionAt,\n });\n\n return <DevicePixelRatioProvider>{frame}</DevicePixelRatioProvider>;\n};\n","import React from 'react';\nimport { MediaElementWaveformRoot } from './MediaElementWaveformRoot';\nimport {\n WaveformPlayhead,\n WaveformSelection,\n WaveformTimescale,\n WaveformTracks,\n} from './waveformParts';\nimport { WaveformAnnotationBoxes } from './WaveformAnnotationBoxes';\nimport { AnnotationList } from './AnnotationList';\n\n/**\n * `className`. What the view is made of is not an option here, and neither\n * are the options of its parts: compose the parts inside\n * `MediaElementWaveformRoot` for anything else.\n */\nexport interface MediaElementWaveformProps {\n className?: string;\n}\n\n// The same elements on every render, so a render of the composition does not\n// render these parts (see Waveform.tsx).\nconst TIMESCALE = <WaveformTimescale />;\nconst TRACKS = <WaveformTracks />;\nconst SELECTION = <WaveformSelection />;\nconst PLAYHEAD = <WaveformPlayhead />;\nconst ANNOTATION_BOXES = <WaveformAnnotationBoxes />;\n// Draws nothing while there are no annotations.\nconst ANNOTATION_LIST = <AnnotationList />;\n\n/**\n * The view of `MediaElementPlaylistProvider`, ready-made: the timescale, the\n * one track, the annotation boxes, the selection and the playhead, with the\n * annotation text list below when there are annotations.\n *\n * It is a composition of the public parts with no options for them. To leave\n * the timescale out, show fades, use your own playhead or give the\n * annotation boxes or the annotation list an option, write the composition\n * yourself:\n *\n * ```tsx\n * <MediaElementWaveformRoot>\n * <WaveformTimescale />\n * <WaveformTracks>\n * <WaveformFades />\n * </WaveformTracks>\n * <WaveformAnnotationBoxes />\n * <WaveformSelection />\n * <WaveformPlayhead renderPlayhead={…} />\n * </MediaElementWaveformRoot>\n * <AnnotationList />\n * ```\n */\nexport const MediaElementWaveform: React.FC<MediaElementWaveformProps> = ({ className }) => (\n <>\n <MediaElementWaveformRoot className={className}>\n {TIMESCALE}\n {TRACKS}\n {ANNOTATION_BOXES}\n {SELECTION}\n {PLAYHEAD}\n </MediaElementWaveformRoot>\n {ANNOTATION_LIST}\n </>\n);\n","import React from 'react';\nimport type { KeyboardShortcut } from '@waveform-playlist/core';\nimport { usePlaybackShortcuts } from '../hooks/usePlaybackShortcuts';\nimport { useClipSplitting } from '../hooks/useClipSplitting';\nimport { useAnnotationKeyboardControls } from '../hooks/useAnnotationKeyboardControls';\nimport {\n useActiveAnnotation,\n usePlaylistZoom,\n usePlaylistTimeline,\n useAnnotations,\n useAnnotationOptions,\n usePlaybackControls,\n useEditorControls,\n} from '../contexts/playlistContexts';\n\nexport interface KeyboardShortcutsProps {\n /** Enable default playback shortcuts (Space, Escape, 0). Defaults to false. */\n playback?: boolean;\n /** Enable clip splitting shortcut ('s' key). Defaults to false. */\n clipSplitting?: boolean;\n /** Enable annotation keyboard controls (arrow nav, boundary editing). Defaults to false. */\n annotations?: boolean;\n /** Enable undo/redo shortcuts (Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z). Defaults to false. */\n undo?: boolean;\n /** Additional shortcuts appended to the defaults. */\n additionalShortcuts?: KeyboardShortcut[];\n}\n\n/**\n * Self-closing component that sets up keyboard shortcuts for the playlist.\n * Must be rendered inside a WaveformPlaylistProvider.\n *\n * @example\n * ```tsx\n * <WaveformPlaylistProvider arrangement={arrangement} {...}>\n * <KeyboardShortcuts playback clipSplitting />\n * <Waveform />\n * </WaveformPlaylistProvider>\n * ```\n */\nexport const KeyboardShortcuts: React.FC<KeyboardShortcutsProps> = ({\n playback = false,\n clipSplitting = false,\n annotations = false,\n undo: undoEnabled = false,\n additionalShortcuts = [],\n}) => {\n // Clip splitting setup\n const { samplesPerPixel } = usePlaylistZoom();\n const { duration } = usePlaylistTimeline();\n const { annotations: annotationList } = useAnnotations();\n const { linkEndpoints, continuousPlay } = useAnnotationOptions();\n const { activeAnnotationId } = useActiveAnnotation();\n const { setAnnotations, setActiveAnnotationId, scrollContainerRef, play } = usePlaybackControls();\n const { undo, redo } = useEditorControls();\n\n const { splitClipAtPlayhead } = useClipSplitting({ samplesPerPixel });\n\n // Build additional shortcuts from enabled features\n const allAdditional: KeyboardShortcut[] = [];\n\n if (clipSplitting) {\n allAdditional.push({\n key: 's',\n action: splitClipAtPlayhead,\n description: 'Split clip at playhead',\n preventDefault: true,\n });\n }\n\n if (undoEnabled) {\n allAdditional.push(\n { key: 'z', ctrlKey: true, shiftKey: false, action: undo, description: 'Undo' },\n { key: 'z', metaKey: true, shiftKey: false, action: undo, description: 'Undo' },\n { key: 'z', ctrlKey: true, shiftKey: true, action: redo, description: 'Redo' },\n { key: 'z', metaKey: true, shiftKey: true, action: redo, description: 'Redo' }\n );\n }\n\n if (additionalShortcuts.length > 0) {\n allAdditional.push(...additionalShortcuts);\n }\n\n // Playback shortcuts (or just additional if playback is off)\n usePlaybackShortcuts({\n enabled: playback || allAdditional.length > 0,\n ...(playback ? { additionalShortcuts: allAdditional } : { shortcuts: allAdditional }),\n });\n\n // Annotation keyboard controls\n useAnnotationKeyboardControls({\n annotations: annotationList,\n activeAnnotationId,\n onAnnotationsChange: setAnnotations,\n onActiveAnnotationChange: setActiveAnnotationId,\n duration,\n linkEndpoints,\n continuousPlay,\n scrollContainerRef,\n onPlay: play,\n enabled: annotations && annotationList.length > 0,\n });\n\n return null;\n};\n","import { useEffect } from 'react';\nimport { useEditorControls } from '../contexts/playlistContexts';\n\nexport interface RecordingSessionOptions {\n /** True while a take is being recorded. */\n isRecording: boolean;\n /** The track being recorded into, or null when there is none. */\n trackId: string | null | undefined;\n}\n\n/**\n * Tells the playlist that a take is being recorded into a track, for as long\n * as `isRecording` is true (#685). The provider then keeps playback running\n * past the end of the audio and mutes the armed track in the arrangement for\n * the take, so what it already holds does not play under a punch-in that\n * replaces it (#812: the mixer shows the track muted, its built-in Mute\n * button is disabled and `useTrack().isRecordingArmed` is true). The mute\n * from before the take is written back when the take ends, the track changes\n * or the component unmounts, whatever was set in between; the provider also\n * writes it back in its own cleanup (its unmount or an `<Activity>` hide)\n * while a track is still armed. An `<Activity>` hide of the component ends\n * the session the same way, and the reveal starts it again from the track's\n * mute at that moment.\n *\n * Call it in the component that calls `useIntegratedRecording`, under\n * `WaveformPlaylistProvider`. `<WaveformRecordingPreview>` only draws the\n * take: without this hook the armed track is not muted.\n *\n * A handler that starts playback together with the recording should also call\n * `setRecordingActive(true, trackId)` (from `useEditorControls()`) before\n * `play()`: this effect runs after the render that follows, which is too late\n * for the first animation frame. `play()` does nothing before the playlist's\n * first ready (`usePlaylistTimeline().isReady`), so a take started during the\n * first load records without playback.\n */\nexport function useRecordingSession({ isRecording, trackId }: RecordingSessionOptions): void {\n const { setRecordingActive } = useEditorControls();\n const armedTrackId = trackId ?? null;\n useEffect(() => {\n if (!isRecording) return undefined;\n setRecordingActive(true, armedTrackId);\n return () => setRecordingActive(false);\n }, [isRecording, armedTrackId, setRecordingActive]);\n}\n","import React, { useCallback, useMemo, useRef } from 'react';\nimport { flushSync } from 'react-dom';\nimport { DragDropProvider } from '@dnd-kit/react';\nimport { RestrictToHorizontalAxis } from '@dnd-kit/abstract/modifiers';\nimport type { Modifiers } from '@dnd-kit/abstract';\nimport {\n samplesToTicks,\n ticksToSamples,\n snapToGrid,\n ticksPerBeat,\n ticksPerBar,\n} from '@waveform-playlist/core';\nimport { useBeatsAndBars, getScaleInfo } from '@waveform-playlist/ui-components';\n\nimport {\n usePlaylistView,\n usePlaylistZoom,\n usePlaylistTimeline,\n useEditorControls,\n} from '../contexts/playlistContexts';\nimport { useClipDragHandlers } from '../hooks/useClipDragHandlers';\nimport { useDragSensors } from '../hooks/useDragSensors';\nimport { ClipCollisionModifier } from '../modifiers/ClipCollisionModifier';\nimport { SnapToGridModifier } from '../modifiers/SnapToGridModifier';\nimport { ClipInteractionOptions, useClipInteraction } from '../contexts/ClipInteractionContext';\n\nexport interface ClipInteractionProviderProps {\n /** Enable snap-to-grid for clip moves and boundary trims. When true,\n * auto-detects beats snapping from BeatsAndBarsProvider context\n * (if present with scaleMode=\"beats\" and snapTo!=\"off\"), otherwise\n * falls back to timescale-based snapping. Default: false. */\n snap?: boolean;\n /** Touch-friendly interaction: drag sensors that wait 250ms on touch (so a\n * swipe still scrolls) and wider clip trim handles. Left out: inherited from\n * a `ClipInteractionOptions` or `ClipInteractionProvider` above (false at\n * the top). */\n touchOptimized?: boolean;\n children: React.ReactNode;\n}\n\nexport const ClipInteractionProvider: React.FC<ClipInteractionProviderProps> = ({\n snap = false,\n touchOptimized: touchOptimizedProp,\n children,\n}) => {\n // One value for the sensors and for the handles (which `ClipInteractionOptions`\n // below resolves the same way): the prop, else what is set above.\n const inherited = useClipInteraction();\n const touchOptimized = touchOptimizedProp ?? inherited.touchOptimized;\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n const { tracks } = usePlaylistTimeline();\n const { setSelectedTrackId, reorderTrack, bumpTrackReorderEpoch, setTrackDragPreview } =\n useEditorControls();\n const beatsAndBars = useBeatsAndBars();\n\n // Derive snap mode from context: beats if provider is in beats mode with snap enabled,\n // timescale otherwise, off when snap prop is false.\n const useBeatsSnap =\n snap &&\n beatsAndBars != null &&\n beatsAndBars.scaleMode === 'beats' &&\n beatsAndBars.snapTo !== 'off';\n const useTimescaleSnap = snap && !useBeatsSnap;\n\n // Build snapSamplePosition for boundary trim snapping\n const snapSamplePosition = useMemo(() => {\n if (useBeatsSnap && beatsAndBars) {\n const { bpm, timeSignature, snapTo } = beatsAndBars;\n const gridTicks = snapTo === 'bar' ? ticksPerBar(timeSignature) : ticksPerBeat(timeSignature);\n return (samplePos: number) => {\n const ticks = samplesToTicks(samplePos, bpm, sampleRate);\n const snapped = snapToGrid(ticks, gridTicks);\n return ticksToSamples(snapped, bpm, sampleRate);\n };\n }\n if (useTimescaleSnap) {\n const gridSamples = Math.round((getScaleInfo(samplesPerPixel).smallStep / 1000) * sampleRate);\n return (samplePos: number) => Math.round(samplePos / gridSamples) * gridSamples;\n }\n return undefined;\n }, [useBeatsSnap, useTimescaleSnap, beatsAndBars, sampleRate, samplesPerPixel]);\n\n // The modifiers and the track selection on drag start read the loaded\n // tracks through this ref, so their identity does not change when tracks\n // do: keyed on tracks, the modifiers array handed to DragDropProvider would\n // be rebuilt by any clip operation, also one that lands mid-drag.\n const tracksRef = useRef(tracks);\n tracksRef.current = tracks;\n const getTracks = useCallback(() => tracksRef.current, []);\n\n // Sensors\n const sensors = useDragSensors({ touchOptimized });\n\n // Drag handlers\n const {\n onDragStart: handleDragStart,\n onDragMove,\n onDragEnd,\n } = useClipDragHandlers({ samplesPerPixel, snapSamplePosition });\n\n // True from the start of a track-reorder drag to its end. dnd-kit can send\n // one more dragover AFTER the dragend of a canceled drag (the sorting\n // plugin putting the item back): seen with Escape mid-drag once the slot's\n // element was registered from the reorder handle's effect (#687), where it\n // set the preview again for good. A preview without a drag is never wanted.\n const trackReorderDragActiveRef = React.useRef(false);\n\n // Wrap onDragStart to auto-select track\n const onDragStart = React.useCallback(\n (event: Parameters<typeof handleDragStart>[0]) => {\n const data = event.operation?.source?.data as\n | { kind?: string; trackId?: string; trackIndex?: number }\n | undefined;\n if (data?.kind === 'track-reorder') {\n trackReorderDragActiveRef.current = true;\n if (data.trackId) setSelectedTrackId(data.trackId);\n return; // clip handler guards also skip this kind\n }\n const trackIndex = data?.trackIndex;\n const track = trackIndex !== undefined ? tracksRef.current[trackIndex] : undefined;\n if (track) {\n setSelectedTrackId(track.id);\n }\n handleDragStart(event);\n },\n [handleDragStart, setSelectedTrackId]\n );\n\n // Publish the live track-reorder preview. dnd-kit fires dragover on every\n // collision change; OptimisticSortingPlugin has already updated\n // source.sortable.index by then. Functional set with an equality guard so\n // repeated dragovers at the same index don't re-render the playlist.\n const handleDragOver = React.useCallback(\n (event: { operation: { source?: { data?: unknown } | null } }) => {\n const data = event.operation.source?.data as { kind?: string; trackId?: string } | undefined;\n if (data?.kind !== 'track-reorder' || !data.trackId) return;\n if (!trackReorderDragActiveRef.current) return;\n const sortable = (\n event.operation.source as unknown as {\n sortable?: { index: number; initialIndex: number };\n }\n ).sortable;\n if (!sortable) return;\n const trackId = data.trackId;\n const toIndex = sortable.index;\n setTrackDragPreview((prev) =>\n prev && prev.trackId === trackId && prev.toIndex === toIndex ? prev : { trackId, toIndex }\n );\n },\n [setTrackDragPreview]\n );\n\n // Wrap onDragEnd: track-reorder sources commit via reorderTrack, clip sources\n // flow through to the existing move/trim handler unchanged.\n const handleDragEnd = React.useCallback(\n (event: Parameters<typeof onDragEnd>[0]) => {\n const data = event.operation.source?.data as { kind?: string; trackId?: string } | undefined;\n if (data?.kind === 'track-reorder') {\n trackReorderDragActiveRef.current = false;\n const sortable = (\n event.operation.source as unknown as {\n sortable?: { index: number; initialIndex: number };\n }\n ).sortable;\n const trackId = data.trackId;\n const moves =\n !event.canceled && trackId && sortable && sortable.index !== sortable.initialIndex;\n // ONE commit for the three: the reorder, the cleared preview and the\n // epoch. dnd-kit calls this inside `startTransition`, where the two\n // state updates would wait as transition updates while the reorder\n // (the arrangement, read with `useSyncExternalStore`) renders at\n // once: React would first move the slots under their old keys, which\n // is what the epoch is there to avoid, and remount them a commit\n // later. `flushSync` renders all three together.\n flushSync(() => {\n // Unconditional, regardless of canceled/committed: @dnd-kit/react's\n // sortable plugins can splice React-owned DOM nodes (Feedback's\n // placeholder, OptimisticSortingPlugin's reorder()) during the drag\n // that just ended, desyncing React's fiber tree from the true DOM.\n // Bumping this forces the view's track-controls part to remount the\n // track-controls slots, healing the corruption before the next\n // reorder (drag or button) needs to touch the DOM. See\n // bumpTrackReorderEpoch's doc comment in WaveformPlaylistContext.\n bumpTrackReorderEpoch();\n // The columns go straight from the previewed layout to the\n // committed one, with no frame in between.\n setTrackDragPreview(null);\n if (moves) reorderTrack(trackId, sortable.index);\n });\n return;\n }\n onDragEnd(event);\n },\n [onDragEnd, reorderTrack, bumpTrackReorderEpoch, setTrackDragPreview]\n );\n\n // Build modifiers array\n const modifiers = useMemo(() => {\n const mods: Modifiers = [RestrictToHorizontalAxis];\n\n if (useBeatsSnap && beatsAndBars) {\n mods.push(\n SnapToGridModifier.configure({\n mode: 'beats',\n snapTo: beatsAndBars.snapTo,\n bpm: beatsAndBars.bpm,\n timeSignature: beatsAndBars.timeSignature,\n samplesPerPixel,\n sampleRate,\n })\n );\n } else if (useTimescaleSnap) {\n mods.push(\n SnapToGridModifier.configure({\n mode: 'timescale',\n gridSamples: Math.round((getScaleInfo(samplesPerPixel).smallStep / 1000) * sampleRate),\n samplesPerPixel,\n })\n );\n }\n\n mods.push(ClipCollisionModifier.configure({ tracks: getTracks, samplesPerPixel }));\n return mods;\n }, [useBeatsSnap, useTimescaleSnap, beatsAndBars, getTracks, samplesPerPixel, sampleRate]);\n\n return (\n <ClipInteractionOptions enabled touchOptimized={touchOptimized}>\n <DragDropProvider\n sensors={sensors}\n onDragStart={onDragStart}\n onDragMove={onDragMove}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n modifiers={modifiers}\n >\n {children}\n </DragDropProvider>\n </ClipInteractionOptions>\n );\n};\n","import {\n Modifier,\n configurator,\n type DragDropManager,\n type DragOperation,\n} from '@dnd-kit/abstract';\nimport { constrainClipDrag } from '@waveform-playlist/engine';\nimport type { ClipTrack, AudioClip } from '@waveform-playlist/core';\nimport { sortedClipsOf } from '../utils/sortedClips';\n\ninterface ClipCollisionOptions {\n /**\n * The tracks to check against, or a function returning them. Pass a function\n * (reading a ref, say) to keep the configured modifier's identity stable while\n * tracks change, so the modifiers array handed to DragDropProvider is not\n * rebuilt on every edit.\n */\n tracks: readonly ClipTrack[] | (() => readonly ClipTrack[]);\n samplesPerPixel: number;\n}\n\n/**\n * Modifier that constrains clip drag movement to prevent overlaps.\n *\n * For clip move operations: constrains horizontal transform to valid positions\n * using the engine's collision detection.\n *\n * For boundary trim operations: returns zero transform because the trim is\n * shown by the trim preview, which draws the clip at its previewed geometry,\n * not by a CSS translate.\n */\nexport class ClipCollisionModifier extends Modifier<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n DragDropManager<any, any>,\n ClipCollisionOptions\n> {\n apply(operation: DragOperation): { x: number; y: number } {\n const { transform, source } = operation;\n\n if (!source?.data || !this.options) return transform;\n\n // `clipIndex` is a position in the drawn row, not in `track.clips`: the clip\n // is found by its id.\n const { boundary, trackIndex, clipId } = source.data as {\n boundary?: 'left' | 'right';\n trackIndex: number;\n clipId: string;\n };\n\n // Boundary trims: zero transform (the trim preview draws the clip)\n if (boundary) return { x: 0, y: 0 };\n\n const { samplesPerPixel } = this.options;\n const tracks =\n typeof this.options.tracks === 'function' ? this.options.tracks() : this.options.tracks;\n const track = tracks[trackIndex];\n if (!track) return transform;\n\n const clip = track.clips.find((c: AudioClip) => c.id === clipId);\n if (!clip) return transform;\n\n // Convert pixel delta to samples, constrain, convert back\n const deltaSamples = transform.x * samplesPerPixel;\n const sortedClips = sortedClipsOf(track.clips);\n const sortedIndex = sortedClips.findIndex((c: AudioClip) => c.id === clip.id);\n const constrainedDelta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);\n\n return { x: constrainedDelta / samplesPerPixel, y: 0 };\n }\n\n static configure = configurator(ClipCollisionModifier);\n}\n","import {\n Modifier,\n configurator,\n type DragDropManager,\n type DragOperation,\n} from '@dnd-kit/abstract';\nimport {\n ticksPerBeat,\n ticksPerBar,\n ticksToSamples,\n samplesToTicks,\n snapToGrid,\n} from '@waveform-playlist/core';\nimport type { BeatsAndBarsSnapTo } from '@waveform-playlist/ui-components';\n\ninterface SnapToGridBeatsOptions {\n mode: 'beats';\n snapTo: BeatsAndBarsSnapTo;\n bpm: number;\n timeSignature: [number, number];\n samplesPerPixel: number;\n sampleRate: number;\n}\n\ninterface SnapToGridTimescaleOptions {\n mode: 'timescale';\n gridSamples: number;\n samplesPerPixel: number;\n}\n\ntype SnapToGridOptions = SnapToGridBeatsOptions | SnapToGridTimescaleOptions;\n\n/**\n * dnd-kit modifier that quantizes clip drag movement to a grid.\n *\n * Two modes:\n * - \"beats\": Snaps to beat/bar grid using PPQN tick space for exact musical timing.\n * - \"timescale\": Snaps to a sample-based grid derived from timescale markers.\n *\n * Designed to compose with ClipCollisionModifier — snap first,\n * then collision constrains the snapped position.\n */\nexport class SnapToGridModifier extends Modifier<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n DragDropManager<any, any>,\n SnapToGridOptions\n> {\n apply(operation: DragOperation): { x: number; y: number } {\n const { transform, source } = operation;\n\n if (!this.options || !source?.data) return transform;\n\n // Don't snap boundary trims — snapping for trims is handled in the drag handler\n const { boundary, startSample } = source.data as {\n boundary?: 'left' | 'right';\n startSample?: number;\n };\n if (boundary) return transform;\n\n const { samplesPerPixel } = this.options;\n\n // Snap the absolute position (not just the delta) so clips land exactly\n // on grid lines even if they started off-grid.\n if (this.options.mode === 'timescale') {\n const { gridSamples } = this.options;\n if (startSample !== undefined) {\n const proposedPosition = startSample + transform.x * samplesPerPixel;\n const snappedPosition = Math.round(proposedPosition / gridSamples) * gridSamples;\n return { x: (snappedPosition - startSample) / samplesPerPixel, y: 0 };\n }\n // Fallback: snap delta (no startSample available)\n const deltaSamples = transform.x * samplesPerPixel;\n const snappedSamples = Math.round(deltaSamples / gridSamples) * gridSamples;\n return { x: snappedSamples / samplesPerPixel, y: 0 };\n }\n\n // Beats mode\n const { snapTo, bpm, timeSignature, sampleRate } = this.options;\n\n if (snapTo === 'off') return transform;\n\n const gridTicks = snapTo === 'bar' ? ticksPerBar(timeSignature) : ticksPerBeat(timeSignature);\n\n if (startSample !== undefined) {\n // Snap absolute position in tick space\n const proposedSamples = startSample + transform.x * samplesPerPixel;\n const proposedTicks = samplesToTicks(proposedSamples, bpm, sampleRate);\n const snappedTicks = snapToGrid(proposedTicks, gridTicks);\n const snappedSamples = ticksToSamples(snappedTicks, bpm, sampleRate);\n return { x: (snappedSamples - startSample) / samplesPerPixel, y: 0 };\n }\n\n // Fallback: snap delta (no startSample available)\n const deltaSamples = transform.x * samplesPerPixel;\n const deltaTicks = samplesToTicks(deltaSamples, bpm, sampleRate);\n const snappedTicks = snapToGrid(deltaTicks, gridTicks);\n const snappedSamples = ticksToSamples(snappedTicks, bpm, sampleRate);\n\n return { x: snappedSamples / samplesPerPixel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,EACtE;AAGA,QAAM,YAAYT,UAAQ,MAAM;AAC9B,UAAM,OAAkB,CAACU,yBAAwB;AAEjD,QAAI,gBAAgB,cAAc;AAChC,WAAK;AAAA,QACH,mBAAmB,UAAU;AAAA,UAC3B,MAAM;AAAA,UACN,QAAQ,aAAa;AAAA,UACrB,KAAK,aAAa;AAAA,UAClB,eAAe,aAAa;AAAA,UAC5B;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,WAAW,kBAAkB;AAC3B,WAAK;AAAA,QACH,mBAAmB,UAAU;AAAA,UAC3B,MAAM;AAAA,UACN,aAAa,KAAK,MAAO,aAAa,eAAe,EAAE,YAAY,MAAQ,UAAU;AAAA,UACrF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAEA,SAAK,KAAK,sBAAsB,UAAU,EAAE,QAAQ,WAAW,gBAAgB,CAAC,CAAC;AACjF,WAAO;AAAA,EACT,GAAG,CAAC,cAAc,kBAAkB,cAAc,WAAW,iBAAiB,UAAU,CAAC;AAEzF,SACE,gBAAAX,MAAC,0BAAuB,SAAO,MAAC,gBAC9B,0BAAAA;AAAA,IAACY;AAAA,IAAA;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA,YAAY;AAAA,MACZ,WAAW;AAAA,MACX;AAAA,MAEC;AAAA;AAAA,EACH,GACF;AAEJ;","names":["useState","useEffect","useLayoutEffect","useRef","useCallback","useMemo","cache","formatTime","useState","useCallback","useState","useCallback","useRef","useState","useCallback","useRef","useState","useCallback","useRef","useState","useCallback","useRef","cache","React","useCallback","useCallback","useRef","useCallback","useCallback","useEffect","useRef","useRef","useEffect","useCallback","_a","useCallback","useCallback","useMemo","useEffect","useMemo","useCallback","useEffect","useCallback","useEffect","useRef","useState","useEffect","useRef","useCallback","useState","useRef","useCallback","useEffect","useState","useMemo","useSyncExternalStore","useMemo","useSyncExternalStore","useCallback","useMemo","useRef","useState","useState","useMemo","useRef","useCallback","useCallback","useRef","useCallback","useRef","useState","useMemo","useRef","useMemo","useRef","useState","createValueSource","WaveformData","WaveformData","bits","emptyPeaks","useState","createValueSource","useRef","useCallback","useEffect","useMemo","useRef","useState","useState","useCallback","useRef","useEffect","useMemo","useMemo","useRef","useSyncExternalStore","isLoadingClip","isLoadingClip","useMemo","useSyncExternalStore","useRef","useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect","useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","createValueSource","useRef","useState","createValueSource","useCallback","armedTrackId","useEffect","useSyncExternalStore","useMemo","useEffect","useRef","useRef","useEffect","useMemo","useState","useRef","useCallback","useLayoutEffect","useEffect","useState","useEffect","useLayoutEffect","useRef","useCallback","useMemo","ThemeProvider","installHint","jsx","useState","useRef","useCallback","useLayoutEffect","useMemo","useEffect","ThemeProvider","useCallback","jsx","useCallback","BaseControlButton","jsx","BaseControlButton","useRef","useEffect","jsx","useRef","useEffect","_a","use","useLayoutEffect","useRef","useState","useMemo","useCallback","useEffect","useState","useCallback","useSyncExternalStore","useCallback","useMemo","useSyncExternalStore","subscribeToNothing","useMemo","useCallback","_a","preview","useSyncExternalStore","trackKind","createContext","use","createContext","use","styled","React","Fragment","useCallback","useMemo","useTheme","waveformColorToCss","createContext","memo","useLayoutEffect","useMemo","useRef","useState","createValueSource","useEffect","useLayoutEffect","useRef","createContext","memo","AutomaticScrollFlag","useLayoutEffect","useState","useRef","useMemo","createValueSource","createContext","use","React","use","React","createContext","useCallback","use","useMemo","useSyncExternalStore","useTheme","usePlaylistInfo","waveformColorToCss","createContext","use","useMemo","jsx","useId","useRef","useEffect","styled","jsx","styled","useRef","useId","useEffect","_a","jsx","jsxs","createContext","React","ClipView","use","useCallback","useSyncExternalStore","TrackRow","useTheme","waveformColorToCss","usePlaylistInfo","useMemo","React","use","useMemo","useRef","useState","useTheme","React","styled","use","createContext","use","use","useEffect","use","useEffect","jsx","jsxs","use","jsx","jsxs","styled","React","useRef","jsx","useTheme","use","useRef","useMemo","value","useState","React","React","use","useSyncExternalStore","useTheme","useRef","useEffect","useId","styled","usePlaylistInfo","jsx","styled","useRef","useId","usePlaylistInfo","useEffect","jsx","subscribeToNothing","React","WaveformSelection","useTheme","use","useSyncExternalStore","WaveformLoopRegion","createContext","use","useMemo","jsx","createContext","use","useMemo","jsx","React","WaveformTimescale","use","Fragment","jsx","jsxs","React","useMemo","useTheme","useCallback","waveformColorToCss","jsx","jsxs","use","useMemo","_a","_b","_c","_d","_e","_f","_g","useState","useCallback","useLayoutEffect","useRef","trackKind","React","use","useTheme","createContext","use","createContext","use","React","use","jsx","React","AnnotationBoxItem","use","jsx","React","WaveformAnnotationBoxes","use","useTheme","use","useMemo","jsx","use","useMemo","Fragment","jsx","jsxs","useCallback","useMemo","DevicePixelRatioProvider","CLIP_HEADER_HEIGHT","jsx","useMemo","CLIP_HEADER_HEIGHT","useCallback","DevicePixelRatioProvider","Fragment","jsx","jsxs","TIMESCALE","TRACKS","SELECTION","PLAYHEAD","ANNOTATION_BOXES","ANNOTATION_LIST","useEffect","useEffect","React","useCallback","useMemo","useRef","flushSync","DragDropProvider","RestrictToHorizontalAxis","samplesToTicks","ticksToSamples","snapToGrid","ticksPerBeat","ticksPerBar","Modifier","configurator","deltaSamples","snappedSamples","snappedTicks","jsx","useMemo","ticksPerBar","ticksPerBeat","samplesToTicks","snapToGrid","ticksToSamples","useRef","useCallback","React","flushSync","RestrictToHorizontalAxis","DragDropProvider"]}
1
+ {"version":3,"sources":["<define:__INSTALL_SPECS__>","../src/WaveformPlaylistContext.tsx","../src/soundFontSync.ts","../src/hooks/useTimeFormat.ts","../src/hooks/useZoomControls.ts","../src/hooks/useMasterVolume.ts","../src/hooks/useSelectionState.ts","../src/hooks/useLoopState.ts","../src/hooks/useSelectedTrack.ts","../src/hooks/useClipDragHandlers.ts","../src/utils/boundaryTrim.ts","../src/utils/sortedClips.ts","../src/utils/loadedTracks.ts","../src/utils/sameItems.ts","../src/contexts/playlistContexts.ts","../src/hooks/useAnnotationDragHandlers.ts","../src/hooks/useAnnotationsWithPreview.ts","../src/hooks/useDragSensors.ts","../src/hooks/useClipSplitting.ts","../src/hooks/useKeyboardShortcuts.ts","../src/hooks/usePlaybackShortcuts.ts","../src/hooks/usePlayFromSelectionOrCursor.ts","../src/hooks/useAnnotationKeyboardControls.ts","../src/utils/annotationBoundaryKeys.ts","../src/hooks/useAnimationFrameLoop.ts","../src/hooks/useWaveformDataCache.ts","../src/workers/peaksWorker.ts","../src/hooks/useCreateArrangement.ts","../src/hooks/useArrangementTracks.ts","../src/hooks/useArrangementSources.ts","../src/hooks/useCreateAnnotationStore.ts","../src/hooks/useStoredAnnotations.ts","../src/providerInternals/followAnnotations.ts","../src/providerInternals/useAnnotationState.ts","../src/utils/annotationLookup.ts","../src/providerInternals/useFrameCallbacks.ts","../src/providerInternals/useScrollFollow.ts","../src/providerInternals/useMergedTheme.ts","../src/hooks/useShallowStable.ts","../src/providerInternals/useTrimPreview.ts","../src/waveformDataLoader.ts","../src/utils/derivePeaks.ts","../src/providerInternals/useEngineLifetime.ts","../src/utils/installCommand.ts","../src/playout/resolvePlayoutAdapter.ts","../src/providerInternals/useArrangementView.ts","../src/utils/placeholderPeaks.ts","../src/utils/timelineDuration.ts","../src/providerInternals/useReadyOnce.ts","../src/utils/isDevelopmentBuild.ts","../src/providerInternals/useArrangementEditing.ts","../src/components/partWarnings.ts","../src/providerInternals/arrangementIdentity.ts","../src/MediaElementPlaylistContext.tsx","../src/playout/resolveMediaElementPlayout.ts","../src/components/PlaybackControls.tsx","../src/components/ZoomControls.tsx","../src/components/ContextualControls.tsx","../src/components/WaveformRoot.tsx","../src/utils/trackOrderPreview.ts","../src/hooks/useTrailingActive.ts","../src/hooks/useRecordingLayout.ts","../src/hooks/useTrimPreviewView.ts","../src/SpectrogramIntegrationContext.tsx","../src/utils/trackRenderMode.ts","../src/components/visualizationLayout.tsx","../src/components/waveformFrame.tsx","../src/hooks/useSelectionDrag.ts","../src/hooks/useWindowDrag.ts","../src/components/waveformLayoutContext.ts","../src/components/waveformParts.tsx","../src/components/TrackRows.tsx","../src/contexts/ClipInteractionContext.tsx","../src/components/ChannelWithProgress.tsx","../src/components/TrackControlsColumn.tsx","../src/components/DefaultTrackControls.tsx","../src/components/TrackControlPieces.tsx","../src/components/trackContext.ts","../src/hooks/useTrackReorderHandle.ts","../src/utils/dragPopoverHealer.ts","../src/utils/stableTemplate.ts","../src/components/VisualizationOverlays.tsx","../src/components/AnimatedPlayhead.tsx","../src/components/WaveformViewOptions.tsx","../src/components/WaveformAnnotationBoxes.tsx","../src/AnnotationIntegrationContext.tsx","../src/components/AnnotationBoxes.tsx","../src/components/AnnotationList.tsx","../src/components/Waveform.tsx","../src/components/MediaElementWaveformRoot.tsx","../src/components/MediaElementWaveform.tsx","../src/components/KeyboardShortcuts.tsx","../src/hooks/useRecordingSession.ts","../src/components/ClipInteractionProvider.tsx","../src/modifiers/ClipCollisionModifier.ts","../src/modifiers/SnapToGridModifier.ts"],"sourcesContent":["{\"@dawcore/wam\":\"@dawcore/wam@^0.0.5-next.0\",\"@dnd-kit/abstract\":\"@dnd-kit/abstract@^0.5.0\",\"@dnd-kit/dom\":\"@dnd-kit/dom@^0.5.0\",\"@dnd-kit/react\":\"@dnd-kit/react@^0.5.0\",\"@waveform-playlist/annotations\":\"@waveform-playlist/annotations@^14.0.0-next.4\",\"@waveform-playlist/media-element-playout\":\"@waveform-playlist/media-element-playout@^12.4.0-next.2\",\"@waveform-playlist/playout\":\"@waveform-playlist/playout@^13.0.0-next.2\",\"@waveform-playlist/recording\":\"@waveform-playlist/recording@^14.0.0-next.4\",\"react\":\"react@^19.0.0\",\"react-dom\":\"react-dom@^19.0.0\",\"styled-components\":\"styled-components@^6.0.0\",\"tone\":\"tone@^15.0.0\",\"@waveform-playlist/spectrogram\":\"@waveform-playlist/spectrogram@^15.0.0-next.2\"}","import React, {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useCallback,\n useMemo,\n type ReactNode,\n} from 'react';\nimport { ThemeProvider } from 'styled-components';\nimport type {\n EffectsFunction,\n TrackEffectsFunction,\n SoundFontCache,\n} from '@waveform-playlist/playout';\nimport type {\n Arrangement,\n EngineState,\n PlaylistEngine,\n PlayoutAdapter,\n} from '@waveform-playlist/engine';\nimport { type Fade, type MidiNoteData } from '@waveform-playlist/core';\nimport { type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport { syncSoundFontCacheToAdapter } from './soundFontSync';\nimport type { TrackDragPreview } from './utils/trackOrderPreview';\nimport type { PeakData } from '@waveform-playlist/core';\nimport type { AnnotationData, AnnotationStore } from '@waveform-playlist/core';\nimport {\n useTimeFormat,\n useZoomControls,\n useMasterVolume,\n useSelectionState,\n useLoopState,\n useSelectedTrack,\n useAnimationFrameLoop,\n} from './hooks';\nimport { followAnnotations } from './providerInternals/followAnnotations';\nimport {\n useAnnotationState,\n type AnnotationListProp,\n} from './providerInternals/useAnnotationState';\nimport { useFrameCallbacks, type FrameData } from './providerInternals/useFrameCallbacks';\nimport { centrePlayhead, useScrollFollow } from './providerInternals/useScrollFollow';\nimport { useMergedTheme } from './providerInternals/useMergedTheme';\nimport { useTrimPreview } from './providerInternals/useTrimPreview';\nimport { useEngineLifetime } from './providerInternals/useEngineLifetime';\nimport { useArrangementView } from './providerInternals/useArrangementView';\nimport { useReadyOnce } from './providerInternals/useReadyOnce';\nimport { useArrangementEditing } from './providerInternals/useArrangementEditing';\nimport { useArrangementKey } from './providerInternals/arrangementIdentity';\n\n// Types\n/**\n * What one clip is drawn from.\n *\n * `isPlaceholder` is true for the record of a clip whose audio is still loading\n * (`placeholderPeaks`): it is drawn without drag or trim handles, and there is\n * NO clip for it in `usePlaylistTimeline().tracks`, so look it up by `clipId`,\n * never by position. Every other record has it false.\n */\nexport interface ClipPeaks {\n clipId: string;\n trackName: string;\n peaks: PeakData;\n startSample: number;\n durationSamples: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n midiNotes?: MidiNoteData[];\n sampleRate?: number;\n offsetSamples?: number;\n /** The clip's linear gain — drawn into the waveform when\n * `<WaveformTracks gainScaled />` is set. */\n gain?: number;\n isPlaceholder: boolean;\n}\n\nexport type TrackClipPeaks = ClipPeaks[];\n\nexport type { TrackDragPreview };\n\nexport interface TrackState {\n name: string;\n muted: boolean;\n soloed: boolean;\n volume: number;\n pan: number;\n}\n\nimport {\n BLOCKED,\n ActiveAnnotationContext,\n ArrangementContext,\n AnnotationOptionsContext,\n AnnotationsContext,\n CurrentTimeContext,\n EditorControlsContext,\n EngineRefsContext,\n IsPlayingContext,\n LoopContext,\n MediaElementTrackContext,\n PlaybackControlsContext,\n PlaybackRateContext,\n PlaybackRefsContext,\n PlaylistMixerContext,\n PlaylistSettingsContext,\n PlaylistTimelineContext,\n PlaylistViewContext,\n PlaylistZoomContext,\n SelectedTrackIdContext,\n SelectedRowContext,\n SelectionContext,\n TrackReorderPreviewContext,\n TrimPreviewContext,\n RecordingArmContext,\n TrimPreviewPeaksContext,\n UndoRedoContext,\n type ActiveAnnotationContextValue,\n type CurrentTimeContextValue,\n type EditorControlsContextValue,\n type EngineRefsContextValue,\n type IsPlayingContextValue,\n type LoopContextValue,\n type PlaybackControlsContextValue,\n type PlaybackRefsContextValue,\n type PlaylistMixerContextValue,\n type PlaylistSettingsContextValue,\n type PlaylistTimelineContextValue,\n type PlaylistViewContextValue,\n type PlaylistZoomContextValue,\n type SelectedTrackIdContextValue,\n type SelectionContextValue,\n type TrackReorderPreviewContextValue,\n type UndoRedoContextValue,\n} from './contexts/playlistContexts';\n\nexport interface WaveformPlaylistProviderProps {\n /**\n * What the provider plays and draws: the tracks, their mix, the undo\n * history and the loading of their audio (#812). Make it with\n * `useCreateArrangement` and change it through its methods (or\n * `useArrangement()` below the provider); the provider follows it. A new\n * object is a new playlist: everything below the provider mounts again.\n */\n arrangement: Arrangement;\n /**\n * Draw and analyse every track as one channel. A provider option, not a\n * view option: the provider computes the peaks with it.\n */\n mono?: boolean;\n samplesPerPixel?: number;\n zoomLevels?: number[]; // Array of zoom levels in samples per pixel (lower = more zoomed in)\n automaticScroll?: boolean;\n theme?: Partial<WaveformPlaylistTheme>;\n /**\n * The owner of the annotations (#867): make it with\n * `useCreateAnnotationStore` and change the annotations with its methods.\n * The provider publishes what it holds and writes nothing back. Without it\n * there are no annotations.\n */\n annotationStore?: AnnotationStore;\n /**\n * The three annotation options (`editable`, `linkEndpoints`,\n * `isContinuousPlay`); the annotations are `annotationStore`'s. The provider\n * follows the three: an option takes a new value of its field, and a setter\n * or checkbox changes it in between.\n */\n annotationList?: AnnotationListProp;\n /** Master effects chain (default Tone.js adapter only). A new function builds a new engine. */\n effects?: EffectsFunction;\n /**\n * Returns the effects function of a track by id, or `undefined` for none:\n * pass `getTrackEffectsFunction` from `useTrackDynamicEffects()`. Default\n * Tone.js adapter only; with `createAdapter`, give the same function to your\n * own `createToneAdapter({ trackEffects })`.\n *\n * It is called when a track's audio graph is built, with the function passed\n * on the latest render. A new function identity does not rebuild anything,\n * so an inline arrow is fine; a different result for a track that is already\n * built applies the next time that track is built.\n */\n trackEffects?: (trackId: string) => TrackEffectsFunction | undefined;\n /**\n * Called once per mount, the first time an engine is attached and no source\n * of the arrangement is still pending. Read when it is called: a new\n * function identity builds nothing.\n */\n onReady?: () => void;\n /** Called when the engine or its adapter cannot be built (e.g. a missing\n * optional peer, a throwing `createAdapter`, or an invalid\n * `zoomLevels`/`samplesPerPixel`), and when `onReady` throws. A source that\n * fails to load is not reported here: see `useArrangementSources`. The\n * provider already logs the error; use this to surface it in your UI. */\n onError?: (err: Error) => void;\n /** SoundFont cache for sample-based MIDI playback. When provided, MIDI clips\n * use SoundFont samples instead of PolySynth synthesis. */\n soundFontCache?: SoundFontCache;\n /** Disable the automatic stop when the cursor reaches the end of the\n * longest track — the transport rolls until an explicit stop/pause\n * (DAW-style). The multitrack view then draws the timeline as wide as its\n * container, as `<WaveformViewOptions fillViewport>` does. Recording\n * sessions suppress the auto-stop automatically, so most recording UIs\n * don't need this. A provider option, not a view option: the animation\n * loop and `seekTo` follow it. */\n indefinitePlayback?: boolean;\n /** Desired AudioContext sample rate. Creates a cross-browser AudioContext at\n * this rate via standardized-audio-context. Pre-computed peaks (.dat files)\n * render instantly when they match. On mismatch, falls back to worker. */\n sampleRate?: number;\n /** Factory for a custom PlayoutAdapter. When omitted, the Tone.js engine\n * (@waveform-playlist/playout) is dynamically imported — so a custom adapter\n * lets a consumer use neither @waveform-playlist/playout nor tone. Called once\n * per engine build; the provider owns and disposes the returned instance.\n * Read when an engine is built: a new function identity builds nothing. */\n createAdapter?: () => PlayoutAdapter;\n children: ReactNode;\n}\n\nexport const WaveformPlaylistProvider: React.FC<WaveformPlaylistProviderProps> = (props) => {\n // A new arrangement object is a new playlist: everything below mounts again.\n const key = useArrangementKey(props.arrangement);\n return <ProviderOnArrangement key={key} {...props} />;\n};\n\n// Resting (non-playing) cursor positions display the raw time unchanged.\n// Latency compensation (outputLatency + lookAhead) models the gap between\n// the Transport's scheduling position and audible output — a property of\n// *playing*, not of position. A seeked/paused/stopped cursor has no audible\n// counterpart; the commanded position is the truth. During playback the\n// animation loop uses engine.getAudibleTime() instead.\nfunction toVisualTime(rawTime: number): number {\n return Number.isFinite(rawTime) ? Math.max(0, rawTime) : 0;\n}\n\n/** What a new engine is given and how the provider follows it; set after the hooks that own it. */\ninterface EngineFollowers {\n seed: (engine: PlaylistEngine) => void;\n follow: (engine: PlaylistEngine) => void;\n mirror: (state: EngineState) => void;\n}\n\nconst ProviderOnArrangement: React.FC<WaveformPlaylistProviderProps> = ({\n arrangement,\n mono = false,\n samplesPerPixel: initialSamplesPerPixel = 1024,\n zoomLevels,\n automaticScroll = false,\n theme: userThemeProp,\n annotationStore,\n annotationList,\n effects,\n trackEffects,\n onReady,\n onError,\n soundFontCache,\n indefinitePlayback = false,\n sampleRate: sampleRateProp,\n createAdapter,\n children,\n}) => {\n const mergedTheme = useMergedTheme(userThemeProp);\n\n // Content-stable: an inline array is new on every render. The engine's\n // lifetime compares the levels by content too.\n const stableZoomLevels = useMemo(\n () => zoomLevels,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [zoomLevels?.join(',')]\n );\n\n // The annotations are the annotation store's (#867); the provider derives\n // what it publishes from it. Shared with the MediaElement provider (#769).\n const {\n getAnnotations,\n annotationLookup,\n annotationPreview,\n activeAnnotationId,\n activeAnnotationIdRef,\n setActiveAnnotationId,\n continuousPlay,\n continuousPlayRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationsValue,\n annotationOptionsValue,\n } = useAnnotationState({\n annotationStore,\n annotationList,\n });\n const {\n scrollContainerRef,\n setScrollContainer,\n isAutomaticScroll,\n isAutomaticScrollRef,\n setAutomaticScroll,\n } = useScrollFollow(automaticScroll);\n // Components register per-frame DOM updates here instead of running their\n // own rAF loops; the single loop below drives them all.\n const { registerFrameCallback, unregisterFrameCallback, runFrameCallbacks } = useFrameCallbacks();\n\n // State\n const [isPlaying, setIsPlaying] = useState(false);\n const [currentTime, setCurrentTime] = useState(0);\n // Bumped after every track-reorder DRAG interaction (committed or not) —\n // see bumpTrackReorderEpoch below for the full rationale.\n const [trackReorderEpoch, setTrackReorderEpoch] = useState(0);\n // Live track-reorder drag preview (view-level only; see the\n // \"Track Reordering\" section of packages/browser/CLAUDE.md). Set by\n // ClipInteractionProvider's onDragOver, cleared on drag end/cancel.\n // The committed order is untouched until drop.\n const [trackDragPreview, setTrackDragPreview] = useState<TrackDragPreview | null>(null);\n\n // Refs\n // Ref for animation loop access (avoids adding the prop to useCallback deps)\n const indefinitePlaybackRef = useRef(indefinitePlayback);\n indefinitePlaybackRef.current = indefinitePlayback;\n const isPlayingRef = useRef<boolean>(false);\n isPlayingRef.current = isPlaying;\n const playStartPositionRef = useRef<number>(0);\n const currentTimeRef = useRef<number>(0);\n // Visually-aligned playback time (see toVisualTime / getAudibleTime). The\n // animation loop updates this per frame. Pause/seek/stop paths sync it\n // explicitly so the static playhead reflects the commanded resting position.\n const visualTimeRef = useRef<number>(0);\n const soundFontCacheRef = useRef(soundFontCache);\n soundFontCacheRef.current = soundFontCache;\n // The adapter keeps ONE lookup for its whole life and calls it whenever it\n // builds a track. It reads the prop through a ref so that a new function\n // identity (an inline arrow) is not a reason to rebuild the engine (#752).\n const trackEffectsRef = useRef(trackEffects);\n trackEffectsRef.current = trackEffects;\n const resolveTrackEffects = useCallback(\n (trackId: string) => trackEffectsRef.current?.(trackId),\n []\n );\n // The latest committed callbacks (QG): read when they are called, so a new\n // identity builds nothing.\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n useLayoutEffect(() => {\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n });\n const playbackStartTimeRef = useRef<number>(0); // context.currentTime when playback started\n const audioStartPositionRef = useRef<number>(0); // Audio position when playback started\n const playbackEndTimeRef = useRef<number | null>(null); // Audio position where playback should stop (for selections)\n // Suppresses the engine 'stop' mirror (below) around provider-initiated\n // engine.stop() calls that immediately seek/restart playback in the same\n // synchronous block (play(), setSelection, reschedulePlayback). Without\n // this, the mirror's ref writes would race the restart's own writes and\n // briefly show the pre-restart position/isPlaying=false. Stop paths that\n // don't restart afterward don't need suppression — see the mirror's own\n // comment for why.\n const suppressEngineStopMirrorRef = useRef(false);\n // Provider-level ref for scroll-position math and animation loop pixel\n // calculation. Distinct from useZoomControls's internal ref (statechange guard).\n const samplesPerPixelRef = useRef<number>(initialSamplesPerPixel);\n // True while the bounded play in progress is the highlighted selection itself\n // (its start and end are the selection's). Set by play(). Selection playback\n // ignores continuous play; anything else, including an annotation clicked\n // while a selection is highlighted elsewhere, follows it.\n const isSelectionPlayRef = useRef(false);\n // Incremented by every play(), stop() and pause(). A play() that has been\n // waiting on engine.init() compares it afterwards: if it moved, the user has\n // since asked for something else and the older play must not start.\n const playRequestIdRef = useRef(0);\n\n const { animationFrameRef, startAnimationFrameLoop, stopAnimationFrameLoop } =\n useAnimationFrameLoop();\n\n // A build that fails while playback shows as running (a rebuild began\n // during playback and queued its resume, which the failure dropped): no\n // engine is coming, so playback shows stopped where it was. Nothing starts\n // by itself after a later build (maintainer, D3).\n const onBuildFailure = useCallback(() => {\n if (!isPlayingRef.current) return;\n setIsPlaying(false);\n stopAnimationFrameLoop();\n visualTimeRef.current = toVisualTime(currentTimeRef.current);\n setCurrentTime(currentTimeRef.current);\n }, [stopAnimationFrameLoop]);\n\n // The engine's own state is mirrored by the hooks below, which need the\n // engine ref first; these three reach them through a ref set after them.\n const followersRef = useRef<EngineFollowers | null>(null);\n const seedEngine = useCallback(\n (engine: PlaylistEngine) => followersRef.current?.seed(engine),\n []\n );\n const onEngine = useCallback(\n (engine: PlaylistEngine) => followersRef.current?.follow(engine),\n []\n );\n const onEngineState = useCallback(\n (state: EngineState) => followersRef.current?.mirror(state),\n []\n );\n\n // The engine around the arrangement: built on mount and when `effects` or\n // the zoom levels change, disposed in every cleanup (#812). A track edit\n // builds nothing.\n const {\n engineRef,\n adapterRef,\n engineEpoch,\n bumpEngineEpoch,\n isEngineAttached,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n sampleRate,\n isSampleRateKnown,\n } = useEngineLifetime({\n arrangement,\n createAdapter,\n effects,\n resolveTrackEffects,\n soundFontCacheRef,\n sampleRateProp,\n zoomLevels,\n samplesPerPixelRef,\n playbackEndTimeRef,\n seedEngine,\n onEngine,\n onEngineState,\n stopAnimationFrameLoop,\n onErrorRef,\n onBuildFailure,\n });\n // For the animation loop and the zoom scroll math, which run outside render.\n const sampleRateRef = useRef(sampleRate);\n sampleRateRef.current = sampleRate;\n\n // Custom hooks — engine-owned state delegated to hooks with onEngineState() pattern\n const { timeFormat, setTimeFormat } = useTimeFormat();\n const zoom = useZoomControls({ engineRef, initialSamplesPerPixel });\n const { samplesPerPixel, onEngineState: onZoomEngineState } = zoom;\n const volume = useMasterVolume({ engineRef, initialVolume: 1.0 });\n const {\n masterVolume,\n setMasterVolume,\n masterVolumeRef,\n onEngineState: onVolumeEngineState,\n } = volume;\n const {\n selectionStart,\n selectionEnd,\n setSelection: setSelectionEngine,\n selectionStartRef,\n selectionEndRef,\n onEngineState: onSelectionEngineState,\n } = useSelectionState({ engineRef });\n const {\n isLoopEnabled,\n loopStart,\n loopEnd,\n setLoopEnabled,\n setLoopRegion,\n clearLoopRegion,\n isLoopEnabledRef,\n loopStartRef,\n loopEndRef,\n onEngineState: onLoopEngineState,\n } = useLoopState({ engineRef });\n const {\n selectedTrackId,\n setSelectedTrackId: setSelectedTrackIdControl,\n onEngineState: onSelectedTrackEngineState,\n selectedTrackIdRef,\n } = useSelectedTrack({ engineRef });\n\n // Everything the provider publishes about the tracks, derived from the\n // arrangement during render and never written back (#812).\n const baseScale = useMemo(\n () => Math.min(...(stableZoomLevels ?? [256, 512, 1024, 2048, 4096, 8192])),\n [stableZoomLevels]\n );\n const view = useArrangementView(arrangement, {\n samplesPerPixel,\n mono,\n baseScale,\n placeholderSampleRate: isSampleRateKnown ? sampleRate : null,\n });\n const { tracks, duration } = view;\n // The animation loop and `seekTo` read the timeline end from here, so that\n // neither changes identity when it moves: `seekTo` and `play` are in the\n // controls value, which must not follow `duration` (#767). Written during\n // render, like `isPlayingRef`, so that a child that calls `seekTo` from a\n // layout effect of the same commit already gets the new end.\n const durationRef = useRef(duration);\n durationRef.current = duration;\n\n const { isReady, refusePlayBeforeFirstReady } = useReadyOnce({\n isEngineAttached,\n arrangement,\n onReadyRef,\n onErrorRef,\n trackCount: tracks.length,\n duration,\n });\n\n // A trim drag in progress (#812): moves go to this source, and only the\n // dragged clip's view follows them. The tracks change once, on release.\n const { trimPreview, trimPreviewPeaks } = useTrimPreview({\n tracks,\n peaksOptions: view.peaksOptions,\n peaksCacheRef: view.peaksCacheRef,\n });\n\n // The mixer setters, reorder, undo, redo and the recording session: all\n // through the arrangement, engine or not.\n const editing = useArrangementEditing(arrangement);\n const { recordingActiveRef } = editing;\n\n // Cross-hook concern: reads selection refs to set loop region\n const setLoopRegionFromSelection = useCallback(() => {\n const start = selectionStartRef.current ?? 0;\n const end = selectionEndRef.current ?? 0;\n if (start !== end && end > start) {\n setLoopRegion(start, end);\n }\n }, [setLoopRegion, selectionStartRef, selectionEndRef]);\n\n // Adjust scroll position proportionally when zoom changes\n useEffect(() => {\n if (!scrollContainerRef.current || duration === 0) return;\n\n const container = scrollContainerRef.current;\n const oldSamplesPerPixel = samplesPerPixelRef.current;\n const newSamplesPerPixel = samplesPerPixel;\n\n if (oldSamplesPerPixel === newSamplesPerPixel) return;\n\n // Calculate the current center time in the viewport\n const containerWidth = container.clientWidth;\n const currentScrollLeft = container.scrollLeft;\n const centerPixel = currentScrollLeft + containerWidth / 2;\n const sr = sampleRateRef.current;\n const centerTime = (centerPixel * oldSamplesPerPixel) / sr;\n\n // Calculate new scroll position to keep the same center time\n const newCenterPixel = (centerTime * sr) / newSamplesPerPixel;\n const newScrollLeft = Math.max(0, newCenterPixel - containerWidth / 2);\n\n container.scrollLeft = newScrollLeft;\n samplesPerPixelRef.current = newSamplesPerPixel;\n }, [samplesPerPixel, duration, scrollContainerRef]);\n\n // Forward late-arriving / swapped SoundFontCache to the live adapter so\n // MIDI tracks upgrade from PolySynth without an engine rebuild. Before the\n // first adapter exists this runs against null, which the helper ignores;\n // the build reads the cache from its ref.\n useEffect(() => {\n syncSoundFontCacheToAdapter(adapterRef.current, soundFontCache);\n }, [soundFontCache, adapterRef]);\n\n // A loaded clip with nothing to draw from is almost always a wiring\n // mistake. A clip still loading is not in `tracks`, so it is never reported.\n useEffect(() => {\n for (const track of tracks) {\n for (const clip of track.clips) {\n if (!clip.audioBuffer && !clip.waveformData && !clip.midiNotes) {\n console.warn(`[waveform-playlist] Clip \"${clip.id}\" has no audio data or waveform data`);\n }\n }\n }\n }, [tracks]);\n\n // Audio clock from the adapter's own AudioContext (#510 — replaces tone's\n // getContext()). Stable; reads a ref so identity never changes.\n const getAudioContextTime = useCallback(\n () => adapterRef.current?.audioContext.currentTime ?? 0,\n [adapterRef]\n );\n\n // Returns current playback time from engine (auto-wraps at loop boundaries).\n // Falls back to manual calculation when engine is unavailable.\n const getPlaybackTimeFallbackWarnedRef = useRef(false);\n const getPlaybackTime = useCallback(() => {\n if (engineRef.current) {\n return engineRef.current.getCurrentTime();\n }\n // Fallback: manual calculation (does not handle loop wrapping)\n if (!getPlaybackTimeFallbackWarnedRef.current) {\n getPlaybackTimeFallbackWarnedRef.current = true;\n console.warn(\n '[waveform-playlist] getPlaybackTime called without engine. ' +\n 'Falling back to manual elapsed time (loop wrapping will not work).'\n );\n }\n const elapsed = getAudioContextTime() - (playbackStartTimeRef.current ?? 0);\n return (audioStartPositionRef.current ?? 0) + elapsed;\n }, [getAudioContextTime, engineRef]);\n\n // Pair-write helper for the dual-ref pattern. Storage stays raw on\n // `currentTimeRef`; display gets the guard-clamped raw version on `visualTimeRef`\n // (compensation happens in the animation loop via engine.getAudibleTime() while playing).\n // Use this at every pause/seek/stop/loop site — never assign one ref alone\n // (browser/CLAUDE.md: \"Display uses visualTimeRef\").\n const setCurrentTimeRefs = useCallback((rawTime: number) => {\n currentTimeRef.current = rawTime;\n visualTimeRef.current = toVisualTime(rawTime);\n }, []);\n\n // Read the engine's scheduler lookahead (Tone adapter ~0.1s, native 0).\n // Exposed through PlaybackRefsContextValue so consumers (e.g., recording\n // live preview) compute audible-latency from the same source as the playhead.\n const getLookAhead = useCallback((): number => {\n return engineRef.current?.lookAhead ?? 0;\n }, [engineRef]);\n\n const getOutputLatency = useCallback((): number => {\n const audioCtx = adapterRef.current?.audioContext;\n return audioCtx && 'outputLatency' in audioCtx ? (audioCtx as AudioContext).outputLatency : 0;\n }, [adapterRef]);\n\n // Engine-initiated stop mirror (final-review CRITICAL 1, #608 follow-up).\n // PlaylistEngine self-stops when a bounded play(start, end) completes on\n // an adapter that reports onPlaybackEnded (Tone) — see engine CLAUDE.md\n // \"onPlaybackEnded hook\". That self-stop rewinds the engine's own current\n // time to playStartPosition BEFORE the rAF loop's own end-of-playback\n // checks (below) can observe it, so the loop's `time >= playbackEndTimeRef`\n // / `time >= duration` comparisons never fire — React isPlaying stays\n // true and the loop spins forever at the rewound position. Mirroring the\n // engine's 'stop' event makes React authoritative-from-engine for ANY\n // engine-initiated stop, closing that race. The engine already rewound\n // its own time (`_currentTime = _playStartPosition`) — we only mirror\n // that into React's refs/state, we never seek() again here.\n //\n // Suppressed via suppressEngineStopMirrorRef around provider-initiated\n // engine.stop() calls that immediately seek/restart playback (play(),\n // setSelection, reschedulePlayback) — those already set the correct target\n // position themselves; an unguarded mirror would clobber it mid-transition\n // with the pre-restart position. Stop paths that terminate playback\n // (stop(), the rAF loop's own annotation/selection/duration-end branches)\n // don't need suppression: they either write the identical value the\n // mirror would (both read _playStartPosition), or run their own\n // setCurrentTimeRefs call synchronously right after this listener, which —\n // as plain refs, not batched state — simply overwrites the mirror's write\n // with no other code observing the transient value in between.\n const mirrorEngineStop = useCallback(\n (engine: PlaylistEngine) => {\n if (suppressEngineStopMirrorRef.current) return;\n setIsPlaying(false);\n stopAnimationFrameLoop();\n // The engine rewound to where its play began. For the selection,\n // return to the selection start instead (see play()): a play that\n // resumed part-way must not leave the cursor inside the selection.\n let stoppedAt = engine.getCurrentTime();\n if (isSelectionPlayRef.current) {\n stoppedAt = playStartPositionRef.current;\n engine.seek(stoppedAt);\n }\n setCurrentTimeRefs(stoppedAt);\n setCurrentTime(stoppedAt);\n },\n [stopAnimationFrameLoop, setCurrentTimeRefs]\n );\n\n // What a new engine is given and how the provider follows it. The engine\n // owns selection, loop, selected track, zoom and master volume; the hooks\n // mirror them from `statechange`. Seeded so that a fresh engine does not\n // put them back to defaults.\n useLayoutEffect(() => {\n const mirror = (state: EngineState) => {\n onSelectionEngineState(state);\n onLoopEngineState(state);\n onSelectedTrackEngineState(state);\n onZoomEngineState(state);\n onVolumeEngineState(state);\n };\n followersRef.current = {\n seed: (engine) => {\n engine.setSelection(selectionStartRef.current ?? 0, selectionEndRef.current ?? 0);\n engine.setLoopRegion(loopStartRef.current ?? 0, loopEndRef.current ?? 0);\n if (isLoopEnabledRef.current) engine.setLoopEnabled(true);\n engine.setMasterVolume(masterVolumeRef.current ?? 1.0);\n if (selectedTrackIdRef.current) engine.selectTrack(selectedTrackIdRef.current);\n },\n follow: (engine) => {\n engine.on('statechange', mirror);\n engine.on('stop', () => mirrorEngineStop(engine));\n },\n mirror,\n };\n });\n\n // Animation loop\n const startAnimationLoop = useCallback(() => {\n const updateTime = () => {\n // Get current time from engine (auto-wraps at loop boundaries via Transport.seconds)\n const time = getPlaybackTime();\n currentTimeRef.current = time;\n\n // Compute visual time once — all visual consumers use this same value.\n // engine.getAudibleTime() subtracts outputLatency (hardware DAC delay)\n // and adapter.lookAhead (Tone.js Transport runs ~100ms ahead of audible),\n // holding at the play-start position during the pre-roll window. Native\n // adapters report lookAhead 0, so this is a near no-op there.\n const visualRaw = engineRef.current ? engineRef.current.getAudibleTime() : time;\n const visualTime = Number.isFinite(visualRaw) ? Math.max(0, visualRaw) : 0;\n visualTimeRef.current = visualTime;\n\n // Drive registered per-frame callbacks BEFORE stop checks so the\n // final frame renders at the correct stop position (not one frame behind).\n const sr = sampleRateRef.current;\n const spp = samplesPerPixelRef.current;\n const frameData: FrameData = {\n time,\n visualTime,\n sampleRate: sr,\n samplesPerPixel: spp,\n };\n runFrameCallbacks(frameData);\n\n // Annotations. Playing the selection takes continuous play out of the\n // picture: playback is not cut at annotation boundaries, whichever way\n // the toggle is set, and the active annotation still follows the\n // playhead. On the frame that reaches a bounded play's end the\n // highlight is held: the end check below stops there, and it must not\n // move on to the next annotation first.\n const activeAnnotationEnded = followAnnotations({\n annotations: getAnnotations(),\n lookup: annotationLookup,\n time,\n activeId: activeAnnotationIdRef.current,\n followOnly: continuousPlayRef.current || isSelectionPlayRef.current,\n holdHighlight: playbackEndTimeRef.current !== null && time >= playbackEndTimeRef.current,\n setActiveAnnotationId,\n });\n if (activeAnnotationEnded) {\n // Continuous play off: stop at the end of the active annotation and\n // return the cursor to where playback started.\n if (engineRef.current) {\n engineRef.current.stop();\n }\n setIsPlaying(false);\n setCurrentTimeRefs(playStartPositionRef.current);\n setCurrentTime(playStartPositionRef.current);\n return;\n }\n\n // Automatic scroll: the shared visual time, so it lines up with the playhead.\n if (isAutomaticScrollRef.current && scrollContainerRef.current && durationRef.current > 0) {\n centrePlayhead(scrollContainerRef.current, visualTime, sr, spp);\n }\n\n // Check if we've reached the playback end time (for selection playback)\n if (playbackEndTimeRef.current !== null && time >= playbackEndTimeRef.current) {\n // Stop playback at selection end (selection playback is separate from looping)\n if (engineRef.current) {\n engineRef.current.stop();\n }\n setIsPlaying(false);\n // The selection finishing returns the cursor to the selection's start,\n // the same as when the engine ends the play itself (see the stop\n // mirror): which of the two notices the end first is a race on the\n // Tone path, and they must not disagree. Other bounded plays leave the\n // cursor at their end.\n const endCursor = isSelectionPlayRef.current\n ? playStartPositionRef.current\n : playbackEndTimeRef.current;\n setCurrentTimeRefs(endCursor);\n setCurrentTime(endCursor);\n playbackEndTimeRef.current = null; // Clear the end time\n return;\n }\n\n // Loop is handled natively by Tone.js Transport (Transport.loop/loopStart/loopEnd).\n // Transport.seconds auto-wraps at loop boundaries, so getPlaybackTime() returns\n // the correct position without manual detection here.\n\n // Auto-stop at the end of the timeline (player-style default), unless:\n // - indefinitePlayback: the transport rolls until an explicit\n // stop/pause (DAW-style, matching dawcore's indefinite-playback), or\n // - a recording session is active: overdub playback must run past the\n // end of existing material (#589/#590).\n // Explicit ends (selection playback, annotation boundaries) are\n // handled above regardless.\n if (\n time >= durationRef.current &&\n !indefinitePlaybackRef.current &&\n !recordingActiveRef.current\n ) {\n // Stop playback - inline to avoid circular dependency\n if (engineRef.current) {\n engineRef.current.stop();\n }\n setIsPlaying(false);\n setCurrentTimeRefs(playStartPositionRef.current);\n setCurrentTime(playStartPositionRef.current);\n setActiveAnnotationId(null);\n return;\n }\n startAnimationFrameLoop(updateTime);\n };\n startAnimationFrameLoop(updateTime);\n }, [\n setActiveAnnotationId,\n startAnimationFrameLoop,\n getPlaybackTime,\n setCurrentTimeRefs,\n annotationLookup,\n // Refs and a stable function from the shared provider hooks: they never\n // change, and are listed because the linter cannot see that.\n getAnnotations,\n activeAnnotationIdRef,\n continuousPlayRef,\n isAutomaticScrollRef,\n scrollContainerRef,\n runFrameCallbacks,\n engineRef,\n recordingActiveRef,\n ]);\n\n const stopAnimationLoop = stopAnimationFrameLoop;\n\n // Two jobs, during playback only:\n // - restart the animation loop when playback starts and if its closure\n // changes, so the running loop always has current values (its\n // dependencies are stable today; the timeline end is read from\n // `durationRef`, so a duration change does not restart it);\n // - when continuous play is switched ON, reschedule the audio without an end,\n // so it runs past the annotation it was bounded to.\n // The reschedule is tied to that false -> true transition, not to the current\n // value: this effect also runs when playback starts and when the loop is\n // rebuilt, and with continuous play already on those used to stop and restart\n // the audio as well (every Play started twice; a duration change restarted it).\n //\n // While the selection is what is playing, continuous play has no effect at\n // all: the loop does not cut playback at annotation boundaries (see the loop)\n // and switching the toggle reschedules nothing.\n const prevContinuousPlayRef = useRef(continuousPlay);\n useEffect(() => {\n const continuousPlayTurnedOn =\n continuousPlay && !prevContinuousPlayRef.current && !isSelectionPlayRef.current;\n prevContinuousPlayRef.current = continuousPlay;\n\n const reschedulePlayback = async () => {\n if (isPlaying && animationFrameRef.current && engineRef.current) {\n if (continuousPlayTurnedOn) {\n const currentPos = currentTimeRef.current;\n\n // Stop current playout (which may have duration limit + pause callback).\n // Suppressed: this immediately restarts playback below — see\n // suppressEngineStopMirrorRef declaration.\n suppressEngineStopMirrorRef.current = true;\n engineRef.current.stop();\n suppressEngineStopMirrorRef.current = false;\n stopAnimationLoop();\n\n const timeNow = getAudioContextTime();\n playbackStartTimeRef.current = timeNow;\n audioStartPositionRef.current = currentPos;\n\n // What continuous play removes is the end of the annotation being\n // played. Only an end that IS the active annotation's end is dropped\n // (the loop's own end check with it, or it would stop playback there\n // anyway). Any other bounded play, such as a programmatic\n // play(start, duration), keeps its end.\n const boundedEnd = playbackEndTimeRef.current;\n const activeId = activeAnnotationIdRef.current;\n const activeAnnotation = activeId\n ? annotationLookup.byId(getAnnotations(), activeId)\n : undefined;\n const endsWithAnnotation =\n boundedEnd !== null &&\n activeAnnotation !== undefined &&\n Math.abs(boundedEnd - activeAnnotation.end) < 1e-6;\n const endTime = endsWithAnnotation ? null : boundedEnd;\n playbackEndTimeRef.current = endTime;\n engineRef.current.play(currentPos, endTime ?? undefined);\n startAnimationLoop();\n } else {\n // Nothing about the audio changed: only refresh the loop.\n stopAnimationLoop();\n startAnimationLoop();\n }\n }\n };\n\n reschedulePlayback().catch((err) => {\n console.warn('[waveform-playlist] Failed to reschedule playback:', err);\n setIsPlaying(false);\n stopAnimationLoop();\n });\n }, [\n continuousPlay,\n isPlaying,\n startAnimationLoop,\n stopAnimationLoop,\n animationFrameRef,\n getAudioContextTime,\n annotationLookup,\n getAnnotations,\n activeAnnotationIdRef,\n engineRef,\n ]);\n\n // Start a play that waited for an engine: playback a rebuild interrupted, or a\n // play() asked for while one was being built (#675). Runs when a freshly\n // built engine is assigned (and when play() asks for another run).\n useEffect(() => {\n const resumePlayback = async () => {\n // engineRef is null while a rebuild is in flight — the pending play\n // stays queued until the run triggered by engineEpoch.\n const engine = engineRef.current;\n const request = pendingResumeRef.current;\n if (request && engine) {\n if (!audioInitializedRef.current) {\n // The request STAYS in the slot across this await, so whatever\n // happens meanwhile is unambiguous: stop()/pause()/a newer play()\n // replace or clear it, and if the engine is replaced, the new\n // engine's own run of this effect finds it still waiting.\n await engine.init();\n if (engineRef.current !== engine || pendingResumeRef.current !== request) {\n return;\n }\n audioInitializedRef.current = true;\n }\n\n // Read the request only now: setSelection may have re-pointed it (in\n // place, keeping its identity) while init() was pending.\n const { position, endTime } = request;\n playbackStartTimeRef.current = getAudioContextTime();\n audioStartPositionRef.current = position;\n\n pendingResumeRef.current = null;\n engine.play(position, endTime);\n setIsPlaying(true);\n startAnimationLoop();\n }\n };\n\n resumePlayback().catch((err) => {\n console.warn('[waveform-playlist] Failed to resume playback on the new engine:', err);\n setIsPlaying(false);\n stopAnimationLoop();\n });\n }, [\n engineEpoch,\n startAnimationLoop,\n stopAnimationLoop,\n getAudioContextTime,\n engineRef,\n pendingResumeRef,\n audioInitializedRef,\n ]);\n\n // Playback controls\n const play = useCallback(\n async (startTime?: number, playDuration?: number) => {\n // Before the first ready of this mount nothing plays and nothing is\n // queued (#812): no ref, no request id, no pending resume is touched.\n if (refusePlayBeforeFirstReady()) return;\n const actualStartTime = startTime ?? currentTimeRef.current;\n const endTime = playDuration !== undefined ? actualStartTime + playDuration : undefined;\n\n // Is this the highlighted selection being played?\n const selectionStartNow = selectionStartRef.current ?? 0;\n const selectionEndNow = selectionEndRef.current ?? 0;\n // It may start inside the selection (resuming after a pause) but always\n // runs to the selection's end.\n isSelectionPlayRef.current =\n endTime !== undefined &&\n selectionEndNow > selectionStartNow &&\n actualStartTime >= selectionStartNow - 1e-6 &&\n actualStartTime < selectionEndNow &&\n Math.abs(endTime - selectionEndNow) < 1e-6;\n // Where a Stop (or the play finishing) returns the cursor. For the\n // selection that is its start even when this play resumed part-way in:\n // otherwise the cursor would land back inside the selection and every\n // later Play would repeat only the tail.\n const playStartPosition = isSelectionPlayRef.current ? selectionStartNow : actualStartTime;\n const requestId = ++playRequestIdRef.current;\n\n const engine = engineRef.current;\n if (!engine) {\n // The engine is being built. Queue the play: the\n // resume effect starts it when the new engine is assigned. isPlaying\n // stays false until audio actually starts (#675).\n if (engineBuildInFlightRef.current) {\n playStartPositionRef.current = playStartPosition;\n setCurrentTimeRefs(actualStartTime);\n playbackEndTimeRef.current = endTime ?? null;\n pendingResumeRef.current = { position: actualStartTime, endTime };\n }\n return;\n }\n // A direct play supersedes anything queued for a rebuild.\n pendingResumeRef.current = null;\n\n playStartPositionRef.current = playStartPosition;\n\n // Update currentTimeRef to match the actual start position\n // This ensures the animation loop starts from the correct position\n setCurrentTimeRefs(actualStartTime);\n\n // Stop existing playback and animation loop before restarting.\n // engine.stop() resets engine._currentTime to _playStartPosition (could be 0)\n // and sets _isPlaying=false. AnimatedPlayhead's RAF may fire during this\n // window and call engine.getCurrentTime() which would return 0.\n // The seek() immediately sets _currentTime to the intended start position,\n // preventing the cursor flash.\n // Suppressed: seek()+play() below immediately re-establish the correct\n // position — see suppressEngineStopMirrorRef declaration.\n suppressEngineStopMirrorRef.current = true;\n engine.stop();\n suppressEngineStopMirrorRef.current = false;\n engine.seek(actualStartTime);\n stopAnimationLoop();\n\n // Record timing for accurate position tracking using the adapter's AudioContext\n const startTimeNow = getAudioContextTime();\n playbackStartTimeRef.current = startTimeNow;\n audioStartPositionRef.current = actualStartTime;\n\n // Set playback end time if playing with duration (e.g., selection playback)\n playbackEndTimeRef.current = endTime ?? null;\n\n // Don't set up playback complete callback for annotations\n // The animation loop handles stopping at annotation boundaries\n // This avoids callback timing issues when switching between annotations\n\n // Ensure AudioContext is resumed (requires user gesture, no-op after first call).\n // Guarded by ref so subsequent plays skip the await entirely.\n if (!audioInitializedRef.current) {\n await engine.init();\n if (playRequestIdRef.current !== requestId) {\n // stop(), pause() or a newer play() happened while init() was\n // pending. This request is obsolete — starting it now would play\n // after the user's Stop, or over their newer request.\n return;\n }\n if (engineRef.current !== engine) {\n // A rebuild disposed this engine while init() was pending. Hand the\n // play to its replacement instead of starting a dead engine — if\n // there is one: after a failed build nothing is coming, and a\n // stranded request would fire on some later, unrelated rebuild.\n if (engineRef.current) {\n pendingResumeRef.current = { position: actualStartTime, endTime };\n // Already assigned, so its epoch run has passed — ask for another.\n bumpEngineEpoch();\n } else if (engineBuildInFlightRef.current) {\n pendingResumeRef.current = { position: actualStartTime, endTime };\n }\n return;\n }\n audioInitializedRef.current = true;\n }\n\n try {\n engine.play(actualStartTime, endTime);\n } catch (err) {\n console.warn('[waveform-playlist] Playback failed to start:', err);\n // The play never started, so the UI must not keep saying it is\n // playing. The engine.stop() above is suppressed (the mirror would\n // otherwise clear the flag before the seek that follows it), so\n // nothing else turns isPlaying off on this path: a restart that\n // throws — a seek or an annotation click while playing — would\n // leave the transport showing playback that is not running (#827).\n setIsPlaying(false);\n stopAnimationLoop();\n return;\n }\n setIsPlaying(true);\n startAnimationLoop();\n },\n [\n startAnimationLoop,\n stopAnimationLoop,\n setCurrentTimeRefs,\n getAudioContextTime,\n selectionStartRef,\n selectionEndRef,\n engineRef,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n bumpEngineEpoch,\n refusePlayBeforeFirstReady,\n ]\n );\n\n const pause = useCallback(() => {\n // Cancels a play queued behind an engine rebuild or parked in init().\n pendingResumeRef.current = null;\n playRequestIdRef.current += 1;\n\n // With no engine (a rebuild is in flight) there is nothing to pause, but\n // the UI state must still change: playback that was running when the\n // rebuild began leaves isPlaying true until its resume, which was just\n // cancelled. Hold the cursor where it is.\n const engine = engineRef.current;\n // Get current position from engine (auto-wraps at loop boundaries)\n const pauseTime = engine ? getPlaybackTime() : currentTimeRef.current;\n\n engine?.pause();\n setIsPlaying(false);\n stopAnimationLoop();\n\n // Update to the calculated pause position\n setCurrentTimeRefs(pauseTime);\n setCurrentTime(pauseTime);\n }, [stopAnimationLoop, getPlaybackTime, setCurrentTimeRefs, engineRef, pendingResumeRef]);\n\n const stop = useCallback(() => {\n // Cancels a play queued behind an engine rebuild or parked in init().\n pendingResumeRef.current = null;\n playRequestIdRef.current += 1;\n\n // No engine while a rebuild is in flight — the UI state still resets\n // (see pause()).\n engineRef.current?.stop();\n // The engine rewinds to where ITS play began; for a selection resumed\n // part-way that is not the selection start. Keep the two in step.\n if (isSelectionPlayRef.current) engineRef.current?.seek(playStartPositionRef.current);\n setIsPlaying(false);\n stopAnimationLoop();\n\n // Return cursor to where playback started (Audacity-style)\n setCurrentTimeRefs(playStartPositionRef.current);\n setCurrentTime(playStartPositionRef.current);\n setActiveAnnotationId(null);\n }, [stopAnimationLoop, setActiveAnnotationId, setCurrentTimeRefs, engineRef, pendingResumeRef]);\n\n // Seek to a specific time - works whether playing or stopped\n const seekTo = useCallback(\n (time: number) => {\n // Clamp to the audio. Where the transport may run past its end (an\n // `indefinitePlayback` provider, a recording session) a finite time\n // past the end is a valid position: Skip Backward from 30 s over 10 s\n // of material must land at 25 s, not at 10 s. An infinite one\n // (Fast Forward) still means the end of the audio.\n const pastEndAllowed =\n Number.isFinite(time) && (indefinitePlaybackRef.current || recordingActiveRef.current);\n const upperLimit = pastEndAllowed ? Infinity : durationRef.current;\n const clampedTime = Math.max(0, Math.min(time, upperLimit));\n\n // Update the current time state\n setCurrentTimeRefs(clampedTime);\n setCurrentTime(clampedTime);\n\n // If currently playing, restart at the new position. play() handles\n // stop+seek+restart internally, and with the engine mid-rebuild it\n // re-points the play that is waiting for the new engine (#688: the\n // transport buttons are `seekTo` only, and used to do this themselves).\n if (isPlayingRef.current) {\n play(clampedTime);\n }\n },\n [play, setCurrentTimeRefs, recordingActiveRef]\n );\n\n // @dnd-kit/react's Feedback and OptimisticSortingPlugin sortable plugins\n // perform raw, React-bypassing DOM node moves (insertAdjacentElement /\n // replaceWith) as part of their live drag-preview and collision-commit\n // mechanics — confirmed via MutationObserver instrumentation to physically\n // relocate the React-owned track-controls row during a track-reorder drag,\n // leaving its parent/nextSibling different from what React's fiber tree\n // still believes. That desync is permanent for the session: every LATER\n // React-driven reorder (button OR drag) computes correct data but silently\n // fails to patch the DOM for these rows. `useTrackReorderHandle` already\n // sets `feedback: 'move'` to avoid the placeholder-splice half of this (see\n // its comment), but OptimisticSortingPlugin's own `reorder()` DOM splice\n // fires independently on any drag that commits a real index change and\n // isn't configurable away without losing live index tracking. Bumping this\n // epoch forces the view's track-controls part to re-key (remount) its\n // slots after every track-reorder drag ends — committed or canceled, since\n // corruption can occur before a final index is even decided — discarding\n // any corrupted fiber state so the NEXT reorder (drag or button) starts\n // from a clean DOM. Called from ClipInteractionProvider's onDragEnd.\n const bumpTrackReorderEpoch = useCallback(() => {\n setTrackReorderEpoch((epoch) => epoch + 1);\n }, []);\n\n // Selection — wraps hook setter with playback side-effects (provider concern).\n const setSelection = useCallback(\n (start: number, end: number) => {\n setSelectionEngine(start, end);\n setCurrentTimeRefs(start);\n setCurrentTime(start);\n\n // What playback does from here, if it is running or queued. A new\n // highlighted range is played start to end, as the Play button would\n // (looping on: open-ended, the transport's loop handles the bounds). A\n // plain cursor move carries on open-ended from the new position.\n const playsRange = end > start && !(isLoopEnabledRef.current ?? false);\n const endTime = playsRange ? end : undefined;\n\n // Whatever bounded play was running or queued (a selection, an\n // annotation) is over, so nothing of it may outlive it. Its end stopped\n // playback at once when the new position was past it; its active\n // annotation did the same through the loop's stop-at-annotation-end;\n // and its play-start position is where a later Stop would have\n // returned the cursor.\n const replaceBoundedPlay = () => {\n playbackEndTimeRef.current = endTime ?? null;\n isSelectionPlayRef.current = playsRange;\n playStartPositionRef.current = start;\n if (activeAnnotationIdRef.current !== null) setActiveAnnotationId(null);\n };\n\n // A play queued behind an engine rebuild follows the selection too. The\n // request is changed IN PLACE: a resume parked in init() recognises its\n // request by identity, and a new object would strand it (#675, rule 4).\n const queued = pendingResumeRef.current;\n if (queued) {\n // The queued play will start it; restarting the engine here as well\n // would start it twice.\n queued.position = start;\n queued.endTime = endTime;\n replaceBoundedPlay();\n return;\n }\n\n if (!isPlayingRef.current) {\n // Nothing is playing: whatever play ended earlier no longer says\n // anything about this position. Without this, Stop (Escape) pressed\n // while stopped sent the cursor back to an old play's start.\n isSelectionPlayRef.current = false;\n playStartPositionRef.current = start;\n return;\n }\n\n if (engineRef.current) {\n // Stop + seek before restarting playback from selection start.\n // engine.stop() resets _currentTime and _isPlaying, creating a window\n // where getCurrentTime() returns wrong value. seek() immediately\n // corrects _currentTime so any RAF firing in between reads the\n // intended position. engine.play() then restarts everything.\n // Suppressed: seek()+play() below immediately re-establish the correct\n // position — see suppressEngineStopMirrorRef declaration. Unguarded,\n // the mirror would also flip isPlaying to false with nothing here to\n // set it back true (isPlaying was already true on entry to this branch).\n suppressEngineStopMirrorRef.current = true;\n engineRef.current.stop();\n suppressEngineStopMirrorRef.current = false;\n engineRef.current.seek(start);\n replaceBoundedPlay();\n // This is a new play: say when and where it started, as `play()` does.\n // `useEngineRefs()` hands these two to consumers (a custom readout or\n // playhead), and until 2026-11 they kept describing the play this one\n // replaced.\n playbackStartTimeRef.current = getAudioContextTime();\n audioStartPositionRef.current = start;\n engineRef.current.play(start, endTime);\n }\n },\n [\n setSelectionEngine,\n setCurrentTimeRefs,\n setActiveAnnotationId,\n isLoopEnabledRef,\n activeAnnotationIdRef,\n getAudioContextTime,\n engineRef,\n pendingResumeRef,\n ]\n );\n\n // Context values, grouped by how often their fields change (#768). A\n // subscription is to a whole value, so a field belongs with the fields that\n // change when it does: a component that reads `sampleRate` must not render\n // on every step of a volume slider.\n\n // Changes on play, pause and stop only. Not on a seek: the resting cursor\n // position has its own context (#740).\n const isPlayingValue: IsPlayingContextValue = useMemo(() => ({ isPlaying }), [isPlaying]);\n\n // Refs and stable functions: these two values never change. The first is\n // the part the MediaElement provider has too (#688).\n const refsValue: PlaybackRefsContextValue = useMemo(\n () => ({\n currentTimeRef,\n visualTimeRef,\n registerFrameCallback,\n unregisterFrameCallback,\n }),\n [currentTimeRef, visualTimeRef, registerFrameCallback, unregisterFrameCallback]\n );\n\n const engineRefsValue: EngineRefsContextValue = useMemo(\n () => ({\n playbackStartTimeRef,\n audioStartPositionRef,\n getPlaybackTime,\n getAudioContextTime,\n getLookAhead,\n getOutputLatency,\n playoutRef: engineRef,\n }),\n [\n playbackStartTimeRef,\n audioStartPositionRef,\n getPlaybackTime,\n getAudioContextTime,\n getLookAhead,\n getOutputLatency,\n engineRef,\n ]\n );\n\n const loopValue: LoopContextValue = useMemo(\n () => ({ isLoopEnabled, loopStart, loopEnd }),\n [isLoopEnabled, loopStart, loopEnd]\n );\n\n const selectedTrackIdValue: SelectedTrackIdContextValue = useMemo(\n () => ({ selectedTrackId }),\n [selectedTrackId]\n );\n\n const { canUndo, canRedo } = view;\n const undoRedoValue: UndoRedoContextValue = useMemo(\n () => ({ canUndo, canRedo }),\n [canUndo, canRedo]\n );\n\n // Its own context: these two change on every pointer move of a selection\n // drag, and nothing else in the state value does (#733).\n const selectionValue: SelectionContextValue = useMemo(\n () => ({ selectionStart, selectionEnd }),\n [selectionStart, selectionEnd]\n );\n\n // Their own contexts too (#740): the resting cursor position changes on\n // every seek and on every pointer move of a leftward selection drag; the\n // active annotation changes at every annotation boundary during playback.\n const currentTimeValue: CurrentTimeContextValue = useMemo(() => ({ currentTime }), [currentTime]);\n const activeAnnotationValue: ActiveAnnotationContextValue = useMemo(\n () => ({ activeAnnotationId }),\n [activeAnnotationId]\n );\n\n const setCurrentTimeControl = useCallback(\n (time: number) => {\n setCurrentTimeRefs(time);\n setCurrentTime(time);\n },\n [setCurrentTimeRefs]\n );\n\n // What a click on an annotation does (#686). A play of the annotation's\n // length, so the audio ends on the sample; with continuous play on, an\n // open-ended one. Continuous play is read when the click happens, so the\n // function never changes.\n const playAnnotation = useCallback(\n (annotation: AnnotationData) => {\n // Before the first ready the click does nothing, highlight included.\n if (refusePlayBeforeFirstReady()) return;\n setActiveAnnotationId(annotation.id);\n const playDuration = continuousPlayRef.current\n ? undefined\n : annotation.end - annotation.start;\n play(annotation.start, playDuration).catch((err) => {\n console.warn(\n '[waveform-playlist] Failed to start playback for annotation ' +\n annotation.id +\n ': ' +\n String(err)\n );\n });\n },\n [play, setActiveAnnotationId, continuousPlayRef, refusePlayBeforeFirstReady]\n );\n\n // The actions both providers have (#688). Changes only with the\n // `annotationStore` prop.\n const controlsValue: PlaybackControlsContextValue = useMemo(\n () => ({\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationPreview,\n annotationStore,\n setActiveAnnotationId,\n playAnnotation,\n }),\n [\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationPreview,\n annotationStore,\n setActiveAnnotationId,\n playAnnotation,\n ]\n );\n\n // The actions only the multitrack editor has. Never changes.\n const editorControlsValue: EditorControlsContextValue = useMemo(\n () => ({\n setCurrentTime: setCurrentTimeControl,\n\n // Track controls (the arrangement's mix and order)\n setTrackMute: editing.setTrackMute,\n setTrackSolo: editing.setTrackSolo,\n setTrackVolume: editing.setTrackVolume,\n setTrackPan: editing.setTrackPan,\n reorderTrack: editing.reorderTrack,\n bumpTrackReorderEpoch,\n setTrackDragPreview,\n setSelectedTrackId: setSelectedTrackIdControl,\n\n // Zoom\n zoomIn: zoom.zoomIn,\n zoomOut: zoom.zoomOut,\n\n // Master volume\n setMasterVolume,\n\n // Loop controls\n setLoopEnabled,\n setLoopRegion,\n setLoopRegionFromSelection,\n clearLoopRegion,\n\n // Undo/redo (the arrangement's history)\n undo: editing.undo,\n redo: editing.redo,\n\n // Recording\n setRecordingActive: editing.setRecordingActive,\n }),\n [\n setCurrentTimeControl,\n editing.setTrackMute,\n editing.setTrackSolo,\n editing.setTrackVolume,\n editing.setTrackPan,\n editing.reorderTrack,\n bumpTrackReorderEpoch,\n setTrackDragPreview,\n setSelectedTrackIdControl,\n zoom.zoomIn,\n zoom.zoomOut,\n setMasterVolume,\n setLoopEnabled,\n setLoopRegion,\n setLoopRegionFromSelection,\n clearLoopRegion,\n editing.undo,\n editing.redo,\n editing.setRecordingActive,\n ]\n );\n\n const viewValue: PlaylistViewContextValue = useMemo(\n () => ({\n sampleRate,\n mono,\n indefinitePlayback,\n }),\n [sampleRate, mono, indefinitePlayback]\n );\n\n const settingsValue: PlaylistSettingsContextValue = useMemo(\n () => ({ timeFormat, isAutomaticScroll }),\n [timeFormat, isAutomaticScroll]\n );\n\n const zoomValue: PlaylistZoomContextValue = useMemo(\n () => ({ samplesPerPixel, canZoomIn: zoom.canZoomIn, canZoomOut: zoom.canZoomOut }),\n [samplesPerPixel, zoom.canZoomIn, zoom.canZoomOut]\n );\n\n // Changes on every clip operation (a trim once, on release: its moves are\n // the trim preview, #812), on a zoom (the peaks are computed per zoom\n // level) and when audio arrives for a clip.\n const { peaksDataArray, trackStates } = view;\n const timelineValue: PlaylistTimelineContextValue = useMemo(\n () => ({ tracks, peaksDataArray, duration, isReady }),\n [tracks, peaksDataArray, duration, isReady]\n );\n\n // Changes on every mute, solo, volume or pan change.\n const mixerValue: PlaylistMixerContextValue = useMemo(\n () => ({ trackStates, masterVolume }),\n [trackStates, masterVolume]\n );\n\n // Changes on every drag-over of a track reorder.\n const reorderPreviewValue: TrackReorderPreviewContextValue = useMemo(\n () => ({ trackDragPreview, trackReorderEpoch }),\n [trackDragPreview, trackReorderEpoch]\n );\n\n // Outermost: the values that change least. The order has no effect on\n // behaviour (every value is committed together); it is for reading.\n // The two MediaElement-only contexts are blocked: inside this provider\n // `usePlaybackRate()` must not reach a MediaElement provider further out.\n return (\n <ThemeProvider theme={mergedTheme}>\n <PlaybackRateContext value={BLOCKED}>\n <MediaElementTrackContext value={BLOCKED}>\n <ArrangementContext value={arrangement}>\n <PlaybackRefsContext value={refsValue}>\n <EngineRefsContext value={engineRefsValue}>\n <TrimPreviewContext value={trimPreview}>\n <TrimPreviewPeaksContext value={trimPreviewPeaks}>\n <PlaybackControlsContext value={controlsValue}>\n <EditorControlsContext value={editorControlsValue}>\n <PlaylistViewContext value={viewValue}>\n <PlaylistSettingsContext value={settingsValue}>\n <PlaylistZoomContext value={zoomValue}>\n <UndoRedoContext value={undoRedoValue}>\n <SelectedTrackIdContext value={selectedTrackIdValue}>\n <SelectedRowContext value={selectedTrackIdValue}>\n <LoopContext value={loopValue}>\n <AnnotationOptionsContext value={annotationOptionsValue}>\n <AnnotationsContext value={annotationsValue}>\n <IsPlayingContext value={isPlayingValue}>\n <ActiveAnnotationContext value={activeAnnotationValue}>\n <CurrentTimeContext value={currentTimeValue}>\n <SelectionContext value={selectionValue}>\n <TrackReorderPreviewContext\n value={reorderPreviewValue}\n >\n <PlaylistMixerContext value={mixerValue}>\n <PlaylistTimelineContext\n value={timelineValue}\n >\n <RecordingArmContext\n value={editing.recordingArm}\n >\n {children}\n </RecordingArmContext>\n </PlaylistTimelineContext>\n </PlaylistMixerContext>\n </TrackReorderPreviewContext>\n </SelectionContext>\n </CurrentTimeContext>\n </ActiveAnnotationContext>\n </IsPlayingContext>\n </AnnotationsContext>\n </AnnotationOptionsContext>\n </LoopContext>\n </SelectedRowContext>\n </SelectedTrackIdContext>\n </UndoRedoContext>\n </PlaylistZoomContext>\n </PlaylistSettingsContext>\n </PlaylistViewContext>\n </EditorControlsContext>\n </PlaybackControlsContext>\n </TrimPreviewPeaksContext>\n </TrimPreviewContext>\n </EngineRefsContext>\n </PlaybackRefsContext>\n </ArrangementContext>\n </MediaElementTrackContext>\n </PlaybackRateContext>\n </ThemeProvider>\n );\n};\n","import type { PlayoutAdapter } from '@waveform-playlist/engine';\nimport type { SoundFontCache } from '@waveform-playlist/playout';\n\n/** Adapters that accept a SoundFontCache (e.g. the Tone.js adapter). */\ninterface SoundFontCapableAdapter {\n setSoundFontCache(cache: SoundFontCache | undefined): void;\n}\n\n/**\n * Structural check for soundfont support — avoids a runtime import of\n * `@waveform-playlist/playout`. `isToneAdapter` from playout does the same\n * structural check (via optional chaining); our local `supportsSoundFont`\n * adds an explicit `adapter != null` guard. Keeping it structural lets the\n * core barrel stay engine-free (#510) and works for any custom adapter that\n * exposes `setSoundFontCache`.\n */\nfunction supportsSoundFont(\n adapter: PlayoutAdapter | null\n): adapter is PlayoutAdapter & SoundFontCapableAdapter {\n return (\n adapter != null &&\n typeof (adapter as Partial<SoundFontCapableAdapter>).setSoundFontCache === 'function'\n );\n}\n\n/**\n * Forward a (possibly late-loaded or swapped) SoundFontCache to the live\n * adapter. Safe no-op when the adapter is absent or doesn't support\n * soundfonts. The adapter itself skips MIDI tracks whose routing is\n * unchanged, so redundant calls (e.g. on mount) cause no rebuild churn.\n */\nexport function syncSoundFontCacheToAdapter(\n adapter: PlayoutAdapter | null,\n cache: SoundFontCache | undefined\n): void {\n if (!supportsSoundFont(adapter)) return;\n adapter.setSoundFontCache(cache);\n}\n","import { useCallback, useState } from 'react';\nimport {\n formatTime as formatTimeUtil,\n parseTime as parseTimeUtil,\n type TimeFormat,\n} from '@waveform-playlist/ui-components';\n\nexport interface TimeFormatControls {\n timeFormat: TimeFormat;\n setTimeFormat: (format: TimeFormat) => void;\n formatTime: (seconds: number) => string;\n parseTime: (timeString: string) => number;\n}\n\n/**\n * Hook to manage time format state\n *\n * @example\n * ```tsx\n * const { timeFormat, setTimeFormat, formatTime, parseTime } = useTimeFormat();\n *\n * <TimeFormatSelect\n * value={timeFormat}\n * onChange={setTimeFormat}\n * />\n * <span>{formatTime(currentTime)}</span>\n * <input onChange={(e) => seekTo(parseTime(e.target.value))} />\n * ```\n */\nexport function useTimeFormat(): TimeFormatControls {\n const [timeFormat, setTimeFormat] = useState<TimeFormat>('hh:mm:ss.uuu');\n\n const formatTime = useCallback(\n (seconds: number) => formatTimeUtil(seconds, timeFormat),\n [timeFormat]\n );\n\n const parseTime = useCallback(\n (timeString: string) => parseTimeUtil(timeString, timeFormat),\n [timeFormat]\n );\n\n return {\n timeFormat,\n setTimeFormat,\n formatTime,\n parseTime,\n };\n}\n","import { useState, useCallback, useRef, startTransition, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface ZoomControls {\n samplesPerPixel: number;\n zoomIn: () => void;\n zoomOut: () => void;\n canZoomIn: boolean;\n canZoomOut: boolean;\n}\n\nexport interface UseZoomControlsProps {\n engineRef: RefObject<PlaylistEngine | null>;\n initialSamplesPerPixel: number;\n}\n\n/**\n * Hook for managing zoom controls via PlaylistEngine delegation.\n *\n * zoomIn/zoomOut delegate to the engine. State is mirrored back from\n * the engine via onEngineState(), which the provider's statechange\n * handler calls on every engine event.\n *\n * samplesPerPixel updates use startTransition so React treats them as\n * non-urgent — during playback, animation RAF callbacks interleave\n * with the zoom re-render instead of being blocked.\n */\nexport function useZoomControls({\n engineRef,\n initialSamplesPerPixel,\n}: UseZoomControlsProps): ZoomControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [samplesPerPixel, setSamplesPerPixel] = useState(initialSamplesPerPixel);\n const [canZoomIn, setCanZoomIn] = useState(true);\n const [canZoomOut, setCanZoomOut] = useState(true);\n\n // Internal refs for statechange guards — prevent redundant setState\n // calls during high-frequency engine events (clip drags, play/pause).\n const canZoomInRef = useRef(true);\n const canZoomOutRef = useRef(true);\n const samplesPerPixelRef = useRef(initialSamplesPerPixel);\n\n const zoomIn = useCallback(() => {\n engineRef.current?.zoomIn();\n }, [engineRef]);\n\n const zoomOut = useCallback(() => {\n engineRef.current?.zoomOut();\n }, [engineRef]);\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.samplesPerPixel !== samplesPerPixelRef.current) {\n samplesPerPixelRef.current = state.samplesPerPixel;\n startTransition(() => {\n setSamplesPerPixel(state.samplesPerPixel);\n });\n }\n if (state.canZoomIn !== canZoomInRef.current) {\n canZoomInRef.current = state.canZoomIn;\n setCanZoomIn(state.canZoomIn);\n }\n if (state.canZoomOut !== canZoomOutRef.current) {\n canZoomOutRef.current = state.canZoomOut;\n setCanZoomOut(state.canZoomOut);\n }\n }, []);\n\n return {\n samplesPerPixel,\n zoomIn,\n zoomOut,\n canZoomIn,\n canZoomOut,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseMasterVolumeProps {\n engineRef: RefObject<PlaylistEngine | null>;\n initialVolume?: number; // 0-1.0 (linear gain, consistent with Web Audio API)\n}\n\nexport interface MasterVolumeControls {\n masterVolume: number;\n setMasterVolume: (volume: number) => void;\n /** Ref holding the current masterVolume for seeding a fresh engine. */\n masterVolumeRef: React.RefObject<number>;\n}\n\n/**\n * Hook for managing master volume via PlaylistEngine delegation.\n *\n * setMasterVolume delegates to the engine. State is mirrored back from\n * the engine via onEngineState(), which the provider's statechange\n * handler calls on every engine event.\n */\nexport function useMasterVolume({\n engineRef,\n initialVolume = 1.0,\n}: UseMasterVolumeProps): MasterVolumeControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [masterVolume, setMasterVolumeState] = useState(initialVolume);\n\n // Internal ref for statechange guard + engine seeding on rebuild.\n const masterVolumeRef = useRef(initialVolume);\n\n const setMasterVolume = useCallback(\n (volume: number) => {\n if (engineRef.current) {\n // Engine exists — delegate; statechange will update ref + React state.\n engineRef.current.setMasterVolume(volume);\n } else {\n // No engine yet — persist locally so loadAudio() seeds correctly.\n masterVolumeRef.current = volume;\n setMasterVolumeState(volume);\n }\n },\n [engineRef]\n );\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.masterVolume !== masterVolumeRef.current) {\n masterVolumeRef.current = state.masterVolume;\n setMasterVolumeState(state.masterVolume);\n }\n }, []);\n\n return {\n masterVolume,\n setMasterVolume,\n masterVolumeRef,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseSelectionStateProps {\n engineRef: RefObject<PlaylistEngine | null>;\n}\n\nexport interface SelectionControls {\n selectionStart: number;\n selectionEnd: number;\n setSelection: (start: number, end: number) => void;\n selectionStartRef: React.RefObject<number>;\n selectionEndRef: React.RefObject<number>;\n}\n\n/**\n * Hook for managing selection state via PlaylistEngine delegation.\n *\n * setSelection delegates to the engine. State is mirrored back from\n * the engine via onEngineState(), which the provider's statechange\n * handler calls on every engine event.\n *\n * Note: The provider wraps this setter with playback side-effects\n * (updating currentTime, restarting playback). This hook only handles\n * the engine delegation + state mirroring.\n */\nexport function useSelectionState({ engineRef }: UseSelectionStateProps): SelectionControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [selectionStart, setSelectionStartState] = useState(0);\n const [selectionEnd, setSelectionEndState] = useState(0);\n\n // Internal refs for statechange guard + engine seeding on rebuild.\n const selectionStartRef = useRef(0);\n const selectionEndRef = useRef(0);\n\n const setSelection = useCallback(\n (start: number, end: number) => {\n engineRef.current?.setSelection(start, end);\n },\n [engineRef]\n );\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.selectionStart !== selectionStartRef.current) {\n selectionStartRef.current = state.selectionStart;\n setSelectionStartState(state.selectionStart);\n }\n if (state.selectionEnd !== selectionEndRef.current) {\n selectionEndRef.current = state.selectionEnd;\n setSelectionEndState(state.selectionEnd);\n }\n }, []);\n\n return {\n selectionStart,\n selectionEnd,\n setSelection,\n selectionStartRef,\n selectionEndRef,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseLoopStateProps {\n engineRef: RefObject<PlaylistEngine | null>;\n}\n\nexport interface LoopControls {\n isLoopEnabled: boolean;\n loopStart: number;\n loopEnd: number;\n setLoopEnabled: (value: boolean) => void;\n setLoopRegion: (start: number, end: number) => void;\n clearLoopRegion: () => void;\n isLoopEnabledRef: React.RefObject<boolean>;\n loopStartRef: React.RefObject<number>;\n loopEndRef: React.RefObject<number>;\n}\n\n/**\n * Hook for managing loop state via PlaylistEngine delegation.\n *\n * setLoopEnabled, setLoopRegion, and clearLoopRegion delegate to the\n * engine. State is mirrored back from the engine via onEngineState(),\n * which the provider's statechange handler calls on every engine event.\n */\nexport function useLoopState({ engineRef }: UseLoopStateProps): LoopControls & {\n onEngineState: (state: EngineState) => void;\n} {\n const [isLoopEnabled, setIsLoopEnabledState] = useState(false);\n const [loopStart, setLoopStartState] = useState(0);\n const [loopEnd, setLoopEndState] = useState(0);\n\n // Internal refs for statechange guard + animation loop reads.\n const isLoopEnabledRef = useRef(false);\n const loopStartRef = useRef(0);\n const loopEndRef = useRef(0);\n\n const setLoopEnabled = useCallback(\n (value: boolean) => {\n engineRef.current?.setLoopEnabled(value);\n },\n [engineRef]\n );\n\n const setLoopRegion = useCallback(\n (start: number, end: number) => {\n engineRef.current?.setLoopRegion(start, end);\n },\n [engineRef]\n );\n\n const clearLoopRegion = useCallback(() => {\n engineRef.current?.setLoopRegion(0, 0);\n }, [engineRef]);\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.isLoopEnabled !== isLoopEnabledRef.current) {\n isLoopEnabledRef.current = state.isLoopEnabled;\n setIsLoopEnabledState(state.isLoopEnabled);\n }\n if (state.loopStart !== loopStartRef.current) {\n loopStartRef.current = state.loopStart;\n setLoopStartState(state.loopStart);\n }\n if (state.loopEnd !== loopEndRef.current) {\n loopEndRef.current = state.loopEnd;\n setLoopEndState(state.loopEnd);\n }\n }, []);\n\n return {\n isLoopEnabled,\n loopStart,\n loopEnd,\n setLoopEnabled,\n setLoopRegion,\n clearLoopRegion,\n isLoopEnabledRef,\n loopStartRef,\n loopEndRef,\n onEngineState,\n };\n}\n","import { useState, useCallback, useRef, type RefObject } from 'react';\nimport type { PlaylistEngine, EngineState } from '@waveform-playlist/engine';\n\nexport interface UseSelectedTrackProps {\n engineRef: RefObject<PlaylistEngine | null>;\n}\n\nexport interface SelectedTrackControls {\n selectedTrackId: string | null;\n setSelectedTrackId: (trackId: string | null) => void;\n}\n\n/**\n * Hook for managing selected track state via PlaylistEngine delegation.\n *\n * setSelectedTrackId delegates to the engine's selectTrack method.\n * State is mirrored back from the engine via onEngineState(), which\n * the provider's statechange handler calls on every engine event.\n */\nexport function useSelectedTrack({ engineRef }: UseSelectedTrackProps): SelectedTrackControls & {\n onEngineState: (state: EngineState) => void;\n selectedTrackIdRef: React.RefObject<string | null>;\n} {\n const [selectedTrackId, setSelectedTrackIdState] = useState<string | null>(null);\n\n // Internal ref for statechange guard.\n const selectedTrackIdRef = useRef<string | null>(null);\n\n const setSelectedTrackId = useCallback(\n (trackId: string | null) => {\n engineRef.current?.selectTrack(trackId);\n },\n [engineRef]\n );\n\n // Called by the provider's statechange handler to mirror engine state.\n const onEngineState = useCallback((state: EngineState) => {\n if (state.selectedTrackId !== selectedTrackIdRef.current) {\n selectedTrackIdRef.current = state.selectedTrackId;\n setSelectedTrackIdState(state.selectedTrackId);\n }\n }, []);\n\n return {\n selectedTrackId,\n setSelectedTrackId,\n onEngineState,\n selectedTrackIdRef,\n };\n}\n","import React from 'react';\nimport type { DragStartEvent, DragMoveEvent, DragEndEvent } from '@dnd-kit/abstract';\nimport type { AudioClip } from '@waveform-playlist/core';\nimport { calculateBoundaryTrim } from '../utils/boundaryTrim';\nimport { sortedClipsOf } from '../utils/sortedClips';\nimport { loadedClipsOf } from '../utils/loadedTracks';\nimport {\n useArrangement,\n usePlaylistView,\n useTrimPreviewOptional,\n} from '../contexts/playlistContexts';\nimport type { TrimPreview } from '../providerInternals/useTrimPreview';\n\ninterface UseClipDragHandlersOptions {\n samplesPerPixel: number;\n /** Optional function that snaps a sample position to the nearest grid position.\n * Used for boundary trim snapping (move snapping is handled by the SnapToGridModifier). */\n snapSamplePosition?: (samplePosition: number) => number;\n}\n\ntype Boundary = 'left' | 'right';\n\n/** What dnd-kit's source data holds for a clip (see `Clip` in ui-components). */\ninterface ClipDragData {\n kind?: string;\n clipId: string;\n boundary?: Boundary;\n trackIndex: number;\n clipIndex: number;\n}\n\ntype Geometry = Pick<AudioClip, 'startSample' | 'durationSamples' | 'offsetSamples'>;\n\n/** A boundary trim in progress: which clip, and its bounds when the drag started. */\ninterface TrimDrag {\n trackId: string;\n clipId: string;\n boundary: Boundary;\n original: Geometry;\n}\n\n/** A clip move in progress: the track it was picked up on, by id. */\ninterface MoveDrag {\n trackId: string;\n clipId: string;\n}\n\n/** A track's clips in timeline order, and where `clip` sits in it. */\nfunction trimOrderFor(clips: readonly AudioClip[], clip: AudioClip) {\n const sortedClips = sortedClipsOf(clips);\n return { clips, sortedClips, sortedIndex: sortedClips.indexOf(clip) };\n}\n\ntype TrimOrder = ReturnType<typeof trimOrderFor>;\n\n/** Whether every clip except the one with id `clipId` is the same object in both arrays. */\nfunction sameNeighbours(a: readonly AudioClip[], b: readonly AudioClip[], clipId: string): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].id !== clipId && a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/** The geometry of a clip whose `boundary` has moved by `delta` samples. */\nfunction trimmedGeometry(original: Geometry, boundary: Boundary, delta: number): Geometry {\n return boundary === 'left'\n ? {\n startSample: original.startSample + delta,\n durationSamples: original.durationSamples - delta,\n offsetSamples: original.offsetSamples + delta,\n }\n : { ...original, durationSamples: original.durationSamples + delta };\n}\n\ninterface ProposedTrim {\n drag: TrimDrag;\n clip: AudioClip;\n pixelDelta: number;\n samplesPerPixel: number;\n sampleRate: number;\n order: TrimOrder;\n snap: ((samplePosition: number) => number) | undefined;\n}\n\n/**\n * The trim delta, in whole samples, for a pointer `pixelDelta` from where the\n * drag started: constrained by the clip's neighbours and source, then with the\n * moved boundary's absolute position snapped to the grid.\n */\nfunction proposedTrimDelta({\n drag,\n clip,\n pixelDelta,\n samplesPerPixel,\n sampleRate,\n order,\n snap,\n}: ProposedTrim): number {\n const { original, boundary } = drag;\n const trimmed = calculateBoundaryTrim({\n originalClip: original,\n clip,\n pixelDelta,\n samplesPerPixel,\n sampleRate,\n boundary,\n sortedClips: order.sortedClips,\n sortedIndex: order.sortedIndex,\n });\n if (boundary === 'left') {\n const start = snap ? snap(trimmed.startSample) : trimmed.startSample;\n return Math.floor(start - original.startSample);\n }\n const end = trimmed.startSample + trimmed.durationSamples;\n const snappedEnd = snap ? snap(end) : end;\n return Math.floor(snappedEnd - original.startSample - original.durationSamples);\n}\n\n/**\n * Custom hook for handling clip drag operations (movement and trimming)\n *\n * Provides drag handlers for use with @dnd-kit/react DragDropProvider.\n * Handles both clip movement (dragging entire clips) and boundary trimming (adjusting clip edges).\n *\n * Collision detection for clip moves is handled by `ClipCollisionModifier` (passed to DragDropProvider).\n *\n * It changes the provider's arrangement (`useArrangement()`), so it works\n * whether an engine is attached or not, and throws outside\n * `WaveformPlaylistProvider`.\n *\n * **Move:** `onDragStart` notes the clip and its track by id; `onDragEnd`\n * makes one `arrangement.moveClip()` of that clip on that track, also when\n * the tracks were reordered or the row's clips changed meanwhile.\n *\n * **Trim (#812):** each `onDragMove` publishes where the clip would be to the\n * provider's trim preview, which only the dragged clip's view follows; the\n * tracks are not changed. Each move is computed from the clip as it was when\n * the drag started, constrained as the release will be\n * (`arrangement.constrainTrimDelta`), so the preview shows what the release\n * commits. `onDragEnd` makes one `arrangement.trimClip()` with the delta of\n * the last preview and clears the preview in the same render; Escape clears\n * the preview only. Each of `moveClip` and `trimClip` is one undo step.\n *\n * The returned handlers read the tracks from the arrangement when they run,\n * so they keep their identity and are safe to pass straight to\n * `DragDropProvider`.\n *\n * @example\n * ```tsx\n * const { tracks } = usePlaylistTimeline();\n * const { onDragStart, onDragMove, onDragEnd } = useClipDragHandlers({ samplesPerPixel });\n *\n * return (\n * <DragDropProvider\n * onDragStart={onDragStart}\n * onDragMove={onDragMove}\n * onDragEnd={onDragEnd}\n * modifiers={[RestrictToHorizontalAxis, ClipCollisionModifier.configure({ tracks, samplesPerPixel })]}\n * >\n * <WaveformEditor />\n * </DragDropProvider>\n * );\n * ```\n */\nexport function useClipDragHandlers({\n samplesPerPixel,\n snapSamplePosition,\n}: UseClipDragHandlersOptions) {\n const arrangement = useArrangement();\n const { sampleRate } = usePlaylistView();\n // The provider's trim preview; none under another provider or outside one,\n // and then a trim is committed on release without being shown.\n const preview = useTrimPreviewOptional();\n // Store snap function in ref so onDragMove doesn't need it as a dependency\n const snapSamplePositionRef = React.useRef(snapSamplePosition);\n snapSamplePositionRef.current = snapSamplePosition;\n // The trimmed clip's neighbours in timeline order. Collision constraints\n // keep the clip between the same two neighbours, so the order found at drag\n // start holds for the drag and is not re-sorted on every pointer move.\n // `clips` is the array it was computed from: if any OTHER clip of the track\n // has been replaced since (an undo during the drag, a recording landing on\n // the track, audio arriving for it), it is recomputed.\n const trimOrderRef = React.useRef<TrimOrder | null>(null);\n // The trim in progress, with the clip's bounds at drag start (each move is\n // computed from them, never from the previous move).\n const trimDragRef = React.useRef<TrimDrag | null>(null);\n // The delta (samples) of the last published preview: what the release sends.\n const lastBoundaryDeltaRef = React.useRef(0);\n // The move in progress: the clip's track by id, so a reorder before the\n // drop does not move a clip of another track.\n const moveDragRef = React.useRef<MoveDrag | null>(null);\n\n // A drag that never ends (its component unmounts mid-drag) must not leave\n // its preview on screen.\n React.useEffect(() => {\n if (!preview) return;\n return () => {\n if (trimDragRef.current) {\n trimDragRef.current = null;\n preview.publish(null);\n }\n };\n }, [preview]);\n\n const onDragStart = React.useCallback(\n (event: DragStartEvent) => {\n const data = event.operation.source?.data as ClipDragData | undefined;\n if (!data || data.kind === 'track-reorder') return;\n trimDragRef.current = null;\n trimOrderRef.current = null;\n moveDragRef.current = null;\n lastBoundaryDeltaRef.current = 0;\n // The row the drag began on is the arrangement's track at that index.\n const track = arrangement.getTracks()[data.trackIndex];\n if (!track) return;\n // A move needs nothing else until the drop.\n if (!data.boundary) {\n moveDragRef.current = { trackId: track.id, clipId: data.clipId };\n return;\n }\n\n // By id: `clipIndex` is a position in the drawn row, which can hold\n // placeholders that are not loaded clips.\n const clips = loadedClipsOf(track);\n const clip = clips.find((c) => c.id === data.clipId);\n if (!clip) return;\n trimDragRef.current = {\n trackId: track.id,\n clipId: clip.id,\n boundary: data.boundary,\n original: {\n startSample: clip.startSample,\n durationSamples: clip.durationSamples,\n offsetSamples: clip.offsetSamples,\n },\n };\n trimOrderRef.current = trimOrderFor(clips, clip);\n },\n [arrangement]\n );\n\n const onDragMove = React.useCallback(\n (event: DragMoveEvent) => {\n const data = event.operation.source?.data as ClipDragData | undefined;\n const drag = trimDragRef.current;\n if (!data?.boundary || !drag || !trimOrderRef.current) return;\n // By the id captured at drag start: the track's row can move mid-drag\n // (a reorder), and `data.trackIndex` is the row it had then. While the\n // track is gone, a move does nothing.\n const track = arrangement.getTracks().find((t) => t.id === drag.trackId);\n const currentClips = track ? loadedClipsOf(track) : undefined;\n const clip = currentClips?.find((c) => c.id === drag.clipId);\n if (!currentClips || !clip) return;\n if (!sameNeighbours(trimOrderRef.current.clips, currentClips, drag.clipId)) {\n trimOrderRef.current = trimOrderFor(currentClips, clip);\n }\n\n // The dragmove event is dispatched BEFORE position.current is updated (happens\n // in a microtask), so the snapshot's position.current is stale. Use event.to\n // (the pointer's current coordinates from the sensor) for the correct position.\n const currentX = event.to?.x ?? event.operation.position.current.x;\n const proposed = proposedTrimDelta({\n drag,\n clip,\n pixelDelta: currentX - event.operation.position.initial.x,\n samplesPerPixel,\n sampleRate,\n order: trimOrderRef.current,\n snap: snapSamplePositionRef.current,\n });\n // What `trimClip` will apply on release: the clip has not been\n // changed during the drag, so it constrains from the same bounds.\n const delta = arrangement.constrainTrimDelta(\n drag.trackId,\n drag.clipId,\n drag.boundary,\n proposed\n );\n\n lastBoundaryDeltaRef.current = delta;\n const next: TrimPreview = {\n trackId: drag.trackId,\n clipId: drag.clipId,\n ...trimmedGeometry(drag.original, drag.boundary, delta),\n };\n preview?.publish(next);\n },\n [samplesPerPixel, sampleRate, arrangement, preview]\n );\n\n /** Ends a trim: one `trimClip` with the last preview's delta, the preview cleared with it. */\n const commitTrim = React.useCallback(\n (drag: TrimDrag, delta: number) => {\n // No frame shows the clip where it was before the drag: dnd-kit calls\n // this inside `startTransition`, but the view reads both the\n // arrangement and the preview with `useSyncExternalStore`, whose\n // updates React applies at once, together, even inside a transition.\n arrangement.trimClip(drag.trackId, drag.clipId, drag.boundary, delta);\n preview?.publish(null);\n },\n [arrangement, preview]\n );\n\n const onDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n const data = event.operation.source?.data as ClipDragData | undefined;\n if (data?.kind === 'track-reorder') return;\n\n const drag = trimDragRef.current;\n const move = moveDragRef.current;\n const delta = lastBoundaryDeltaRef.current;\n trimDragRef.current = null;\n trimOrderRef.current = null;\n moveDragRef.current = null;\n lastBoundaryDeltaRef.current = 0;\n\n // Canceled (Escape, focus loss, unmount): nothing was changed but the\n // preview. A canceled move needs nothing: the Feedback plugin puts the\n // clip back and the engine was never told.\n if (event.canceled || !data) {\n if (drag) preview?.publish(null);\n return;\n }\n\n // A trim commits the clip captured at drag start (`drag`).\n if (data.boundary) {\n if (drag) commitTrim(drag, delta);\n return;\n }\n\n // Clip move: transform.x is modifier-constrained, cached as a plain\n // object in the snapshot.\n const sampleDelta = event.operation.transform.x * samplesPerPixel;\n const tracks = arrangement.getTracks();\n // The clip and track picked up at drag start, never the clip the drop's\n // data names: the row can have changed under the drag (a clip arriving\n // earlier in it shifts every later clip's position). From the drop's\n // data only when the drag start was not seen (a custom wiring that\n // calls onDragEnd alone).\n const clipId = move ? move.clipId : data.clipId;\n const trackId = move ? move.trackId : tracks[data.trackIndex]?.id;\n const track = trackId === undefined ? undefined : tracks.find((t) => t.id === trackId);\n if (!track) {\n console.warn(\n `[waveform-playlist] The move was dropped: the clip's track is not there ` +\n `(row ${data.trackIndex}). The clip stays where it was.`\n );\n } else if (!loadedClipsOf(track).some((c) => c.id === clipId)) {\n console.warn(\n `[waveform-playlist] The move was dropped: track \"${track.id}\" has no clip \"${clipId}\".`\n );\n } else {\n arrangement.moveClip(track.id, clipId, Math.floor(sampleDelta));\n }\n },\n [samplesPerPixel, arrangement, preview, commitTrim]\n );\n\n return {\n onDragStart,\n onDragMove,\n onDragEnd,\n };\n}\n","import type { AudioClip } from '@waveform-playlist/core';\nimport { constrainBoundaryTrim } from '@waveform-playlist/engine';\n\n/**\n * Result of a boundary trim calculation — the new clip dimensions\n * after dragging a left or right boundary by a given pixel delta.\n */\nexport interface BoundaryTrimResult {\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n}\n\nexport interface CalculateBoundaryTrimParams {\n /** The original clip state captured at drag start */\n originalClip: Pick<AudioClip, 'startSample' | 'durationSamples' | 'offsetSamples'>;\n /** The current clip with full AudioClip shape (used for constraint calculation) */\n clip: AudioClip;\n /** Raw pixel delta from drag start (positive = rightward) */\n pixelDelta: number;\n /** Samples per pixel (zoom level) */\n samplesPerPixel: number;\n /** Audio sample rate (used to compute minimum duration) */\n sampleRate: number;\n /** Which boundary is being dragged */\n boundary: 'left' | 'right';\n /** Clips on the same track, sorted by startSample (for collision detection) */\n sortedClips: AudioClip[];\n /** Index of the clip being trimmed within sortedClips */\n sortedIndex: number;\n}\n\n/**\n * Pure function that calculates new clip dimensions after a boundary trim drag.\n *\n * Converts a pixel delta to sample delta, constrains it via the engine's\n * `constrainBoundaryTrim`, and applies the constrained delta to the original\n * clip snapshot to produce new startSample, durationSamples, and offsetSamples.\n *\n * For left boundary: startSample and offsetSamples increase by the constrained delta,\n * durationSamples decreases by the same amount.\n *\n * For right boundary: only durationSamples changes (increases by the constrained delta).\n */\nexport function calculateBoundaryTrim({\n originalClip,\n clip,\n pixelDelta,\n samplesPerPixel,\n sampleRate,\n boundary,\n sortedClips,\n sortedIndex,\n}: CalculateBoundaryTrimParams): BoundaryTrimResult {\n const sampleDelta = pixelDelta * samplesPerPixel;\n const MIN_DURATION_SAMPLES = Math.floor(0.1 * sampleRate);\n\n // Build a temporary clip with original state for constraint calculation\n const tempClip: AudioClip = {\n ...clip,\n startSample: originalClip.startSample,\n offsetSamples: originalClip.offsetSamples,\n durationSamples: originalClip.durationSamples,\n };\n\n const constrainedDelta = constrainBoundaryTrim(\n tempClip,\n Math.floor(sampleDelta),\n boundary,\n sortedClips,\n sortedIndex,\n MIN_DURATION_SAMPLES\n );\n\n if (boundary === 'left') {\n return {\n startSample: originalClip.startSample + constrainedDelta,\n durationSamples: originalClip.durationSamples - constrainedDelta,\n offsetSamples: originalClip.offsetSamples + constrainedDelta,\n };\n } else {\n return {\n startSample: originalClip.startSample,\n durationSamples: originalClip.durationSamples + constrainedDelta,\n offsetSamples: originalClip.offsetSamples,\n };\n }\n}\n","import type { AudioClip } from '@waveform-playlist/core';\n\nconst cache = new WeakMap<readonly AudioClip[], AudioClip[]>();\n\n/**\n * A track's clips in timeline order.\n *\n * The result is cached per clips array, so calling this on every pointer move\n * of a drag sorts once: tracks are updated immutably, and a clips array that\n * has not been replaced has not changed order. Do not mutate the result.\n */\nexport function sortedClipsOf(clips: readonly AudioClip[]): AudioClip[] {\n let sorted = cache.get(clips);\n if (!sorted) {\n sorted = [...clips].sort((a, b) => a.startSample - b.startSample);\n cache.set(clips, sorted);\n }\n return sorted;\n}\n","/**\n * loadedTracks\n *\n * An arrangement's tracks without their loading clips (#812): what the\n * provider publishes as `usePlaylistTimeline().tracks` and what the engine\n * plays. A clip that is still loading is drawn from its placeholder record\n * (`placeholderPeaks`) and is in no tracks array.\n *\n * Identities are kept as `derivePeaks` keeps them, because they are compared\n * downstream: a track that holds no loading clip is the arrangement's own\n * object; a track that holds one gives the same projection for as long as the\n * arrangement hands back the same track object; and the result is the same\n * array while no element changed. Nothing here writes to the arrangement's\n * objects (they are frozen in development).\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, AudioClip, ClipTrack } from '@waveform-playlist/core';\nimport { sameItems } from './sameItems';\n\nexport interface LoadedTracksCache {\n /** The projection of each arrangement track of the last pass. */\n readonly byTrack: ReadonlyMap<ArrangementTrack, ClipTrack>;\n readonly result: readonly ClipTrack[];\n}\n\nexport const EMPTY_LOADED_TRACKS: LoadedTracksCache = { byTrack: new Map(), result: [] };\n\n// The loaded clips of each arrangement track object. The objects never change\n// (a change replaces them), so one array per object is right for its life.\nconst loadedClipsByTrack = new WeakMap<ArrangementTrack, AudioClip[]>();\n\nfunction cachedLoadedClips(track: ArrangementTrack): AudioClip[] {\n let clips = loadedClipsByTrack.get(track);\n if (!clips) {\n clips = track.clips.filter((clip): clip is AudioClip => !isLoadingClip(clip));\n loadedClipsByTrack.set(track, clips);\n }\n return clips;\n}\n\n/**\n * The clips of `track` that have their audio, in its order: the same array\n * for the same track object. What a drag can pick up and a split can cut.\n */\nexport function loadedClipsOf(track: ArrangementTrack): readonly AudioClip[] {\n return cachedLoadedClips(track);\n}\n\nfunction projection(track: ArrangementTrack, previous: LoadedTracksCache): ClipTrack {\n if (!track.clips.some(isLoadingClip)) {\n // Every clip is loaded: the track is a `ClipTrack` as it is.\n return track as ClipTrack;\n }\n const known = previous.byTrack.get(track);\n if (known) return known;\n return { ...track, clips: cachedLoadedClips(track) };\n}\n\n/**\n * `tracks` without their loading clips, reusing `cache` (the previous pass).\n * Keep the returned cache and pass it to the next call.\n */\nexport function loadedTracks(\n tracks: readonly ArrangementTrack[],\n cache: LoadedTracksCache\n): { tracks: readonly ClipTrack[]; cache: LoadedTracksCache } {\n const byTrack = new Map<ArrangementTrack, ClipTrack>();\n const projected = tracks.map((track) => {\n const loaded = projection(track, cache);\n byTrack.set(track, loaded);\n return loaded;\n });\n const result = sameItems(cache.result, projected) ? cache.result : projected;\n return { tracks: result, cache: { byTrack, result } };\n}\n","/**\n * True when `a` holds the same items as `b`, in the same order, compared by\n * identity. The derivations that keep identities (`derivePeaks`,\n * `loadedTracks`, the view of an arrangement) hand back the previous array\n * when it does.\n */\nexport function sameItems<T>(a: readonly T[] | undefined, b: readonly T[]): a is T[] {\n return a !== undefined && a.length === b.length && a.every((item, i) => item === b[i]);\n}\n","/**\n * The context objects, their value types and their hooks (#688).\n *\n * Both providers render the SAME context objects for the part they share, so\n * a control written against `useIsPlaying()` or `usePlaybackControls()` works\n * under either. What only one provider has is on its own context, and the\n * other provider blocks it (see `BLOCKED`), so that a hook never reaches\n * through one provider to an outer one of the other kind.\n *\n * This file imports no provider and no engine: a MediaElement-only bundle\n * must not pull in the WebAudio provider through it.\n */\nimport { createContext, use } from 'react';\nimport type { ClipTrack, AnnotationData, AnnotationStore } from '@waveform-playlist/core';\nimport type { Arrangement, PlaylistEngine } from '@waveform-playlist/engine';\nimport type { MediaElementPlayout, FadeConfig } from '@waveform-playlist/media-element-playout';\nimport type { TimeFormat } from '@waveform-playlist/ui-components';\nimport type { AnnotationPreviewHandle } from '../hooks/useAnnotationDragHandlers';\nimport type { FrameData } from '../providerInternals/useFrameCallbacks';\nimport type { TrackDragPreview } from '../utils/trackOrderPreview';\nimport type { TrimPreviewHandle, TrimPreviewPeaksValue } from '../providerInternals/useTrimPreview';\nimport type { TrackClipPeaks, TrackState } from '../WaveformPlaylistContext';\n\nexport type { FrameData };\n\nconst WEB_AUDIO = 'WaveformPlaylistProvider';\nconst MEDIA_ELEMENT = 'MediaElementPlaylistProvider';\n\n/** The id of the one track of a MediaElement player (its row and its clip carry it). */\nexport const MEDIA_ELEMENT_TRACK_ID = 'media-element-track-0';\n\n/**\n * What a provider puts in a context it does not serve. The hook then throws\n * and names the provider that is needed, instead of reading an outer provider\n * of the other kind.\n */\nexport const BLOCKED = Symbol('waveform-playlist.blocked-context');\ntype Blocked = typeof BLOCKED;\ntype Slot<T> = T | Blocked | null;\n\n// ---------------------------------------------------------------------------\n// Shared: rendered by both providers\n// ---------------------------------------------------------------------------\n\n/**\n * Whether playback is running. Its own context (#768): it is the only value of\n * the playback state that changes on play, pause and stop, and a component\n * that needs a ref or a frame callback (`usePlaybackRefs`) must not re-render\n * with it.\n */\nexport interface IsPlayingContextValue {\n isPlaying: boolean;\n}\n\n/**\n * Refs and functions that keep their identity for the life of the provider\n * (#768). Reading this never causes a re-render: read a ref's `.current` in an\n * event handler, an effect or a frame callback, not during render.\n */\nexport interface PlaybackRefsContextValue {\n /** The playback position, in seconds. Advances during playback. */\n currentTimeRef: React.RefObject<number>;\n /**\n * The position to DRAW. Under the WebAudio provider it is the audible\n * position (the raw time less output latency and lookahead while playing);\n * under the MediaElement provider it is `currentTimeRef` itself, because a\n * media element reports the audible position.\n */\n visualTimeRef: React.RefObject<number>;\n /** Register a per-frame callback driven by the provider's one animation loop. */\n registerFrameCallback: (id: string, cb: (data: FrameData) => void) => void;\n /** Unregister a per-frame callback. */\n unregisterFrameCallback: (id: string) => void;\n}\n\n/**\n * The selected time range, in seconds. Apart from the state context because it\n * is the only state that changes on every pointer move of a selection drag\n * (#733). `selectionStart === selectionEnd` means nothing is selected.\n */\nexport interface SelectionContextValue {\n selectionStart: number;\n selectionEnd: number;\n}\n\n/**\n * Where the cursor rests, in seconds: the position playback starts from. It\n * changes on a seek, a pause, a stop (including playback reaching the end) and\n * a selection whose start moves; it does NOT advance during playback (read\n * `currentTimeRef`, or register a frame callback, for that). Apart from the\n * other values so that a component reading `isPlaying` or a ref is not\n * re-rendered by every seek, nor by every pointer move of a leftward selection\n * drag (#740).\n */\nexport interface CurrentTimeContextValue {\n currentTime: number;\n}\n\n/**\n * The annotation that is playing or was last chosen. Its own context because\n * it changes at every annotation boundary during playback (#740).\n */\nexport interface ActiveAnnotationContextValue {\n activeAnnotationId: string | null;\n}\n\n/**\n * The annotations. Changes on an annotation edit; an edge drag changes it\n * once, on release (its moves go through the preview source).\n */\nexport interface AnnotationsContextValue {\n /** The annotation store's list: never write to it (frozen in development). */\n annotations: readonly AnnotationData[];\n}\n\n/**\n * The three annotation options, under both providers (#686): whether\n * annotations can be edited, whether an edge takes the edge it touches along,\n * and whether playback runs on past the end of an annotation. They start from\n * the provider's `annotationList` prop and are set with\n * `setAnnotationsEditable`, `setLinkEndpoints` and `setContinuousPlay` of\n * `usePlaybackControls()`.\n */\nexport interface AnnotationOptionsContextValue {\n editable: boolean;\n linkEndpoints: boolean;\n continuousPlay: boolean;\n}\n\n/**\n * The actions both providers have (#688). The value changes only when the\n * provider's `annotationStore` prop does, so reading it does not re-render\n * on playback, edits or option changes.\n */\nexport interface PlaybackControlsContextValue {\n /**\n * Starts playback at `startTime` (default: the cursor). With `playDuration`\n * it stops by itself after that many seconds of audio.\n */\n play: (startTime?: number, playDuration?: number) => Promise<void>;\n pause: () => void;\n /** Ends playback and returns the cursor to where playback started. */\n stop: () => void;\n /** Moves the cursor, clamped to the audio. During playback, playback restarts there. */\n seekTo: (time: number) => void;\n /** Sets the selected range and moves the cursor to its start. During playback, playback\n * restarts: a range is played start to end (open-ended under WaveformPlaylistProvider with\n * looping on), a collapsed one carries on from there. */\n setSelection: (start: number, end: number) => void;\n\n setTimeFormat: (format: TimeFormat) => void;\n\n setAutomaticScroll: (enabled: boolean) => void;\n setScrollContainer: (element: HTMLDivElement | null) => void;\n scrollContainerRef: React.RefObject<HTMLDivElement | null>;\n\n setContinuousPlay: (enabled: boolean) => void;\n setAnnotationsEditable: (enabled: boolean) => void;\n setLinkEndpoints: (enabled: boolean) => void;\n /**\n * Where an annotation edge drag shows its moves while it is in progress.\n * Pass it to `useAnnotationDragHandlers({ preview })`; read it in a custom\n * annotation renderer with `useAnnotationsWithPreview`. Stable identity.\n */\n annotationPreview: AnnotationPreviewHandle;\n /**\n * The provider's `annotationStore` prop, or `undefined` without one: the\n * owner of the annotations. Change them with its `set` and `update`. Its\n * identity changes only when the prop does.\n */\n annotationStore: AnnotationStore | undefined;\n setActiveAnnotationId: (id: string | null) => void;\n /**\n * What a click on an annotation does (its box, or its row in the list): the\n * annotation becomes the active one and is played from its start. With\n * continuous play off, playback ends where the annotation ends. Call it\n * from a box or a row of your own. Each provider plays an annotation its\n * own way: `WaveformPlaylistProvider` starts a play of the annotation's\n * length, `MediaElementPlaylistProvider` starts an open-ended play that its\n * loop ends with the active annotation. Left alone, both end at the\n * annotation's end. They differ when something changes during the play:\n * under MediaElement the play follows an end that is moved, and continuous\n * play switched on lets it run on; under WebAudio the first keeps the end\n * it started with. A start that fails is logged as a warning.\n */\n playAnnotation: (annotation: AnnotationData) => void;\n}\n\n/**\n * What the provider was configured with that a view also reads (#768, #689).\n * Changes on a prop change (and once when the real sample rate is known),\n * never during an interaction.\n *\n * The options that only affect how a view draws (row height, bar style,\n * playhead width, the filled layout) are not here: they are\n * `<WaveformViewOptions>`, and what is drawn reads them from ui-components'\n * `usePlaylistInfo()` inside a root.\n */\nexport interface PlaylistViewContextValue {\n sampleRate: number;\n /**\n * Whether tracks are drawn and analysed as one channel. On the provider\n * because the provider computes the peaks with it. Always false under the\n * MediaElement provider.\n */\n mono: boolean;\n /**\n * Whether playback continues past the end of the audio instead of stopping\n * there. On the provider because its animation loop and `seekTo` follow it;\n * the multitrack root also draws the timeline as wide as its container\n * then. Always false under the MediaElement provider.\n */\n indefinitePlayback: boolean;\n}\n\n/**\n * The two settings a user toggles (#768). Apart from the view value because\n * every clip overlay and the visualization shell read that one: a toggle here\n * renders only the components that show the setting.\n */\nexport interface PlaylistSettingsContextValue {\n timeFormat: TimeFormat;\n isAutomaticScroll: boolean;\n}\n\n/**\n * The zoom level (#768). Changes on a zoom. Under the MediaElement provider\n * the level is fixed: `canZoomIn` and `canZoomOut` are always false.\n */\nexport interface PlaylistZoomContextValue {\n samplesPerPixel: number;\n canZoomIn: boolean;\n canZoomOut: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// WaveformPlaylistProvider only\n// ---------------------------------------------------------------------------\n\n/**\n * The actions only the multitrack editor has (#688). The value never changes.\n */\nexport interface EditorControlsContextValue {\n /**\n * Moves the cursor without touching playback. `seekTo` is the one to use\n * from a control; this is for the view's own press and drag handling.\n */\n setCurrentTime: (time: number) => void;\n\n // Track mixer, by track id (#687; by index until then). An id no track has\n // is ignored. They change the arrangement's mix, also while no engine is\n // attached (#812). Inside a track's control panel, `useTrack()` has the\n // same actions already bound to that track.\n setTrackMute: (trackId: string, muted: boolean) => void;\n setTrackSolo: (trackId: string, soloed: boolean) => void;\n setTrackVolume: (trackId: string, volume: number) => void;\n setTrackPan: (trackId: string, pan: number) => void;\n\n /** Move a track to a new index in the vertical track order. Purely\n * organizational — playback is not interrupted. An undo step of the\n * arrangement (#812). */\n reorderTrack: (trackId: string, toIndex: number) => void;\n\n /** Internal: call after every track-reorder DRAG interaction ends\n * (committed or canceled) to force the view's track-controls part to remount\n * its slots, discarding any @dnd-kit sortable-plugin DOM\n * corruption. Not needed for button-driven reorderTrack calls (they never\n * touch dnd-kit's DOM). See bumpTrackReorderEpoch in the provider. */\n bumpTrackReorderEpoch: () => void;\n\n /** INTERNAL wiring for ClipInteractionProvider: publishes/clears the live\n * track-reorder drag preview. Custom drag integrations may call it, but\n * most consumers only ever READ trackDragPreview from useTrackReorderPreview(). */\n setTrackDragPreview: React.Dispatch<React.SetStateAction<TrackDragPreview | null>>;\n\n setSelectedTrackId: (trackId: string | null) => void;\n\n // Zoom\n zoomIn: () => void;\n zoomOut: () => void;\n\n // Master volume\n setMasterVolume: (volume: number) => void;\n\n // Loop controls\n setLoopEnabled: (enabled: boolean) => void;\n setLoopRegion: (start: number, end: number) => void;\n setLoopRegionFromSelection: () => void;\n clearLoopRegion: () => void;\n\n // Undo/redo: the arrangement's history, engine or not (#812).\n undo: () => void;\n redo: () => void;\n\n // Recording\n /** Mark a recording session active/inactive. While active: (1) the\n * end-of-audio auto-stop is suppressed so overdub playback runs past the\n * end of existing material, and (2) with an `armedTrackId`, that track is\n * muted in the arrangement's mix for the session (#812): punch-in\n * recording replaces whatever the take overlaps (#579), so the doomed\n * material must not play under the overdub. The mixer and the track's Mute\n * button show it muted, the built-in `<TrackMuteButton />` of that track\n * is disabled, and `useTrack().isRecordingArmed` is true for it. The mute\n * from before the session is written back when it ends or the armed track\n * changes, whatever was set in between; nothing is written for a track\n * that is no longer in the arrangement. `useRecordingSession` calls it for\n * the length of a take; overdub flows should also call it eagerly (before\n * `play()`). */\n setRecordingActive: (active: boolean, armedTrackId?: string | null) => void;\n}\n\n/**\n * Refs and functions of the multitrack engine (#688). Like\n * `usePlaybackRefs()`, the value never changes.\n */\nexport interface EngineRefsContextValue {\n // Refs for direct time calculation in animated components (avoids timing drift)\n playbackStartTimeRef: React.RefObject<number>; // context.currentTime when playback started\n audioStartPositionRef: React.RefObject<number>; // Audio position when playback started\n /** Returns raw playback time from engine (auto-wraps at loop boundaries). */\n getPlaybackTime: () => number;\n /** Current time of the adapter's AudioContext, in seconds. */\n getAudioContextTime: () => number;\n /**\n * Returns the current adapter scheduler lookahead (Tone ~0.1s, native 0).\n * Use this for any audible-latency calculation that must match the playhead\n * (e.g., recording live-preview peak slicing).\n */\n getLookAhead: () => number;\n /**\n * Returns the adapter AudioContext's output latency in seconds.\n * Use this for audible-latency calculations (e.g., recording live-preview peak slicing).\n */\n getOutputLatency: () => number;\n /** The engine. `current` is null until the first build and during a rebuild. */\n playoutRef: React.RefObject<PlaylistEngine | null>;\n}\n\n/** Loop region (separate from selection), Audacity-style loop points (#768). */\nexport interface LoopContextValue {\n isLoopEnabled: boolean;\n loopStart: number;\n loopEnd: number;\n}\n\n/** The track selected for editing operations (#768). */\nexport interface SelectedTrackIdContextValue {\n selectedTrackId: string | null;\n}\n\n/** Whether undo and redo are available (#768). Changes after an edit. */\nexport interface UndoRedoContextValue {\n canUndo: boolean;\n canRedo: boolean;\n}\n\n/**\n * What is on the timeline (#768). Changes on every clip operation (a trim\n * once, on release: its moves are a preview only the dragged clip follows,\n * #812) and on a zoom (the peaks are computed per zoom level), so call\n * `usePlaylistTimeline()` only in a component\n * that draws tracks or needs the timeline length during render.\n */\nexport interface PlaylistTimelineContextValue {\n /**\n * The arrangement's tracks without the clips that are still loading\n * (#812): derived from the arrangement, never written back. Change them\n * through `useArrangement()`.\n */\n tracks: readonly ClipTrack[];\n /**\n * One row per track, in the order of `tracks`. A row also holds the\n * placeholder record (`isPlaceholder: true`) of each clip still loading,\n * which `tracks` does not have: find a record by `clipId`, never by position.\n */\n peaksDataArray: TrackClipPeaks[];\n /** The end, in seconds, of the loaded audio. */\n duration: number;\n /**\n * False until an engine is attached and the first sources have settled;\n * then false while a later engine is being built.\n */\n isReady: boolean;\n}\n\n/** Mixer state (#768). Changes on every mute, solo, volume or pan change. */\nexport interface PlaylistMixerContextValue {\n trackStates: TrackState[];\n masterVolume: number;\n}\n\n/** The live track-reorder drag (#768). Changes on every drag-over. */\nexport interface TrackReorderPreviewContextValue {\n /** Non-null while a track-reorder drag is live: the dragged track and the\n * index it would drop at. Both playlist columns derive their display\n * layout from it; a track's panel can read it to mirror the preview in\n * its own UI. */\n trackDragPreview: TrackDragPreview | null;\n /** Internal: incremented after every track-reorder drag interaction ends.\n * The view's track-controls part folds this into each slot's `key` to\n * force a remount, working around @dnd-kit sortable-plugin DOM corruption\n * (see bumpTrackReorderEpoch in EditorControlsContextValue). */\n trackReorderEpoch: number;\n}\n\n/**\n * INTERNAL (the context and its hook are not exported from the package,\n * #812): the track a take is being recorded onto, set by\n * `setRecordingActive(true, trackId)` and cleared when the session ends.\n * Changes when a take starts and ends and when the armed track changes. The\n * track controls read it and give each track's panel `isRecordingArmed`.\n */\nexport interface RecordingArmContextValue {\n armedTrackId: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// MediaElementPlaylistProvider only\n// ---------------------------------------------------------------------------\n\n/** The playback speed and its setter (#688). Changes when the speed does. */\nexport interface PlaybackRateContextValue {\n /** 0.5 to 2. */\n playbackRate: number;\n /** Clamped to 0.5–2. Stable identity. */\n setPlaybackRate: (rate: number) => void;\n}\n\n/**\n * The one track of a MediaElement player (#688). Changes when the track or the\n * zoom level does, and when the player becomes ready.\n */\nexport interface MediaElementTrackContextValue {\n /** The length of the track's audio, from its waveform data. Never 0 for a real track. */\n duration: number;\n /**\n * True once the media element has loaded its metadata, false again while a\n * replaced player loads. Use this, not `duration`, as \"the player can be used\".\n */\n isReady: boolean;\n /** One track with one clip (`[]` when the peak data could not be read). The clip carries the track's fadeIn / fadeOut. */\n peaksDataArray: TrackClipPeaks[];\n fadeIn?: FadeConfig;\n fadeOut?: FadeConfig;\n /** The player. `current` is null until it has been created. */\n playoutRef: React.RefObject<MediaElementPlayout | null>;\n}\n\n// ---------------------------------------------------------------------------\n// The contexts. Each holds fields that change together (#733, #740, #768).\n// ---------------------------------------------------------------------------\n\nconst slot = <T>() => createContext<Slot<T>>(null);\n\n// Shared\nexport const IsPlayingContext = slot<IsPlayingContextValue>();\nexport const PlaybackRefsContext = slot<PlaybackRefsContextValue>();\nexport const SelectionContext = slot<SelectionContextValue>();\nexport const CurrentTimeContext = slot<CurrentTimeContextValue>();\nexport const ActiveAnnotationContext = slot<ActiveAnnotationContextValue>();\nexport const AnnotationsContext = slot<AnnotationsContextValue>();\nexport const AnnotationOptionsContext = slot<AnnotationOptionsContextValue>();\nexport const PlaybackControlsContext = slot<PlaybackControlsContextValue>();\nexport const PlaylistViewContext = slot<PlaylistViewContextValue>();\nexport const PlaylistSettingsContext = slot<PlaylistSettingsContextValue>();\nexport const PlaylistZoomContext = slot<PlaylistZoomContextValue>();\n/**\n * INTERNAL (the context and its hook are not exported from the package): which\n * row the view draws as selected. Both providers serve it, so the tracks part\n * of the view needs no provider-specific hook: the multitrack provider gives\n * the value of `useSelectedTrackId()` (the same object), the MediaElement\n * provider its one track, always.\n */\nexport const SelectedRowContext = slot<SelectedTrackIdContextValue>();\n\n// WaveformPlaylistProvider only\n/** The arrangement the provider was given (#812). Never changes for a mount. */\nexport const ArrangementContext = slot<Arrangement>();\nexport const EditorControlsContext = slot<EditorControlsContextValue>();\nexport const EngineRefsContext = slot<EngineRefsContextValue>();\nexport const LoopContext = slot<LoopContextValue>();\nexport const SelectedTrackIdContext = slot<SelectedTrackIdContextValue>();\nexport const UndoRedoContext = slot<UndoRedoContextValue>();\nexport const PlaylistTimelineContext = slot<PlaylistTimelineContextValue>();\nexport const PlaylistMixerContext = slot<PlaylistMixerContextValue>();\nexport const TrackReorderPreviewContext = slot<TrackReorderPreviewContextValue>();\n/**\n * INTERNAL (neither context is exported from the package, #812): a clip trim\n * drag in progress. The first holds the preview source, which the drag\n * handlers write on every pointer move and clear on release and on cancel;\n * the second the stable function that draws the previewed clip. Both values\n * keep their identity for the life of the provider; only the dragged clip's\n * view and the root (for the width) subscribe to the source.\n */\nexport const TrimPreviewContext = slot<TrimPreviewHandle>();\nexport const TrimPreviewPeaksContext = slot<TrimPreviewPeaksValue>();\n/** INTERNAL (#812): see {@link RecordingArmContextValue}. */\nexport const RecordingArmContext = slot<RecordingArmContextValue>();\n\n// MediaElementPlaylistProvider only\nexport const PlaybackRateContext = slot<PlaybackRateContextValue>();\nexport const MediaElementTrackContext = slot<MediaElementTrackContextValue>();\n\n// ---------------------------------------------------------------------------\n// One hook per context. A component re-renders only when the value of a\n// context it reads changes, so read the smallest group that has the field.\n// ---------------------------------------------------------------------------\n\nfunction useSlot<T>(context: React.Context<Slot<T>>, hookName: string, needs: string): T {\n const value = use(context);\n if (value === BLOCKED) {\n const nearest = needs === WEB_AUDIO ? MEDIA_ELEMENT : WEB_AUDIO;\n throw new Error(\n `${hookName} needs ${needs}, and the nearest playlist provider here is ${nearest}, ` +\n 'which does not provide it'\n );\n }\n if (!value) {\n throw new Error(`${hookName} must be used within ${needs}`);\n }\n return value;\n}\n\nconst EITHER = `${WEB_AUDIO} or ${MEDIA_ELEMENT}`;\n\n/** `{ isPlaying }`. Re-renders on play, pause and stop. */\nexport const useIsPlaying = () => useSlot(IsPlayingContext, 'useIsPlaying', EITHER);\n\n/**\n * Refs and functions that never change identity: `currentTimeRef`,\n * `visualTimeRef`, `registerFrameCallback`, `unregisterFrameCallback`. Calling\n * this never re-renders the component. Read `.current` in a handler, an effect\n * or a frame callback; to re-render when the value behind a ref changes, also\n * call the hook that carries it (`useCurrentTime()`, `useIsPlaying()`).\n */\nexport const usePlaybackRefs = () => useSlot(PlaybackRefsContext, 'usePlaybackRefs', EITHER);\n\n/**\n * The selected time range. A component that calls this re-renders on every\n * pointer move of a selection drag, so call it in the smallest component that\n * shows the selection.\n */\nexport const useSelection = () => useSlot(SelectionContext, 'useSelection', EITHER);\n\n/**\n * Where the cursor rests, in seconds. A component that calls this re-renders\n * on every seek, pause and stop, and on every pointer move of a selection drag\n * to the left. The value does not advance during playback: for a live position\n * read `currentTimeRef` from `usePlaybackRefs()` or register a frame callback\n * there.\n */\nexport const useCurrentTime = () => useSlot(CurrentTimeContext, 'useCurrentTime', EITHER);\n\n/**\n * The id of the annotation that is playing or was last chosen, or `null`. A\n * component that calls this re-renders at every annotation boundary during\n * playback, so call it in the smallest component that shows the active one.\n */\nexport const useActiveAnnotation = () =>\n useSlot(ActiveAnnotationContext, 'useActiveAnnotation', EITHER);\n\n/** `{ annotations }`. Re-renders on an annotation edit. */\nexport const useAnnotations = () => useSlot(AnnotationsContext, 'useAnnotations', EITHER);\n\n/**\n * `{ editable, linkEndpoints, continuousPlay }`: the one home of the three\n * annotation options, under both providers. Re-renders when one is toggled.\n */\nexport const useAnnotationOptions = () =>\n useSlot(AnnotationOptionsContext, 'useAnnotationOptions', EITHER);\n\n/**\n * The actions both providers have: `play`, `pause`, `stop`, `seekTo`,\n * `setSelection`, the annotation store, and the annotation, scroll and\n * time-format setters. The value changes only when the provider's\n * `annotationStore` prop does.\n */\nexport const usePlaybackControls = () =>\n useSlot(PlaybackControlsContext, 'usePlaybackControls', EITHER);\n\n/**\n * `{ sampleRate, mono, indefinitePlayback }`: what the provider was\n * configured with that a view also reads. Re-renders on a prop change.\n */\nexport const usePlaylistView = () => useSlot(PlaylistViewContext, 'usePlaylistView', EITHER);\n\n/** `{ timeFormat, isAutomaticScroll }`. Re-renders when the user changes either. */\nexport const usePlaylistSettings = () =>\n useSlot(PlaylistSettingsContext, 'usePlaylistSettings', EITHER);\n\n/** `{ samplesPerPixel, canZoomIn, canZoomOut }`. Re-renders on a zoom. */\nexport const usePlaylistZoom = () => useSlot(PlaylistZoomContext, 'usePlaylistZoom', EITHER);\n\n/**\n * The arrangement of the nearest WaveformPlaylistProvider: the owner of the\n * tracks, the mix, the undo history and the loading (#812). Change the tracks\n * through it; the provider and the engine follow. The value never changes,\n * so calling this never re-renders.\n */\nexport const useArrangement = () => useSlot(ArrangementContext, 'useArrangement', WEB_AUDIO);\n\n/**\n * The multitrack editor's actions: track mixer and order, zoom, loop, undo,\n * annotation editing settings, recording. WaveformPlaylistProvider only. The\n * value never changes.\n */\nexport const useEditorControls = () =>\n useSlot(EditorControlsContext, 'useEditorControls', WEB_AUDIO);\n\n/**\n * The multitrack engine's refs and clock functions (`playoutRef`,\n * `getPlaybackTime`, `getLookAhead`, …). WaveformPlaylistProvider only. The\n * value never changes.\n */\nexport const useEngineRefs = () => useSlot(EngineRefsContext, 'useEngineRefs', WEB_AUDIO);\n\n/** `{ isLoopEnabled, loopStart, loopEnd }`. Re-renders on a loop change. */\nexport const useLoop = () => useSlot(LoopContext, 'useLoop', WEB_AUDIO);\n\n/** `{ selectedTrackId }`. Re-renders when another track is selected. */\nexport const useSelectedTrackId = () =>\n useSlot(SelectedTrackIdContext, 'useSelectedTrackId', WEB_AUDIO);\n\n/**\n * INTERNAL (not exported from the package): `{ selectedTrackId }` for the row\n * the view draws as selected, under either provider. Consumers use\n * `useSelectedTrackId()`, which only the multitrack provider serves.\n */\nexport const useSelectedRow = () => useSlot(SelectedRowContext, 'The tracks of the view', EITHER);\n\n/** `{ canUndo, canRedo }`. Re-renders after an edit. */\nexport const useUndoRedo = () => useSlot(UndoRedoContext, 'useUndoRedo', WEB_AUDIO);\n\n/**\n * `{ tracks, peaksDataArray, duration, isReady }`. A component that calls this\n * re-renders on every clip operation (a trim once, on release), on a zoom and\n * when audio arrives for a clip.\n */\nexport const usePlaylistTimeline = () =>\n useSlot(PlaylistTimelineContext, 'usePlaylistTimeline', WEB_AUDIO);\n\n/**\n * `{ trackStates, masterVolume }`. A component that calls this re-renders on\n * every mute, solo, volume or pan change (each step of a slider drag).\n */\nexport const usePlaylistMixer = () => useSlot(PlaylistMixerContext, 'usePlaylistMixer', WEB_AUDIO);\n\n/**\n * `{ trackDragPreview, trackReorderEpoch }`. A component that calls this\n * re-renders on every drag-over of a track reorder.\n */\nexport const useTrackReorderPreview = () =>\n useSlot(TrackReorderPreviewContext, 'useTrackReorderPreview', WEB_AUDIO);\n\n/**\n * INTERNAL (not exported from the package, #812): `{ armedTrackId }`, the\n * track a take is being recorded onto. Re-renders when a take starts or ends.\n */\nexport const useRecordingArm = () => useSlot(RecordingArmContext, 'useRecordingArm', WEB_AUDIO);\n\n/** `{ playbackRate, setPlaybackRate }`. MediaElementPlaylistProvider only. */\nexport const usePlaybackRate = () => useSlot(PlaybackRateContext, 'usePlaybackRate', MEDIA_ELEMENT);\n\n/**\n * `{ duration, isReady, peaksDataArray, fadeIn, fadeOut, playoutRef }`: the\n * one track of a MediaElement player. MediaElementPlaylistProvider only.\n */\nexport const useMediaElementTrack = () =>\n useSlot(MediaElementTrackContext, 'useMediaElementTrack', MEDIA_ELEMENT);\n\n/**\n * INTERNAL (not exported from the package): throws under\n * MediaElementPlaylistProvider, in the name of a hook that reads only shared\n * contexts but is not meant to run there. `usePlaybackShortcuts()` listens on\n * the window; what keys do for the single-track player is not decided yet.\n */\nexport const useWebAudioProviderOnly = (hookName: string): void => {\n useSlot(EditorControlsContext, hookName, WEB_AUDIO);\n};\n\n/**\n * INTERNAL (not exported from the package): the loop state, or `null` where\n * there is none (under the MediaElement provider). For the one hook that\n * starts playback under both providers.\n */\nexport const useLoopOptional = (): LoopContextValue | null => {\n const value = use(LoopContext);\n return value === BLOCKED ? null : value;\n};\nconst orNull = <T>(value: T | typeof BLOCKED | null): T | null =>\n value === BLOCKED ? null : value;\n\n/**\n * INTERNAL (not exported from the package): like {@link usePlaylistView} and\n * {@link usePlaylistZoom} but `null` when there is no provider above. For a\n * hook that may also be called outside one with explicit options.\n */\nexport const usePlaylistViewOptional = () => orNull(use(PlaylistViewContext));\nexport const usePlaylistZoomOptional = () => orNull(use(PlaylistZoomContext));\n\n/**\n * INTERNAL (not exported from the package): the trim preview source and the\n * previewed clip's drawing, or `null` under the MediaElement provider (which\n * blocks both) and outside a provider. The clip rows are shared by both\n * views, so their reads mean \"no preview\" there instead of throwing.\n */\nexport const useTrimPreviewOptional = () => orNull(use(TrimPreviewContext));\nexport const useTrimPreviewPeaksOptional = () => orNull(use(TrimPreviewPeaksContext));\n","import React from 'react';\nimport { flushSync } from 'react-dom';\nimport type { DragStartEvent, DragMoveEvent, DragEndEvent } from '@dnd-kit/abstract';\nimport {\n applyAnnotationBounds,\n updateAnnotationBoundaries,\n type AnnotationBoundsChange,\n type AnnotationData,\n type AnnotationStore,\n type ValueSourceHandle,\n} from '@waveform-playlist/core';\n\n/**\n * Where an annotation edge drag shows its moves while it is in progress:\n * the store's current annotations with the drag's moves on top, or `null`\n * when no drag is running. Both providers have one (`annotationPreview` in their controls).\n */\nexport type AnnotationPreviewHandle = ValueSourceHandle<AnnotationData[] | null>;\n\ninterface UseAnnotationDragHandlersOptions {\n /**\n * The owner of the annotations (`usePlaybackControls().annotationStore`).\n * The drag writes only the bounds it moved, by id, onto the store's list\n * as it is at the time of the write (#867). Without a store the handlers\n * do nothing.\n */\n store: AnnotationStore | undefined;\n samplesPerPixel: number;\n /** Sample rate for pixel-to-time conversion. Providers pass the real rate from\n * context; defaults to 48000 (the engine default) for out-of-provider usage. */\n sampleRate?: number;\n duration: number;\n linkEndpoints: boolean;\n /**\n * Pass the provider's `annotationPreview` to keep the drag out of your own\n * state: each move is published there (the built-in annotation boxes and\n * list follow it), and the annotations are written once, on release.\n * Without it they are written on every move, which re-renders whatever\n * reads them for each one.\n */\n preview?: AnnotationPreviewHandle;\n}\n\ninterface DragState {\n /** The store the drag began on: a drag ends when the provider's store changes. */\n store: AnnotationStore;\n /** The annotations as they were when the drag began, for Escape. */\n snapshot: readonly AnnotationData[];\n /**\n * The bounds of every annotation the drag has moved so far, by id, the\n * dragged one included. Kept for an annotation even when it is moved back\n * to where it was, so the next write and Escape include it.\n */\n touched: Map<string, AnnotationBoundsChange>;\n draggedId: string;\n edge: 'start' | 'end';\n /** The dragged annotation's bounds when the drag began. */\n start: number;\n end: number;\n}\n\n/** The drag's touched bounds as a list of changes. */\nfunction touchedChanges(drag: DragState): AnnotationBoundsChange[] {\n return [...drag.touched.values()];\n}\n\n/** The touched ids with the bounds they had when the drag began. */\nfunction snapshotBounds(drag: DragState): AnnotationBoundsChange[] {\n const before = new Map(drag.snapshot.map((a) => [a.id, a]));\n return [...drag.touched.keys()].flatMap((id) => {\n const old = before.get(id);\n return old ? [{ id, start: old.start, end: old.end }] : [];\n });\n}\n\n/** The store's current list with the drag's moves on top. */\nfunction shownDuringDrag(drag: DragState): readonly AnnotationData[] {\n return applyAnnotationBounds(drag.store.getAnnotations(), touchedChanges(drag));\n}\n\n/**\n * Custom hook for handling annotation drag operations (boundary trimming)\n *\n * Provides drag handlers for use with @dnd-kit/react DragDropProvider.\n * Handles annotation boundary resizing with linked endpoints support.\n * A cancelled drag (Escape) puts back every annotation it moved.\n *\n * @example\n * ```tsx\n * const { annotationStore, annotationPreview } = usePlaybackControls();\n * const { onDragStart, onDragMove, onDragEnd } = useAnnotationDragHandlers({\n * store: annotationStore,\n * preview: annotationPreview,\n * samplesPerPixel,\n * sampleRate,\n * duration,\n * linkEndpoints,\n * });\n *\n * return (\n * <DragDropProvider\n * onDragStart={onDragStart}\n * onDragMove={onDragMove}\n * onDragEnd={onDragEnd}\n * modifiers={[RestrictToHorizontalAxis]}\n * >\n * {renderAnnotations()}\n * </DragDropProvider>\n * );\n * ```\n */\nexport function useAnnotationDragHandlers({\n store,\n samplesPerPixel,\n // Default mirrors the engine default; the providers always pass the real rate from context (#510).\n sampleRate = 48000,\n duration,\n linkEndpoints,\n preview,\n}: UseAnnotationDragHandlersOptions) {\n const dragRef = React.useRef<DragState | null>(null);\n\n // Read through refs so the handlers keep their identity for the whole drag.\n const storeRef = React.useRef(store);\n storeRef.current = store;\n const previewRef = React.useRef(preview);\n previewRef.current = preview;\n\n /** End the drag without writing anything; clear its preview. */\n const abandon = React.useCallback(() => {\n if (!dragRef.current) return;\n dragRef.current = null;\n previewRef.current?.publish(null);\n }, []);\n\n // The drag follows its store (#867). A change made elsewhere is drawn at\n // once under the drag's moves (maintainer, 2026-11-24). When the dragged\n // annotation is removed (or the list cleared), or the provider is given\n // another store, or the component unmounts, the drag ends and writes nothing.\n React.useEffect(() => {\n if (!store) return;\n const unsubscribe = store.subscribe(() => {\n const drag = dragRef.current;\n if (!drag || drag.store !== store) return;\n if (!store.getAnnotations().some((a) => a.id === drag.draggedId)) {\n abandon();\n return;\n }\n const shown = previewRef.current;\n if (shown && shown.source.getSnapshot() !== null) {\n shown.publish(shownDuringDrag(drag) as AnnotationData[]);\n }\n });\n return () => {\n unsubscribe();\n abandon();\n };\n }, [store, abandon]);\n\n // A drag that never ends (its component unmounts mid-drag) must not leave\n // its preview on screen.\n React.useEffect(() => abandon, [preview, abandon]);\n\n const onDragStart = React.useCallback((event: DragStartEvent) => {\n const data = event.operation.source?.data as\n | {\n annotationId: string;\n annotationIndex: number;\n edge: 'start' | 'end';\n }\n | undefined;\n\n const owner = storeRef.current;\n if (!owner || !data) {\n dragRef.current = null;\n return;\n }\n const snapshot = owner.getAnnotations();\n const annotation =\n data.annotationIndex === undefined ? undefined : snapshot[data.annotationIndex];\n dragRef.current = annotation\n ? {\n store: owner,\n snapshot,\n touched: new Map(),\n draggedId: annotation.id,\n edge: data.edge,\n start: annotation.start,\n end: annotation.end,\n }\n : null;\n }, []);\n\n const onDragMove = React.useCallback(\n (event: DragMoveEvent) => {\n const drag = dragRef.current;\n if (!drag) return;\n if (drag.store !== storeRef.current) {\n abandon();\n return;\n }\n\n // The dragmove event is dispatched BEFORE position.current is updated (happens\n // in a microtask), so the snapshot's position.current is stale. Use event.to\n // (the pointer's current coordinates from the sensor) for the correct position.\n const currentX = event.to?.x ?? event.operation.position.current.x;\n const rawDeltaX = currentX - event.operation.position.initial.x;\n const timeDelta = (rawDeltaX * samplesPerPixel) / sampleRate;\n const newTime = drag.edge === 'start' ? drag.start + timeDelta : drag.end + timeDelta;\n\n // Each move runs over the store's current list with the drag's moves so\n // far on top: a neighbour the app moved during the drag collides where\n // it is now (maintainer's choice, 2026-11-24), and #747 still holds (an\n // edge dragged into a separated neighbour carries it along, because the\n // carried neighbour stays in `touched`). The dragged annotation is found\n // by id: an insert before it shifts its index.\n const base = shownDuringDrag(drag);\n const annotationIndex = base.findIndex((a) => a.id === drag.draggedId);\n if (annotationIndex < 0) {\n abandon();\n return;\n }\n // The boundary logic (linked endpoints, collisions) is core's, shared with\n // dawcore's annotation track.\n const updated = updateAnnotationBoundaries({\n annotationIndex,\n newTime,\n isDraggingStart: drag.edge === 'start',\n annotations: base,\n duration,\n linkEndpoints,\n });\n updated.forEach((annotation, i) => {\n const was = base[i];\n if (\n drag.touched.has(annotation.id) ||\n was.start !== annotation.start ||\n was.end !== annotation.end\n ) {\n drag.touched.set(annotation.id, {\n id: annotation.id,\n start: annotation.start,\n end: annotation.end,\n });\n }\n });\n\n if (preview) {\n preview.publish(updated);\n } else {\n const changes = touchedChanges(drag);\n drag.store.update((current) => applyAnnotationBounds(current, changes));\n }\n },\n [samplesPerPixel, sampleRate, duration, linkEndpoints, preview, abandon]\n );\n\n const onDragEnd = React.useCallback(\n (event: DragEndEvent) => {\n const drag = dragRef.current;\n dragRef.current = null;\n if (!drag) return;\n if (drag.store !== storeRef.current) {\n preview?.publish(null);\n return;\n }\n\n if (!preview) {\n // The moves were written as they happened; a cancelled drag takes\n // them all back, the neighbours it moved included.\n if (event.canceled) {\n const restore = snapshotBounds(drag);\n drag.store.update((current) => applyAnnotationBounds(current, restore));\n }\n return;\n }\n\n if (preview.source.getSnapshot() === null) return;\n if (event.canceled) {\n preview.publish(null);\n return;\n }\n // Committed and cleared in one synchronous render, so the boxes never\n // show the old positions between the two.\n flushSync(() => {\n // Only what the drag moved, onto the list as it is now. When the\n // dragged annotation is gone, the release does nothing (#867).\n // The preview is cleared also when the app's rule throws.\n try {\n const changes = touchedChanges(drag);\n drag.store.update((current) =>\n current.some((a) => a.id === drag.draggedId)\n ? applyAnnotationBounds(current, changes)\n : current\n );\n } finally {\n preview.publish(null);\n }\n });\n },\n [preview]\n );\n\n return {\n onDragStart,\n onDragMove,\n onDragEnd,\n };\n}\n","import { useSyncExternalStore } from 'react';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport type { AnnotationPreviewHandle } from './useAnnotationDragHandlers';\n\n/**\n * The annotations to draw: the provider's, or while an edge is being dragged\n * with a preview (`useAnnotationDragHandlers({ preview })`), the annotations\n * as the drag would leave them.\n *\n * Call it in the component that draws annotations (a custom list or row of\n * boxes), with `annotationPreview` from the provider's controls. Only that\n * component then re-renders per pointer move of the drag.\n */\nexport function useAnnotationsWithPreview(\n annotations: readonly AnnotationData[],\n preview: AnnotationPreviewHandle\n): readonly AnnotationData[] {\n const { subscribe, getSnapshot } = preview.source;\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot) ?? annotations;\n}\n","/**\n * Hook for configuring @dnd-kit sensors for clip dragging\n *\n * Provides consistent drag activation behavior across all examples.\n * Always overrides PointerSensor defaults with custom activation constraints:\n * - Default mode: distance-based activation (1px) for all pointer types\n * - Touch-optimized mode: delay-based activation for touch (250ms),\n * distance-based for mouse/pen\n */\n\nimport { useMemo } from 'react';\nimport { PointerSensor, PointerActivationConstraints } from '@dnd-kit/dom';\nimport type { PluginDescriptor } from '@dnd-kit/abstract';\n\nexport interface DragSensorOptions {\n /**\n * Enable mobile-optimized touch handling with delay-based activation.\n * When true, touch events get delay-based activation while mouse/pen get distance-based.\n * When false (default), all pointer types use distance-based activation (1px).\n */\n touchOptimized?: boolean;\n /**\n * Delay in milliseconds before touch drag activates (only when touchOptimized is true).\n * Default: 250ms - long enough to distinguish from scroll intent\n */\n touchDelay?: number;\n /**\n * Distance tolerance during touch delay (only when touchOptimized is true).\n * If finger moves more than this during delay, drag is cancelled.\n * Default: 5px - allows slight finger movement\n */\n touchTolerance?: number;\n /**\n * Distance in pixels before mouse drag activates.\n * Default: 1px for immediate feedback on desktop\n */\n mouseDistance?: number;\n}\n\n/**\n * Returns configured sensors for @dnd-kit drag operations\n *\n * @param options - Configuration options for drag sensors\n * @returns Array of sensor constructors/descriptors for DragDropProvider's sensors prop\n *\n * @example\n * // Desktop-optimized (default — 1px distance activation for all pointer types)\n * const sensors = useDragSensors();\n *\n * @example\n * // Mobile-optimized with custom touch delay\n * const sensors = useDragSensors({ touchOptimized: true, touchDelay: 300 });\n */\nexport function useDragSensors(\n options: DragSensorOptions = {}\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): (typeof PointerSensor | PluginDescriptor<any, any, any>)[] {\n const {\n touchOptimized = false,\n touchDelay = 250,\n touchTolerance = 5,\n mouseDistance = 1,\n } = options;\n\n return useMemo(() => {\n if (touchOptimized) {\n // Custom activation constraints for touch-optimized mode\n return [\n PointerSensor.configure({\n activationConstraints(event) {\n // Touch events get delay-based activation\n if (event.pointerType === 'touch') {\n return [\n new PointerActivationConstraints.Delay({\n value: touchDelay,\n tolerance: touchTolerance,\n }),\n ];\n }\n // Mouse/pen get distance-based activation\n return [new PointerActivationConstraints.Distance({ value: mouseDistance })];\n },\n }),\n ];\n }\n\n // Default: PointerSensor with distance-based activation\n return [\n PointerSensor.configure({\n activationConstraints: [\n new PointerActivationConstraints.Distance({ value: mouseDistance }),\n ],\n }),\n ];\n }, [touchOptimized, touchDelay, touchTolerance, mouseDistance]);\n}\n","import { useCallback } from 'react';\nimport { calculateSplitPoint, canSplitAt } from '@waveform-playlist/engine';\nimport {\n useArrangement,\n usePlaylistView,\n usePlaybackRefs,\n useSelectedTrackId,\n} from '../contexts/playlistContexts';\nimport { loadedClipsOf } from '../utils/loadedTracks';\n\nexport interface UseClipSplittingOptions {\n samplesPerPixel: number;\n}\n\nexport interface UseClipSplittingResult {\n splitClipAtPlayhead: () => boolean;\n splitClipAt: (trackId: string, clipId: string, splitTime: number) => boolean;\n}\n\n/**\n * Hook for splitting clips at the playhead or at a specific time\n *\n * Splitting is one `arrangement.splitClip()` on the provider's arrangement\n * (`useArrangement()`): an undo step, engine or not; the engine and the view\n * follow the arrangement. Throws outside `WaveformPlaylistProvider`.\n *\n * @param options - Configuration options\n * @returns Object with split functions\n *\n * @example\n * ```tsx\n * const { samplesPerPixel } = usePlaylistZoom();\n * const { splitClipAtPlayhead } = useClipSplitting({ samplesPerPixel });\n *\n * // In keyboard handler\n * const handleKeyPress = (e: KeyboardEvent) => {\n * if (e.key === 's' || e.key === 'S') {\n * splitClipAtPlayhead();\n * }\n * };\n * ```\n */\nexport const useClipSplitting = (options: UseClipSplittingOptions): UseClipSplittingResult => {\n const { samplesPerPixel } = options;\n const arrangement = useArrangement();\n const { sampleRate } = usePlaylistView();\n const { currentTimeRef } = usePlaybackRefs();\n const { selectedTrackId } = useSelectedTrackId();\n\n /**\n * Split a specific clip at a given time\n *\n * @param trackId - Id of the track containing the clip\n * @param clipId - Id of the clip\n * @param splitTime - Timeline position where to split (in seconds)\n * @returns true if pre-validation passed and the arrangement was called, false otherwise\n * (also for a track id or clip id that is not there, or a clip still loading:\n * nothing changes). Note: splitClip() returns void so a true here assumes the\n * arrangement accepted the split (it performs its own canSplitAt check).\n */\n const splitClipAt = useCallback(\n (trackId: string, clipId: string, splitTime: number): boolean => {\n const track = arrangement.getTracks().find((t) => t.id === trackId);\n if (!track) return false;\n\n // A clip still loading cannot be split.\n const clip = loadedClipsOf(track).find((c) => c.id === clipId);\n if (!clip) return false;\n\n // Convert split time to sample position, snapped to pixel boundary\n const splitSample = Math.round(splitTime * sampleRate);\n const snappedSplitSample = calculateSplitPoint(splitSample, samplesPerPixel);\n\n // Pre-flight validation before sending to engine (engine also validates internally).\n // Duplicated here to provide early user feedback via console.warn.\n const MIN_DURATION_SAMPLES = Math.floor(0.1 * sampleRate);\n if (!canSplitAt(clip, snappedSplitSample, MIN_DURATION_SAMPLES)) {\n console.warn('Split point is invalid (outside bounds or too close to edge)');\n return false;\n }\n\n arrangement.splitClip(track.id, clip.id, snappedSplitSample);\n return true;\n },\n [arrangement, samplesPerPixel, sampleRate]\n );\n\n /**\n * Split clip at the current playhead position on the selected track\n * If no track is selected, does nothing\n *\n * @returns true if a clip was split, false otherwise\n */\n const splitClipAtPlayhead = useCallback((): boolean => {\n // If no track is selected, cannot split\n if (!selectedTrackId) {\n console.warn('[waveform-playlist] No track selected — click a clip to select a track first');\n return false;\n }\n\n // Find the selected track\n const track = arrangement.getTracks().find((t) => t.id === selectedTrackId);\n if (!track) {\n console.warn('Selected track not found');\n return false;\n }\n\n // Use ref for real-time position during playback (state updates are throttled)\n const currentTime = currentTimeRef.current ?? 0;\n\n // Find clip at current time on the selected track\n for (const clip of loadedClipsOf(track)) {\n const clipStartTime = clip.startSample / sampleRate;\n const clipEndTime = (clip.startSample + clip.durationSamples) / sampleRate;\n\n // Check if currentTime is within this clip (not at boundaries)\n if (currentTime > clipStartTime && currentTime < clipEndTime) {\n // Found a clip! Split it\n return splitClipAt(track.id, clip.id, currentTime);\n }\n }\n\n console.warn(`[waveform-playlist] No clip found at playhead position on track \"${track.name}\"`);\n return false;\n }, [arrangement, currentTimeRef, selectedTrackId, splitClipAt, sampleRate]);\n\n return {\n splitClipAtPlayhead,\n splitClipAt,\n };\n};\n","import { useEffect, useRef } from 'react';\nimport { handleKeyboardEvent } from '@waveform-playlist/core';\nimport type { KeyboardShortcut } from '@waveform-playlist/core';\n\nexport interface UseKeyboardShortcutsOptions {\n shortcuts: KeyboardShortcut[];\n enabled?: boolean;\n}\n\n/**\n * Hook for managing keyboard shortcuts\n *\n * @param options - Configuration options\n *\n * @example\n * ```tsx\n * useKeyboardShortcuts({\n * shortcuts: [\n * {\n * key: ' ',\n * action: togglePlayPause,\n * description: 'Play/Pause',\n * preventDefault: true,\n * },\n * {\n * key: 's',\n * action: splitClipAtPlayhead,\n * description: 'Split clip at playhead',\n * preventDefault: true,\n * },\n * ],\n * });\n * ```\n */\nexport const useKeyboardShortcuts = (options: UseKeyboardShortcutsOptions): void => {\n const { shortcuts, enabled = true } = options;\n\n // The listener reads the latest shortcuts from a ref. Callers build the array\n // inline, so its identity changes on every render; keyed on it, the window\n // listener was removed and re-added each time.\n const shortcutsRef = useRef(shortcuts);\n useEffect(() => {\n shortcutsRef.current = shortcuts;\n });\n\n useEffect(() => {\n if (!enabled) return;\n\n const handleKeyDown = (event: KeyboardEvent) =>\n handleKeyboardEvent(event, shortcutsRef.current, true);\n window.addEventListener('keydown', handleKeyDown);\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown);\n };\n }, [enabled]);\n};\n","import { useCallback } from 'react';\nimport {\n usePlaybackControls,\n useIsPlaying,\n useWebAudioProviderOnly,\n} from '../contexts/playlistContexts';\nimport { usePlayFromSelectionOrCursor } from './usePlayFromSelectionOrCursor';\nimport type { KeyboardShortcut } from '@waveform-playlist/core';\nimport { useKeyboardShortcuts } from './useKeyboardShortcuts';\n\nexport interface UsePlaybackShortcutsOptions {\n /**\n * Enable the shortcuts. Defaults to true.\n */\n enabled?: boolean;\n /**\n * Additional shortcuts to include alongside the default playback shortcuts.\n */\n additionalShortcuts?: KeyboardShortcut[];\n /**\n * Override default shortcuts. If provided, only these shortcuts will be used.\n */\n shortcuts?: KeyboardShortcut[];\n}\n\nexport interface UsePlaybackShortcutsReturn {\n /** Rewind to the beginning (time = 0) */\n rewindToStart: () => void;\n /** Toggle play/pause */\n togglePlayPause: () => void;\n /** Stop playback and return to start position */\n stopPlayback: () => void;\n /** The list of active keyboard shortcuts */\n shortcuts: KeyboardShortcut[];\n}\n\n/**\n * Hook that provides common playback keyboard shortcuts for the playlist.\n *\n * Default shortcuts:\n * - `Space` - Toggle play/pause\n * - `Escape` - Stop playback\n * - `0` - Rewind to start (seek to time 0)\n *\n * @example\n * ```tsx\n * // Basic usage - enables default shortcuts\n * usePlaybackShortcuts();\n *\n * // With additional custom shortcuts\n * usePlaybackShortcuts({\n * additionalShortcuts: [\n * { key: 's', action: splitClipAtPlayhead, description: 'Split clip' },\n * ],\n * });\n *\n * // Completely override shortcuts\n * usePlaybackShortcuts({\n * shortcuts: [\n * { key: 'Home', action: rewindToStart, description: 'Go to start' },\n * ],\n * });\n * ```\n */\nexport const usePlaybackShortcuts = (\n options: UsePlaybackShortcutsOptions = {}\n): UsePlaybackShortcutsReturn => {\n const { enabled = true, additionalShortcuts = [], shortcuts: overrideShortcuts } = options;\n\n // The keys act on the whole window, so this hook is not for a page that may\n // hold several single-track players (maintainer's decision, #688).\n useWebAudioProviderOnly('usePlaybackShortcuts');\n const { isPlaying } = useIsPlaying();\n const { seekTo, pause, stop } = usePlaybackControls();\n // Space starts playback exactly as the Play button does.\n const playFromSelectionOrCursor = usePlayFromSelectionOrCursor();\n\n /**\n * Toggle between play and pause.\n */\n const togglePlayPause = useCallback(() => {\n if (isPlaying) {\n pause();\n } else {\n playFromSelectionOrCursor().catch((err) => {\n console.warn('[waveform-playlist] Playback failed to start: ' + String(err));\n });\n }\n }, [isPlaying, playFromSelectionOrCursor, pause]);\n\n /**\n * Stop playback and return to start position.\n */\n const stopPlayback = useCallback(() => {\n stop();\n }, [stop]);\n\n /**\n * Rewind to the beginning of the timeline.\n * If playing, stops and restarts playback from the beginning.\n */\n const rewindToStart = useCallback(() => {\n seekTo(0);\n }, [seekTo]);\n\n // Default playback shortcuts\n const defaultShortcuts: KeyboardShortcut[] = [\n {\n key: ' ',\n action: togglePlayPause,\n description: 'Play/Pause',\n preventDefault: true,\n },\n {\n key: 'Escape',\n action: stopPlayback,\n description: 'Stop',\n preventDefault: true,\n },\n {\n key: '0',\n action: rewindToStart,\n description: 'Rewind to start',\n preventDefault: true,\n },\n ];\n\n // Use override shortcuts if provided, otherwise combine defaults with additional\n const activeShortcuts = overrideShortcuts ?? [...defaultShortcuts, ...additionalShortcuts];\n\n // Register the keyboard shortcuts\n useKeyboardShortcuts({\n shortcuts: activeShortcuts,\n enabled,\n });\n\n return {\n rewindToStart,\n togglePlayPause,\n stopPlayback,\n shortcuts: activeShortcuts,\n };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n usePlaybackControls,\n useSelection,\n usePlaybackRefs,\n useLoopOptional,\n} from '../contexts/playlistContexts';\n\n/**\n * The one way playback is started by the built-in controls, so the Play button\n * and the Space shortcut cannot drift apart:\n *\n * - a highlighted selection, with looping off: play the selection, then stop.\n * If the cursor is inside the selection (playback was paused there), resume\n * from the cursor to the selection's end instead of starting over;\n * - otherwise: play from the cursor. With looping on, the transport's own loop\n * handles the boundaries.\n *\n * The returned function keeps its identity; it reads the latest selection and\n * loop state when it is called.\n */\nexport function usePlayFromSelectionOrCursor(): () => Promise<void> {\n const { currentTimeRef } = usePlaybackRefs();\n const { selectionStart, selectionEnd } = useSelection();\n // No loop under the MediaElement provider.\n const isLoopEnabled = useLoopOptional()?.isLoopEnabled ?? false;\n const { play } = usePlaybackControls();\n\n const latest = useRef({ selectionStart, selectionEnd, isLoopEnabled });\n useEffect(() => {\n latest.current = { selectionStart, selectionEnd, isLoopEnabled };\n });\n\n return useCallback(async () => {\n const { selectionStart: start, selectionEnd: end, isLoopEnabled: looping } = latest.current;\n const cursor = currentTimeRef.current ?? 0;\n if (end > start && !looping) {\n // Paused part-way through the selection: carry on from the cursor.\n const from = cursor > start && cursor < end ? cursor : start;\n await play(from, end - from);\n } else {\n await play(cursor);\n }\n }, [play, currentTimeRef]);\n}\n","import { useCallback, useMemo, useEffect, useSyncExternalStore } from 'react';\nimport type { AnnotationData, AnnotationStore } from '@waveform-playlist/core';\nimport { usePlaylistViewOptional, usePlaylistZoomOptional } from '../contexts/playlistContexts';\nimport { useKeyboardShortcuts } from './useKeyboardShortcuts';\nimport { moveAnnotationEnd, moveAnnotationStart } from '../utils/annotationBoundaryKeys';\n\nconst TIME_DELTA = 0.01; // 10ms adjustment per keypress\n\ninterface UseAnnotationKeyboardControlsOptions {\n /**\n * The owner of the annotations (`usePlaybackControls().annotationStore`).\n * The keys read the store, and each boundary key changes the active\n * annotation, found by id, in the store's list as it is when the key is\n * pressed (#867). Without a store there is nothing to move or select.\n */\n store: AnnotationStore | undefined;\n activeAnnotationId: string | null;\n /** Callback to set the active annotation ID for selection */\n onActiveAnnotationChange?: (id: string | null) => void;\n duration: number;\n linkEndpoints: boolean;\n /** Whether continuous play is enabled (affects playback duration) */\n continuousPlay?: boolean;\n enabled?: boolean;\n /** Optional: scroll container ref for auto-scrolling to annotation */\n scrollContainerRef?: React.RefObject<HTMLDivElement | null>;\n /** Optional: callback to start playback at a time with optional duration */\n onPlay?: (startTime: number, duration?: number) => void;\n /**\n * Pixels-per-sample for auto-scroll positioning. Falls back to the\n * WaveformPlaylistProvider context when omitted (WebAudio path). Pass\n * explicitly when used outside that provider (e.g. the MediaElement path).\n */\n samplesPerPixel?: number;\n /** Sample rate for auto-scroll positioning. Falls back to context. */\n sampleRate?: number;\n}\n\n/**\n * Hook for keyboard-based annotation navigation and boundary editing\n *\n * Navigation Shortcuts:\n * - ArrowUp / ArrowLeft = Select previous annotation\n * - ArrowDown / ArrowRight = Select next annotation\n * - Home = Select first annotation\n * - End = Select last annotation\n * - Escape = Deselect annotation\n * - Enter = Play selected annotation\n *\n * Boundary Editing Shortcuts (requires active annotation):\n * - [ = Move start boundary earlier (left)\n * - ] = Move start boundary later (right)\n * - Shift+[ = Move end boundary earlier (left)\n * - Shift+] = Move end boundary later (right)\n *\n * Respects linkEndpoints and continuousPlay settings.\n *\n * @example\n * ```tsx\n * const { annotationStore, setActiveAnnotationId } = usePlaybackControls();\n * useAnnotationKeyboardControls({\n * store: annotationStore,\n * activeAnnotationId,\n * onActiveAnnotationChange: setActiveAnnotationId,\n * duration,\n * linkEndpoints,\n * });\n * ```\n */\nconst NO_ANNOTATIONS: readonly AnnotationData[] = Object.freeze([]);\nconst noSubscription = () => () => {};\nconst noAnnotations = () => NO_ANNOTATIONS;\n\nexport function useAnnotationKeyboardControls({\n store,\n activeAnnotationId,\n onActiveAnnotationChange,\n duration,\n linkEndpoints,\n continuousPlay = false,\n enabled = true,\n scrollContainerRef,\n onPlay,\n samplesPerPixel: samplesPerPixelProp,\n sampleRate: sampleRateProp,\n}: UseAnnotationKeyboardControlsOptions) {\n // Called on every render, with a stand-in when there is no store.\n // Wrapped, so a store whose methods use `this` keeps working.\n const source = useMemo(\n () =>\n store\n ? {\n subscribe: (listener: () => void) => store.subscribe(listener),\n getSnapshot: () => store.getAnnotations(),\n }\n : { subscribe: noSubscription, getSnapshot: noAnnotations },\n [store]\n );\n const stored = useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);\n const annotations = stored;\n\n // Auto-scroll positioning needs samplesPerPixel/sampleRate. Prefer explicit\n // props (works in the MediaElement path); otherwise read them from the\n // provider's contexts (either provider renders them). The optional readers\n // return null instead of throwing, so this hook is safe outside a provider.\n const playlistView = usePlaylistViewOptional();\n const playlistZoom = usePlaylistZoomOptional();\n const samplesPerPixel = samplesPerPixelProp ?? playlistZoom?.samplesPerPixel;\n const sampleRate = sampleRateProp ?? playlistView?.sampleRate;\n\n const activeIndex = useMemo(() => {\n if (!activeAnnotationId) return -1;\n return annotations.findIndex((a) => a.id === activeAnnotationId);\n }, [annotations, activeAnnotationId]);\n\n // Scroll waveform to show a specific annotation\n const scrollToAnnotation = useCallback(\n (annotationId: string) => {\n if (!scrollContainerRef?.current || !samplesPerPixel || !sampleRate) return;\n\n const annotation = annotations.find((a) => a.id === annotationId);\n if (!annotation) return;\n\n const container = scrollContainerRef.current;\n const containerWidth = container.clientWidth;\n\n // Calculate pixel positions for annotation start and center\n const startPixel = (annotation.start * sampleRate) / samplesPerPixel;\n const endPixel = (annotation.end * sampleRate) / samplesPerPixel;\n const annotationCenter = (startPixel + endPixel) / 2;\n\n // Check if annotation is currently visible\n const scrollLeft = container.scrollLeft;\n const visibleStart = scrollLeft;\n const visibleEnd = scrollLeft + containerWidth;\n\n // If annotation is not fully visible, scroll to center it\n if (startPixel < visibleStart || endPixel > visibleEnd) {\n const targetScrollLeft = Math.max(0, annotationCenter - containerWidth / 2);\n container.scrollTo({\n left: targetScrollLeft,\n behavior: 'smooth',\n });\n }\n },\n [annotations, scrollContainerRef, samplesPerPixel, sampleRate]\n );\n\n // Auto-scroll when active annotation changes via keyboard navigation\n useEffect(() => {\n if (activeAnnotationId && scrollContainerRef?.current && samplesPerPixel && sampleRate) {\n scrollToAnnotation(activeAnnotationId);\n }\n }, [activeAnnotationId, scrollToAnnotation, scrollContainerRef, samplesPerPixel, sampleRate]);\n\n const moveStartBoundary = useCallback(\n (delta: number) => {\n store?.update((current) => {\n const index = current.findIndex((a) => a.id === activeAnnotationId);\n return index < 0 ? current : moveAnnotationStart(current, index, delta, { linkEndpoints });\n });\n },\n [store, activeAnnotationId, linkEndpoints]\n );\n\n const moveEndBoundary = useCallback(\n (delta: number) => {\n store?.update((current) => {\n const index = current.findIndex((a) => a.id === activeAnnotationId);\n return index < 0\n ? current\n : moveAnnotationEnd(current, index, delta, { linkEndpoints, duration });\n });\n },\n [store, activeAnnotationId, duration, linkEndpoints]\n );\n\n // Navigation functions\n const selectPrevious = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n\n if (activeIndex <= 0) {\n // If no selection or at first, select last annotation\n onActiveAnnotationChange(annotations[annotations.length - 1].id);\n } else {\n onActiveAnnotationChange(annotations[activeIndex - 1].id);\n }\n }, [annotations, activeIndex, onActiveAnnotationChange]);\n\n const selectNext = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n\n if (activeIndex < 0 || activeIndex >= annotations.length - 1) {\n // If no selection or at last, select first annotation\n onActiveAnnotationChange(annotations[0].id);\n } else {\n onActiveAnnotationChange(annotations[activeIndex + 1].id);\n }\n }, [annotations, activeIndex, onActiveAnnotationChange]);\n\n const selectFirst = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n onActiveAnnotationChange(annotations[0].id);\n }, [annotations, onActiveAnnotationChange]);\n\n const selectLast = useCallback(() => {\n if (!onActiveAnnotationChange || annotations.length === 0) return;\n onActiveAnnotationChange(annotations[annotations.length - 1].id);\n }, [annotations, onActiveAnnotationChange]);\n\n const clearSelection = useCallback(() => {\n if (!onActiveAnnotationChange) return;\n onActiveAnnotationChange(null);\n }, [onActiveAnnotationChange]);\n\n // Play the currently selected annotation\n const playActiveAnnotation = useCallback(() => {\n if (activeIndex < 0 || !onPlay) return;\n\n const annotation = annotations[activeIndex];\n // If continuous play is off, play just this annotation's duration\n const playDuration = !continuousPlay ? annotation.end - annotation.start : undefined;\n onPlay(annotation.start, playDuration);\n }, [annotations, activeIndex, continuousPlay, onPlay]);\n\n // Shortcuts that require an active annotation (boundary editing + playback)\n const activeAnnotationShortcuts = useMemo(\n () => [\n {\n key: '[',\n action: () => moveStartBoundary(-TIME_DELTA),\n description: 'Move annotation start earlier',\n preventDefault: true,\n },\n {\n key: ']',\n action: () => moveStartBoundary(TIME_DELTA),\n description: 'Move annotation start later',\n preventDefault: true,\n },\n {\n key: '{',\n shiftKey: true,\n action: () => moveEndBoundary(-TIME_DELTA),\n description: 'Move annotation end earlier',\n preventDefault: true,\n },\n {\n key: '}',\n shiftKey: true,\n action: () => moveEndBoundary(TIME_DELTA),\n description: 'Move annotation end later',\n preventDefault: true,\n },\n {\n key: 'Enter',\n action: playActiveAnnotation,\n description: 'Play selected annotation',\n preventDefault: true,\n },\n ],\n [moveStartBoundary, moveEndBoundary, playActiveAnnotation]\n );\n\n // Navigation shortcuts (always active when enabled and there are annotations)\n const navigationShortcuts = useMemo(\n () => [\n {\n key: 'ArrowUp',\n action: selectPrevious,\n description: 'Select previous annotation',\n preventDefault: true,\n },\n {\n key: 'ArrowLeft',\n action: selectPrevious,\n description: 'Select previous annotation',\n preventDefault: true,\n },\n {\n key: 'ArrowDown',\n action: selectNext,\n description: 'Select next annotation',\n preventDefault: true,\n },\n {\n key: 'ArrowRight',\n action: selectNext,\n description: 'Select next annotation',\n preventDefault: true,\n },\n {\n key: 'Home',\n action: selectFirst,\n description: 'Select first annotation',\n preventDefault: true,\n },\n {\n key: 'End',\n action: selectLast,\n description: 'Select last annotation',\n preventDefault: true,\n },\n {\n key: 'Escape',\n action: clearSelection,\n description: 'Deselect annotation',\n preventDefault: true,\n },\n ],\n [selectPrevious, selectNext, selectFirst, selectLast, clearSelection]\n );\n\n // Active annotation shortcuts only work when an annotation is selected\n useKeyboardShortcuts({\n shortcuts: activeAnnotationShortcuts,\n enabled: enabled && activeIndex >= 0,\n });\n\n // Navigation shortcuts work whenever there are annotations\n useKeyboardShortcuts({\n shortcuts: navigationShortcuts,\n enabled: enabled && annotations.length > 0 && !!onActiveAnnotationChange,\n });\n\n return {\n moveStartBoundary,\n moveEndBoundary,\n selectPrevious,\n selectNext,\n selectFirst,\n selectLast,\n clearSelection,\n scrollToAnnotation,\n playActiveAnnotation,\n };\n}\n","import type { AnnotationData } from '@waveform-playlist/core';\n\n/** Edges closer than this (10 ms) count as linked. */\nconst LINK_THRESHOLD = 0.01;\n/** The shortest an annotation can be made by a boundary key. */\nconst MIN_LENGTH = 0.1;\n\n/** `list` itself when no bound changed, so an update with it tells nobody. */\nfunction unlessUnchanged(\n list: readonly AnnotationData[],\n updated: readonly AnnotationData[]\n): readonly AnnotationData[] {\n const same = updated.every((a, i) => a.start === list[i].start && a.end === list[i].end);\n return same ? list : updated;\n}\n\n/**\n * Move the start of `list[index]` by `delta` seconds, as the `[` and `]` keys\n * do: clamped to 0 and to `MIN_LENGTH` before the end. With linked endpoints\n * the previous annotation's end follows when it touched; without, it is\n * pushed back when the new start would overlap it. Returns a new list.\n */\nexport function moveAnnotationStart(\n list: readonly AnnotationData[],\n index: number,\n delta: number,\n { linkEndpoints }: { linkEndpoints: boolean }\n): readonly AnnotationData[] {\n const annotation = list[index];\n const newStart = Math.max(0, Math.min(annotation.end - MIN_LENGTH, annotation.start + delta));\n const actualDelta = newStart - annotation.start;\n\n const updated = [...list];\n updated[index] = { ...annotation, start: newStart };\n\n if (linkEndpoints && index > 0) {\n const prev = updated[index - 1];\n if (Math.abs(prev.end - annotation.start) < LINK_THRESHOLD) {\n // Already linked: move the previous annotation's end together.\n updated[index - 1] = {\n ...prev,\n end: Math.max(prev.start + MIN_LENGTH, prev.end + actualDelta),\n };\n }\n } else if (!linkEndpoints && index > 0) {\n // Not linked: do not overlap the previous annotation.\n const prev = updated[index - 1];\n if (newStart < prev.end) {\n updated[index - 1] = { ...prev, end: newStart };\n }\n }\n return unlessUnchanged(list, updated);\n}\n\n/**\n * Move the end of `list[index]` by `delta` seconds, as the `{` and `}` keys\n * do: clamped to `duration` and to `MIN_LENGTH` after the start. With linked\n * endpoints the next annotation's start follows when it touched, and the\n * change cascades along a chain of linked edges; without, the next\n * annotations are pushed forward when they would overlap. Returns a new list.\n */\nexport function moveAnnotationEnd(\n list: readonly AnnotationData[],\n index: number,\n delta: number,\n { linkEndpoints, duration }: { linkEndpoints: boolean; duration: number }\n): readonly AnnotationData[] {\n const annotation = list[index];\n const newEnd = Math.max(\n annotation.start + MIN_LENGTH,\n Math.min(duration, annotation.end + delta)\n );\n const actualDelta = newEnd - annotation.end;\n\n const updated = [...list];\n updated[index] = { ...annotation, end: newEnd };\n\n if (linkEndpoints && index < list.length - 1) {\n const next = updated[index + 1];\n if (Math.abs(next.start - annotation.end) < LINK_THRESHOLD) {\n // Already linked: move the next annotation's start together.\n updated[index + 1] = {\n ...next,\n start: Math.min(next.end - MIN_LENGTH, next.start + actualDelta),\n };\n\n // Cascade along linked edges.\n let current = index + 1;\n while (current < updated.length - 1) {\n const moved = updated[current];\n const following = updated[current + 1];\n if (Math.abs(following.start - list[current].end) < LINK_THRESHOLD) {\n const nextDelta = moved.end - list[current].end;\n updated[current + 1] = {\n ...following,\n start: Math.min(following.end - MIN_LENGTH, following.start + nextDelta),\n };\n current++;\n } else {\n break;\n }\n }\n }\n } else if (!linkEndpoints && index < list.length - 1) {\n // Not linked: do not overlap the next annotation.\n const next = updated[index + 1];\n if (newEnd > next.start) {\n updated[index + 1] = { ...next, start: newEnd };\n\n // Cascade collisions.\n let current = index + 1;\n while (current < updated.length - 1) {\n const pushed = updated[current];\n const following = updated[current + 1];\n if (pushed.end > following.start) {\n updated[current + 1] = { ...following, start: pushed.end };\n current++;\n } else {\n break;\n }\n }\n }\n }\n return unlessUnchanged(list, updated);\n}\n","import { useCallback, useEffect, useRef } from 'react';\n\nexport interface AnimationFrameLoopControls {\n animationFrameRef: React.MutableRefObject<number | null>;\n startAnimationFrameLoop: (callback: () => void) => void;\n stopAnimationFrameLoop: () => void;\n}\n\n/**\n * Shared RAF loop controller used by playlist providers.\n * Always guarantees a single in-flight animation frame.\n */\nexport const useAnimationFrameLoop = (): AnimationFrameLoopControls => {\n const animationFrameRef = useRef<number | null>(null);\n\n const stopAnimationFrameLoop = useCallback(() => {\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n animationFrameRef.current = null;\n }\n }, []);\n\n const startAnimationFrameLoop = useCallback(\n (callback: () => void) => {\n stopAnimationFrameLoop();\n animationFrameRef.current = requestAnimationFrame(callback);\n },\n [stopAnimationFrameLoop]\n );\n\n useEffect(() => {\n return () => {\n stopAnimationFrameLoop();\n };\n }, [stopAnimationFrameLoop]);\n\n return {\n animationFrameRef,\n startAnimationFrameLoop,\n stopAnimationFrameLoop,\n };\n};\n","/**\n * useWaveformDataCache\n *\n * Generates a WaveformData object per unique AudioBuffer in a web worker.\n * These enable near-instant zoom changes via WaveformData.resample() instead\n * of re-scanning raw audio samples.\n *\n * Results are looked up by AudioBuffer during render (`getWaveformData`), so a\n * `tracks` change that only rearranges clips of already-generated buffers\n * causes no state update here (#692). The only state is `version`, bumped when\n * a worker job finishes: depend on it to recompute peaks for the clips that\n * share that buffer.\n *\n * Behavior:\n * - Creates the worker lazily on first clip needing generation\n * - Generates waveform data once per unique AudioBuffer; a job keeps running\n * across `tracks` changes\n * - A failed job is tried again on the next `tracks` change, three attempts\n * per buffer in all\n * - Terminates the worker on unmount\n */\n\nimport { useState, useEffect, useRef, useCallback } from 'react';\nimport type { ClipTrack } from '@waveform-playlist/core';\nimport type WaveformData from 'waveform-data';\nimport { createPeaksWorker, type PeaksWorkerApi } from '../workers/peaksWorker';\n\nexport interface UseWaveformDataCacheReturn {\n /** Worker-generated waveform data for a buffer, once ready. Stable identity. */\n getWaveformData: (audioBuffer: AudioBuffer) => WaveformData | undefined;\n /** Bumped each time a buffer's waveform data becomes available. */\n version: number;\n}\n\n/**\n * Attempts per buffer before giving up. A failed job is tried again on the\n * next `tracks` change (a crashed worker is replaced), but a buffer that can\n * never succeed (a CSP that blocks blob workers) must not be copied and sent\n * again on every change of the tracks.\n */\nconst MAX_GENERATION_ATTEMPTS = 3;\n\nfunction buffersNeedingGeneration(\n tracks: readonly ClipTrack[],\n generated: WeakMap<AudioBuffer, WaveformData>,\n inflight: WeakMap<AudioBuffer, Promise<void>>,\n failures: WeakMap<AudioBuffer, number>\n): Set<AudioBuffer> {\n const buffers = new Set<AudioBuffer>();\n for (const track of tracks) {\n for (const clip of track.clips) {\n // Clips with their own waveformData never need the worker.\n if (!clip.audioBuffer || clip.waveformData) continue;\n if (generated.has(clip.audioBuffer) || inflight.has(clip.audioBuffer)) continue;\n if ((failures.get(clip.audioBuffer) ?? 0) >= MAX_GENERATION_ATTEMPTS) continue;\n buffers.add(clip.audioBuffer);\n }\n }\n return buffers;\n}\n\nexport function useWaveformDataCache(\n tracks: readonly ClipTrack[],\n baseScale: number\n): UseWaveformDataCacheReturn {\n const [version, setVersion] = useState(0);\n\n const workerRef = useRef<PeaksWorkerApi | null>(null);\n const generatedByBufferRef = useRef<WeakMap<AudioBuffer, WaveformData>>(new WeakMap());\n const inflightByBufferRef = useRef<WeakMap<AudioBuffer, Promise<void>>>(new WeakMap());\n const failuresByBufferRef = useRef<WeakMap<AudioBuffer, number>>(new WeakMap());\n // Changes on unmount. A job started in an earlier mount (StrictMode\n // remounts, or a real unmount) must not set state or warn.\n const mountSessionRef = useRef(0);\n\n // Stable callback to get or create the worker.\n // Also replaces a crashed worker (onerror marks it terminated) — reusing\n // it would reject every later generation until the component remounts.\n const getWorker = useCallback(() => {\n if (!workerRef.current || workerRef.current.isTerminated()) {\n workerRef.current = createPeaksWorker();\n }\n return workerRef.current;\n }, []);\n\n const getWaveformData = useCallback(\n (audioBuffer: AudioBuffer) => generatedByBufferRef.current.get(audioBuffer),\n []\n );\n\n useEffect(() => {\n const generatedByBuffer = generatedByBufferRef.current;\n const inflightByBuffer = inflightByBufferRef.current;\n const session = mountSessionRef.current;\n const failuresByBuffer = failuresByBufferRef.current;\n const buffers = buffersNeedingGeneration(\n tracks,\n generatedByBuffer,\n inflightByBuffer,\n failuresByBuffer\n );\n if (buffers.size === 0) return;\n\n const worker = getWorker();\n\n for (const audioBuffer of buffers) {\n // .slice() channel buffers to avoid detaching the original AudioBuffer views\n const channels: ArrayBuffer[] = [];\n for (let c = 0; c < audioBuffer.numberOfChannels; c++) {\n channels.push(audioBuffer.getChannelData(c).slice().buffer as ArrayBuffer);\n }\n\n // Only clear the in-flight marker if it is still this job's: after an\n // unmount the map is replaced and a new job may own the buffer.\n const settle = () => {\n if (inflightByBuffer.get(audioBuffer) === job) {\n inflightByBuffer.delete(audioBuffer);\n }\n };\n\n const id = `buffer-${Math.random().toString(36).slice(2, 11)}`;\n const job: Promise<void> = worker\n .generate({\n id,\n channels,\n length: audioBuffer.length,\n sampleRate: audioBuffer.sampleRate,\n scale: baseScale,\n bits: 16,\n splitChannels: true,\n })\n .then((waveformData) => {\n generatedByBuffer.set(audioBuffer, waveformData);\n settle();\n if (mountSessionRef.current !== session) return;\n setVersion((v) => v + 1);\n })\n .catch((err) => {\n settle();\n // A job rejected by the unmount's terminate() is not a failure of\n // the buffer.\n if (mountSessionRef.current !== session) return;\n const attempts = (failuresByBuffer.get(audioBuffer) ?? 0) + 1;\n failuresByBuffer.set(audioBuffer, attempts);\n console.warn(\n '[waveform-playlist] Worker peak generation failed' +\n (attempts >= MAX_GENERATION_ATTEMPTS\n ? ' ' + attempts + ' times, giving up on this audio buffer: '\n : ': ') +\n String(err)\n );\n });\n\n inflightByBuffer.set(audioBuffer, job);\n }\n }, [tracks, baseScale, getWorker]);\n\n // Terminate worker on unmount. Terminating rejects the jobs still running,\n // so forget them: a remount (StrictMode) starts them again on a new worker.\n useEffect(() => {\n return () => {\n mountSessionRef.current += 1;\n inflightByBufferRef.current = new WeakMap();\n workerRef.current?.terminate();\n workerRef.current = null;\n };\n }, []);\n\n return { getWaveformData, version };\n}\n","/**\n * Inline Web Worker for generating WaveformData binary format from AudioBuffer channels.\n *\n * Uses a Blob URL approach (portable across all bundlers) with the generateWaveformData\n * algorithm adapted from BBC's waveform-data.js (MIT licensed, adapted from Audacity).\n *\n * The worker generates peaks at a base scale (finest zoom level). The main thread\n * then uses WaveformData.resample() for near-instant zoom changes.\n */\n\nimport WaveformData from 'waveform-data';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Worker code (runs inside the Blob URL worker)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Self-contained worker source.\n * Contains the generateWaveformData function from waveform-data.js/src/waveform-generator.js\n * (MIT License, BBC). Pure JS, zero dependencies.\n */\nconst workerSource = `\n\"use strict\";\n\nvar INT8_MAX = 127;\nvar INT8_MIN = -128;\nvar INT16_MAX = 32767;\nvar INT16_MIN = -32768;\n\nfunction calculateWaveformDataLength(audio_sample_count, scale) {\n var data_length = Math.floor(audio_sample_count / scale);\n var samples_remaining = audio_sample_count - (data_length * scale);\n if (samples_remaining > 0) {\n data_length++;\n }\n return data_length;\n}\n\nfunction generateWaveformData(options) {\n var scale = options.scale;\n var amplitude_scale = options.amplitude_scale;\n var split_channels = options.split_channels;\n var length = options.length;\n var sample_rate = options.sample_rate;\n var channels = options.channels.map(function(channel) {\n return new Float32Array(channel);\n });\n var output_channels = split_channels ? channels.length : 1;\n var header_size = 24;\n var data_length = calculateWaveformDataLength(length, scale);\n var bytes_per_sample = options.bits === 8 ? 1 : 2;\n var total_size = header_size + data_length * 2 * bytes_per_sample * output_channels;\n var buffer = new ArrayBuffer(total_size);\n var data_view = new DataView(buffer);\n\n var scale_counter = 0;\n var offset = header_size;\n\n var min_value = new Array(output_channels);\n var max_value = new Array(output_channels);\n\n for (var channel = 0; channel < output_channels; channel++) {\n min_value[channel] = Infinity;\n max_value[channel] = -Infinity;\n }\n\n var range_min = options.bits === 8 ? INT8_MIN : INT16_MIN;\n var range_max = options.bits === 8 ? INT8_MAX : INT16_MAX;\n\n data_view.setInt32(0, 2, true);\n data_view.setUint32(4, options.bits === 8, true);\n data_view.setInt32(8, sample_rate, true);\n data_view.setInt32(12, scale, true);\n data_view.setInt32(16, data_length, true);\n data_view.setInt32(20, output_channels, true);\n\n for (var i = 0; i < length; i++) {\n var sample = 0;\n\n if (output_channels === 1) {\n for (var ch = 0; ch < channels.length; ++ch) {\n sample += channels[ch][i];\n }\n sample = Math.floor(range_max * sample * amplitude_scale / channels.length);\n\n if (sample < min_value[0]) {\n min_value[0] = sample;\n if (min_value[0] < range_min) {\n min_value[0] = range_min;\n }\n }\n if (sample > max_value[0]) {\n max_value[0] = sample;\n if (max_value[0] > range_max) {\n max_value[0] = range_max;\n }\n }\n }\n else {\n for (var ch2 = 0; ch2 < output_channels; ++ch2) {\n sample = Math.floor(range_max * channels[ch2][i] * amplitude_scale);\n\n if (sample < min_value[ch2]) {\n min_value[ch2] = sample;\n if (min_value[ch2] < range_min) {\n min_value[ch2] = range_min;\n }\n }\n if (sample > max_value[ch2]) {\n max_value[ch2] = sample;\n if (max_value[ch2] > range_max) {\n max_value[ch2] = range_max;\n }\n }\n }\n }\n\n if (++scale_counter === scale) {\n for (var ch3 = 0; ch3 < output_channels; ch3++) {\n if (options.bits === 8) {\n data_view.setInt8(offset++, min_value[ch3]);\n data_view.setInt8(offset++, max_value[ch3]);\n }\n else {\n data_view.setInt16(offset, min_value[ch3], true);\n data_view.setInt16(offset + 2, max_value[ch3], true);\n offset += 4;\n }\n min_value[ch3] = Infinity;\n max_value[ch3] = -Infinity;\n }\n scale_counter = 0;\n }\n }\n\n if (scale_counter > 0) {\n for (var ch4 = 0; ch4 < output_channels; ch4++) {\n if (options.bits === 8) {\n data_view.setInt8(offset++, min_value[ch4]);\n data_view.setInt8(offset++, max_value[ch4]);\n }\n else {\n data_view.setInt16(offset, min_value[ch4], true);\n data_view.setInt16(offset + 2, max_value[ch4], true);\n }\n }\n }\n\n return buffer;\n}\n\nself.onmessage = function(e) {\n var msg = e.data;\n try {\n var result = generateWaveformData({\n scale: msg.scale,\n bits: msg.bits,\n amplitude_scale: msg.amplitude_scale,\n split_channels: msg.split_channels,\n length: msg.length,\n sample_rate: msg.sample_rate,\n channels: msg.channels\n });\n self.postMessage({ id: msg.id, buffer: result }, [result]);\n } catch (err) {\n self.postMessage({ id: msg.id, error: err.message || String(err) });\n }\n};\n`;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Promise-based worker API (runs on the main thread)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface PeaksWorkerApi {\n generate(params: {\n id: string;\n channels: ArrayBuffer[];\n length: number;\n sampleRate: number;\n scale: number;\n bits: 8 | 16;\n splitChannels: boolean;\n }): Promise<WaveformData>;\n /** True once the worker has crashed (onerror) or been terminated — every\n * generate() will reject. Callers should discard this instance and create\n * a fresh worker. */\n isTerminated(): boolean;\n terminate(): void;\n}\n\ninterface PendingEntry {\n resolve: (value: WaveformData) => void;\n reject: (reason: unknown) => void;\n}\n\nlet idCounter = 0;\n\nexport function createPeaksWorker(): PeaksWorkerApi {\n let worker: Worker;\n try {\n const blob = new Blob([workerSource], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n worker = new Worker(url);\n URL.revokeObjectURL(url);\n } catch (err) {\n // Worker creation can fail in CSP-restricted environments that block blob: URLs.\n // Return a no-op API that rejects all generate calls gracefully.\n console.warn('[waveform-playlist] Failed to create peaks worker (CSP restriction?):', err);\n return {\n generate() {\n return Promise.reject(new Error('Worker creation failed'));\n },\n // Reports NOT terminated: CSP blocking is permanent for the page, so\n // recreating on every call would just re-attempt (and re-warn about)\n // Worker construction each time.\n isTerminated() {\n return false;\n },\n terminate() {\n /* no-op */\n },\n };\n }\n\n const pending = new Map<string, PendingEntry>();\n let terminated = false;\n\n worker.onmessage = (e: MessageEvent) => {\n const msg = e.data;\n const entry = pending.get(msg.id);\n if (!entry) return;\n pending.delete(msg.id);\n\n if (msg.error) {\n entry.reject(new Error(msg.error));\n } else {\n try {\n const waveformData = WaveformData.create(msg.buffer);\n entry.resolve(waveformData);\n } catch (err) {\n entry.reject(err);\n }\n }\n };\n\n worker.onerror = (e: ErrorEvent) => {\n terminated = true;\n worker.terminate();\n for (const [, entry] of pending) {\n entry.reject(e.error ?? new Error(e.message));\n }\n pending.clear();\n };\n\n return {\n isTerminated() {\n return terminated;\n },\n\n generate(params) {\n if (terminated) return Promise.reject(new Error('Worker terminated'));\n const messageId = String(++idCounter);\n\n return new Promise<WaveformData>((resolve, reject) => {\n pending.set(messageId, { resolve, reject });\n\n worker.postMessage(\n {\n id: messageId,\n scale: params.scale,\n bits: params.bits,\n amplitude_scale: 1.0,\n split_channels: params.splitChannels,\n length: params.length,\n sample_rate: params.sampleRate,\n channels: params.channels,\n },\n params.channels // Transfer ownership\n );\n });\n },\n\n terminate() {\n terminated = true;\n worker.terminate();\n for (const [, entry] of pending) {\n entry.reject(new Error('Worker terminated'));\n }\n pending.clear();\n },\n };\n}\n","import { useState } from 'react';\nimport { createArrangement } from '@waveform-playlist/engine';\nimport type { Arrangement, LoadSource } from '@waveform-playlist/engine';\nimport type { ArrangementTrack } from '@waveform-playlist/core';\n\nexport interface UseCreateArrangementOptions {\n /** How a clip's source is fetched and decoded. Nothing is fetched until a decode context is attached. */\n loadSource?: LoadSource;\n /** How many undo steps the arrangement keeps. */\n undoLimit?: number;\n}\n\n/**\n * Create the `Arrangement` that owns a multitrack editor's tracks, one per\n * component instance. Returns the same arrangement on every render.\n *\n * `init` and `options` are read once, on the first render; a later render\n * with other values changes nothing. An initializer that throws (a track\n * with a wrong kind, a duplicate track id, two clips with one id) throws out\n * of the render, to the nearest error boundary.\n *\n * Under StrictMode React calls the initializer twice and keeps one result;\n * neither arrangement fetches anything, because none has a decode context.\n */\nexport function useCreateArrangement(\n init?: () => readonly ArrangementTrack[],\n options?: UseCreateArrangementOptions\n): Arrangement {\n // Only the two documented options: a stray `tracks` key (plain JS) must not\n // replace what the initializer returns.\n const [arrangement] = useState(() =>\n createArrangement({\n tracks: init?.(),\n loadSource: options?.loadSource,\n undoLimit: options?.undoLimit,\n })\n );\n return arrangement;\n}\n","import { useMemo, useSyncExternalStore } from 'react';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport type { ArrangementTrack } from '@waveform-playlist/core';\n\n/**\n * The tracks of `arrangement`, loaded and loading clips alike. The same\n * array until the tracks change: a mix change (volume, mute, solo, pan)\n * does not re-render. Never write to what it returns.\n */\nexport function useArrangementTracks(arrangement: Arrangement): readonly ArrangementTrack[] {\n const store = useMemo(\n () => ({\n subscribe: (listener: () => void) => arrangement.subscribe(listener),\n getSnapshot: () => arrangement.getTracks(),\n }),\n [arrangement]\n );\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n","import { useMemo, useSyncExternalStore } from 'react';\nimport type { Arrangement, ArrangementSourcesValue } from '@waveform-playlist/engine';\n\n/**\n * The audio sources the clips of `arrangement` name, and whether each is\n * pending, loaded or failed. The same object until a source settles or the\n * set of sources changes.\n */\nexport function useArrangementSources(arrangement: Arrangement): ArrangementSourcesValue {\n const store = useMemo(\n () => ({\n subscribe: (listener: () => void) => arrangement.sources.subscribe(() => listener()),\n getSnapshot: () => arrangement.sources.getSnapshot(),\n }),\n [arrangement]\n );\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport { createAnnotationStore } from '@waveform-playlist/core';\nimport type {\n AnnotationData,\n AnnotationStore,\n AnnotationStoreOptions,\n} from '@waveform-playlist/core';\n\n/**\n * Create the `AnnotationStore` that owns an editor's annotations, one per\n * component instance. Give it to a provider's `annotationStore` prop and\n * read it with `useStoredAnnotations`. Returns the same store on every render.\n *\n * `init` is read once, on the first render; it may throw (an annotation\n * without numeric `start`/`end`, two with one id), and the throw goes to the\n * nearest error boundary. Unlike `init`, `options.beforeChange` is followed:\n * the store calls the function passed on the most recent committed render,\n * so a rule that reads the app's state sees its current value.\n *\n * Under StrictMode React calls the initializer twice and keeps one result.\n */\nexport function useCreateAnnotationStore(\n init?: () => readonly AnnotationData[],\n options?: AnnotationStoreOptions\n): AnnotationStore {\n const beforeChange = options?.beforeChange;\n const ruleRef = useRef(beforeChange);\n // Written after commit, so a render React throws away never sets the rule.\n useLayoutEffect(() => {\n ruleRef.current = beforeChange;\n }, [beforeChange]);\n\n const [store] = useState(() =>\n createAnnotationStore(init?.(), {\n beforeChange: (next, current) => (ruleRef.current ? ruleRef.current(next, current) : next),\n })\n );\n return store;\n}\n","import { useMemo, useSyncExternalStore } from 'react';\nimport type { AnnotationData, AnnotationStore } from '@waveform-playlist/core';\n\n/**\n * The annotations of `store`, for the app's own components (inside or outside\n * a provider). The same array until the annotations change. Never write to\n * what it returns: change them with `store.set` or `store.update`.\n */\nexport function useStoredAnnotations(store: AnnotationStore): readonly AnnotationData[] {\n const source = useMemo(\n () => ({\n subscribe: (listener: () => void) => store.subscribe(listener),\n getSnapshot: () => store.getAnnotations(),\n }),\n [store]\n );\n return useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);\n}\n","import type { AnnotationData } from '@waveform-playlist/core';\nimport type { AnnotationLookup } from '../utils/annotationLookup';\n\nexport interface FollowAnnotationsOptions {\n annotations: readonly AnnotationData[];\n lookup: AnnotationLookup<AnnotationData>;\n /** Playback position of this frame, in seconds. */\n time: number;\n activeId: string | null;\n /**\n * True: the highlight follows the playhead and playback is never cut\n * (continuous play). False: playback ends with the active annotation.\n */\n followOnly: boolean;\n /**\n * Leave the highlight where it is this frame. Only read when `followOnly`\n * is true: a bounded play that reaches its end on this frame stops right\n * after, and the highlight must not move on to the next annotation first.\n */\n holdHighlight: boolean;\n setActiveAnnotationId: (id: string | null) => void;\n}\n\n/**\n * The annotation step of a provider's animation loop, once per frame.\n *\n * Returns true when the active annotation has played to its end and playback\n * must stop. What \"stop\" does (where the cursor goes) is the provider's.\n */\nexport function followAnnotations({\n annotations,\n lookup,\n time,\n activeId,\n followOnly,\n holdHighlight,\n setActiveAnnotationId,\n}: FollowAnnotationsOptions): boolean {\n if (annotations.length === 0) return false;\n\n const current = lookup.atTime(annotations, time);\n\n if (followOnly) {\n if (holdHighlight) return false;\n if (current && current.id !== activeId) {\n setActiveAnnotationId(current.id);\n } else if (!current && activeId !== null) {\n // Past the active annotation, in a gap: clear it, keep playing.\n setActiveAnnotationId(null);\n }\n return false;\n }\n\n if (activeId) {\n const active = lookup.byId(annotations, activeId);\n return active !== undefined && time >= active.end;\n }\n // Nothing active yet: adopt the annotation under the playhead.\n if (current) setActiveAnnotationId(current.id);\n return false;\n}\n","import { useCallback, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { createValueSource } from '@waveform-playlist/core';\nimport type { AnnotationData, AnnotationStore } from '@waveform-playlist/core';\nimport type { AnnotationPreviewHandle } from '../hooks/useAnnotationDragHandlers';\nimport { createAnnotationLookup, type AnnotationLookup } from '../utils/annotationLookup';\nimport type {\n AnnotationOptionsContextValue,\n AnnotationsContextValue,\n} from '../contexts/playlistContexts';\n\n/**\n * The `annotationList` prop of both providers: the three annotation options.\n * The annotations themselves are the `annotationStore` prop's (#867). The\n * provider holds the three options as state (`useAnnotationOptions()`, and the three setters of\n * `usePlaybackControls()`), and that state follows the prop: when the value\n * of a field changes, the option takes it. Between two changes of the prop a\n * setter (or one of the checkboxes) changes the option; the prop is not told.\n */\nexport interface AnnotationListProp {\n /** Whether annotations can be edited (text, ids, edges). Default: false. */\n editable?: boolean;\n /** Whether a dragged edge takes the edge it touches along. Default: false. */\n linkEndpoints?: boolean;\n /** Whether playback runs on past the end of an annotation. Default: false. */\n isContinuousPlay?: boolean;\n}\n\nexport interface UseAnnotationStateOptions {\n /** The owner of the annotations (#867); without it there are none. */\n annotationStore: AnnotationStore | undefined;\n annotationList: AnnotationListProp | undefined;\n}\n\nexport interface AnnotationState {\n /** The store's annotations; `[]` without a store. */\n annotations: readonly AnnotationData[];\n /**\n * The current annotations, for the animation loop, so an annotation edit\n * does not restart it. Reads the store at the moment of the call. Stable.\n */\n getAnnotations: () => readonly AnnotationData[];\n /** Cached per-frame lookups. */\n annotationLookup: AnnotationLookup<AnnotationData>;\n /** Created once: the annotations as an edge drag in progress would leave them. */\n annotationPreview: AnnotationPreviewHandle;\n activeAnnotationId: string | null;\n activeAnnotationIdRef: React.RefObject<string | null>;\n setActiveAnnotationId: (id: string | null) => void;\n continuousPlay: boolean;\n continuousPlayRef: React.RefObject<boolean>;\n setContinuousPlay: (enabled: boolean) => void;\n setAnnotationsEditable: (enabled: boolean) => void;\n setLinkEndpoints: (enabled: boolean) => void;\n /** `{ annotations }`, memoized: the public annotations value. */\n annotationsValue: AnnotationsContextValue;\n /** The three options, memoized: the public options value. */\n annotationOptionsValue: AnnotationOptionsContextValue;\n}\n\n/**\n * A boolean option held as state that follows a prop (#686): it starts from\n * the prop (false when absent), a setter changes it, and when the prop's\n * value changes the option takes the new value. The comparison is made during\n * render against the last prop value seen, kept as state: no effect, so a\n * StrictMode remount or a revealed `<Activity>` does not put an unchanged\n * prop back over a value the user chose. The setter keeps its identity.\n */\nfunction useFollowedOption(prop: boolean | undefined): [boolean, (value: boolean) => void] {\n // A field that is left out says false: leaving it out and writing `false`\n // are the same value, not a change.\n const wanted = prop ?? false;\n const [value, setValue] = useState(wanted);\n const [seen, setSeen] = useState(wanted);\n if (seen !== wanted) {\n setSeen(wanted);\n setValue(wanted);\n return [wanted, setValue];\n }\n return [value, setValue];\n}\n\n/**\n * The annotation state of a provider. The two setters that the animation loop\n * depends on write their ref first and the state second, so a running loop\n * reads the new value on its next frame, before React has rendered. Every\n * function and the preview keep their identity.\n */\nconst NO_ANNOTATIONS: readonly AnnotationData[] = Object.freeze([]);\nconst noSubscription = () => () => {};\nconst noAnnotations = () => NO_ANNOTATIONS;\n\nexport function useAnnotationState({\n annotationStore,\n annotationList,\n}: UseAnnotationStateOptions): AnnotationState {\n // Called on every render, with a stand-in when there is no store. The\n // store validates what it holds (numeric start/end, unique ids).\n // Wrapped, so a store whose methods use `this` keeps working.\n const source = useMemo(\n () =>\n annotationStore\n ? {\n subscribe: (listener: () => void) => annotationStore.subscribe(listener),\n getSnapshot: () => annotationStore.getAnnotations(),\n }\n : { subscribe: noSubscription, getSnapshot: noAnnotations },\n [annotationStore]\n );\n const annotations = useSyncExternalStore(\n source.subscribe,\n source.getSnapshot,\n source.getSnapshot\n );\n\n // The animation loop reads the store at each frame, through the latest prop.\n const storeRef = useRef(annotationStore);\n storeRef.current = annotationStore;\n const getAnnotations = useCallback(\n () => (storeRef.current ? storeRef.current.getAnnotations() : NO_ANNOTATIONS),\n []\n );\n const [annotationLookup] = useState(() => createAnnotationLookup<AnnotationData>());\n\n const [activeAnnotationId, setActiveAnnotationIdState] = useState<string | null>(null);\n const activeAnnotationIdRef = useRef<string | null>(null);\n const setActiveAnnotationId = useCallback((value: string | null) => {\n activeAnnotationIdRef.current = value;\n setActiveAnnotationIdState(value);\n }, []);\n\n const [continuousPlay, setContinuousPlayState] = useFollowedOption(\n annotationList?.isContinuousPlay\n );\n // Written during render as well as by the setter, so that a value taken\n // from the prop reaches the animation loop too. The setter writes it first:\n // a running loop reads the new value on its next frame, before React has\n // rendered.\n const continuousPlayRef = useRef<boolean>(continuousPlay);\n continuousPlayRef.current = continuousPlay;\n const setContinuousPlay = useCallback(\n (value: boolean) => {\n continuousPlayRef.current = value;\n setContinuousPlayState(value);\n },\n [setContinuousPlayState]\n );\n\n const [editable, setAnnotationsEditable] = useFollowedOption(annotationList?.editable);\n const [linkEndpoints, setLinkEndpoints] = useFollowedOption(annotationList?.linkEndpoints);\n\n const annotationsValue = useMemo(() => ({ annotations }), [annotations]);\n const annotationOptionsValue = useMemo(\n () => ({ editable, linkEndpoints, continuousPlay }),\n [editable, linkEndpoints, continuousPlay]\n );\n\n const [annotationPreview] = useState<AnnotationPreviewHandle>(() =>\n createValueSource<AnnotationData[] | null>(null)\n );\n\n return {\n annotations,\n getAnnotations,\n annotationLookup,\n annotationPreview,\n activeAnnotationId,\n activeAnnotationIdRef,\n setActiveAnnotationId,\n continuousPlay,\n continuousPlayRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationsValue,\n annotationOptionsValue,\n };\n}\n","/**\n * Per-frame annotation lookups for the playback animation loops.\n *\n * Both lookups return exactly what the `Array.prototype.find` calls they replace\n * would return; they only avoid scanning the whole list on every frame.\n *\n * The list is treated as immutable: results are cached against the array's\n * identity, so a changed annotation must arrive in a new array (it does: the\n * providers hold annotations in React state).\n */\ninterface TimedAnnotation {\n readonly id: string;\n readonly start: number;\n readonly end: number;\n}\n\nexport interface AnnotationLookup<T extends TimedAnnotation> {\n /** Same result as `annotations.find((a) => time >= a.start && time < a.end)`. */\n atTime(annotations: readonly T[], time: number): T | undefined;\n /** Same result as `annotations.find((a) => a.id === id)`. */\n byId(annotations: readonly T[], id: string): T | undefined;\n}\n\nconst contains = (annotation: TimedAnnotation, time: number): boolean =>\n time >= annotation.start && time < annotation.end;\n\n/**\n * True when every range ends at or before the next one starts. Only then is\n * \"the first annotation containing `time`\" also the only one, which is what\n * lets `atTime` trust a cached hit and binary-search a miss. NaN bounds fail\n * the comparisons and fall back to the linear scan.\n */\nfunction isOrdered(annotations: readonly TimedAnnotation[]): boolean {\n for (let i = 0; i < annotations.length; i++) {\n const current = annotations[i];\n if (!(current.start <= current.end)) return false;\n if (i + 1 < annotations.length && !(current.end <= annotations[i + 1].start)) return false;\n }\n return true;\n}\n\nexport function createAnnotationLookup<T extends TimedAnnotation>(): AnnotationLookup<T> {\n let list: readonly T[] | null = null;\n let ordered = false;\n let lastIndex = -1;\n let lastById: T | undefined;\n\n const sync = (annotations: readonly T[]) => {\n if (annotations === list) return;\n list = annotations;\n ordered = isOrdered(annotations);\n lastIndex = -1;\n lastById = undefined;\n };\n\n return {\n atTime(annotations, time) {\n sync(annotations);\n if (!ordered) return annotations.find((annotation) => contains(annotation, time));\n // NaN compares false both ways and would look like a hit to the search below.\n if (Number.isNaN(time)) return undefined;\n\n // Playback moves forward, so the last hit is nearly always still the answer.\n if (lastIndex >= 0 && contains(annotations[lastIndex], time)) return annotations[lastIndex];\n\n let low = 0;\n let high = annotations.length - 1;\n while (low <= high) {\n const mid = (low + high) >> 1;\n const candidate = annotations[mid];\n if (time < candidate.start) {\n high = mid - 1;\n } else if (time >= candidate.end) {\n low = mid + 1;\n } else {\n lastIndex = mid;\n return candidate;\n }\n }\n return undefined;\n },\n\n byId(annotations, id) {\n sync(annotations);\n if (lastById?.id === id) return lastById;\n // A miss is not cached: the id may be added in a later list.\n lastById = annotations.find((annotation) => annotation.id === id);\n return lastById;\n },\n };\n}\n","import { useCallback, useRef } from 'react';\n\n/** Per-frame data passed to registered animation callbacks. */\nexport interface FrameData {\n /** Raw engine time (for state/logic — NOT for visual positioning). */\n readonly time: number;\n /** Visually-aligned time for DOM positioning: engine.getAudibleTime() while\n * playing (matches speaker output), raw time when resting. */\n readonly visualTime: number;\n readonly sampleRate: number;\n readonly samplesPerPixel: number;\n}\n\nexport type FrameCallback = (data: FrameData) => void;\n\nexport interface FrameCallbacks {\n /** Register a per-frame callback. A second registration under the same id replaces the first. */\n registerFrameCallback: (id: string, cb: FrameCallback) => void;\n unregisterFrameCallback: (id: string) => void;\n /** For the provider's animation loop: call every registered callback. */\n runFrameCallbacks: (data: FrameData) => void;\n}\n\n/**\n * The frame-callback registry of a provider. Components that draw during\n * playback register a callback instead of running their own\n * `requestAnimationFrame` loop; the provider's one loop calls them all with\n * the time it read for that frame. All three functions are stable.\n */\nexport function useFrameCallbacks(): FrameCallbacks {\n const callbacksRef = useRef<Map<string, FrameCallback>>(new Map());\n\n const registerFrameCallback = useCallback((id: string, cb: FrameCallback) => {\n callbacksRef.current.set(id, cb);\n }, []);\n\n const unregisterFrameCallback = useCallback((id: string) => {\n callbacksRef.current.delete(id);\n }, []);\n\n const runFrameCallbacks = useCallback((data: FrameData) => {\n for (const cb of callbacksRef.current.values()) {\n cb(data);\n }\n }, []);\n\n return { registerFrameCallback, unregisterFrameCallback, runFrameCallbacks };\n}\n","import { useCallback, useRef, useState } from 'react';\n\n/**\n * Scrolls so that the playhead is in the middle of the container. Whole\n * pixels: a fractional `scrollLeft` is rounded by the browser anyway, and not\n * always the same way from frame to frame, which shows as jitter.\n */\nexport function centrePlayhead(\n container: HTMLDivElement,\n time: number,\n sampleRate: number,\n samplesPerPixel: number\n): void {\n const pixelPosition = (time * sampleRate) / samplesPerPixel;\n container.scrollLeft = Math.round(Math.max(0, pixelPosition - container.clientWidth / 2));\n}\n\nexport interface ScrollFollow {\n scrollContainerRef: React.RefObject<HTMLDivElement | null>;\n setScrollContainer: (element: HTMLDivElement | null) => void;\n isAutomaticScroll: boolean;\n /** For the animation loop: current without waiting for a render. */\n isAutomaticScrollRef: React.RefObject<boolean>;\n setAutomaticScroll: (enabled: boolean) => void;\n}\n\n/** The scroll container and the automatic-scroll setting of a provider. */\nexport function useScrollFollow(initialAutomaticScroll: boolean): ScrollFollow {\n const scrollContainerRef = useRef<HTMLDivElement | null>(null);\n const [isAutomaticScroll, setIsAutomaticScroll] = useState(initialAutomaticScroll);\n const isAutomaticScrollRef = useRef<boolean>(initialAutomaticScroll);\n\n const setScrollContainer = useCallback((element: HTMLDivElement | null) => {\n scrollContainerRef.current = element;\n }, []);\n\n const setAutomaticScroll = useCallback((enabled: boolean) => {\n isAutomaticScrollRef.current = enabled;\n setIsAutomaticScroll(enabled);\n }, []);\n\n return {\n scrollContainerRef,\n setScrollContainer,\n isAutomaticScroll,\n isAutomaticScrollRef,\n setAutomaticScroll,\n };\n}\n","import { useMemo } from 'react';\nimport { defaultTheme, type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport { useShallowStable } from '../hooks/useShallowStable';\n\n/**\n * The theme both providers hand to styled-components: the `theme` prop merged\n * over `defaultTheme`. An inline object prop (`theme={{ … }}`) gets a new\n * identity on every render of the parent; it keeps the previous one here\n * while its contents are unchanged, so nothing styled is re-rendered.\n *\n * The theme stays on the provider (#689): it is not an option of one view.\n * The transport controls, the checkboxes and the annotation list are drawn\n * outside a root and read it too.\n */\nexport function useMergedTheme(\n themeProp: Partial<WaveformPlaylistTheme> | undefined\n): WaveformPlaylistTheme {\n const userTheme = useShallowStable(themeProp);\n return useMemo(() => ({ ...defaultTheme, ...userTheme }), [userTheme]);\n}\n","import { useRef } from 'react';\n\nfunction shallowEqual(a: object, b: object): boolean {\n if (a === b) return true;\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n const aRecord = a as Record<string, unknown>;\n const bRecord = b as Record<string, unknown>;\n return aKeys.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(bRecord, key) && Object.is(aRecord[key], bRecord[key])\n );\n}\n\n/**\n * Returns the previous object while the new one is shallow-equal to it.\n *\n * Consumers usually pass small config objects as inline literals\n * (`theme={{ playheadColor: 'red' }}`), which have a new identity on every\n * render of the parent. Passing such a prop through this hook before using it\n * as a `useMemo` dependency keeps the memo from being invalidated by a render\n * in which the object's contents did not change.\n */\nexport function useShallowStable<T extends object | undefined>(value: T): T {\n const ref = useRef(value);\n const previous = ref.current;\n if (previous !== value) {\n if (previous === undefined || value === undefined || !shallowEqual(previous, value)) {\n ref.current = value;\n }\n }\n return ref.current;\n}\n","import { useRef, useState } from 'react';\nimport { createValueSource } from '@waveform-playlist/core';\nimport type { ClipTrack, ValueSourceHandle } from '@waveform-playlist/core';\nimport { clipPeaksFor, type DerivePeaksOptions, type PeaksCache } from '../utils/derivePeaks';\nimport type { ClipPeaks } from '../WaveformPlaylistContext';\n\n/**\n * A clip trim drag in progress (#812): where the dragged clip would be if the\n * pointer were released now. View-only: the tracks are not changed until the\n * release, which commits the same geometry through one `engine.trimClip`.\n */\nexport interface TrimPreview {\n trackId: string;\n clipId: string;\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n}\n\n/** The one place a trim drag in progress is kept: written by the drag handlers. */\nexport type TrimPreviewHandle = ValueSourceHandle<TrimPreview | null>;\n\n/**\n * The drawing record of the clip a preview names, with the previewed\n * geometry. A stable object: reading it never re-renders; `peaksFor` reads the\n * provider's latest tracks and peak inputs when it is called.\n */\nexport interface TrimPreviewPeaksValue {\n /** `null` when no track or clip has the preview's ids. */\n peaksFor: (preview: TrimPreview) => ClipPeaks | null;\n}\n\n/** What `peaksFor` derives a previewed clip from: the provider's, as of its last render. */\nexport interface TrimPreviewInputs {\n /** The loaded tracks (no loading clip: a placeholder is never trimmed). */\n tracks: readonly ClipTrack[];\n peaksOptions: DerivePeaksOptions;\n /** The last pass of `derivePeaks`, so an unchanged geometry reuses its record. */\n peaksCacheRef: React.RefObject<PeaksCache>;\n}\n\n/** The previewed clip's record, by the same per-clip step as every other clip. */\nexport function previewedClipPeaks(\n preview: TrimPreview,\n { tracks, peaksOptions, peaksCacheRef }: TrimPreviewInputs\n): ClipPeaks | null {\n const track = tracks.find((t) => t.id === preview.trackId);\n const clip = track?.clips.find((c) => c.id === preview.clipId);\n if (!track || !clip) return null;\n const previewed = {\n ...clip,\n startSample: preview.startSample,\n durationSamples: preview.durationSamples,\n offsetSamples: preview.offsetSamples,\n };\n const previous = peaksCacheRef.current.clips.get(clip.id);\n return clipPeaksFor(previewed, track.name, peaksOptions, previous).clipPeaks;\n}\n\nexport interface TrimPreviewState {\n trimPreview: TrimPreviewHandle;\n trimPreviewPeaks: TrimPreviewPeaksValue;\n}\n\n/**\n * The trim preview of `WaveformPlaylistProvider`: the source, made once, and\n * the stable function that draws a previewed clip. Both are put in internal\n * contexts (`TrimPreviewContext`, `TrimPreviewPeaksContext`), read by\n * `useClipDragHandlers`, the clip view and the root.\n */\nexport function useTrimPreview(inputs: TrimPreviewInputs): TrimPreviewState {\n const [trimPreview] = useState<TrimPreviewHandle>(() =>\n createValueSource<TrimPreview | null>(null)\n );\n // The latest inputs, read when the dragged clip's view asks; a projection\n // of the provider's own values, never written back.\n const inputsRef = useRef(inputs);\n inputsRef.current = inputs;\n const [trimPreviewPeaks] = useState<TrimPreviewPeaksValue>(() => ({\n peaksFor: (preview) => previewedClipPeaks(preview, inputsRef.current),\n }));\n return { trimPreview, trimPreviewPeaks };\n}\n","/**\n * Waveform Data Loader\n *\n * Utilities for loading pre-computed waveform data in waveform-data.js format.\n * Supports both binary (.dat) and JSON formats from BBC's audiowaveform tool.\n */\n\nimport WaveformData from 'waveform-data';\nimport type { PeakData, Peaks } from '@waveform-playlist/core';\n\n/**\n * Load waveform data from a .dat or .json file\n *\n * @param src - URL to waveform data file (.dat or .json)\n * @returns WaveformData instance\n */\nexport async function loadWaveformData(src: string): Promise<WaveformData> {\n const response = await fetch(src);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waveform data: ${response.statusText}`);\n }\n\n // Detect binary format from pathname (ignores query string and fragment)\n const { pathname } = new URL(src, globalThis.location?.href ?? 'http://localhost');\n const isBinary = pathname.toLowerCase().endsWith('.dat');\n\n if (isBinary) {\n const arrayBuffer = await response.arrayBuffer();\n return WaveformData.create(arrayBuffer);\n } else {\n const json = await response.json();\n return WaveformData.create(json);\n }\n}\n\n/**\n * Convert WaveformData to our internal Peaks format\n *\n * @param waveformData - WaveformData instance from waveform-data.js\n * @param channelIndex - Channel index (0 for mono/left, 1 for right)\n * @returns Peaks data with alternating min/max values, preserving original bit depth\n */\nexport function waveformDataToPeaks(\n waveformData: WaveformData,\n channelIndex: number = 0\n): { data: Int8Array | Int16Array; bits: 8 | 16; length: number; sampleRate: number } {\n const channel = waveformData.channel(channelIndex);\n const bits = waveformData.bits as 8 | 16;\n\n // Get the min/max arrays to determine length\n const minArray = channel.min_array();\n const maxArray = channel.max_array();\n const length = minArray.length;\n\n // Use appropriate typed array based on source file bit depth\n // 8-bit: values range from -128 to 127\n // 16-bit: values range from -32768 to 32767\n const peaks = bits === 8 ? new Int8Array(length * 2) : new Int16Array(length * 2);\n\n // Interleave min/max pairs\n for (let i = 0; i < length; i++) {\n peaks[i * 2] = minArray[i];\n peaks[i * 2 + 1] = maxArray[i];\n }\n\n return {\n data: peaks,\n bits,\n length,\n sampleRate: waveformData.sample_rate,\n };\n}\n\n/**\n * Load waveform data file and convert to Peaks format in one step\n *\n * @param src - URL to waveform data file (.dat or .json)\n * @param channelIndex - Channel index (default: 0)\n * @returns Peaks data ready for rendering\n */\nexport async function loadPeaksFromWaveformData(\n src: string,\n channelIndex: number = 0\n): Promise<{ data: Int8Array | Int16Array; bits: 8 | 16; length: number; sampleRate: number }> {\n const waveformData = await loadWaveformData(src);\n return waveformDataToPeaks(waveformData, channelIndex);\n}\n\n/**\n * Get metadata from waveform data file without converting to peaks\n *\n * @param src - URL to waveform data file\n * @returns Metadata (sample rate, channels, duration, bits, etc.)\n */\nexport async function getWaveformDataMetadata(src: string): Promise<{\n sampleRate: number;\n channels: number;\n duration: number;\n samplesPerPixel: number;\n length: number;\n bits: 8 | 16;\n}> {\n const waveformData = await loadWaveformData(src);\n\n return {\n sampleRate: waveformData.sample_rate,\n channels: waveformData.channels,\n duration: waveformData.duration,\n samplesPerPixel: waveformData.scale,\n length: waveformData.length,\n bits: waveformData.bits as 8 | 16,\n };\n}\n\n/**\n * Slice and resample WaveformData with aligned source indices.\n *\n * Handles three cases:\n * 1. Scale differs + offset/duration given → aligned slice then resample\n * 2. Same scale + offset/duration given → direct slice\n * 3. No offset/duration → full-file resample (or identity)\n *\n * @returns Processed WaveformData ready for peak extraction\n */\nfunction sliceAndResample(\n waveformData: WaveformData,\n samplesPerPixel: number,\n offsetSamples?: number,\n durationSamples?: number\n): WaveformData | null {\n let processedData = waveformData;\n\n if (offsetSamples !== undefined && durationSamples !== undefined) {\n if (processedData.scale !== samplesPerPixel) {\n const sourceScale = waveformData.scale;\n const ratio = samplesPerPixel / sourceScale;\n\n // Compute clip's pixel range in target-scale bins\n const targetStart = Math.floor(offsetSamples / samplesPerPixel);\n const targetEnd = Math.ceil((offsetSamples + durationSamples) / samplesPerPixel);\n\n // Convert to source indices using floor/ceil for inclusive slicing.\n // For integer ratios (power-of-two scales), this gives exact alignment.\n // For non-integer ratios, floor/ceil ensures we always include all source\n // bins that contribute to the target bins — never underrepresenting peaks.\n const sourceStart = Math.floor(targetStart * ratio);\n const sourceEnd = Math.min(waveformData.length, Math.ceil(targetEnd * ratio));\n\n if (sourceStart >= sourceEnd) {\n return null; // Clip offset beyond waveform data\n }\n\n processedData = processedData.slice({\n startIndex: sourceStart,\n endIndex: sourceEnd,\n });\n processedData = processedData.resample({ scale: samplesPerPixel });\n } else {\n // No resampling needed — slice directly at base scale\n const startIndex = Math.floor(offsetSamples / samplesPerPixel);\n const endIndex = Math.ceil((offsetSamples + durationSamples) / samplesPerPixel);\n processedData = processedData.slice({ startIndex, endIndex });\n }\n } else if (processedData.scale !== samplesPerPixel) {\n processedData = processedData.resample({ scale: samplesPerPixel });\n }\n\n return processedData;\n}\n\n/**\n * Extract peaks from a WaveformData object at a specific scale (samplesPerPixel)\n * and optionally slice to a sample range.\n *\n * @param waveformData - WaveformData instance from waveform-data.js\n * @param samplesPerPixel - Target samples per pixel (will resample if different)\n * @param channelIndex - Channel index (default: 0)\n * @param offsetSamples - Optional start offset in samples (for clip trimming)\n * @param durationSamples - Optional duration in samples (for clip trimming)\n * @returns Peaks data ready for rendering\n */\nexport function extractPeaksFromWaveformData(\n waveformData: WaveformData,\n samplesPerPixel: number,\n channelIndex: number = 0,\n offsetSamples?: number,\n durationSamples?: number\n): { data: Int8Array | Int16Array; bits: 8 | 16; length: number } {\n const processedData = sliceAndResample(\n waveformData,\n samplesPerPixel,\n offsetSamples,\n durationSamples\n );\n\n if (processedData === null) {\n const bits = waveformData.bits as 8 | 16;\n const emptyPeaks = bits === 8 ? new Int8Array(0) : new Int16Array(0);\n return { data: emptyPeaks, bits, length: 0 };\n }\n\n // Convert to our peaks format\n const channel = processedData.channel(channelIndex);\n const bits = processedData.bits as 8 | 16;\n const minArray = channel.min_array();\n const maxArray = channel.max_array();\n const length = minArray.length;\n\n const peaks = bits === 8 ? new Int8Array(length * 2) : new Int16Array(length * 2);\n\n for (let i = 0; i < length; i++) {\n peaks[i * 2] = minArray[i];\n peaks[i * 2 + 1] = maxArray[i];\n }\n\n return { data: peaks, bits, length };\n}\n\n/**\n * Extract peaks from a WaveformData object, handling ALL channels, mono merging,\n * slicing, and resampling.\n *\n * Bit depth is determined by the WaveformData source — all typed arrays match\n * the source's bit depth for consistent data/metadata.\n *\n * @param waveformData - WaveformData instance (should be generated with split_channels: true)\n * @param samplesPerPixel - Target samples per pixel\n * @param isMono - Whether to merge channels to mono\n * @param offsetSamples - Optional start offset in samples (for clip trimming)\n * @param durationSamples - Optional duration in samples (for clip trimming)\n * @returns PeakData matching the interface from @waveform-playlist/core\n */\nexport function extractPeaksFromWaveformDataFull(\n waveformData: WaveformData,\n samplesPerPixel: number,\n isMono: boolean,\n offsetSamples?: number,\n durationSamples?: number\n): PeakData {\n const processedData = sliceAndResample(\n waveformData,\n samplesPerPixel,\n offsetSamples,\n durationSamples\n );\n\n if (processedData === null) {\n const bits = waveformData.bits as 8 | 16;\n return { length: 0, data: [], bits };\n }\n\n const numChannels = processedData.channels;\n const bits = processedData.bits as 8 | 16;\n\n // Extract peaks for all channels\n const channelPeaks: Peaks[] = [];\n for (let c = 0; c < numChannels; c++) {\n const channel = processedData.channel(c);\n const minArray = channel.min_array();\n const maxArray = channel.max_array();\n const len = minArray.length;\n\n const peaks: Peaks = bits === 8 ? new Int8Array(len * 2) : new Int16Array(len * 2);\n\n for (let i = 0; i < len; i++) {\n peaks[i * 2] = minArray[i];\n peaks[i * 2 + 1] = maxArray[i];\n }\n channelPeaks.push(peaks);\n }\n\n // Handle mono merging (same algorithm as makeMono in webaudio-peaks)\n if (isMono && channelPeaks.length > 1) {\n const weight = 1 / channelPeaks.length;\n const numPeaks = channelPeaks[0].length / 2;\n const monoPeaks: Peaks =\n bits === 8 ? new Int8Array(numPeaks * 2) : new Int16Array(numPeaks * 2);\n\n for (let i = 0; i < numPeaks; i++) {\n let min = 0;\n let max = 0;\n for (let c = 0; c < channelPeaks.length; c++) {\n min += weight * channelPeaks[c][i * 2];\n max += weight * channelPeaks[c][i * 2 + 1];\n }\n monoPeaks[i * 2] = min;\n monoPeaks[i * 2 + 1] = max;\n }\n\n return {\n length: numPeaks,\n data: [monoPeaks],\n bits,\n };\n }\n\n const peakLength = channelPeaks.length > 0 ? channelPeaks[0].length / 2 : 0;\n\n return {\n length: peakLength,\n data: channelPeaks,\n bits,\n };\n}\n","/**\n * derivePeaks\n *\n * Turns `tracks` into the per-track, per-clip peaks the visualization draws,\n * reusing everything from the previous pass that still applies (#692).\n *\n * Three identities are preserved, because three different things are keyed on\n * them downstream:\n * - the typed arrays (`ClipPeaks.peaks`): `Channel` redraws its canvas when\n * they change;\n * - the `ClipPeaks` object: a memoized clip re-renders when it changes;\n * - the per-track array: a memoized track row re-renders when it changes.\n *\n * Peak sources, in priority order:\n * A) `clip.waveformData` — external pre-computed peaks (e.g. BBC audiowaveform)\n * B) worker-generated WaveformData for `clip.audioBuffer`\n * C) empty peaks — the clip is still loading, or is a MIDI clip\n *\n * The function does not mutate `previous`; the caller keeps the returned cache\n * and passes it to the next call.\n */\n\nimport type { AudioClip, ClipTrack, PeakData } from '@waveform-playlist/core';\nimport type WaveformData from 'waveform-data';\nimport { extractPeaksFromWaveformDataFull } from '../waveformDataLoader';\nimport type { ClipPeaks, TrackClipPeaks } from '../WaveformPlaylistContext';\nimport { sameItems } from './sameItems';\n\nexport interface DerivePeaksOptions {\n samplesPerPixel: number;\n mono: boolean;\n /** Worker-generated waveform data for a buffer, when it is ready. */\n getGeneratedWaveformData: (audioBuffer: AudioBuffer) => WaveformData | undefined;\n}\n\n/** What a clip's typed arrays were computed from. */\nexport interface PeakInputs {\n waveformData: WaveformData | undefined;\n /** Compared only when path A is absent or failed (`usesGenerated`). */\n generated: WaveformData | undefined;\n offsetSamples: number;\n durationSamples: number;\n sampleRate: number;\n samplesPerPixel: number;\n mono: boolean;\n /** Channel count used for empty peaks (path C). */\n fallbackChannels: number;\n isMidi: boolean;\n}\n\n/** What `clipPeaksFor` returns: a clip's drawing record and what it was computed from. */\nexport interface ClipPeaksEntry {\n inputs: PeakInputs;\n /** True when path A was absent or failed, so `generated` matters. */\n usesGenerated: boolean;\n peaks: PeakData;\n clipPeaks: ClipPeaks;\n}\n\nexport interface PeaksCache {\n readonly clips: ReadonlyMap<string, ClipPeaksEntry>;\n readonly tracks: ReadonlyMap<string, TrackClipPeaks>;\n readonly result: TrackClipPeaks[];\n}\n\nexport const EMPTY_PEAKS_CACHE: PeaksCache = {\n clips: new Map(),\n tracks: new Map(),\n result: [],\n};\n\n/** The slice rule for a clip drawn from its own pre-computed peaks (path A). */\nexport function extractFromOwnWaveformData(\n clip: Pick<AudioClip, 'sampleRate' | 'offsetSamples' | 'durationSamples'>,\n waveformData: WaveformData,\n samplesPerPixel: number,\n mono: boolean\n): PeakData | undefined {\n // When sample rates match, use clip offsets directly. When they differ (e.g.\n // waveformData at 48000 Hz, clip rebuilt at 44100 Hz after audio decode),\n // convert offsets to the waveformData's sample space and adjust\n // samplesPerPixel so peaks fill the correct container width.\n try {\n const wdRate = waveformData.sample_rate;\n const clipRate = clip.sampleRate;\n let peakOffset = clip.offsetSamples;\n let peakDuration = clip.durationSamples;\n let peakSpp = samplesPerPixel;\n if (wdRate !== clipRate && clipRate > 0 && wdRate > 0) {\n const ratio = wdRate / clipRate;\n peakOffset = Math.round(clip.offsetSamples * ratio);\n peakDuration = Math.round(clip.durationSamples * ratio);\n peakSpp = Math.max(1, Math.round(samplesPerPixel * ratio));\n }\n return extractPeaksFromWaveformDataFull(waveformData, peakSpp, mono, peakOffset, peakDuration);\n } catch (err) {\n console.warn('[waveform-playlist] Failed to extract peaks from waveformData: ' + String(err));\n return undefined;\n }\n}\n\nfunction extractFromGenerated(\n clip: AudioClip,\n generated: WaveformData,\n samplesPerPixel: number,\n mono: boolean\n): PeakData | undefined {\n try {\n return extractPeaksFromWaveformDataFull(\n generated,\n samplesPerPixel,\n mono,\n clip.offsetSamples,\n clip.durationSamples\n );\n } catch (err) {\n console.warn('[waveform-playlist] Failed to extract peaks from cache: ' + String(err));\n return undefined;\n }\n}\n\nfunction emptyPeaks(inputs: PeakInputs): PeakData {\n // MIDI clips: derive pixel width from sample duration so the clip renders at\n // the correct width instead of zero-width. Audio clips keep the buffer's\n // channel count so the track height does not shift when peaks arrive.\n const pixelLength = inputs.isMidi\n ? Math.ceil(inputs.durationSamples / inputs.samplesPerPixel)\n : 0;\n return {\n length: pixelLength,\n data: Array.from({ length: inputs.fallbackChannels }, () => new Int16Array(pixelLength * 2)),\n bits: 16,\n };\n}\n\nfunction sameInputs(a: PeakInputs, b: PeakInputs, usesGenerated: boolean): boolean {\n return (\n a.waveformData === b.waveformData &&\n (!usesGenerated || a.generated === b.generated) &&\n a.offsetSamples === b.offsetSamples &&\n a.durationSamples === b.durationSamples &&\n a.sampleRate === b.sampleRate &&\n a.samplesPerPixel === b.samplesPerPixel &&\n a.mono === b.mono &&\n a.fallbackChannels === b.fallbackChannels &&\n a.isMidi === b.isMidi\n );\n}\n\nfunction computePeaks(\n clip: AudioClip,\n inputs: PeakInputs\n): { peaks: PeakData; usesGenerated: boolean } {\n const { waveformData, generated, samplesPerPixel, mono } = inputs;\n const own = waveformData\n ? extractFromOwnWaveformData(clip, waveformData, samplesPerPixel, mono)\n : undefined;\n if (own) return { peaks: own, usesGenerated: false };\n\n const fromWorker = generated\n ? extractFromGenerated(clip, generated, samplesPerPixel, mono)\n : undefined;\n return { peaks: fromWorker ?? emptyPeaks(inputs), usesGenerated: true };\n}\n\nfunction sameClipPeaks(a: ClipPeaks, clip: AudioClip, trackName: string, peaks: PeakData): boolean {\n return (\n a.peaks === peaks &&\n a.trackName === trackName &&\n a.startSample === clip.startSample &&\n a.durationSamples === clip.durationSamples &&\n a.fadeIn === clip.fadeIn &&\n a.fadeOut === clip.fadeOut &&\n a.midiNotes === clip.midiNotes &&\n a.sampleRate === clip.sampleRate &&\n a.offsetSamples === clip.offsetSamples &&\n a.gain === clip.gain &&\n !a.isPlaceholder\n );\n}\n\n/**\n * One clip's peaks and drawing record, reusing `previous` (the entry of the\n * same clip from the last pass) when nothing it depends on changed. The step\n * `derivePeaks` runs for every clip, exported so that a clip drawn with a\n * trim preview's geometry is computed by the same code (#812).\n */\nexport function clipPeaksFor(\n clip: AudioClip,\n trackName: string,\n options: DerivePeaksOptions,\n previous?: ClipPeaksEntry\n): ClipPeaksEntry {\n const inputs: PeakInputs = {\n waveformData: clip.waveformData as WaveformData | undefined,\n generated: clip.audioBuffer ? options.getGeneratedWaveformData(clip.audioBuffer) : undefined,\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n sampleRate: clip.sampleRate,\n samplesPerPixel: options.samplesPerPixel,\n mono: options.mono,\n fallbackChannels: options.mono ? 1 : (clip.audioBuffer?.numberOfChannels ?? 1),\n isMidi: Boolean(clip.midiNotes),\n };\n\n const reusable = previous && sameInputs(previous.inputs, inputs, previous.usesGenerated);\n const { peaks, usesGenerated } = reusable\n ? { peaks: previous.peaks, usesGenerated: previous.usesGenerated }\n : computePeaks(clip, inputs);\n\n if (previous && reusable && sameClipPeaks(previous.clipPeaks, clip, trackName, peaks)) {\n return previous;\n }\n\n return {\n inputs,\n usesGenerated,\n peaks,\n clipPeaks: {\n clipId: clip.id,\n trackName,\n peaks,\n startSample: clip.startSample,\n durationSamples: clip.durationSamples,\n fadeIn: clip.fadeIn,\n fadeOut: clip.fadeOut,\n midiNotes: clip.midiNotes,\n sampleRate: clip.sampleRate,\n offsetSamples: clip.offsetSamples,\n gain: clip.gain,\n isPlaceholder: false,\n },\n };\n}\n\nexport function derivePeaks(\n tracks: readonly ClipTrack[],\n options: DerivePeaksOptions,\n previous: PeaksCache\n): PeaksCache {\n const clips = new Map<string, ClipPeaksEntry>();\n const trackPeaks = new Map<string, TrackClipPeaks>();\n\n const derived = tracks.map((track) => {\n const clipPeaks = track.clips.map((clip) => {\n const entry = clipPeaksFor(clip, track.name, options, previous.clips.get(clip.id));\n clips.set(clip.id, entry);\n return entry.clipPeaks;\n });\n const before = previous.tracks.get(track.id);\n const stable = sameItems(before, clipPeaks) ? before : clipPeaks;\n trackPeaks.set(track.id, stable);\n return stable;\n });\n\n return {\n clips,\n tracks: trackPeaks,\n result: sameItems(previous.result, derived) ? previous.result : derived,\n };\n}\n","/**\n * useEngineLifetime\n *\n * The engine of `WaveformPlaylistProvider` around an arrangement (#812). The\n * arrangement owns the tracks, the mix, the undo history and the loading, and\n * outlives every engine: this hook builds an engine on it on mount and when\n * `effects` changes identity or `zoomLevels` changes content (QG), disposes\n * it in every cleanup, and gives the arrangement the context it decodes with.\n * A track edit builds nothing: the engine follows the arrangement (#798).\n *\n * It also owns what a play waiting for an engine needs (#675, the six rules of\n * `notes/playback-and-engine.md`, \"Engine Rebuilds vs Playback\"):\n * `pendingResumeRef`, `engineBuildInFlightRef` and `engineEpoch`. The\n * provider's `play`, `pause`, `stop` and resume effect read and write them.\n */\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport {\n attachDecodeContext,\n PlaylistEngine,\n type Arrangement,\n type EngineState,\n type PlayoutAdapter,\n} from '@waveform-playlist/engine';\nimport type {\n EffectsFunction,\n SoundFontCache,\n TrackEffectsFunction,\n} from '@waveform-playlist/playout';\nimport { resolvePlayoutAdapter } from '../playout/resolvePlayoutAdapter';\n\n/** The rate the provider assumes until its first adapter says otherwise. */\nconst PROVISIONAL_SAMPLE_RATE = 48000;\n\n/** A play that must start once the engine being built is assigned. */\nexport interface PendingResume {\n position: number;\n /** Set for duration-limited playback. */\n endTime?: number;\n}\n\nexport interface UseEngineLifetimeOptions {\n arrangement: Arrangement;\n /** Read when an engine is built; a new identity builds nothing. */\n createAdapter?: () => PlayoutAdapter;\n /** Master effects chain (default Tone.js adapter). A new identity rebuilds. */\n effects?: EffectsFunction;\n /** Read when an engine is built; the adapter keeps it for its whole life. */\n resolveTrackEffects: (trackId: string) => TrackEffectsFunction | undefined;\n soundFontCacheRef: React.RefObject<SoundFontCache | undefined>;\n /** The provider's `sampleRate` prop. Read when an engine is built. */\n sampleRateProp?: number;\n /** Compared by content: an inline array with the same levels builds nothing. */\n zoomLevels?: number[];\n samplesPerPixelRef: React.RefObject<number>;\n /** Where a bounded play stops: carried into the resume of a play a rebuild interrupts. */\n playbackEndTimeRef: React.RefObject<number | null>;\n /** Give a new engine the provider's selection, loop, volume and selected track. */\n seedEngine: (engine: PlaylistEngine) => void;\n /** Subscribe to a new engine (`statechange`, `stop`). */\n onEngine: (engine: PlaylistEngine) => void;\n /**\n * A new engine's first state, once, after `onEngine`: an engine built on\n * an arrangement sends its tracks in its constructor and emits no\n * `statechange`, so this is where `canZoomIn` / `canZoomOut` first arrive.\n */\n onEngineState: (state: EngineState) => void;\n stopAnimationFrameLoop: () => void;\n /** The latest committed `onError` (QG). */\n onErrorRef: React.RefObject<((error: Error) => void) | undefined>;\n /**\n * A build that is still current failed: no engine is coming until a later\n * build. Called before `onError`.\n */\n onBuildFailure?: () => void;\n}\n\nexport interface EngineLifetime {\n engineRef: React.RefObject<PlaylistEngine | null>;\n adapterRef: React.RefObject<PlayoutAdapter | null>;\n /** Bumped each time a freshly built engine is assigned. */\n engineEpoch: number;\n /** Ask for another run of what follows `engineEpoch` (a play handed to an engine already assigned). */\n bumpEngineEpoch: () => void;\n /** True while an assigned engine is current: false from the start of each\n * build until its engine is assigned, and after a cleanup disposed it. */\n isEngineAttached: boolean;\n /** True from the start of a build until its engine is assigned, it fails or it is superseded. */\n engineBuildInFlightRef: React.RefObject<boolean>;\n /** The play waiting for the engine being built (#675). */\n pendingResumeRef: React.RefObject<PendingResume | null>;\n /** Whether the current engine's `init()` has run; false for each new engine. */\n audioInitializedRef: React.RefObject<boolean>;\n /** Dispose the engine, leaving nothing reachable; queue a resume if it was playing. */\n disposeEngineKeepingPlayback: () => void;\n /** The `sampleRate` prop or 48000 until the first adapter exists, then the adapter's. */\n sampleRate: number;\n /** True from mount with the `sampleRate` prop, else from the first adapter on. */\n isSampleRateKnown: boolean;\n}\n\ninterface Deferred<T> {\n promise: Promise<T>;\n resolve(value: T): void;\n}\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n const promise = new Promise<T>((done) => {\n resolve = done;\n });\n return { promise, resolve };\n}\n\n/** What one run of the build effect needs; `latest` is read when the build reaches it. */\ninterface BuildContext {\n arrangement: Arrangement;\n effects: EffectsFunction | undefined;\n zoomLevels: number[] | undefined;\n latest: React.RefObject<UseEngineLifetimeOptions>;\n engineRef: React.RefObject<PlaylistEngine | null>;\n adapterRef: React.RefObject<PlayoutAdapter | null>;\n engineBuildInFlightRef: React.RefObject<boolean>;\n pendingResumeRef: React.RefObject<PendingResume | null>;\n audioInitializedRef: React.RefObject<boolean>;\n /** Called with a new engine's adapter once the engine is assigned. */\n onAssigned: (adapter: PlayoutAdapter) => void;\n setSampleRate: (rate: number) => void;\n setIsEngineAttached: (attached: boolean) => void;\n bumpEngineEpoch: () => void;\n}\n\ninterface BuildRun {\n cancelled: boolean;\n}\n\nasync function buildEngine(ctx: BuildContext, run: BuildRun): Promise<void> {\n let engine: PlaylistEngine | null = null;\n try {\n const options = ctx.latest.current;\n // A new adapter needs its AudioContext resumed on the first play.\n ctx.audioInitializedRef.current = false;\n const adapter = await resolvePlayoutAdapter({\n createAdapter: options.createAdapter,\n effects: ctx.effects,\n trackEffects: options.resolveTrackEffects,\n soundFontCache: options.soundFontCacheRef.current,\n sampleRate: options.sampleRateProp,\n });\n if (run.cancelled) {\n // Superseded: the next run owns engineBuildInFlightRef now.\n adapter.dispose();\n return;\n }\n ctx.setSampleRate(adapter.audioContext.sampleRate);\n ctx.adapterRef.current = adapter;\n engine = new PlaylistEngine({\n adapter,\n arrangement: ctx.arrangement,\n // The provider attaches the decode context itself, once per mount.\n attachDecodeContext: false,\n samplesPerPixel: ctx.latest.current.samplesPerPixelRef.current,\n zoomLevels: ctx.zoomLevels,\n });\n const latest = ctx.latest.current;\n latest.seedEngine(engine);\n latest.onEngine(engine);\n latest.onEngineState(engine.getState());\n ctx.engineRef.current = engine;\n ctx.engineBuildInFlightRef.current = false;\n ctx.onAssigned(adapter);\n ctx.setIsEngineAttached(true);\n // Starts any play queued for this engine (the provider's resume effect).\n ctx.bumpEngineEpoch();\n } catch (error) {\n reportBuildFailure(ctx, run, engine, error);\n }\n}\n\n/** A build that failed: nothing it made stays reachable, and no queued play waits for it. */\nfunction reportBuildFailure(\n ctx: BuildContext,\n run: BuildRun,\n engine: PlaylistEngine | null,\n error: unknown\n): void {\n if (ctx.engineRef.current === null) {\n // Made but never assigned: the cleanup cannot reach it. Disposing the\n // engine disposes its adapter and lets go of the arrangement.\n const leftover = engine ?? ctx.adapterRef.current;\n try {\n leftover?.dispose();\n } catch (disposeErr) {\n console.warn(\n '[waveform-playlist] adapter dispose after load failure threw: ' + String(disposeErr)\n );\n }\n ctx.adapterRef.current = null;\n }\n // A build that was superseded or unmounted says nothing, neither to the\n // console nor to `onError`: the build that replaced it speaks for itself\n // (maintainer, C1 = b; on `main` `onError` was called for it too).\n if (run.cancelled) return;\n const onError = ctx.latest.current.onErrorRef.current;\n // No engine is coming: a queued play would otherwise wait forever and fire\n // on some later, unrelated rebuild.\n ctx.engineBuildInFlightRef.current = false;\n ctx.pendingResumeRef.current = null;\n ctx.latest.current.onBuildFailure?.();\n // An error, not a warning: the playlist cannot be played until a later\n // build succeeds.\n const reason = error instanceof Error ? error.message : String(error);\n console.error(\n '[waveform-playlist] The playlist could not be built and stays in its loading ' +\n 'state (it cannot be played). Reason: ' +\n reason +\n (onError ? '' : ' Pass `onError` to WaveformPlaylistProvider to show this in your app.')\n );\n onError?.(error instanceof Error ? error : new Error(String(error)));\n}\n\n/** The provider's rate: the prop or 48000 until an adapter says otherwise (B1b). */\nfunction useKnownSampleRate(sampleRateProp: number | undefined) {\n const [sampleRate, setSampleRateState] = useState(\n () => sampleRateProp ?? PROVISIONAL_SAMPLE_RATE\n );\n const [isSampleRateKnown, setIsSampleRateKnown] = useState(() => sampleRateProp !== undefined);\n const setSampleRate = useCallback((rate: number) => {\n setSampleRateState(rate);\n setIsSampleRateKnown(true);\n }, []);\n return { sampleRate, isSampleRateKnown, setSampleRate };\n}\n\n/**\n * The decode context: attached once per mount (and again after an\n * <Activity> reveal), detached in the cleanup, which aborts the loads in\n * flight. The getter gives the current adapter's context; while there is no\n * adapter it waits for the next engine's (`onAssigned`). It never rejects.\n */\nfunction useDecodeContext(\n arrangement: Arrangement,\n adapterRef: React.RefObject<PlayoutAdapter | null>\n): (adapter: PlayoutAdapter) => void {\n const arrivalRef = useRef<Deferred<BaseAudioContext> | null>(null);\n const getDecodeContext = useCallback(async (): Promise<BaseAudioContext> => {\n const adapter = adapterRef.current;\n if (adapter) return adapter.audioContext;\n arrivalRef.current ??= deferred<BaseAudioContext>();\n return arrivalRef.current.promise;\n }, [adapterRef]);\n useEffect(\n () => attachDecodeContext(arrangement, getDecodeContext),\n [arrangement, getDecodeContext]\n );\n return useCallback((adapter: PlayoutAdapter) => {\n const arrival = arrivalRef.current;\n arrivalRef.current = null;\n arrival?.resolve(adapter.audioContext);\n }, []);\n}\n\n/**\n * Dispose the current engine ahead of a rebuild, leaving nothing reachable\n * through engineRef or adapterRef. If the engine is PLAYING at this moment,\n * queue a resume for its replacement. The engine is asked directly, not\n * React's `isPlaying`, which is only as fresh as the last render (#675).\n */\nfunction useDisposeKeepingPlayback(\n refs: Pick<BuildContext, 'engineRef' | 'adapterRef' | 'pendingResumeRef' | 'latest'>\n): () => void {\n const { engineRef, adapterRef, pendingResumeRef, latest } = refs;\n return useCallback(() => {\n const engine = engineRef.current;\n if (!engine) return;\n if (engine.getState().isPlaying && !pendingResumeRef.current) {\n pendingResumeRef.current = {\n position: engine.getCurrentTime(),\n endTime: latest.current.playbackEndTimeRef.current ?? undefined,\n };\n }\n engine.dispose();\n engineRef.current = null;\n // The adapter went with the engine. Nothing may reach it either: the\n // soundfont sync, the clock and the decode context read it (#811).\n adapterRef.current = null;\n }, [engineRef, adapterRef, pendingResumeRef, latest]);\n}\n\nexport function useEngineLifetime(options: UseEngineLifetimeOptions): EngineLifetime {\n const { arrangement, effects, zoomLevels, sampleRateProp } = options;\n // Callbacks and build-time inputs, as of the latest committed render.\n const latest = useRef(options);\n useLayoutEffect(() => {\n latest.current = options;\n });\n // An inline array (zoomLevels={[256, 512]}) is new on every render; only\n // its content is a reason to rebuild.\n const stableZoomLevels = useMemo(\n () => zoomLevels,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [zoomLevels?.join(',')]\n );\n\n const engineRef = useRef<PlaylistEngine | null>(null);\n const adapterRef = useRef<PlayoutAdapter | null>(null);\n const engineBuildInFlightRef = useRef(false);\n const pendingResumeRef = useRef<PendingResume | null>(null);\n const audioInitializedRef = useRef(false);\n const [engineEpoch, setEngineEpoch] = useState(0);\n const [isEngineAttached, setIsEngineAttached] = useState(false);\n const bumpEngineEpoch = useCallback(() => setEngineEpoch((epoch) => epoch + 1), []);\n const { sampleRate, isSampleRateKnown, setSampleRate } = useKnownSampleRate(sampleRateProp);\n const onAssigned = useDecodeContext(arrangement, adapterRef);\n const disposeEngineKeepingPlayback = useDisposeKeepingPlayback({\n engineRef,\n adapterRef,\n pendingResumeRef,\n latest,\n });\n\n useEffect(() => {\n const run: BuildRun = { cancelled: false };\n engineBuildInFlightRef.current = true;\n setIsEngineAttached(false);\n const ctx: BuildContext = {\n arrangement,\n effects,\n zoomLevels: stableZoomLevels,\n latest,\n engineRef,\n adapterRef,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n onAssigned,\n setSampleRate,\n setIsEngineAttached,\n bumpEngineEpoch,\n };\n void buildEngine(ctx, run);\n return () => {\n run.cancelled = true;\n engineBuildInFlightRef.current = false;\n latest.current.stopAnimationFrameLoop();\n // Never leave a disposed engine reachable (#675).\n disposeEngineKeepingPlayback();\n };\n }, [\n arrangement,\n effects,\n stableZoomLevels,\n onAssigned,\n setSampleRate,\n bumpEngineEpoch,\n disposeEngineKeepingPlayback,\n ]);\n\n return {\n engineRef,\n adapterRef,\n engineEpoch,\n bumpEngineEpoch,\n // The state goes false only when a build starts, so it is still true\n // after a cleanup disposed the engine without a new build yet (an\n // <Activity> hide): a render then must not see an engine. The ref is\n // non-null only between an assignment (followed by the state's true) and\n // the dispose that nulls it, which every dispose does; a render can read\n // a null that is newer than the state, never a stale non-null. Clearing\n // the state in the cleanup instead left published tracks stale after a\n // reveal in the final review's random probe (#812).\n isEngineAttached: isEngineAttached && engineRef.current !== null,\n engineBuildInFlightRef,\n pendingResumeRef,\n audioInitializedRef,\n disposeEngineKeepingPlayback,\n sampleRate,\n isSampleRateKnown,\n };\n}\n","/**\n * The `npm install` command an error message gives for a missing optional\n * package (#884). A bare name installs npm `latest`, which can fail the peer\n * range of this build (a `next` prerelease, or a stable build of an older\n * major), so each name carries the range this package was published with (for\n * spectrogram, which browser does not peer on, a caret on its version).\n *\n * The ranges are written in at build time (`__INSTALL_SPECS__`, from\n * `scripts/build/install-specs.mjs` through `tsup.config.ts`). Code compiled\n * from source without that define (the website and the React examples alias\n * this source) prints the bare name, quoted.\n */\ndeclare const __INSTALL_SPECS__: Readonly<Record<string, string>> | undefined;\n\nconst BUILT_SPECS: Readonly<Record<string, string>> =\n typeof __INSTALL_SPECS__ === 'undefined' ? {} : __INSTALL_SPECS__;\n\n/** `npm install \"<name>@<range>\" …`, quoted: a range can hold `>`, `^` and `||`. */\nexport function formatInstallCommand(\n specs: Readonly<Record<string, string>>,\n names: readonly string[]\n): string {\n return 'npm install ' + names.map((name) => `\"${specs[name] ?? name}\"`).join(' ');\n}\n\n/** The install command for `names`, with the ranges of this build. */\nexport function installCommand(...names: string[]): string {\n return formatInstallCommand(BUILT_SPECS, names);\n}\n","import type { PlayoutAdapter } from '@waveform-playlist/engine';\nimport type {\n EffectsFunction,\n SoundFontCache,\n TrackEffectsFunction,\n} from '@waveform-playlist/playout';\nimport { installCommand } from '../utils/installCommand';\n\n/** Options for {@link resolvePlayoutAdapter}. */\nexport interface ResolvePlayoutAdapterOptions {\n /** Consumer-supplied factory. When present, the default engine is never imported. */\n createAdapter?: () => PlayoutAdapter;\n /** Master effects function — forwarded to the default Tone.js adapter only. */\n effects?: EffectsFunction;\n /** Per-track effects lookup by track id — forwarded to the default Tone.js adapter only. */\n trackEffects?: (trackId: string) => TrackEffectsFunction | undefined;\n /** SoundFont cache — forwarded to the default Tone.js adapter only. */\n soundFontCache?: SoundFontCache;\n /** Desired AudioContext sample rate — configures the global Tone context (default path only). */\n sampleRate?: number;\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst installHint = (): string =>\n '@waveform-playlist/playout (and its peer `tone`) is required for the default WebAudio engine. ' +\n 'Install with: ' +\n installCommand('@waveform-playlist/playout', 'tone') +\n ' — or pass a custom `createAdapter`.';\n\n/**\n * Resolve a {@link PlayoutAdapter}. With `createAdapter`, returns its result and\n * never touches the default engine — so consumers with a custom adapter install\n * neither `@waveform-playlist/playout` nor `tone`. Otherwise dynamically imports\n * the Tone.js engine, rethrowing a friendly install hint (and console.warn-ing the\n * original error) when the optional peer is absent.\n */\nexport async function resolvePlayoutAdapter(\n opts: ResolvePlayoutAdapterOptions\n): Promise<PlayoutAdapter> {\n if (opts.createAdapter) {\n return opts.createAdapter();\n }\n\n let mod: typeof import('@waveform-playlist/playout');\n try {\n mod = await import('@waveform-playlist/playout');\n } catch (originalErr) {\n console.warn(\n '[waveform-playlist] @waveform-playlist/playout dynamic import failed: ' + String(originalErr)\n );\n throw new Error(installHint());\n }\n\n if (opts.sampleRate !== undefined) {\n // Non-fatal: a failed context configuration falls back to the default rate\n // (restores pre-#510 behavior — it was caught in the old mount-time initializer).\n try {\n mod.configureGlobalContext({ sampleRate: opts.sampleRate });\n } catch (ctxErr) {\n console.warn(\n '[waveform-playlist] configureGlobalContext failed (continuing with default rate): ' +\n String(ctxErr)\n );\n }\n }\n return mod.createToneAdapter({\n effects: opts.effects,\n trackEffects: opts.trackEffects,\n soundFontCache: opts.soundFontCache,\n });\n}\n","/**\n * useArrangementView\n *\n * What `WaveformPlaylistProvider` publishes about an arrangement (#812),\n * DERIVED from it during render and never written back: the loaded tracks,\n * one drawing row per track (the loaded clips' records and the placeholder\n * records of the clips still loading, in the arrangement's clip order), the\n * timeline length, `trackStates` from the arrangement's mixer, and the undo\n * state. The arrangement is the one owner of all of it.\n *\n * Every result keeps its identity while nothing it depends on changed: a\n * fader move changes `trackStates` and nothing else; a clip edit changes\n * `tracks` and the rows of the clips it touched, not `trackStates`.\n */\nimport { useMemo, useRef, useSyncExternalStore } from 'react';\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, ClipTrack } from '@waveform-playlist/core';\nimport type { Arrangement, TrackMixerValues } from '@waveform-playlist/engine';\nimport type { ClipPeaks, TrackClipPeaks, TrackState } from '../WaveformPlaylistContext';\nimport { useArrangementTracks } from '../hooks/useArrangementTracks';\nimport { useWaveformDataCache } from '../hooks/useWaveformDataCache';\nimport {\n derivePeaks,\n EMPTY_PEAKS_CACHE,\n type DerivePeaksOptions,\n type PeaksCache,\n} from '../utils/derivePeaks';\nimport { EMPTY_LOADED_TRACKS, loadedTracks, type LoadedTracksCache } from '../utils/loadedTracks';\nimport { placeholderPeaks } from '../utils/placeholderPeaks';\nimport { sameItems } from '../utils/sameItems';\nimport { timelineDuration } from '../utils/timelineDuration';\n\nexport interface ArrangementViewOptions {\n samplesPerPixel: number;\n mono: boolean;\n /** The finest zoom level: the scale the worker generates peaks at. */\n baseScale: number;\n /**\n * The rate placeholder records are built at, or `null` while the provider\n * does not know its real rate yet: then no placeholder record is built\n * (B1b; the provider passes `isSampleRateKnown ? sampleRate : null`).\n */\n placeholderSampleRate: number | null;\n}\n\nexport interface ArrangementView {\n /** The arrangement's tracks without their loading clips. Never write to them. */\n tracks: readonly ClipTrack[];\n /** One row per track, in the arrangement's clip order, placeholders included. */\n peaksDataArray: TrackClipPeaks[];\n /** The end, in seconds, of the loaded audio (placeholders do not count). */\n duration: number;\n /** One entry per track, in order, from the arrangement's mixer. */\n trackStates: TrackState[];\n canUndo: boolean;\n canRedo: boolean;\n /** The last pass of `derivePeaks` (loaded clips): for the trim preview. */\n peaksCacheRef: React.RefObject<PeaksCache>;\n /** What the loaded clips' peaks are derived with: for the trim preview. */\n peaksOptions: DerivePeaksOptions;\n}\n\ninterface RowsCache {\n readonly byTrackId: ReadonlyMap<string, TrackClipPeaks>;\n readonly result: TrackClipPeaks[];\n}\n\ninterface StatesCache {\n readonly byTrackId: ReadonlyMap<string, TrackState>;\n readonly result: TrackState[];\n}\n\nconst EMPTY_ROWS: RowsCache = { byTrackId: new Map(), result: [] };\nconst EMPTY_STATES: StatesCache = { byTrackId: new Map(), result: [] };\nconst DEFAULT_MIX: TrackMixerValues = { volume: 1, muted: false, soloed: false, pan: 0 };\n\ninterface RowInputs {\n loadedPeaks: PeaksCache;\n samplesPerPixel: number;\n mono: boolean;\n placeholderSampleRate: number | null;\n}\n\n/** A track's row: each clip's record by clip id, placeholders where they can be drawn. */\nfunction rowFor(track: ArrangementTrack, index: number, inputs: RowInputs): TrackClipPeaks {\n const loadedRow = inputs.loadedPeaks.result[index];\n if (!track.clips.some(isLoadingClip)) return loadedRow;\n const rate = inputs.placeholderSampleRate;\n const row: ClipPeaks[] = [];\n for (const clip of track.clips) {\n if (!isLoadingClip(clip)) {\n const entry = inputs.loadedPeaks.clips.get(clip.id);\n if (entry) row.push(entry.clipPeaks);\n continue;\n }\n if (rate === null) continue;\n const record = placeholderPeaks(clip, track.name, {\n contextSampleRate: rate,\n samplesPerPixel: inputs.samplesPerPixel,\n mono: inputs.mono,\n });\n if (record) row.push(record);\n }\n return row;\n}\n\nfunction deriveRows(\n tracks: readonly ArrangementTrack[],\n inputs: RowInputs,\n previous: RowsCache\n): RowsCache {\n const byTrackId = new Map<string, TrackClipPeaks>();\n const rows = tracks.map((track, index) => {\n const row = rowFor(track, index, inputs);\n const before = previous.byTrackId.get(track.id);\n const stable = sameItems(before, row) ? before : row;\n byTrackId.set(track.id, stable);\n return stable;\n });\n return { byTrackId, result: sameItems(previous.result, rows) ? previous.result : rows };\n}\n\nfunction sameState(a: TrackState, name: string, mix: TrackMixerValues): boolean {\n return (\n a.name === name &&\n a.volume === mix.volume &&\n a.muted === mix.muted &&\n a.soloed === mix.soloed &&\n a.pan === mix.pan\n );\n}\n\nfunction deriveTrackStates(\n tracks: readonly ArrangementTrack[],\n mixer: ReadonlyMap<string, TrackMixerValues>,\n previous: StatesCache\n): StatesCache {\n const byTrackId = new Map<string, TrackState>();\n const states = tracks.map((track) => {\n // Every track the arrangement holds has a mixer entry; the default is\n // there so that the array never holds `undefined`.\n const mix = mixer.get(track.id) ?? DEFAULT_MIX;\n const before = previous.byTrackId.get(track.id);\n const state =\n before && sameState(before, track.name, mix)\n ? before\n : {\n name: track.name,\n volume: mix.volume,\n muted: mix.muted,\n soloed: mix.soloed,\n pan: mix.pan,\n };\n byTrackId.set(track.id, state);\n return state;\n });\n return { byTrackId, result: sameItems(previous.result, states) ? previous.result : states };\n}\n\n/** A value of the arrangement, read with `useSyncExternalStore` (a primitive or a kept object). */\nfunction useArrangementValue<T>(arrangement: Arrangement, read: (a: Arrangement) => T): T {\n const store = useMemo(\n () => ({\n subscribe: (listener: () => void) => arrangement.subscribe(listener),\n getSnapshot: () => read(arrangement),\n }),\n [arrangement, read]\n );\n return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n\nconst readMixer = (arrangement: Arrangement) => arrangement.getMixer();\nconst readCanUndo = (arrangement: Arrangement) => arrangement.canUndo;\nconst readCanRedo = (arrangement: Arrangement) => arrangement.canRedo;\n\nexport function useArrangementView(\n arrangement: Arrangement,\n options: ArrangementViewOptions\n): ArrangementView {\n const { samplesPerPixel, mono, baseScale, placeholderSampleRate } = options;\n const arrangementTracks = useArrangementTracks(arrangement);\n const mixer = useArrangementValue(arrangement, readMixer);\n const canUndo = useArrangementValue(arrangement, readCanUndo);\n const canRedo = useArrangementValue(arrangement, readCanRedo);\n\n // The caches below are projections of the arrangement, kept so that each\n // pass can hand back what did not change; nothing reads them as state.\n const loadedCacheRef = useRef<LoadedTracksCache>(EMPTY_LOADED_TRACKS);\n const tracks = useMemo(() => {\n const next = loadedTracks(arrangementTracks, loadedCacheRef.current);\n loadedCacheRef.current = next.cache;\n return next.tracks;\n }, [arrangementTracks]);\n\n const { getWaveformData, version } = useWaveformDataCache(tracks, baseScale);\n const peaksOptions = useMemo<DerivePeaksOptions>(\n () => ({ samplesPerPixel, mono, getGeneratedWaveformData: getWaveformData }),\n [samplesPerPixel, mono, getWaveformData]\n );\n\n const peaksCacheRef = useRef<PeaksCache>(EMPTY_PEAKS_CACHE);\n const loadedPeaks = useMemo(() => {\n const next = derivePeaks(tracks, peaksOptions, peaksCacheRef.current);\n peaksCacheRef.current = next;\n return next;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `version` invalidates the ref-backed lookup\n }, [tracks, peaksOptions, version]);\n\n const rowsCacheRef = useRef<RowsCache>(EMPTY_ROWS);\n const peaksDataArray = useMemo(() => {\n const inputs = { loadedPeaks, samplesPerPixel, mono, placeholderSampleRate };\n const next = deriveRows(arrangementTracks, inputs, rowsCacheRef.current);\n rowsCacheRef.current = next;\n return next.result;\n }, [arrangementTracks, loadedPeaks, samplesPerPixel, mono, placeholderSampleRate]);\n\n const duration = useMemo(() => timelineDuration(tracks), [tracks]);\n\n const statesCacheRef = useRef<StatesCache>(EMPTY_STATES);\n const trackStates = useMemo(() => {\n const next = deriveTrackStates(arrangementTracks, mixer, statesCacheRef.current);\n statesCacheRef.current = next;\n return next.result;\n }, [arrangementTracks, mixer]);\n\n return {\n tracks,\n peaksDataArray,\n duration,\n trackStates,\n canUndo,\n canRedo,\n peaksCacheRef,\n peaksOptions,\n };\n}\n","/**\n * placeholderPeaks\n *\n * The drawing record of a clip whose audio is still loading (#812). It is a\n * `ClipPeaks` with `isPlaceholder: true` and exists nowhere else: no tracks\n * array holds a clip for it. The caller finds it by `clipId`.\n *\n * Drawn from the loading clip's own `waveformData` when it has usable ones,\n * else an empty box as long as its `duration`. `null` when neither gives a\n * length, or when a time is not a usable number. Its sample positions and\n * `sampleRate` are at `contextSampleRate`, whatever the rate of the peaks.\n */\nimport type { LoadingClip } from '@waveform-playlist/core';\nimport type WaveformData from 'waveform-data';\nimport type { ClipPeaks, TrackClipPeaks } from '../WaveformPlaylistContext';\nimport { extractFromOwnWaveformData } from './derivePeaks';\n\nexport interface PlaceholderPeaksOptions {\n contextSampleRate: number;\n samplesPerPixel: number;\n mono: boolean;\n}\n\ninterface MemoEntry {\n trackName: string;\n options: PlaceholderPeaksOptions;\n result: ClipPeaks | null;\n}\n\n// The last result per loading-clip object: the provider asks again on every\n// derivation and a new object would redraw the row.\nconst memo = new WeakMap<LoadingClip, MemoEntry>();\n\nfunction sameOptions(a: PlaceholderPeaksOptions, b: PlaceholderPeaksOptions): boolean {\n return (\n a.contextSampleRate === b.contextSampleRate &&\n a.samplesPerPixel === b.samplesPerPixel &&\n a.mono === b.mono\n );\n}\n\nfunction isTime(value: number | undefined): boolean {\n return value === undefined || (Number.isFinite(value) && value >= 0);\n}\n\nfunction usableWaveformData(clip: LoadingClip): WaveformData | undefined {\n const data = clip.waveformData as WaveformData | undefined;\n if (!data) return undefined;\n const ok =\n Number.isFinite(data.sample_rate) &&\n data.sample_rate > 0 &&\n Number.isFinite(data.duration) &&\n data.duration >= 0;\n return ok ? data : undefined;\n}\n\nfunction build(\n clip: LoadingClip,\n trackName: string,\n options: PlaceholderPeaksOptions\n): ClipPeaks | null {\n const wdata = usableWaveformData(clip);\n // A null duration is \"not given\", as in the engine's resolveLoadingClip: plain\n // JavaScript or JSON input can carry one although the type does not.\n const duration = (clip.duration as number | null | undefined) ?? undefined;\n if (duration === undefined && !wdata) return null;\n if (!isTime(clip.start) || !isTime(clip.offset) || !isTime(duration)) return null;\n // The geometry is at the context's rate, also for peaks at another rate:\n // the audio is decoded at the context's rate, so that is the rate of the\n // loaded clip this record stands in for (B1, #812).\n const rate = options.contextSampleRate;\n if (!(Number.isFinite(rate) && rate > 0)) return null;\n\n const startSample = Math.round((clip.start ?? 0) * rate);\n const offsetSamples = Math.round((clip.offset ?? 0) * rate);\n // With peaks the clip cannot be longer than the file: the same cut as the\n // loaded clip's, the file's length in seconds at the context's rate. An\n // offset at or past the end leaves no samples (`rest` < 1), which gives null\n // below.\n const total = wdata ? Math.ceil(wdata.duration * rate) : undefined;\n const rest = total === undefined ? undefined : total - offsetSamples;\n const wanted = duration === undefined ? rest : Math.round(duration * rate);\n const durationSamples =\n rest === undefined ? (wanted as number) : Math.min(wanted as number, rest);\n if (![startSample, offsetSamples, durationSamples, total ?? 0].every(Number.isSafeInteger)) {\n return null;\n }\n if (durationSamples < 1) return null;\n\n // Converted to the file's own sample positions through the ratio of the two\n // rates, as for a loaded clip drawn from its own peaks.\n const drawn = wdata\n ? extractFromOwnWaveformData(\n { sampleRate: rate, offsetSamples, durationSamples },\n wdata,\n options.samplesPerPixel,\n options.mono\n )\n : undefined;\n const peaks = drawn ?? { length: 0, data: [new Int16Array(0)], bits: 16 as const };\n\n return {\n clipId: clip.id,\n trackName,\n peaks,\n startSample,\n durationSamples,\n offsetSamples,\n sampleRate: rate,\n fadeIn: clip.fadeIn,\n fadeOut: clip.fadeOut,\n gain: clip.gain,\n isPlaceholder: true,\n };\n}\n\nexport function placeholderPeaks(\n clip: LoadingClip,\n trackName: string,\n options: PlaceholderPeaksOptions\n): ClipPeaks | null {\n const hit = memo.get(clip);\n if (hit && hit.trackName === trackName && sameOptions(hit.options, options)) return hit.result;\n const result = build(clip, trackName, options);\n memo.set(clip, { trackName, options: { ...options }, result });\n return result;\n}\n\n/** The end in seconds of the last placeholder record of `rows`, 0 when there is none. */\nexport function placeholdersEnd(rows: readonly TrackClipPeaks[]): number {\n let end = 0;\n for (const row of rows) {\n for (const record of row) {\n if (!record.isPlaceholder || !record.sampleRate) continue;\n end = Math.max(end, (record.startSample + record.durationSamples) / record.sampleRate);\n }\n }\n return end;\n}\n","import type { ClipTrack } from '@waveform-playlist/core';\n\n/**\n * Timeline length in seconds: the end of the last clip across all tracks.\n * Uses each clip's own `sampleRate`, which is always defined (peaks-only clips\n * have no AudioBuffer to ask).\n */\nexport function timelineDuration(tracks: readonly ClipTrack[]): number {\n let maxDuration = 0;\n for (const track of tracks) {\n for (const clip of track.clips) {\n const clipEnd = (clip.startSample + clip.durationSamples) / clip.sampleRate;\n if (clipEnd > maxDuration) maxDuration = clipEnd;\n }\n }\n return maxDuration;\n}\n","/**\n * useReadyOnce\n *\n * \"Ready\" for `WaveformPlaylistProvider` on an arrangement (#812, QE). The\n * provider is the one owner of `isReady` and of \"ready has fired\".\n *\n * - `isReady` is false until an engine is attached and no source of the\n * arrangement is pending, for the first time; from then on it is \"an\n * engine is attached\" (false while a later engine is being built, true\n * again when it is assigned, whatever is still loading then).\n * - `onReady` and the `waveform-playlist:ready` event fire ONCE per mount, at\n * that first time: not again after a rebuild, a StrictMode remount or an\n * `<Activity>` hide and reveal. The event's `trackCount` counts every track\n * of the arrangement, its `duration` the loaded audio (A5).\n * - A failed source counts as settled, and is not reported through `onError`\n * (QB). An `onReady` that throws is the app's own error: it is written to\n * the console and given to `onError`.\n * - Play does nothing before that first time (maintainer, 2026-11-15):\n * `refusePlayBeforeFirstReady()` says so to `play()` at call time, and\n * writes one console warning per mount in a development build (none in a\n * production build). It queues nothing, so Play pressed\n * during the first load never starts by itself.\n */\nimport { useCallback, useEffect, useInsertionEffect, useRef, useState } from 'react';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { useArrangementSources } from '../hooks/useArrangementSources';\nimport { isDevelopmentBuild } from '../utils/isDevelopmentBuild';\n\nconst READY_EVENT = 'waveform-playlist:ready';\n\nconst PLAY_BEFORE_READY_WARNING =\n '[waveform-playlist] play() was called before the playlist was ready and did nothing: ' +\n 'playback starts once the playlist is ready. Wait for `isReady` ' +\n '(usePlaylistTimeline) or the `onReady` callback before calling play().';\n\ninterface ReadyEventDetail {\n trackCount: number;\n duration: number;\n}\n\nexport interface UseReadyOnceOptions {\n /** From `useEngineLifetime`: false from the start of each build until its engine is assigned. */\n isEngineAttached: boolean;\n arrangement: Arrangement;\n /** The latest committed `onReady` (QG). */\n onReadyRef: React.RefObject<(() => void) | undefined>;\n /** The latest committed `onError` (QG). */\n onErrorRef: React.RefObject<((error: Error) => void) | undefined>;\n /** The number of tracks in the arrangement, loaded or not. */\n trackCount: number;\n /** The end, in seconds, of the loaded audio. */\n duration: number;\n}\n\nfunction callOnReady({\n onReadyRef,\n onErrorRef,\n}: Pick<UseReadyOnceOptions, 'onReadyRef' | 'onErrorRef'>): void {\n try {\n onReadyRef.current?.();\n } catch (callbackError) {\n const thrown =\n callbackError instanceof Error ? callbackError : new Error(String(callbackError));\n console.error('[waveform-playlist] The onReady callback threw: ' + thrown.message);\n onErrorRef.current?.(thrown);\n }\n}\n\nexport interface ReadyOnce {\n isReady: boolean;\n /**\n * True when the first ready of this mount has not happened yet, so a play\n * must do nothing; warns the first time per mount, in development builds\n * only. Never changes identity.\n */\n refusePlayBeforeFirstReady: () => boolean;\n}\n\nexport function useReadyOnce(options: UseReadyOnceOptions): ReadyOnce {\n const { isEngineAttached, arrangement, onReadyRef, onErrorRef, trackCount, duration } = options;\n const { pendingCount } = useArrangementSources(arrangement);\n // State, for the render; the ref, so that StrictMode's second run of the\n // effect and an <Activity> reveal do not fire again.\n const [hasBeenReady, setHasBeenReady] = useState(false);\n const firedRef = useRef(false);\n const isReady = isEngineAttached && (hasBeenReady || pendingCount === 0);\n // \"The first ready has happened\", for play() at call time. Written where\n // React commits, so a discarded render cannot leave it true, and never\n // back to false. In an insertion effect: those run in the commit's mutation\n // phase, before every layout effect, ref callback and passive effect of the\n // same commit, so a descendant that calls play() from any of them (or from\n // onReady) on the first `isReady` is not refused. A layout effect here ran\n // after the descendants' layout effects and refused theirs.\n const firstReadyRef = useRef(false);\n const warnedPlayRef = useRef(false);\n useInsertionEffect(() => {\n if (isReady) firstReadyRef.current = true;\n }, [isReady]);\n\n const refusePlayBeforeFirstReady = useCallback(() => {\n if (firstReadyRef.current) return false;\n if (!warnedPlayRef.current && isDevelopmentBuild()) {\n warnedPlayRef.current = true;\n console.warn(PLAY_BEFORE_READY_WARNING);\n }\n return true;\n }, []);\n\n useEffect(() => {\n if (!isReady || firedRef.current) return;\n firedRef.current = true;\n setHasBeenReady(true);\n const detail: ReadyEventDetail = { trackCount, duration };\n window.dispatchEvent(new CustomEvent<ReadyEventDetail>(READY_EVENT, { detail }));\n callOnReady({ onReadyRef, onErrorRef });\n }, [isReady, trackCount, duration, onReadyRef, onErrorRef]);\n\n return { isReady, refusePlayBeforeFirstReady };\n}\n","/**\n * The one definition of \"development build\" in this package: true unless\n * this is a production build. Bundlers replace `process.env.NODE_ENV` with a\n * literal; where there is no `process` at all (a page that loads the module\n * without a bundler) this is false, so nothing development-only runs and\n * nothing throws. Not exported from the package entry.\n */\nexport function isDevelopmentBuild(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n","/**\n * useArrangementEditing\n *\n * The editor actions of `WaveformPlaylistProvider` that change the\n * arrangement (#812): the four mixer setters, `reorderTrack`, `undo`, `redo`\n * and `setRecordingActive`. Each asks the arrangement, which owns the tracks,\n * the mix and the history, and works whether an engine is attached or not;\n * the engine follows the arrangement. Every function keeps its identity for\n * the life of the provider (the arrangement does not change within a mount).\n * Also the value of `RecordingArmContext`: which track is armed for a take.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { createValueSource } from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { warnOnce } from '../components/partWarnings';\nimport type { RecordingArmContextValue } from '../contexts/playlistContexts';\n\ntype MixerSetter = 'setTrackMute' | 'setTrackSolo' | 'setTrackVolume' | 'setTrackPan';\n\n/** A call with anything but a string id is a call from before #687: ignored, once said. */\nfunction isTrackId(setter: MixerSetter, trackId: unknown): trackId is string {\n if (typeof trackId === 'string') return true;\n warnOnce(\n `${setter}() takes a track id since the track controls became parts: ` +\n `${setter}(tracks[index].id, value). A call with anything but a string is ignored.`\n );\n return false;\n}\n\nexport interface ArrangementEditing {\n setTrackMute: (trackId: string, muted: boolean) => void;\n setTrackSolo: (trackId: string, soloed: boolean) => void;\n setTrackVolume: (trackId: string, volume: number) => void;\n setTrackPan: (trackId: string, pan: number) => void;\n reorderTrack: (trackId: string, toIndex: number) => void;\n undo: () => void;\n redo: () => void;\n setRecordingActive: (active: boolean, armedTrackId?: string | null) => void;\n /** True while a recording session is active: the animation loop and `seekTo` read it. */\n recordingActiveRef: React.RefObject<boolean>;\n /** The value of `RecordingArmContext`; a new object only when the armed track changes. */\n recordingArm: RecordingArmContextValue;\n}\n\n/** The armed track and its mute from before the session. */\ninterface ArmedTrack {\n trackId: string;\n prevMuted: boolean;\n}\n\n/**\n * Recording session state. While active:\n * 1. the animation loop's end-of-audio auto-stop is suppressed, so overdub\n * playback runs past the end of existing material (#589/#590);\n * 2. the armed track is muted in the arrangement: punch-in replaces whatever\n * the take overlaps (#579), so that material must not play under the\n * overdub. Its mute from before the session is written back when the\n * session ends or the armed track changes, whatever was set in between\n * (QJ, #812); the arrangement's setter does nothing for a track that is gone.\n * Called by useRecordingSession for the length of a take; overdub flows also\n * call it eagerly before play(), because a render round-trip loses the race\n * against the first animation frame (play() does nothing before the first\n * ready, so a take started during the first load records without playback).\n * The provider also writes the mute from before the session back in its own\n * cleanup (below) when a track is still armed.\n *\n * The armed track is one value source, its owner: the setter reads and\n * writes it synchronously (a start and an end in one handler), and the\n * provider renders from it, so the armed track's panel follows.\n */\nfunction useRecordingActive(arrangement: Arrangement) {\n const recordingActiveRef = useRef(false);\n const [armed] = useState(() => createValueSource<ArmedTrack | null>(null));\n const setRecordingActive = useCallback(\n (active: boolean, armedTrackId?: string | null) => {\n recordingActiveRef.current = active;\n const current = armed.source.getSnapshot();\n if (active && armedTrackId) {\n if (current?.trackId === armedTrackId) return; // already armed\n // Armed track changed mid-session: restore the previous one first.\n if (current) arrangement.setTrackMute(current.trackId, current.prevMuted);\n const prevMuted = arrangement.getMixer().get(armedTrackId)?.muted ?? false;\n armed.publish({ trackId: armedTrackId, prevMuted });\n arrangement.setTrackMute(armedTrackId, true);\n } else if (!active && current) {\n arrangement.setTrackMute(current.trackId, current.prevMuted);\n armed.publish(null);\n }\n },\n [arrangement, armed]\n );\n // The arrangement outlives the provider (maintainer, F1): when the provider\n // goes (unmount, an <Activity> hide, a StrictMode or Fast Refresh remount)\n // with a track still armed, its mute from before the take is written back\n // and the session ends. Nothing happens when the session was already\n // released (by useRecordingSession's own cleanup) or never armed a track;\n // a session armed again after a remount or a reveal works as before.\n useEffect(\n () => () => {\n if (armed.source.getSnapshot()) setRecordingActive(false);\n },\n [armed, setRecordingActive]\n );\n const getArmedTrackId = useCallback(() => armed.source.getSnapshot()?.trackId ?? null, [armed]);\n const armedTrackId = useSyncExternalStore(armed.source.subscribe, getArmedTrackId);\n const recordingArm = useMemo(() => ({ armedTrackId }), [armedTrackId]);\n return { setRecordingActive, recordingActiveRef, recordingArm };\n}\n\nexport function useArrangementEditing(arrangement: Arrangement): ArrangementEditing {\n const setTrackMute = useCallback(\n (trackId: string, muted: boolean) => {\n if (isTrackId('setTrackMute', trackId)) arrangement.setTrackMute(trackId, muted);\n },\n [arrangement]\n );\n const setTrackSolo = useCallback(\n (trackId: string, soloed: boolean) => {\n if (isTrackId('setTrackSolo', trackId)) arrangement.setTrackSolo(trackId, soloed);\n },\n [arrangement]\n );\n const setTrackVolume = useCallback(\n (trackId: string, volume: number) => {\n if (isTrackId('setTrackVolume', trackId)) arrangement.setTrackVolume(trackId, volume);\n },\n [arrangement]\n );\n const setTrackPan = useCallback(\n (trackId: string, pan: number) => {\n if (isTrackId('setTrackPan', trackId)) arrangement.setTrackPan(trackId, pan);\n },\n [arrangement]\n );\n const reorderTrack = useCallback(\n (trackId: string, toIndex: number) => arrangement.reorderTrack(trackId, toIndex),\n [arrangement]\n );\n const undo = useCallback(() => arrangement.undo(), [arrangement]);\n const redo = useCallback(() => arrangement.redo(), [arrangement]);\n const { setRecordingActive, recordingActiveRef, recordingArm } = useRecordingActive(arrangement);\n return {\n setTrackMute,\n setTrackSolo,\n setTrackVolume,\n setTrackPan,\n reorderTrack,\n undo,\n redo,\n setRecordingActive,\n recordingActiveRef,\n recordingArm,\n };\n}\n","/**\n * Development-only warnings, written once per message for the life of the\n * page: for a part of the view that is rendered where it cannot work (#685;\n * it does not throw: it draws nothing, or draws in the wrong place), and for a\n * call with an argument of an older signature (#687).\n */\nimport { isDevelopmentBuild } from '../utils/isDevelopmentBuild';\n\nconst warned = new Set<string>();\n\nexport function warnOnce(message: string): void {\n if (!isDevelopmentBuild()) return;\n if (warned.has(message)) return;\n warned.add(message);\n console.warn('[waveform-playlist] ' + message);\n}\n\n/** A part of the view that is not where it can work. */\nexport const warnMisplacedPart = warnOnce;\n\n/** For tests: forget what has been warned, so each test sees its own warning. */\nexport function resetPartWarnings(): void {\n warned.clear();\n}\n","/**\n * arrangementIdentity\n *\n * Which arrangement object `WaveformPlaylistProvider` was given (#812). The\n * provider keys its body with the arrangement's number, so a new object is a\n * new mount of everything below it, and it says so once in development.\n *\n * Only numbers are kept: the map is weak, and the component remembers the\n * number of the first arrangement, not the object, so an arrangement the app\n * has let go of (its tracks, its decoded audio) can be collected.\n */\nimport { useEffect, useRef } from 'react';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { isDevelopmentBuild } from '../utils/isDevelopmentBuild';\n\nconst arrangementKeys = new WeakMap<Arrangement, number>();\nlet lastArrangementKey = 0;\n\nconst MISSING_ARRANGEMENT_ERROR =\n '[waveform-playlist] WaveformPlaylistProvider needs an `arrangement` prop: an ' +\n 'arrangement made with `useCreateArrangement`, which owns the tracks. The `tracks` and ' +\n '`onTracksChange` props were removed. See ' +\n 'https://naomiaro.github.io/waveform-playlist/docs/react/upgrading';\n\n/**\n * The arrangement's own number: the same for the same object, new for another\n * one. Anything that is not an object (plain JavaScript, or code that still\n * passes only `tracks`) throws: the provider cannot run without one.\n */\nexport function keyOf(arrangement: Arrangement): number {\n if (typeof arrangement !== 'object' || arrangement === null) {\n throw new Error(MISSING_ARRANGEMENT_ERROR);\n }\n let key = arrangementKeys.get(arrangement);\n if (key === undefined) {\n lastArrangementKey += 1;\n key = lastArrangementKey;\n arrangementKeys.set(arrangement, key);\n }\n return key;\n}\n\nconst NEW_ARRANGEMENT_WARNING =\n '[waveform-playlist] WaveformPlaylistProvider was given a new `arrangement` prop: ' +\n 'everything below it mounts again (a new engine, the view and its state). Keep one ' +\n 'arrangement for the life of the playlist (`useCreateArrangement`) and change it ' +\n 'through its methods.';\n\n/**\n * The key of the provider's body for `arrangement`. The first time it differs\n * from the key of the mount's first arrangement, says so in development.\n */\nexport function useArrangementKey(arrangement: Arrangement): number {\n const key = keyOf(arrangement);\n const firstKeyRef = useRef(key);\n const warnedRef = useRef(false);\n useEffect(() => {\n if (key === firstKeyRef.current || warnedRef.current) return;\n warnedRef.current = true;\n if (isDevelopmentBuild()) console.warn(NEW_ARRANGEMENT_WARNING);\n }, [key]);\n return key;\n}\n","import React, {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useCallback,\n useMemo,\n type ReactNode,\n} from 'react';\nimport { ThemeProvider } from 'styled-components';\nimport type { MediaElementPlayout, FadeConfig } from '@waveform-playlist/media-element-playout';\nimport { resolveMediaElementPlayout } from './playout/resolveMediaElementPlayout';\nimport { type WaveformDataObject } from '@waveform-playlist/core';\nimport type { WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport type { AnnotationData, AnnotationStore } from '@waveform-playlist/core';\nimport { extractPeaksFromWaveformData } from './waveformDataLoader';\nimport type WaveformData from 'waveform-data';\nimport type { PeakData } from '@waveform-playlist/core';\nimport type { ClipPeaks, TrackClipPeaks } from './WaveformPlaylistContext';\nimport { useAnimationFrameLoop } from './hooks/useAnimationFrameLoop';\nimport { followAnnotations } from './providerInternals/followAnnotations';\nimport {\n useAnnotationState,\n type AnnotationListProp,\n} from './providerInternals/useAnnotationState';\nimport { useFrameCallbacks } from './providerInternals/useFrameCallbacks';\nimport { centrePlayhead, useScrollFollow } from './providerInternals/useScrollFollow';\nimport { useMergedTheme } from './providerInternals/useMergedTheme';\nimport { useTimeFormat } from './hooks/useTimeFormat';\nimport { useShallowStable } from './hooks/useShallowStable';\nimport {\n BLOCKED,\n ActiveAnnotationContext,\n ArrangementContext,\n AnnotationOptionsContext,\n AnnotationsContext,\n CurrentTimeContext,\n EditorControlsContext,\n EngineRefsContext,\n IsPlayingContext,\n LoopContext,\n MediaElementTrackContext,\n PlaybackControlsContext,\n PlaybackRateContext,\n PlaybackRefsContext,\n PlaylistMixerContext,\n PlaylistSettingsContext,\n PlaylistTimelineContext,\n PlaylistViewContext,\n PlaylistZoomContext,\n SelectedTrackIdContext,\n SelectedRowContext,\n MEDIA_ELEMENT_TRACK_ID,\n SelectionContext,\n TrackReorderPreviewContext,\n TrimPreviewContext,\n RecordingArmContext,\n TrimPreviewPeaksContext,\n UndoRedoContext,\n type ActiveAnnotationContextValue,\n type CurrentTimeContextValue,\n type IsPlayingContextValue,\n type MediaElementTrackContextValue,\n type PlaybackControlsContextValue,\n type PlaybackRateContextValue,\n type PlaybackRefsContextValue,\n type PlaylistSettingsContextValue,\n type PlaylistViewContextValue,\n type PlaylistZoomContextValue,\n type SelectionContextValue,\n} from './contexts/playlistContexts';\n\n// The one row of the view is always drawn as selected. One object, so the\n// context value never changes.\nconst ONLY_ROW_SELECTED = { selectedTrackId: MEDIA_ELEMENT_TRACK_ID };\n\n// Configuration for a single media element track\nexport interface MediaElementTrackConfig {\n /** Audio source URL or Blob URL */\n source: string;\n /** Pre-computed waveform data (required for visualization) */\n waveformData: WaveformDataObject;\n /** Track name for display */\n name?: string;\n /** Fade in configuration (requires audioContext on provider) */\n fadeIn?: FadeConfig;\n /** Fade out configuration (requires audioContext on provider) */\n fadeOut?: FadeConfig;\n}\n\nexport interface MediaElementPlaylistProviderProps {\n /** Single track configuration with source URL and waveform data */\n track: MediaElementTrackConfig;\n /** Initial samples per pixel (zoom level) */\n samplesPerPixel?: number;\n /** Playback rate (default 1). Not clamped by the provider: the bundled\n * engine is created at it as given, while `setPlaybackRate` clamps to\n * 0.5–2. The user's `setPlaybackRate` overrides it; a later change of this\n * prop overrides that, until they choose again. */\n playbackRate?: number;\n /** Whether to preserve pitch when changing playback rate (default: true).\n * Set to false when using an external pitch processor like SoundTouch. */\n preservesPitch?: boolean;\n /** Enable automatic scroll to keep playhead centered */\n automaticScroll?: boolean;\n /** Theme configuration */\n theme?: Partial<WaveformPlaylistTheme>;\n /**\n * The owner of the annotations (#867): make it with\n * `useCreateAnnotationStore` and change the annotations with its methods.\n * The provider publishes what it holds and writes nothing back. Without it\n * there are no annotations.\n */\n annotationStore?: AnnotationStore;\n /**\n * The three annotation options (`editable`, `linkEndpoints`,\n * `isContinuousPlay`); the annotations are `annotationStore`'s. The provider\n * follows the three: an option takes a new value of its field, and a setter\n * or checkbox changes it in between.\n */\n annotationList?: AnnotationListProp;\n /**\n * AudioContext for Web Audio routing (fades, effects).\n * When provided, audio routes through Web Audio nodes:\n * HTMLAudioElement → MediaElementSourceNode → fadeGain → volumeGain → destination\n *\n * Without this, playback uses HTMLAudioElement directly (no fades or effects).\n * Each provider instance should use its own AudioContext or share one —\n * createMediaElementSource() is called once per audio element.\n */\n audioContext?: AudioContext;\n /** Called when the media element has loaded its metadata (it knows its\n * length and can be played and seeked), once per player. */\n onReady?: () => void;\n /** Called when playout initialization fails (e.g. a missing optional peer,\n * a throwing `createPlayout`, or an `addTrack` error) and when the media\n * element reports an error (a source that cannot be loaded or decoded).\n * The provider already logs the error; use this to surface it in your UI. */\n onError?: (err: Error) => void;\n /** Factory for a custom MediaElement playout. When omitted, the bundled engine\n * (@waveform-playlist/media-element-playout) is dynamically imported. A\n * custom playout must implement `on()` and emit `loadedmetadata`: the\n * provider is not ready until it does. */\n createPlayout?: () => MediaElementPlayout;\n children: ReactNode;\n}\n\n/**\n * MediaElementPlaylistProvider\n *\n * A simplified playlist provider for single-track playback using HTMLAudioElement.\n * Key features:\n * - Pitch-preserving playback rate (0.5x - 2.0x)\n * - Pre-computed peaks visualization (no AudioBuffer needed)\n * - Simpler API than full WaveformPlaylistProvider\n *\n * Use this for:\n * - Language learning apps (speed control)\n * - Podcast players\n * - Single-track audio viewers\n *\n * For multi-track editing, use WaveformPlaylistProvider instead.\n */\nexport const MediaElementPlaylistProvider: React.FC<MediaElementPlaylistProviderProps> = ({\n track,\n samplesPerPixel: initialSamplesPerPixel = 1024,\n playbackRate: initialPlaybackRate = 1,\n preservesPitch = true,\n automaticScroll = false,\n theme: userThemeProp,\n annotationStore,\n annotationList,\n audioContext,\n onReady,\n onError,\n createPlayout,\n children,\n}) => {\n const mergedTheme = useMergedTheme(userThemeProp);\n\n // State\n const [isPlaying, setIsPlayingState] = useState(false);\n // Read by `seekTo` and `setSelection`, which must know at call time whether\n // playback is running; written together with the state, never by a render.\n const isPlayingRef = useRef(false);\n const setIsPlaying = useCallback((playing: boolean) => {\n isPlayingRef.current = playing;\n setIsPlayingState(playing);\n }, []);\n const [currentTime, setCurrentTime] = useState(0);\n const [isReady, setIsReady] = useState(false);\n const [playbackRate, setPlaybackRateState] = useState(initialPlaybackRate);\n // The latest instruction wins: the `playbackRate` prop when it changes, or\n // what the user chose with `setPlaybackRate` since. A changed prop becomes\n // the state here, during render (the \"derive state from a prop\" pattern),\n // so the speed select never shows a speed other than the one playing.\n const [ratePropSeen, setRatePropSeen] = useState(initialPlaybackRate);\n // `Object.is`: a NaN prop (a failed parse in the consumer) must compare\n // equal to itself, or this would set state on every render.\n if (!Object.is(ratePropSeen, initialPlaybackRate)) {\n setRatePropSeen(initialPlaybackRate);\n setPlaybackRateState(initialPlaybackRate);\n }\n // The same speed for a player that arrives later (see the init effect).\n // Written by `setPlaybackRate`, and by the layout effect below for a prop\n // VALUE it has not applied yet. Not on every run: the effect also runs\n // again with the same prop (a StrictMode remount, a revealed `<Activity>`),\n // and it runs after a child's layout effect of the same commit; none of\n // those is a new instruction, and each would put the prop's speed back\n // over one that was chosen since. A layout effect, for two reasons: a\n // render React discards leaves nothing here that never committed, and it\n // runs before any child's passive effect of the same commit, so a child\n // that sets a speed in answer to a prop change (restoring a saved one) is\n // the later instruction and wins.\n const playbackRateRef = useRef(initialPlaybackRate);\n const ratePropAppliedRef = useRef(initialPlaybackRate);\n useLayoutEffect(() => {\n if (Object.is(ratePropAppliedRef.current, initialPlaybackRate)) return;\n ratePropAppliedRef.current = initialPlaybackRate;\n playbackRateRef.current = initialPlaybackRate;\n }, [initialPlaybackRate]);\n // The annotations are the annotation store's (#867); the provider derives\n // what it publishes from it. Shared with the WebAudio provider (#769).\n const {\n getAnnotations,\n annotationLookup,\n annotationPreview,\n activeAnnotationId,\n activeAnnotationIdRef,\n setActiveAnnotationId,\n continuousPlayRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationsValue,\n annotationOptionsValue,\n } = useAnnotationState({\n annotationStore,\n annotationList,\n });\n const {\n scrollContainerRef,\n setScrollContainer,\n isAutomaticScroll,\n isAutomaticScrollRef,\n setAutomaticScroll,\n } = useScrollFollow(automaticScroll);\n // The playhead, the progress overlay and `AudioPosition` register here; the\n // one loop below draws them.\n const { registerFrameCallback, unregisterFrameCallback, runFrameCallbacks } = useFrameCallbacks();\n\n // The time selection. Setting it moves the cursor to its start, and Play\n // plays it (see `setSelection` and `play` below), as under the WebAudio\n // provider (#688).\n const [selection, setSelectionState] = useState<SelectionContextValue>({\n selectionStart: 0,\n selectionEnd: 0,\n });\n const selectionRef = useRef(selection);\n\n const [samplesPerPixel] = useState(initialSamplesPerPixel);\n const { timeFormat, setTimeFormat } = useTimeFormat();\n\n // Refs\n const playoutRef = useRef<MediaElementPlayout | null>(null);\n const currentTimeRef = useRef<number>(0);\n const samplesPerPixelRef = useRef<number>(initialSamplesPerPixel);\n const { startAnimationFrameLoop, stopAnimationFrameLoop } = useAnimationFrameLoop();\n\n // What the play that is running (or queued) is, in the WebAudio provider's\n // terms (#688):\n // - where Stop, the end of the audio and the end of an annotation return\n // the cursor (for the selection: its start, even when resumed part-way);\n // - where a bounded play ends (null: it runs on);\n // - whether it is the highlighted selection that is playing. Then\n // continuous play is out of the picture: annotation ends do not stop it.\n const playStartPositionRef = useRef(0);\n const playbackEndTimeRef = useRef<number | null>(null);\n const isSelectionPlayRef = useRef(false);\n // Where a queued play ends is `playbackEndTimeRef`, as for a running one.\n // A play asked for while there is no player (the first one is loading, or\n // one is being replaced). Started by the init effect when the player\n // arrives; cleared by Stop, Pause, new audio and a failed init.\n const pendingPlayRef = useRef<{ position: number } | null>(null);\n // False only after an init failed: otherwise there is a player, or one on\n // its way, for a play to start on or wait for. It starts true: a child's\n // mount effect runs before this provider's init effect, and a `play()`\n // there must be queued like any other. The init's cleanup sets it true\n // again for the same reason (cleanups run before any effect of the commit).\n const playoutInFlightRef = useRef(true);\n\n // Get sample rate from waveform data\n const sampleRate = track.waveformData.sample_rate;\n // The length of the audio is known from the waveform data: it does not wait\n // for the player (#688). \"The player can be used\" is `isReady`.\n const duration = track.waveformData.duration;\n\n // Peaks are derived during render, so the waveform is drawn on first paint.\n const trackName = track.name;\n const trackWaveformData = track.waveformData;\n // The peaks alone first: a new name or new fades must not extract them again.\n const trackPeaks = useMemo<{ peaks: PeakData; durationSamples: number } | null>(() => {\n try {\n const durationSamples = Math.ceil(trackWaveformData.duration * sampleRate);\n const extractedPeaks = extractPeaksFromWaveformData(\n trackWaveformData as WaveformData,\n samplesPerPixel,\n 0, // channel index\n 0, // offset\n durationSamples\n );\n return {\n peaks: {\n length: extractedPeaks.length,\n data: [extractedPeaks.data],\n bits: extractedPeaks.bits,\n } as PeakData,\n durationSamples,\n };\n } catch (err) {\n console.warn(\n '[waveform-playlist] Failed to extract peaks from waveform data: ' + String(err)\n );\n return null;\n }\n }, [trackWaveformData, samplesPerPixel, sampleRate]);\n\n // The one clip of the one track. It carries the track's fades, so the view\n // draws them as it draws any clip's (#685).\n // Compared by value: a fade written inline (`fadeIn: { duration: 1 }` in a\n // `track` that is not memoized) is a new object on every render of the\n // parent, and must neither build a new clip nor a new player (below).\n const trackFadeIn = useShallowStable(track.fadeIn);\n const trackFadeOut = useShallowStable(track.fadeOut);\n const peaksDataArray = useMemo<TrackClipPeaks[]>(() => {\n if (!trackPeaks) return [];\n const clipPeaks: ClipPeaks = {\n clipId: 'media-element-clip',\n trackName: trackName ?? 'Track',\n peaks: trackPeaks.peaks,\n startSample: 0,\n durationSamples: trackPeaks.durationSamples,\n fadeIn: trackFadeIn,\n fadeOut: trackFadeOut,\n isPlaceholder: false,\n };\n return [[clipPeaks]];\n }, [trackPeaks, trackName, trackFadeIn, trackFadeOut]);\n\n // The audio of the latest COMMITTED render, read by two things that must not\n // wait for a render or an effect of their own:\n // - the cleanup below, to tell \"new audio\" from \"the same audio in a new\n // player\" (a new name, fades, the pitch setting, a callback's identity);\n // - `seekTo`, which clamps to the length of this audio. The `duration`\n // state cannot serve: it is 0 until the first player is ready and still\n // the previous file's length while the next one loads (and inside\n // `onReady`), so a saved position restored for a longer file was cut off\n // at the old length. Reading a ref also keeps `seekTo`'s identity (#767).\n // Written in a layout effect, not during render: a render React discards\n // (a transition, Suspense) must not leave audio here that never committed.\n // Layout effects run before the passive cleanups of the same commit.\n const latestAudioRef = useRef({ source: track.source, waveformData: track.waveformData });\n useLayoutEffect(() => {\n latestAudioRef.current = { source: track.source, waveformData: track.waveformData };\n }, [track.source, track.waveformData]);\n\n // Ends playback with the cursor resting at `cursor`. The player is paused\n // and moved there too (not `stop()`, which rewinds the element to 0): its\n // own time must agree with the cursor, because the element reports its\n // position back (`timeupdate` writes `currentTimeRef`).\n const restAt = useCallback(\n (cursor: number) => {\n const playout = playoutRef.current;\n if (playout) {\n playout.pause();\n playout.seekTo(cursor);\n }\n stopAnimationFrameLoop();\n setIsPlaying(false);\n playbackEndTimeRef.current = null;\n currentTimeRef.current = cursor;\n setCurrentTime(cursor);\n // Where playback came to rest is where the next one starts from: a Stop\n // pressed while stopped must not move the cursor (to the start of a\n // range that has played out, say). A pause is not a rest.\n playStartPositionRef.current = cursor;\n },\n [stopAnimationFrameLoop, setIsPlaying]\n );\n\n // The init effect starts a queued play when its player arrives, long after\n // the render that created the effect: it reads the loop starter from here.\n const startAnimationLoopRef = useRef<() => void>(() => {});\n // Likewise the step that ends playback, for the engine's `timeupdate`.\n const endPlaybackIfDueRef = useRef<(time: number) => boolean>(() => false);\n\n // Initialize playout and load track\n useEffect(() => {\n let cancelled = false;\n let createdPlayout: MediaElementPlayout | null = null;\n // The audio this run's player is for.\n const source = track.source;\n const waveformData = track.waveformData;\n playoutInFlightRef.current = true;\n\n (async () => {\n try {\n const playout = await resolveMediaElementPlayout({\n createPlayout,\n playbackRate: initialPlaybackRate,\n preservesPitch,\n });\n if (cancelled) {\n playout.dispose();\n return;\n }\n createdPlayout = playout;\n\n // Subscribed before the track exists: the engine attaches the\n // listeners when it creates the media element, so neither event can\n // be missed. \"Ready\" is the element having its metadata (#688), not\n // this object existing; a source that cannot be loaded never is.\n playout.on('loadedmetadata', () => {\n if (cancelled) return;\n setIsReady(true);\n onReady?.();\n });\n // The URL is left out of the message on purpose: it may carry a\n // token, and consumers show `error.message` in their UI.\n playout.on('error', (mediaError) => {\n if (cancelled) return;\n const detail = mediaError\n ? ' (code ' +\n mediaError.code +\n (mediaError.message ? ': ' + mediaError.message : '') +\n ')'\n : '';\n const error = new Error('Media failed to load' + detail);\n console.warn('[waveform-playlist] ' + error.message);\n // Nothing is audible any more: do not go on showing \"playing\".\n if (isPlayingRef.current) restAt(currentTimeRef.current);\n onError?.(error);\n });\n // The browser refused to start playback (no user gesture, most often\n // for a play that was queued and started here, outside the click).\n playout.on('playrejected', () => {\n if (cancelled) return;\n if (isPlayingRef.current) restAt(currentTimeRef.current);\n });\n\n playout.addTrack({\n source: track.source,\n peaks: track.waveformData,\n name: track.name,\n audioContext,\n fadeIn: trackFadeIn,\n fadeOut: trackFadeOut,\n });\n\n // The media element reports its position about four times a second,\n // also while the tab is hidden and animation frames are not running.\n // It keeps the cursor current, and it is the fallback that ends a\n // range or an annotation in a hidden tab (up to a quarter of a second\n // late); in a visible tab the animation loop sees the end first.\n playout.on('timeupdate', (time) => {\n if (cancelled) return;\n currentTimeRef.current = time;\n if (isPlayingRef.current) endPlaybackIfDueRef.current(time);\n });\n\n // The audio played to its end. The cursor returns to where playback\n // started, as on Stop. A bounded play that is not the selection rests\n // at its own end instead: the loop below does the same when it sees\n // the end first, and which of the two does is a race.\n playout.setOnPlaybackComplete(() => {\n // The element's `ended` also arrives after the loop or `timeupdate`\n // has already ended a range that reaches the end of the audio;\n // that rest stands.\n if (cancelled || !isPlayingRef.current) return;\n const boundedEnd = playbackEndTimeRef.current;\n if (boundedEnd !== null && !isSelectionPlayRef.current) {\n restAt(Math.min(boundedEnd, waveformData.duration));\n return;\n }\n restAt(playStartPositionRef.current);\n setActiveAnnotationId(null);\n });\n\n playoutRef.current = playout;\n // The speed the provider shows (`usePlaybackRate()`, the speed\n // select) is the prop's, or the one chosen since the prop last\n // changed. The bundled engine was created at the prop's speed, as\n // given: it is told only a speed that differs (its setter clamps,\n // its constructor does not, so repeating the prop could change it).\n // A custom `createPlayout` is not given the speed: it is always told.\n const speed = playbackRateRef.current;\n if (createPlayout || !Object.is(speed, initialPlaybackRate)) {\n playout.setPlaybackRate(speed);\n }\n // The cursor may not be at 0: a position kept across a same-audio\n // replacement, or one stored by `seekTo` while there was no player (a\n // restore for this file). Move the new player there now, so its own\n // time agrees with the cursor before Play is pressed (`pause()` reads\n // it, and the media element reports it).\n if (currentTimeRef.current > 0) {\n playout.seekTo(currentTimeRef.current);\n }\n // A play asked for while there was no player starts now. The media\n // element accepts play() before its metadata has loaded.\n const queued = pendingPlayRef.current;\n if (queued) {\n pendingPlayRef.current = null;\n currentTimeRef.current = queued.position;\n playout.play(undefined, queued.position);\n setIsPlaying(true);\n startAnimationLoopRef.current();\n }\n } catch (err) {\n if (!cancelled) {\n // Nothing will arrive for a queued play to wait for.\n playoutInFlightRef.current = false;\n pendingPlayRef.current = null;\n // A play that was queued moved the cursor ref to its start; show it.\n setCurrentTime(currentTimeRef.current);\n }\n console.warn('[waveform-playlist] MediaElement playout init failed: ' + String(err));\n onError?.(err instanceof Error ? err : new Error(String(err)));\n }\n })();\n\n return () => {\n cancelled = true;\n stopAnimationFrameLoop();\n // The player that was playing is about to be disposed: playback has\n // stopped, whatever replaces it. Left true, the UI showed \"playing\"\n // with no audio and no loop, and the playhead and progress overlay\n // (drawn at rest only while not playing) stopped following seeks.\n setIsPlaying(false);\n // Whatever replaces this player has its own metadata to load.\n setIsReady(false);\n // A player is on its way again, also after an init that failed.\n playoutInFlightRef.current = true;\n const latest = latestAudioRef.current;\n if (latest.source !== source || latest.waveformData !== waveformData) {\n // New audio: the old position and the old active annotation mean\n // nothing in it. Done here, in the cleanup, and not when the next\n // player is set up: React runs every cleanup of a commit before any\n // effect, so an effect of a child that restores a saved position for\n // the new audio (`seekTo`, `setActiveAnnotationId`) runs after this\n // and is kept.\n currentTimeRef.current = 0;\n setCurrentTime(0);\n setActiveAnnotationId(null);\n // A play queued for the old audio, and where a Stop would return to\n // in it, mean nothing either. (A play queued AFTER this cleanup, for\n // the new audio, is kept: the cleanup has already run by then.)\n pendingPlayRef.current = null;\n playStartPositionRef.current = 0;\n isSelectionPlayRef.current = false;\n } else {\n // The same audio (or an unmount): keep the listener's place, and\n // bring the state up to it. During playback only the ref advances.\n // That place is also where a Stop leaves the cursor from now on.\n setCurrentTime(currentTimeRef.current);\n // Not while a play is queued: it has set its own play start (the\n // selection's start for a resumed selection), and it is kept.\n if (pendingPlayRef.current === null) {\n playStartPositionRef.current = currentTimeRef.current;\n }\n }\n if (createdPlayout) {\n createdPlayout.dispose();\n }\n playoutRef.current = null;\n };\n }, [\n track.source,\n track.waveformData,\n track.name,\n trackFadeIn,\n trackFadeOut,\n audioContext,\n initialPlaybackRate,\n preservesPitch,\n onReady,\n onError,\n stopAnimationFrameLoop,\n setActiveAnnotationId,\n setIsPlaying,\n restAt,\n createPlayout,\n ]);\n\n // The step that follows the annotations and ends playback when it is due.\n // Returns true when it ended playback. Run by the animation loop on every\n // frame and by the engine's `timeupdate` (see the init effect), so it must\n // give the same result when it runs twice for one position.\n const endPlaybackIfDue = useCallback(\n (time: number): boolean => {\n const activeAnnotationEnded = followAnnotations({\n annotations: getAnnotations(),\n lookup: annotationLookup,\n time,\n activeId: activeAnnotationIdRef.current,\n // Playing the selection takes continuous play out of the picture,\n // and on the frame that reaches a bounded play's end the highlight\n // is held (the end check below stops there). As in the WebAudio loop.\n followOnly: continuousPlayRef.current || isSelectionPlayRef.current,\n holdHighlight: playbackEndTimeRef.current !== null && time >= playbackEndTimeRef.current,\n setActiveAnnotationId,\n });\n if (activeAnnotationEnded) {\n // Continuous play off: stop at the end of the active annotation and\n // return the cursor to where playback started.\n restAt(playStartPositionRef.current);\n return true;\n }\n\n // A bounded play (`play(start, duration)`, the selection) has reached\n // its end. The selection returns the cursor to its start; any other\n // range leaves it at the end.\n const endTime = playbackEndTimeRef.current;\n if (endTime !== null && time >= endTime) {\n restAt(isSelectionPlayRef.current ? playStartPositionRef.current : endTime);\n return true;\n }\n return false;\n },\n [\n getAnnotations,\n annotationLookup,\n activeAnnotationIdRef,\n continuousPlayRef,\n setActiveAnnotationId,\n restAt,\n ]\n );\n\n // Animation loop\n const startAnimationLoop = useCallback(() => {\n const updateTime = () => {\n const time = playoutRef.current?.getCurrentTime() ?? 0;\n currentTimeRef.current = time;\n\n // The media element reports the audible position: one time for logic\n // and for drawing.\n runFrameCallbacks({\n time,\n visualTime: time,\n sampleRate,\n samplesPerPixel: samplesPerPixelRef.current,\n });\n\n if (endPlaybackIfDue(time)) return;\n\n if (isAutomaticScrollRef.current && scrollContainerRef.current) {\n centrePlayhead(scrollContainerRef.current, time, sampleRate, samplesPerPixelRef.current);\n }\n\n startAnimationFrameLoop(updateTime);\n };\n\n startAnimationFrameLoop(updateTime);\n }, [\n sampleRate,\n startAnimationFrameLoop,\n isAutomaticScrollRef,\n scrollContainerRef,\n runFrameCallbacks,\n endPlaybackIfDue,\n ]);\n useLayoutEffect(() => {\n startAnimationLoopRef.current = startAnimationLoop;\n endPlaybackIfDueRef.current = endPlaybackIfDue;\n }, [startAnimationLoop, endPlaybackIfDue]);\n\n const stopAnimationLoop = stopAnimationFrameLoop;\n\n // Playback controls. The rules are the WebAudio provider's (#688), so that\n // one Play, Stop or seek control means the same under either provider.\n const play = useCallback(\n async (startTime?: number, playDuration?: number) => {\n const actualStartTime = startTime ?? currentTimeRef.current;\n const endTime = playDuration !== undefined ? actualStartTime + playDuration : undefined;\n\n const playout = playoutRef.current;\n // No player and none on its way (the init failed): nothing to do.\n if (!playout && !playoutInFlightRef.current) return;\n\n // Is this the highlighted selection being played? It may start inside\n // the selection (resuming after a pause) but always runs to its end.\n const { selectionStart, selectionEnd } = selectionRef.current;\n isSelectionPlayRef.current =\n endTime !== undefined &&\n selectionEnd > selectionStart &&\n actualStartTime >= selectionStart - 1e-6 &&\n actualStartTime < selectionEnd &&\n Math.abs(endTime - selectionEnd) < 1e-6;\n // Where a Stop (or the play finishing) returns the cursor. For the\n // selection that is its start even when this play resumed part-way in.\n playStartPositionRef.current = isSelectionPlayRef.current ? selectionStart : actualStartTime;\n playbackEndTimeRef.current = endTime ?? null;\n currentTimeRef.current = actualStartTime;\n\n if (!playout) {\n // The player is loading or being replaced: the init effect starts\n // this when it arrives. `isPlaying` stays false until audio starts.\n pendingPlayRef.current = { position: actualStartTime };\n return;\n }\n pendingPlayRef.current = null;\n\n // The engine schedules the track's fades in `play()`, relative to the\n // start position; the end is watched by the loop, not by the engine\n // (its own duration timer does not follow a pause or a rate change).\n playout.play(undefined, actualStartTime);\n setIsPlaying(true);\n startAnimationLoop();\n },\n [startAnimationLoop, setIsPlaying]\n );\n\n const pause = useCallback(() => {\n // Cancels a play queued for a player that has not arrived.\n pendingPlayRef.current = null;\n if (!playoutRef.current) {\n // The play it cancelled moved the cursor ref to its start; show it.\n setCurrentTime(currentTimeRef.current);\n return;\n }\n\n playoutRef.current.pause();\n setIsPlaying(false);\n stopAnimationLoop();\n setCurrentTime(playoutRef.current.getCurrentTime());\n }, [stopAnimationLoop, setIsPlaying]);\n\n const stop = useCallback(() => {\n // Cancels a play queued for a player that has not arrived.\n pendingPlayRef.current = null;\n // Return the cursor to where playback started (Audacity-style), with or\n // without a player.\n restAt(playStartPositionRef.current);\n setActiveAnnotationId(null);\n }, [restAt, setActiveAnnotationId]);\n\n const seekTo = useCallback((time: number) => {\n // NaN is not a position: it would go into the time ref, into the state\n // and into the player, and nothing would come back. It is ignored.\n // Infinity is a position — the end of the audio (Fast Forward asks for\n // it, and the clamp below turns it into the track's duration) — so only\n // NaN is rejected here.\n if (Number.isNaN(time)) return;\n const trackDuration = latestAudioRef.current.waveformData.duration;\n const clampedTime = Math.max(0, Math.min(time, trackDuration));\n currentTimeRef.current = clampedTime;\n setCurrentTime(clampedTime);\n\n // Whatever play was running or queued started somewhere else and may\n // have had an end: from here on this position is where playback began.\n playStartPositionRef.current = clampedTime;\n playbackEndTimeRef.current = null;\n isSelectionPlayRef.current = false;\n const queued = pendingPlayRef.current;\n if (queued) {\n queued.position = clampedTime;\n return;\n }\n\n const playout = playoutRef.current;\n if (!playout) return;\n if (isPlayingRef.current) {\n // Restart at the new position instead of moving the element under\n // the running play: the engine schedules fades in `play()`, so a bare\n // seek would land mid-fade at the wrong gain.\n playout.play(undefined, clampedTime);\n } else {\n playout.seekTo(clampedTime);\n }\n }, []);\n\n // Selection. As under the WebAudio provider: the cursor moves to its start,\n // a range set during playback is played start to end, and a collapsed one\n // (a cursor move) carries on open-ended from there.\n const setSelection = useCallback(\n (requestedStart: number, requestedEnd: number) => {\n // Ordered and inside the audio, whoever asks: the highlight, the cursor\n // and what Play plays must be one range (typed times can be reversed\n // or past the end; the multitrack engine orders its pair too).\n const length = latestAudioRef.current.waveformData.duration;\n const clamp = (time: number) => Math.max(0, Math.min(time, length));\n const start = clamp(Math.min(requestedStart, requestedEnd));\n const end = clamp(Math.max(requestedStart, requestedEnd));\n const previous = selectionRef.current;\n if (previous.selectionStart !== start || previous.selectionEnd !== end) {\n selectionRef.current = { selectionStart: start, selectionEnd: end };\n setSelectionState(selectionRef.current);\n }\n const cursorMoved = currentTimeRef.current !== start;\n currentTimeRef.current = start;\n setCurrentTime(start);\n\n const playsRange = end > start;\n const endTime = playsRange ? end : undefined;\n // Whatever bounded play was running or queued is over: its end, its\n // start and its active annotation must not outlive it.\n const replaceBoundedPlay = () => {\n playbackEndTimeRef.current = endTime ?? null;\n isSelectionPlayRef.current = playsRange;\n playStartPositionRef.current = start;\n if (activeAnnotationIdRef.current !== null) setActiveAnnotationId(null);\n };\n\n const queued = pendingPlayRef.current;\n if (queued) {\n queued.position = start;\n replaceBoundedPlay();\n return;\n }\n\n const playout = playoutRef.current;\n if (!isPlayingRef.current) {\n // Nothing is playing: an earlier play no longer says anything about\n // this position.\n playStartPositionRef.current = start;\n // Only when the start moved: a rightward drag keeps its start, and\n // must not seek the media element on every pointer move.\n if (playout && cursorMoved) playout.seekTo(start);\n return;\n }\n\n if (playout) {\n replaceBoundedPlay();\n playout.play(undefined, start);\n }\n },\n [activeAnnotationIdRef, setActiveAnnotationId]\n );\n\n const setPlaybackRate = useCallback((rate: number) => {\n // NaN is not a speed: it would go into the ref, into the state and into\n // the player, and the clamp below would pass it on unchanged (every\n // comparison with NaN is false). It is ignored. An infinite rate is\n // clamped to the upper bound by the same clamp as any other speed.\n if (Number.isNaN(rate)) return;\n const clampedRate = Math.max(0.5, Math.min(2.0, rate));\n playbackRateRef.current = clampedRate;\n setPlaybackRateState(clampedRate);\n if (playoutRef.current) {\n playoutRef.current.setPlaybackRate(clampedRate);\n }\n }, []);\n\n // Context values. The shared ones are the same context objects the\n // WebAudio provider renders (#688), each holding fields that change together.\n const isPlayingValue: IsPlayingContextValue = useMemo(() => ({ isPlaying }), [isPlaying]);\n const currentTimeValue: CurrentTimeContextValue = useMemo(() => ({ currentTime }), [currentTime]);\n const activeAnnotationValue: ActiveAnnotationContextValue = useMemo(\n () => ({ activeAnnotationId }),\n [activeAnnotationId]\n );\n const settingsValue: PlaylistSettingsContextValue = useMemo(\n () => ({ timeFormat, isAutomaticScroll }),\n [timeFormat, isAutomaticScroll]\n );\n\n // Never changes. A media element reports the audible position, so the\n // position to draw is the playback position itself.\n const refsValue: PlaybackRefsContextValue = useMemo(\n () => ({\n currentTimeRef,\n visualTimeRef: currentTimeRef,\n registerFrameCallback,\n unregisterFrameCallback,\n }),\n [registerFrameCallback, unregisterFrameCallback]\n );\n\n // What a click on an annotation does (#686). An open-ended play: where it\n // ends (the annotation's end, or not at all with continuous play) is the\n // animation loop's job, which follows the option and the annotation as they\n // are at that moment. Never changes.\n const playAnnotation = useCallback(\n (annotation: AnnotationData) => {\n setActiveAnnotationId(annotation.id);\n play(annotation.start).catch((err) => {\n console.warn(\n '[waveform-playlist] Failed to start playback for annotation ' +\n annotation.id +\n ': ' +\n String(err)\n );\n });\n },\n [play, setActiveAnnotationId]\n );\n\n // Changes only with the `annotationStore` prop.\n const controlsValue: PlaybackControlsContextValue = useMemo(\n () => ({\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationPreview,\n annotationStore,\n setActiveAnnotationId,\n playAnnotation,\n }),\n [\n play,\n pause,\n stop,\n seekTo,\n setSelection,\n setTimeFormat,\n setAutomaticScroll,\n setScrollContainer,\n scrollContainerRef,\n setContinuousPlay,\n setAnnotationsEditable,\n setLinkEndpoints,\n annotationPreview,\n annotationStore,\n setActiveAnnotationId,\n playAnnotation,\n ]\n );\n\n // A single track at a fixed zoom level: the two provider modes and both\n // zoom directions are always off.\n const viewValue: PlaylistViewContextValue = useMemo(\n () => ({ sampleRate, mono: false, indefinitePlayback: false }),\n [sampleRate]\n );\n const zoomValue: PlaylistZoomContextValue = useMemo(\n () => ({ samplesPerPixel, canZoomIn: false, canZoomOut: false }),\n [samplesPerPixel]\n );\n\n const playbackRateValue: PlaybackRateContextValue = useMemo(\n () => ({ playbackRate, setPlaybackRate }),\n [playbackRate, setPlaybackRate]\n );\n\n const trackValue: MediaElementTrackContextValue = useMemo(\n () => ({\n duration,\n isReady,\n peaksDataArray,\n fadeIn: trackFadeIn,\n fadeOut: trackFadeOut,\n playoutRef,\n }),\n [duration, isReady, peaksDataArray, trackFadeIn, trackFadeOut]\n );\n\n // The twelve contexts only the WebAudio provider serves are blocked, so that\n // inside this provider `useLoop()` (say) throws instead of reading a\n // WebAudio provider further out. Outermost: what changes least.\n return (\n <ThemeProvider theme={mergedTheme}>\n <ArrangementContext value={BLOCKED}>\n <EditorControlsContext value={BLOCKED}>\n <EngineRefsContext value={BLOCKED}>\n <AnnotationOptionsContext value={annotationOptionsValue}>\n <LoopContext value={BLOCKED}>\n <SelectedTrackIdContext value={BLOCKED}>\n <UndoRedoContext value={BLOCKED}>\n <PlaylistTimelineContext value={BLOCKED}>\n <PlaylistMixerContext value={BLOCKED}>\n <TrackReorderPreviewContext value={BLOCKED}>\n <TrimPreviewContext value={BLOCKED}>\n <TrimPreviewPeaksContext value={BLOCKED}>\n <PlaybackRefsContext value={refsValue}>\n <PlaybackControlsContext value={controlsValue}>\n <PlaylistViewContext value={viewValue}>\n <PlaylistZoomContext value={zoomValue}>\n <PlaylistSettingsContext value={settingsValue}>\n <MediaElementTrackContext value={trackValue}>\n <PlaybackRateContext value={playbackRateValue}>\n <AnnotationsContext value={annotationsValue}>\n <IsPlayingContext value={isPlayingValue}>\n <ActiveAnnotationContext\n value={activeAnnotationValue}\n >\n <CurrentTimeContext value={currentTimeValue}>\n <SelectionContext value={selection}>\n <SelectedRowContext value={ONLY_ROW_SELECTED}>\n <RecordingArmContext value={BLOCKED}>\n {children}\n </RecordingArmContext>\n </SelectedRowContext>\n </SelectionContext>\n </CurrentTimeContext>\n </ActiveAnnotationContext>\n </IsPlayingContext>\n </AnnotationsContext>\n </PlaybackRateContext>\n </MediaElementTrackContext>\n </PlaylistSettingsContext>\n </PlaylistZoomContext>\n </PlaylistViewContext>\n </PlaybackControlsContext>\n </PlaybackRefsContext>\n </TrimPreviewPeaksContext>\n </TrimPreviewContext>\n </TrackReorderPreviewContext>\n </PlaylistMixerContext>\n </PlaylistTimelineContext>\n </UndoRedoContext>\n </SelectedTrackIdContext>\n </LoopContext>\n </AnnotationOptionsContext>\n </EngineRefsContext>\n </EditorControlsContext>\n </ArrangementContext>\n </ThemeProvider>\n );\n};\n","import type { MediaElementPlayout } from '@waveform-playlist/media-element-playout';\nimport { installCommand } from '../utils/installCommand';\n\n/** Options for {@link resolveMediaElementPlayout}. */\nexport interface ResolveMediaElementPlayoutOptions {\n /** Consumer-supplied factory. When present, the default engine is never imported. */\n createPlayout?: () => MediaElementPlayout;\n /** Initial playback rate forwarded to the default engine. */\n playbackRate?: number;\n /** Whether to preserve pitch on rate change (default engine only). */\n preservesPitch?: boolean;\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst installHint = (): string =>\n '@waveform-playlist/media-element-playout is required for the default MediaElement engine. ' +\n 'Install with: ' +\n installCommand('@waveform-playlist/media-element-playout') +\n ' — or pass a custom `createPlayout`.';\n\n/**\n * Resolve a MediaElement playout. With `createPlayout`, returns its result and\n * never imports the default engine. Otherwise dynamically imports\n * `@waveform-playlist/media-element-playout`, rethrowing a friendly install hint\n * (and console.warn-ing the original error) when the optional peer is absent.\n */\nexport async function resolveMediaElementPlayout(\n opts: ResolveMediaElementPlayoutOptions\n): Promise<MediaElementPlayout> {\n if (opts.createPlayout) {\n return opts.createPlayout();\n }\n\n let mod: typeof import('@waveform-playlist/media-element-playout');\n try {\n mod = await import('@waveform-playlist/media-element-playout');\n } catch (originalErr) {\n console.warn(\n '[waveform-playlist] @waveform-playlist/media-element-playout dynamic import failed: ' +\n String(originalErr)\n );\n throw new Error(installHint());\n }\n\n return new mod.MediaElementPlayout({\n playbackRate: opts.playbackRate,\n preservesPitch: opts.preservesPitch,\n });\n}\n","import React, { useCallback } from 'react';\nimport { BaseControlButton } from '@waveform-playlist/ui-components';\nimport {\n useSelection,\n usePlaybackControls,\n useEditorControls,\n usePlaylistTimeline,\n usePlaybackRefs,\n usePlaylistView,\n useLoop,\n useIsPlaying,\n} from '../contexts/playlistContexts';\nimport { usePlayFromSelectionOrCursor } from '../hooks/usePlayFromSelectionOrCursor';\n\n// Play, Pause, Stop, Rewind, Fast Forward and the two skips read only what\n// both providers have (#688), so they work under WaveformPlaylistProvider and\n// under MediaElementPlaylistProvider. The loop buttons below are\n// WaveformPlaylistProvider only.\n\nexport const PlayButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isPlaying } = useIsPlaying();\n // Shared with the Space shortcut: the selection if one is highlighted, else the cursor.\n const handleClick = usePlayFromSelectionOrCursor();\n\n return (\n <BaseControlButton onClick={handleClick} disabled={isPlaying} className={className}>\n Play\n </BaseControlButton>\n );\n};\n\nexport const PauseButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isPlaying } = useIsPlaying();\n const { pause } = usePlaybackControls();\n\n return (\n <BaseControlButton onClick={pause} disabled={!isPlaying} className={className}>\n Pause\n </BaseControlButton>\n );\n};\n\nexport const StopButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isPlaying } = useIsPlaying();\n const { stop } = usePlaybackControls();\n\n return (\n <BaseControlButton onClick={stop} disabled={!isPlaying} className={className}>\n Stop\n </BaseControlButton>\n );\n};\n\n// The four below move the cursor with `seekTo`, which clamps to the audio and\n// restarts playback at the new position when it is running.\n\nexport const RewindButton: React.FC<{ className?: string }> = ({ className }) => {\n const { seekTo } = usePlaybackControls();\n const handleClick = () => seekTo(0);\n\n return (\n <BaseControlButton onClick={handleClick} className={className}>\n Rewind\n </BaseControlButton>\n );\n};\n\nexport const FastForwardButton: React.FC<{ className?: string }> = ({ className }) => {\n const { seekTo } = usePlaybackControls();\n // A provider with `indefinitePlayback` has no end to go to: its transport\n // runs on past the audio (never set under the MediaElement provider).\n const { indefinitePlayback } = usePlaylistView();\n // An infinite time is the end of the audio.\n const handleClick = () => seekTo(Infinity);\n\n return (\n <BaseControlButton onClick={handleClick} disabled={indefinitePlayback} className={className}>\n Fast Forward\n </BaseControlButton>\n );\n};\n\nexport const SkipBackwardButton: React.FC<{ skipAmount?: number; className?: string }> = ({\n skipAmount = 5,\n className,\n}) => {\n const { currentTimeRef } = usePlaybackRefs();\n const { seekTo } = usePlaybackControls();\n const handleClick = () => seekTo((currentTimeRef.current ?? 0) - skipAmount);\n\n return (\n <BaseControlButton onClick={handleClick} className={className}>\n Skip Backward\n </BaseControlButton>\n );\n};\n\nexport const SkipForwardButton: React.FC<{ skipAmount?: number; className?: string }> = ({\n skipAmount = 5,\n className,\n}) => {\n const { currentTimeRef } = usePlaybackRefs();\n const { seekTo } = usePlaybackControls();\n const handleClick = () => seekTo((currentTimeRef.current ?? 0) + skipAmount);\n\n return (\n <BaseControlButton onClick={handleClick} className={className}>\n Skip Forward\n </BaseControlButton>\n );\n};\n\nexport const LoopButton: React.FC<{ className?: string }> = ({ className }) => {\n const { isLoopEnabled, loopStart, loopEnd } = useLoop();\n const { setLoopEnabled, setLoopRegion } = useEditorControls();\n const { duration } = usePlaylistTimeline();\n\n const hasValidLoopRegion = loopStart !== loopEnd && loopEnd > loopStart;\n\n const handleClick = () => {\n if (!isLoopEnabled && !hasValidLoopRegion) {\n // Create a default loop region when enabling loop without one\n // Default to first 10 seconds or 25% of duration, whichever is smaller\n const defaultEnd = Math.min(10, duration * 0.25);\n setLoopRegion(0, Math.max(1, defaultEnd)); // At least 1 second\n }\n setLoopEnabled(!isLoopEnabled);\n };\n\n return (\n <BaseControlButton\n onClick={handleClick}\n className={className}\n title={isLoopEnabled ? 'Disable loop' : 'Enable loop'}\n >\n {isLoopEnabled ? 'Loop On' : 'Loop Off'}\n </BaseControlButton>\n );\n};\n\nexport const SetLoopRegionButton: React.FC<{ className?: string }> = ({ className }) => {\n const { selectionStart, selectionEnd } = useSelection();\n const { loopStart, loopEnd } = useLoop();\n const { setLoopRegionFromSelection, clearLoopRegion } = useEditorControls();\n\n const hasValidSelection = selectionStart !== selectionEnd && selectionEnd > selectionStart;\n const hasLoopRegion = loopStart !== loopEnd && loopEnd > loopStart;\n\n const handleClick = () => {\n if (hasLoopRegion) {\n clearLoopRegion();\n } else {\n setLoopRegionFromSelection();\n }\n };\n\n return (\n <BaseControlButton\n onClick={handleClick}\n disabled={!hasValidSelection && !hasLoopRegion}\n className={className}\n title={\n hasLoopRegion\n ? 'Clear loop region'\n : hasValidSelection\n ? 'Set loop region from selection'\n : 'Create a selection first'\n }\n >\n {hasLoopRegion ? 'Clear Loop' : 'Set Loop'}\n </BaseControlButton>\n );\n};\n\nexport interface ClearAllButtonProps {\n onClearAll: () => void;\n label?: string;\n className?: string;\n}\n\nexport const ClearAllButton: React.FC<ClearAllButtonProps> = ({\n onClearAll,\n label = 'Clear All',\n className,\n}) => {\n const { stop } = usePlaybackControls();\n\n const handleClick = useCallback(() => {\n stop();\n onClearAll();\n }, [stop, onClearAll]);\n\n return (\n <BaseControlButton onClick={handleClick} className={className} title=\"Remove all tracks\">\n {label}\n </BaseControlButton>\n );\n};\n","import React from 'react';\nimport { BaseControlButton } from '@waveform-playlist/ui-components';\nimport { useEditorControls, usePlaylistZoom } from '../contexts/playlistContexts';\n\nexport const ZoomInButton: React.FC<{ className?: string; disabled?: boolean }> = ({\n className,\n disabled,\n}) => {\n const { zoomIn } = useEditorControls();\n const { canZoomIn } = usePlaylistZoom();\n\n return (\n <BaseControlButton onClick={zoomIn} disabled={disabled || !canZoomIn} className={className}>\n Zoom In\n </BaseControlButton>\n );\n};\n\nexport const ZoomOutButton: React.FC<{ className?: string; disabled?: boolean }> = ({\n className,\n disabled,\n}) => {\n const { zoomOut } = useEditorControls();\n const { canZoomOut } = usePlaylistZoom();\n\n return (\n <BaseControlButton onClick={zoomOut} disabled={disabled || !canZoomOut} className={className}>\n Zoom Out\n </BaseControlButton>\n );\n};\n","import React, { useRef, useEffect, useId } from 'react';\nimport {\n MasterVolumeControl as BaseMasterVolumeControl,\n TimeFormatSelect as BaseTimeFormatSelect,\n PlaybackRateSelect as BasePlaybackRateSelect,\n AutomaticScrollCheckbox as BaseAutomaticScrollCheckbox,\n SelectionTimeInputs as BaseSelectionTimeInputs,\n formatTime,\n} from '@waveform-playlist/ui-components';\nimport styled from 'styled-components';\nimport {\n useCurrentTime,\n useSelection,\n usePlaybackControls,\n useEditorControls,\n usePlaybackRate,\n usePlaylistSettings,\n usePlaylistMixer,\n usePlaybackRefs,\n useIsPlaying,\n} from '../contexts/playlistContexts';\n\n/**\n * Master volume control that uses the playlist context\n */\nexport const MasterVolumeControl: React.FC<{ className?: string }> = ({ className }) => {\n const { masterVolume } = usePlaylistMixer();\n const { setMasterVolume } = useEditorControls();\n\n return (\n <BaseMasterVolumeControl\n volume={masterVolume}\n onChange={setMasterVolume}\n className={className}\n />\n );\n};\n\n/**\n * Time format selector that uses the playlist context\n */\nexport const TimeFormatSelect: React.FC<{ className?: string }> = ({ className }) => {\n const { timeFormat } = usePlaylistSettings();\n const { setTimeFormat } = usePlaybackControls();\n\n return <BaseTimeFormatSelect value={timeFormat} onChange={setTimeFormat} className={className} />;\n};\n\nconst PositionDisplay = styled.span`\n font-family: 'Courier New', Monaco, monospace;\n font-size: 1rem;\n font-weight: 600;\n color: ${(props) => props.theme?.textColor || '#333'};\n user-select: none;\n`;\n\n/**\n * Audio position display that uses the playlist context.\n * Updates via the shared animation frame registry — no own rAF loop.\n * Direct DOM manipulation avoids React re-renders.\n */\nexport const AudioPosition: React.FC<{ className?: string }> = ({ className }) => {\n const timeRef = useRef<HTMLSpanElement>(null);\n const { currentTimeRef, registerFrameCallback, unregisterFrameCallback } = usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only: what is shown comes from the ref.\n useCurrentTime();\n const { timeFormat: format } = usePlaylistSettings();\n\n // Its own id in the frame registry: under a shared one, a second readout\n // under the same provider replaced the first one's callback.\n const id = useId();\n\n // Register per-frame callback during playback — uses raw time for display\n useEffect(() => {\n if (isPlaying) {\n registerFrameCallback(id, ({ time }) => {\n if (timeRef.current) {\n timeRef.current.textContent = formatTime(time, format);\n }\n });\n }\n return () => unregisterFrameCallback(id);\n }, [id, isPlaying, format, registerFrameCallback, unregisterFrameCallback]);\n\n // Update when stopped (for seeks)\n useEffect(() => {\n if (!isPlaying && timeRef.current) {\n timeRef.current.textContent = formatTime(currentTimeRef.current ?? 0, format);\n }\n });\n\n return (\n <PositionDisplay ref={timeRef} className={className} aria-label=\"Audio position\">\n {formatTime(currentTimeRef.current ?? 0, format)}\n </PositionDisplay>\n );\n};\n\n/**\n * Playback speed dropdown. MediaElementPlaylistProvider only (#688).\n * `rates` lists the speeds to offer (default 0.5× to 2×).\n */\nexport const PlaybackRateSelect: React.FC<{ rates?: readonly number[]; className?: string }> = ({\n rates,\n className,\n}) => {\n const { playbackRate, setPlaybackRate } = usePlaybackRate();\n return (\n <BasePlaybackRateSelect\n value={playbackRate}\n onChange={setPlaybackRate}\n rates={rates}\n className={className}\n />\n );\n};\n\n/**\n * Selection time inputs bound to the provider: its selection, and its time\n * format (the one `TimeFormatSelect` and `setTimeFormat()` set).\n */\nexport const SelectionTimeInputs: React.FC<{ className?: string }> = ({ className }) => {\n const { selectionStart, selectionEnd } = useSelection();\n const { timeFormat } = usePlaylistSettings();\n const { setSelection } = usePlaybackControls();\n\n return (\n <BaseSelectionTimeInputs\n selectionStart={selectionStart}\n selectionEnd={selectionEnd}\n onSelectionChange={setSelection}\n format={timeFormat}\n className={className}\n />\n );\n};\n\n/**\n * Automatic scroll checkbox that uses the playlist context\n * Uses split contexts to avoid re-rendering during animation\n */\nexport const AutomaticScrollCheckbox: React.FC<{ className?: string }> = ({ className }) => {\n const { isAutomaticScroll } = usePlaylistSettings();\n const { setAutomaticScroll } = usePlaybackControls();\n\n return (\n <BaseAutomaticScrollCheckbox\n checked={isAutomaticScroll}\n onChange={setAutomaticScroll}\n className={className}\n />\n );\n};\n","import React, {\n use,\n useLayoutEffect,\n useRef,\n useState,\n useMemo,\n type ReactNode,\n useCallback,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { DevicePixelRatioProvider, CLIP_HEADER_HEIGHT } from '@waveform-playlist/ui-components';\nimport {\n usePlaylistView,\n usePlaylistZoom,\n usePlaylistTimeline,\n useTrackReorderPreview,\n useEditorControls,\n} from '../contexts/playlistContexts';\nimport {\n applyTrackOrderPreview,\n computeTrackLayout,\n trackIdAtOffset,\n} from '../utils/trackOrderPreview';\nimport { useTrailingActive } from '../hooks/useTrailingActive';\nimport { useRecordingLayout } from '../hooks/useRecordingLayout';\nimport { useTrimPreviewExtent } from '../hooks/useTrimPreviewView';\nimport { trackKind, type RenderMode, type SpectrogramConfig } from '@waveform-playlist/core';\nimport { SpectrogramIntegrationContext } from '../SpectrogramIntegrationContext';\nimport { trackRenderMode } from '../utils/trackRenderMode';\nimport { placeholdersEnd } from '../utils/placeholderPeaks';\nimport type { SpectrogramTrackHelpers } from './TrackRows';\nimport { getTrackChannelCount } from './visualizationLayout';\nimport type { WaveformRow, WaveformRowsValue } from './waveformLayoutContext';\nimport { useWaveformFrame, useWaveformParts } from './waveformFrame';\nimport { useResolvedViewOptions } from './WaveformViewOptions';\n\n// Default duration in seconds for empty tracks (used for recording workflow)\nconst DEFAULT_EMPTY_TRACK_DURATION = 60;\n\n// Passed to the spectrogram settings modal when no config exists at any level.\n// A module constant, so the prop keeps its identity across renders.\nconst EMPTY_SPECTROGRAM_CONFIG: SpectrogramConfig = {};\n\nexport interface WaveformRootProps {\n className?: string;\n /** The parts (see waveformParts.tsx), and anything else to draw over the tracks. */\n children?: ReactNode;\n}\n\n/**\n * The root of the multitrack view (#685), exported from the package.\n *\n * It owns what the parts share and nothing they draw: the size of the\n * timeline, the vertical layout of the rows (one layout for the tracks and\n * the controls column, so they cannot disagree), what a press on the tracks\n * does beyond the selection drag, and the spectrogram settings modal. The\n * scrolling frame (`Playlist`), the selection drag and the context for the\n * drawing primitives are shared with the MediaElement root: `useWaveformFrame`.\n *\n * It renders on its own state (a drag in progress, the settings modal, the\n * measured container width), on play and stop (its selection drag reads\n * `isPlaying`), on every change of the timeline, the zoom, the view settings,\n * the reorder preview, the spectrogram integration and the theme, on a\n * recording layout step, on a 10-second step of a trim dragged past the end\n * of the timeline, and whenever the component that composes it renders.\n * None of that renders a part by itself: the\n * parts are `children`, whose elements are the same as on the previous render\n * unless the component that composed them rendered too, and each part follows\n * the two layout values below and the provider contexts it reads. Keep it so:\n * both values are memoized, and everything in them must keep its identity\n * across a render that did not change it.\n */\nexport const WaveformRoot: React.FC<WaveformRootProps> = ({ className, children }) => {\n const { setSelectedTrackId, setCurrentTime } = useEditorControls();\n const { sampleRate, mono, indefinitePlayback } = usePlaylistView();\n const viewOptions = useResolvedViewOptions();\n const { waveHeight, fillViewport } = viewOptions;\n const { samplesPerPixel } = usePlaylistZoom();\n const { peaksDataArray, tracks, duration, isReady } = usePlaylistTimeline();\n const { trackDragPreview } = useTrackReorderPreview();\n\n // Optional spectrogram integration (only available when SpectrogramProvider is present)\n const spectrogram = use(SpectrogramIntegrationContext);\n\n // The parts by place, and what the tracks part was given.\n const parts = useWaveformParts(children);\n const { showClipHeaders, recordingState } = parts.tracksOptions;\n\n // Per-track spectrogram rendering helpers (memoized) — only computed when spectrogram is available\n const spectrogramHelpersById = useMemo(() => {\n const helpers = new Map<string, SpectrogramTrackHelpers>();\n if (!spectrogram) return helpers;\n tracks.forEach((track) => {\n const mode = trackRenderMode(\n track,\n spectrogram.trackSpectrogramOverrides.get(track.id)?.renderMode\n );\n if (mode === 'waveform') return;\n const overrides = spectrogram.trackSpectrogramOverrides.get(track.id);\n const cm =\n overrides?.colorMap ??\n track.spectrogramColorMap ??\n spectrogram.spectrogramColorMap ??\n 'viridis';\n const cfg = overrides?.config ?? track.spectrogramConfig ?? spectrogram.spectrogramConfig;\n helpers.set(track.id, {\n colorLUT: spectrogram.getColorMap(cm),\n frequencyScaleFn: spectrogram.getFrequencyScale(cfg?.frequencyScale ?? 'mel'),\n config: cfg,\n });\n });\n return helpers;\n }, [tracks, spectrogram]);\n\n // Render mode per track (see trackRenderMode): an audio track takes a\n // spectrogram override, else its own mode, else a waveform. A MIDI track is\n // drawn as a piano roll from its kind and has no render mode.\n const renderModeById = useMemo(() => {\n const modes = new Map<string, RenderMode>();\n tracks.forEach((track) => {\n modes.set(\n track.id,\n trackRenderMode(track, spectrogram?.trackSpectrogramOverrides.get(track.id)?.renderMode)\n );\n });\n return modes;\n }, [tracks, spectrogram]);\n\n // The recording, reduced to what the layout depends on: numbers that change\n // rarely, read through selectors. `recordingState` itself is usually a new\n // object literal on every render of the consumer.\n const recordingProgress = recordingState?.isRecording ? recordingState.progress : undefined;\n const recordingLayout = useRecordingLayout(\n recordingProgress,\n recordingState?.startSample ?? 0,\n sampleRate\n );\n const recordingTrackId = recordingState?.isRecording ? recordingState.trackId : null;\n // A trim dragged past the end of the timeline: its end, in 10-second steps (#812).\n const trimPreviewEnd = useTrimPreviewExtent(sampleRate, duration);\n const recordingChannelCount = recordingProgress ? (mono ? 1 : recordingLayout.channelCount) : 0;\n\n // State for spectrogram settings modal\n const [settingsModalTrackId, setSettingsModalTrackId] = useState<string | null>(null);\n const closeSettingsModal = useCallback(() => setSettingsModalTrackId(null), []);\n\n // The frame hands over the scroll container (a state setter: stable).\n const [scrollContainerElement, setScrollContainerElement] = useState<HTMLDivElement | null>(null);\n\n // Fill the visible scroll container when requested — indefinitePlayback\n // implies it (endless playback needs an endless-looking timeline);\n // fillViewport requests the layout alone.\n const fillsContainer = indefinitePlayback || fillViewport;\n\n // The container's width is state, measured in a layout effect (so the first\n // paint already fills it) and kept current by a ResizeObserver. Reading\n // clientWidth in the render body instead forced layout on every render while\n // recording, was 0 on the first render and never followed a container resize.\n const [scrollContainerWidth, setScrollContainerWidth] = useState(0);\n useLayoutEffect(() => {\n if (!fillsContainer || !scrollContainerElement) return;\n const measure = () => setScrollContainerWidth(scrollContainerElement.clientWidth);\n measure();\n if (typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(scrollContainerElement);\n return () => observer.disconnect();\n }, [fillsContainer, scrollContainerElement]);\n\n // Calculate dimensions. `duration` is derived from `tracks` in the provider,\n // so it is already current in this render. It is the loaded audio; a clip\n // still loading is drawn as a placeholder, and the view is as wide as the\n // last one (#812).\n const placeholdersEndSeconds = useMemo(() => placeholdersEnd(peaksDataArray), [peaksDataArray]);\n let displayDuration = Math.max(\n duration > 0 ? duration : DEFAULT_EMPTY_TRACK_DURATION,\n placeholdersEndSeconds\n );\n\n if (fillsContainer) {\n const minContainerDuration = (scrollContainerWidth * samplesPerPixel) / sampleRate;\n displayDuration = Math.max(displayDuration, minContainerDuration);\n }\n\n if (recordingProgress) {\n // Grows in steps, not with every frame of the take (#695).\n displayDuration = Math.max(displayDuration, recordingLayout.displayEndSeconds);\n }\n\n displayDuration = Math.max(displayDuration, trimPreviewEnd);\n\n // Reads `tracks` through a ref so its identity survives `tracks` changes: it\n // is a prop of every memoized clip and control panel.\n const tracksRef = useRef(tracks);\n tracksRef.current = tracks;\n const selectTrack = useCallback(\n (trackIndex: number) => {\n const track = tracksRef.current[trackIndex];\n if (track) {\n setSelectedTrackId(track.id);\n }\n },\n [setSelectedTrackId]\n );\n\n // Shared vertical layout for BOTH columns (waveform rows + control slots).\n // Heights use the existing slot formula; order applies the live drag\n // preview so both columns slide together. Worked out here, once, so the two\n // columns can never disagree.\n const trackHeightById = useMemo(() => {\n const m = new Map<string, number>();\n peaksDataArray.forEach((trackClipPeaks, trackIndex) => {\n const track = tracks[trackIndex];\n if (!track) return;\n const maxChannels = getTrackChannelCount(\n trackClipPeaks,\n track.id === recordingTrackId ? recordingChannelCount : 0\n );\n m.set(track.id, waveHeight * maxChannels + (showClipHeaders ? CLIP_HEADER_HEIGHT : 0));\n });\n return m;\n }, [\n peaksDataArray,\n tracks,\n recordingTrackId,\n recordingChannelCount,\n waveHeight,\n showClipHeaders,\n ]);\n\n const displayOrderIds = useMemo(\n () => applyTrackOrderPreview(tracks, trackDragPreview).map((t) => t.id),\n [tracks, trackDragPreview]\n );\n\n const trackLayout = useMemo(\n () => computeTrackLayout(displayOrderIds, trackHeightById),\n [displayOrderIds, trackHeightById]\n );\n\n const animateTrackLayout = useTrailingActive(trackDragPreview !== null, 200);\n\n // What the parts need to know of each track. Changes with `tracks`, as the\n // peaks beside it do.\n const rowList = useMemo<WaveformRow[]>(\n () => tracks.map((track) => ({ id: track.id, kind: trackKind(track) })),\n [tracks]\n );\n const dragSourceTrackId = trackDragPreview?.trackId ?? null;\n\n const rows = useMemo<WaveformRowsValue>(\n () => ({\n rows: rowList,\n peaksDataArray,\n showClipHeaders,\n trackHeightById,\n trackLayout,\n animateTrackLayout,\n renderModeById,\n spectrogramHelpersById,\n selectTrack,\n setSettingsModalTrackId,\n recordingChannelCount,\n dragSourceTrackId,\n }),\n [\n rowList,\n peaksDataArray,\n showClipHeaders,\n trackHeightById,\n trackLayout,\n animateTrackLayout,\n renderModeById,\n spectrogramHelpersById,\n selectTrack,\n recordingChannelCount,\n dragSourceTrackId,\n ]\n );\n\n // The frame, with the multitrack extras of the selection drag: a press\n // selects the row under the pointer, and a click while stopped moves the\n // cursor only (the selection the press collapsed stays).\n const frame = useWaveformFrame({\n className,\n viewOptions,\n parts,\n displayDuration,\n rows,\n playlistState: isReady ? 'ready' : 'loading',\n controlsWidth: parts.controlsWidth,\n onScrollContainer: setScrollContainerElement,\n onPress: ({ offsetY }) => {\n // The row under the pointer, from the layout the rows are positioned with.\n const clickedTrackId = trackIdAtOffset(\n displayOrderIds,\n trackLayout,\n trackHeightById,\n offsetY\n );\n if (clickedTrackId !== null) {\n setSelectedTrackId(clickedTrackId);\n }\n },\n onClickWhileStopped: setCurrentTime,\n });\n\n return (\n <DevicePixelRatioProvider>\n {frame}\n {spectrogram?.SettingsModal &&\n typeof document !== 'undefined' &&\n createPortal(\n <spectrogram.SettingsModal\n open={settingsModalTrackId !== null}\n onClose={closeSettingsModal}\n config={\n settingsModalTrackId !== null\n ? (spectrogram.trackSpectrogramOverrides.get(settingsModalTrackId)?.config ??\n tracks.find((t) => t.id === settingsModalTrackId)?.spectrogramConfig ??\n spectrogram.spectrogramConfig ??\n EMPTY_SPECTROGRAM_CONFIG)\n : EMPTY_SPECTROGRAM_CONFIG\n }\n colorMap={\n settingsModalTrackId !== null\n ? (spectrogram.trackSpectrogramOverrides.get(settingsModalTrackId)?.colorMap ??\n tracks.find((t) => t.id === settingsModalTrackId)?.spectrogramColorMap ??\n spectrogram.spectrogramColorMap ??\n 'viridis')\n : 'viridis'\n }\n onApply={(newConfig, newColorMap) => {\n if (settingsModalTrackId !== null) {\n spectrogram.setTrackSpectrogramConfig(settingsModalTrackId, newConfig, newColorMap);\n }\n }}\n />,\n document.body\n )}\n </DevicePixelRatioProvider>\n );\n};\n","/**\n * Pure helpers for the track-reorder drag preview.\n *\n * The preview is view-level only: it produces a DISPLAY order/geometry while\n * the engine's committed `tracks` order stays untouched until drop.\n */\n\nexport interface TrackDragPreview {\n trackId: string;\n toIndex: number;\n}\n\n/**\n * Returns the display order with the previewed track moved to `toIndex`.\n * Identity (same reference) when there is nothing to do — null preview,\n * unknown id, or an index that doesn't change the order.\n */\nexport function applyTrackOrderPreview<T extends { id: string }>(\n tracks: readonly T[],\n preview: TrackDragPreview | null\n): readonly T[] {\n if (!preview) return tracks;\n const fromIndex = tracks.findIndex((t) => t.id === preview.trackId);\n if (fromIndex === -1) return tracks;\n const toIndex = Math.max(0, Math.min(tracks.length - 1, preview.toIndex));\n if (toIndex === fromIndex) return tracks;\n const next = tracks.slice();\n const [moved] = next.splice(fromIndex, 1);\n next.splice(toIndex, 0, moved);\n return next;\n}\n\nexport interface TrackLayout {\n topById: Map<string, number>;\n totalHeight: number;\n}\n\n/**\n * Cumulative vertical layout for absolutely-positioned track rows. Both the\n * waveform column and the controls column render from the SAME layout so they\n * can never drift apart mid-preview. Ids missing from `heightById` contribute\n * height 0 (defensive; should not happen in practice).\n */\nexport function computeTrackLayout(\n orderedIds: readonly string[],\n heightById: ReadonlyMap<string, number>\n): TrackLayout {\n const topById = new Map<string, number>();\n let top = 0;\n for (const id of orderedIds) {\n topById.set(id, top);\n top += heightById.get(id) ?? 0;\n }\n return { topById, totalHeight: top };\n}\n\n/**\n * The track whose row contains the vertical offset `y` (measured from the top\n * of the first row), or null when `y` is above the first row or below the\n * last. Reads the SAME layout the rows are positioned with, so a press always\n * lands on the row that is drawn there (#762: the press handler once added up\n * row heights of its own, and counted a 'both' track twice as tall).\n */\nexport function trackIdAtOffset(\n orderedIds: readonly string[],\n layout: TrackLayout,\n heightById: ReadonlyMap<string, number>,\n y: number\n): string | null {\n for (const id of orderedIds) {\n const top = layout.topById.get(id);\n if (top === undefined) continue;\n const height = heightById.get(id) ?? 0;\n if (y >= top && y < top + height) return id;\n }\n return null;\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * True while `active` is true and for `trailingMs` after it turns false.\n * Used to keep the track-reorder transform transition enabled through the\n * cancel-revert animation (the drag ends but the layout still needs to\n * animate back) without animating unrelated layout changes outside a drag.\n */\nexport function useTrailingActive(active: boolean, trailingMs: number): boolean {\n const [trailing, setTrailing] = useState(active);\n useEffect(() => {\n if (active) {\n setTrailing(true);\n return undefined;\n }\n const timer = setTimeout(() => setTrailing(false), trailingMs);\n return () => clearTimeout(timer);\n }, [active, trailingMs]);\n return trailing || active;\n}\n","import { useCallback, useSyncExternalStore } from 'react';\nimport type { RecordingProgressSource } from '@waveform-playlist/core';\n\n/** How far the displayed timeline is extended at a time while a take runs (and a trim is dragged past the end). */\nexport const RECORDING_EXTENT_STEP_SECONDS = 10;\n\n/**\n * Where the displayed timeline should end for a take that currently ends at\n * `takeEndSeconds`: between 10 and 20 seconds further on, moving in 10-second\n * steps. A value that followed the take exactly would change on every\n * animation frame, and with it the width of every track row.\n */\nexport function recordingDisplayEnd(takeEndSeconds: number): number {\n const step = RECORDING_EXTENT_STEP_SECONDS;\n return (Math.floor(Math.max(0, takeEndSeconds) / step) + 2) * step;\n}\n\nconst subscribeToNothing = () => () => {};\n\nexport interface RecordingLayout {\n /** Channels in the take's preview (0 when not recording). */\n channelCount: number;\n /** End of the timeline the take needs, in seconds (0 when not recording). */\n displayEndSeconds: number;\n}\n\n/**\n * The two things the visualization's layout needs from a recording in\n * progress. Both are read through selectors that return numbers, so the\n * calling component re-renders when a number changes (a channel appears, the\n * take crosses a 10-second step) and not on every frame of progress.\n */\nexport function useRecordingLayout(\n progress: RecordingProgressSource | undefined,\n startSample: number,\n sampleRate: number\n): RecordingLayout {\n // Called as a method (not detached), so a source written as a class works.\n const subscribe = useCallback(\n (onChange: () => void) => (progress ? progress.subscribe(onChange) : subscribeToNothing()),\n [progress]\n );\n\n const getChannelCount = useCallback(\n () => (progress ? progress.getSnapshot().peaks.length : 0),\n [progress]\n );\n const getDisplayEnd = useCallback(\n () =>\n progress && sampleRate > 0\n ? recordingDisplayEnd(startSample / sampleRate + progress.getSnapshot().duration)\n : 0,\n [progress, startSample, sampleRate]\n );\n\n const channelCount = useSyncExternalStore(subscribe, getChannelCount, getChannelCount);\n const displayEndSeconds = useSyncExternalStore(subscribe, getDisplayEnd, getDisplayEnd);\n return { channelCount, displayEndSeconds };\n}\n","import { useCallback, useMemo, useSyncExternalStore } from 'react';\nimport type { ValueSource } from '@waveform-playlist/core';\nimport { useTrimPreviewOptional, useTrimPreviewPeaksOptional } from '../contexts/playlistContexts';\nimport type { TrimPreview } from '../providerInternals/useTrimPreview';\nimport type { ClipPeaks } from '../WaveformPlaylistContext';\nimport { RECORDING_EXTENT_STEP_SECONDS } from './useRecordingLayout';\n\n/**\n * How far the view is extended at a time while a trim is dragged past the\n * end of the timeline: the previewed end rounded UP to the next multiple (0 to\n * 10 seconds spare; not the recording layout's 10 to 20).\n */\nconst TRIM_EXTENT_STEP_SECONDS = RECORDING_EXTENT_STEP_SECONDS;\n\nconst NO_UNSUBSCRIBE = () => {};\n/** Where there is no preview source: subscribed to nothing. */\nconst subscribeToNothing = () => NO_UNSUBSCRIBE;\n\n/** `subscribe` for `useSyncExternalStore` over the trim preview, or over nothing. */\nfunction useSubscribe(source: ValueSource<TrimPreview | null> | undefined) {\n // Called as a method (not detached), so a source written as a class works.\n return useMemo(\n () => (source ? (onChange: () => void) => source.subscribe(onChange) : subscribeToNothing),\n [source]\n );\n}\n\n/**\n * The clip to draw: `clip`, or while a trim of this clip is dragged, its\n * record for the previewed geometry (computed by `clipPeaksFor`, as every\n * clip's is). The snapshot is `null` unless the preview names this clip, so a\n * move renders the dragged clip's view and no other. Under the MediaElement\n * provider, or outside a provider, there is no preview and `clip` is drawn.\n */\nexport function usePreviewedClipPeaks(clip: ClipPeaks, trackId: string): ClipPeaks {\n const source = useTrimPreviewOptional()?.source;\n const peaks = useTrimPreviewPeaksOptional();\n const subscribe = useSubscribe(source);\n const clipId = clip.clipId;\n const getSnapshot = useCallback(() => {\n const preview = source?.getSnapshot() ?? null;\n return preview !== null && preview.clipId === clipId && preview.trackId === trackId\n ? preview\n : null;\n }, [source, clipId, trackId]);\n const preview = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n // One record per preview object (and per committed record: a zoom or new\n // peaks during the drag change `clip`).\n return useMemo(\n () => (preview && peaks ? (peaks.peaksFor(preview) ?? clip) : clip),\n [preview, peaks, clip]\n );\n}\n\n/**\n * Where the view must end for a trim dragged past the end of the timeline, in\n * seconds: the previewed end rounded up to the next 10 seconds, or 0 when no\n * trim is dragged or it ends within `durationSeconds`. A selector that returns\n * the stepped number, so the caller renders once per step and not per move.\n */\nexport function useTrimPreviewExtent(sampleRate: number, durationSeconds: number): number {\n const source = useTrimPreviewOptional()?.source;\n const subscribe = useSubscribe(source);\n const getSnapshot = useCallback(() => {\n const preview = source?.getSnapshot() ?? null;\n if (preview === null || !(sampleRate > 0)) return 0;\n const endSeconds = (preview.startSample + preview.durationSamples) / sampleRate;\n if (endSeconds <= durationSeconds) return 0;\n return Math.ceil(endSeconds / TRIM_EXTENT_STEP_SECONDS) * TRIM_EXTENT_STEP_SECONDS;\n }, [source, sampleRate, durationSeconds]);\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","import { createContext, use } from 'react';\nimport { installCommand } from './utils/installCommand';\nimport type {\n SpectrogramConfig,\n ColorMapValue,\n RenderMode,\n TrackSpectrogramOverrides,\n SpectrogramCanvasRegistration,\n} from '@waveform-playlist/core';\nimport type { TrackMenuItem } from '@waveform-playlist/ui-components';\n\nexport interface SpectrogramIntegration {\n trackSpectrogramOverrides: Map<string, TrackSpectrogramOverrides>;\n spectrogramConfig?: SpectrogramConfig;\n spectrogramColorMap?: ColorMapValue;\n setTrackRenderMode: (trackId: string, mode: RenderMode) => void;\n setTrackSpectrogramConfig: (\n trackId: string,\n config: SpectrogramConfig,\n colorMap?: ColorMapValue\n ) => void;\n /** Single-canvas registration. OffscreenCanvas is non-transferable — call once per canvas. */\n registerSpectrogramCanvas: (reg: SpectrogramCanvasRegistration) => void;\n unregisterSpectrogramCanvas: (canvasId: string) => void;\n /** Render spectrogram menu items for a track's context menu */\n renderMenuItems?: (props: {\n renderMode: string;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n }) => TrackMenuItem[];\n /** Settings modal component provided by the spectrogram package */\n SettingsModal?: React.ComponentType<{\n open: boolean;\n onClose: () => void;\n config: SpectrogramConfig;\n colorMap: ColorMapValue;\n onApply: (config: SpectrogramConfig, colorMap: ColorMapValue) => void;\n }>;\n /** Get color lookup table for a color map name */\n getColorMap: (name: ColorMapValue) => Uint8Array;\n /** Get frequency scale function for a scale name */\n getFrequencyScale: (name: string) => (f: number, minF: number, maxF: number) => number;\n}\n\nexport const SpectrogramIntegrationContext = createContext<SpectrogramIntegration | null>(null);\n\nexport const SpectrogramIntegrationProvider = SpectrogramIntegrationContext.Provider;\n\n/**\n * Hook to access spectrogram integration provided by @waveform-playlist/spectrogram.\n * Throws if used without <SpectrogramProvider> wrapping the component tree.\n *\n * Follows the Kent C. Dodds pattern:\n * https://kentcdodds.com/blog/how-to-use-react-context-effectively\n */\nexport function useSpectrogramIntegration(): SpectrogramIntegration {\n const context = use(SpectrogramIntegrationContext);\n if (!context) {\n throw new Error(\n 'useSpectrogramIntegration must be used within <SpectrogramProvider>. ' +\n 'Install @waveform-playlist/spectrogram (' +\n installCommand('@waveform-playlist/spectrogram') +\n ') and wrap your app with <SpectrogramProvider>.'\n );\n }\n return context;\n}\n","import { trackKind } from '@waveform-playlist/core';\nimport type { ClipTrack, RenderMode } from '@waveform-playlist/core';\n\n/**\n * The render mode of a track: the spectrogram override for it, else its own\n * `renderMode`, else a waveform. Render modes are for audio tracks. A MIDI\n * track is drawn as a piano roll from its kind (#756), so it always gets\n * `'waveform'` here, which keeps the spectrogram machinery away from it.\n */\nexport function trackRenderMode(\n track: Pick<ClipTrack, 'kind' | 'renderMode'>,\n override?: RenderMode\n): RenderMode {\n if (trackKind(track) === 'midi') return 'waveform';\n return override ?? track.renderMode ?? 'waveform';\n}\n","import styled from 'styled-components';\nimport type { RecordingProgressSource } from '@waveform-playlist/core';\nimport type { ClipPeaks } from '../WaveformPlaylistContext';\n\n/** Live recording state for the real-time waveform preview. */\nexport interface WaveformRecordingState {\n isRecording: boolean;\n /** Which track is being recorded into. */\n trackId: string;\n /** Where on the timeline the take started. */\n startSample: number;\n /**\n * The take's elapsed time and per-channel preview peaks, from\n * `useRecording` / `useIntegratedRecording`. A source, not values: only the\n * preview clip follows it frame by frame, so the component that renders\n * `<Waveform>` does not re-render while recording.\n */\n progress: RecordingProgressSource;\n /** Bit depth of the peak values. */\n bits: 8 | 16;\n /**\n * Latency offset (seconds) to skip in the live preview. Absolute replacement\n * for the auto-computed outputLatency + lookAhead value. Pass the same value\n * given to useIntegratedRecording so preview and finalized clip match.\n */\n latencyOffset?: number;\n}\n\ninterface PositionedRowProps {\n readonly $top: number;\n readonly $animate: boolean;\n}\n\n/**\n * Shared relative container for absolutely-positioned track rows. Explicit\n * height because absolute children don't size their parent.\n */\nexport const TracksLayout = styled.div.attrs<{ $height: number }>((props) => ({\n style: { height: `${props.$height}px` },\n}))<{ $height: number }>`\n position: relative;\n`;\n\n/**\n * Positions one waveform track row from the shared layout map. Positioned\n * via `top`, NOT `translateY` — a transform (even translateY(0)) creates a\n * stacking context on every row, which flattens the clips' z-index: 105\n * beneath the ClickOverlay (z-index: 1) and blocks all clip interactions\n * (header drag, boundary trim, split). `top` moves the row without a\n * stacking context, so clip z-indexes keep competing globally as before.\n * Transition only while a track drag is active (+trailing window) so\n * unrelated layout changes stay instant.\n */\nexport const TrackRowPositioner = styled.div.attrs<PositionedRowProps>((props) => ({\n style: { top: `${props.$top}px` },\n}))<PositionedRowProps>`\n position: absolute;\n left: 0;\n right: 0;\n ${(props) => props.$animate && 'transition: top 150ms ease;'}\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\ninterface ControlSlotProps {\n readonly $height: number;\n readonly $top: number;\n readonly $animate: boolean;\n readonly $isSelected?: boolean;\n}\n\n/**\n * Height-synced container for each track's controls in the ControlsColumn.\n * Uses the same height formula as Track: waveHeight * numChannels + clipHeaderHeight.\n */\nexport const ControlSlot = styled.div.attrs<ControlSlotProps>((props) => ({\n style: {\n height: `${props.$height}px`,\n top: `${props.$top}px`,\n },\n}))<ControlSlotProps>`\n position: absolute;\n left: 0;\n right: 0;\n overflow: hidden;\n pointer-events: auto;\n background: ${(props) => props.theme.surfaceColor};\n transition: background 0.15s ease-in-out;\n ${(props) => props.$animate && 'transition: top 150ms ease, background 0.15s ease-in-out;'}\n @media (prefers-reduced-motion: reduce) {\n transition: background 0.15s ease-in-out;\n }\n ${(props) => props.$isSelected && `background: ${props.theme.selectedTrackControlsBackground};`}\n`;\n\n/**\n * The maximum channel count for a track, considering both clip peaks and a\n * live recording. `recordingChannels` is the channel count of the recording\n * into THIS track, 0 when it is not being recorded into. It is a number, not\n * the recording state object, so that track heights do not change identity on\n * every recording frame.\n */\nexport function getTrackChannelCount(\n trackClipPeaks: ClipPeaks[],\n recordingChannels: number\n): number {\n const clipChannels =\n trackClipPeaks.length > 0\n ? Math.max(1, ...trackClipPeaks.map((clip) => clip.peaks.data.length))\n : 1;\n return Math.max(clipChannels, recordingChannels);\n}\n","/**\n * What the two roots of the view share (#685): `WaveformRoot` (multitrack) and\n * `MediaElementWaveformRoot`. Internal: not exported from the package.\n *\n * A hook and not a component, so that it adds no component to either tree: a\n * root calls `useWaveformParts` on its children, works out what only its\n * provider knows (how long the timeline is, which rows there are and how tall),\n * and hands that to `useWaveformFrame`, which returns the scrolling frame with\n * the parts in their places.\n *\n * The frame reads shared hooks only (the view settings, the zoom, the playback\n * controls), so it runs under either provider.\n */\nimport React, {\n createElement,\n Fragment,\n useCallback,\n useMemo,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport {\n Playlist,\n PlaylistInfoContext,\n useTheme,\n waveformColorToCss,\n type PlaylistInfo,\n type WaveformPlaylistTheme,\n} from '@waveform-playlist/ui-components';\nimport {\n usePlaybackControls,\n usePlaylistView,\n usePlaylistZoom,\n} from '../contexts/playlistContexts';\nimport {\n useSelectionDrag,\n AutomaticScrollFlag,\n SelectionPreviewContext,\n type UseSelectionDragOptions,\n} from '../hooks/useSelectionDrag';\nimport {\n WaveformExtentContext,\n RootSeesRecordingPreviewContext,\n WaveformPartPlaceContext,\n WaveformRowsContext,\n type WaveformExtentValue,\n type WaveformRowsValue,\n} from './waveformLayoutContext';\nimport { sortWaveformParts, WaveformTimescale } from './waveformParts';\n\n/**\n * The parts of the timescale strip, each under a key made of its kind and\n * its number among that kind, so that one coming or going\n * (`{flag && <WaveformTimescale />}`) does not remount the others. The part\n * elements themselves are passed on untouched.\n */\nfunction keyedByKind(parts: ReactNode[]): ReactElement[] {\n const seen = { timescale: 0, loop: 0 };\n return parts.map((part) => {\n const kind =\n React.isValidElement(part) && part.type === WaveformTimescale ? 'timescale' : 'loop';\n return createElement(Fragment, { key: `${kind}-${seen[kind]++}` }, part);\n });\n}\nimport type { TracksMarkers } from './TrackRows';\nimport type { ResolvedViewOptions } from './WaveformViewOptions';\n\nexport interface WaveformPartsByPlace {\n /** The parts of the timescale strip in one element, or null when there is none. */\n timescale: ReactElement | null;\n /** The parts of the controls column, or undefined when there is none. */\n controls: ReactNode[] | undefined;\n /** Everything drawn in the scrolling tracks area, in order. */\n content: ReactElement;\n /** The per-clip parts the tracks part was given (all off without one). */\n tracksOptions: TracksMarkers;\n /** Width of the controls column the controls part asks for; 0 without one. */\n controlsWidth: number;\n /** Height of the timescale strip the timescale part asks for; 0 without a strip. */\n timescaleHeight: number;\n}\n\n/**\n * The root's children by place. The part elements are passed on as they were\n * given, never cloned: that is what lets React skip every part when the root\n * renders alone (same element, nothing to do). The memo only saves sorting\n * them again.\n */\nexport function useWaveformParts(children: ReactNode): WaveformPartsByPlace {\n return useMemo(() => {\n const sorted = sortWaveformParts(children);\n return {\n // One element per place. The tracks-area and controls parts are its\n // positional children (they carry no keys); the strip's parts are keyed\n // by kind (`keyedByKind`).\n timescale:\n sorted.timescale.length > 0 ? (\n <WaveformPartPlaceContext value=\"timescale\">\n {keyedByKind(sorted.timescale)}\n </WaveformPartPlaceContext>\n ) : null,\n controls:\n sorted.controls.length > 0\n ? [\n <WaveformPartPlaceContext key=\"controls\" value=\"controls\">\n {createElement(Fragment, null, ...sorted.controls)}\n </WaveformPartPlaceContext>,\n ]\n : undefined,\n content: createElement(Fragment, null, ...sorted.content),\n tracksOptions: sorted.tracksOptions,\n controlsWidth: sorted.controlsWidth,\n timescaleHeight: sorted.timescaleHeight,\n };\n }, [children]);\n}\n\nexport interface WaveformFrameOptions {\n className: string | undefined;\n /** From `useResolvedViewOptions()`; published here, memoized on its values, for everything drawn. */\n viewOptions: ResolvedViewOptions;\n parts: WaveformPartsByPlace;\n /** Length of the drawn timeline in seconds. */\n displayDuration: number;\n /** Memoized by the root: the tracks part and the controls part follow it. */\n rows: WaveformRowsValue;\n playlistState: 'ready' | 'loading';\n /** Width of the controls column in pixels; 0 draws none. */\n controlsWidth: number;\n /** Also told the scroll container (the frame registers it with the provider itself). Must be stable. */\n onScrollContainer?: (element: HTMLDivElement | null) => void;\n /** See `useSelectionDrag`. */\n onPress?: UseSelectionDragOptions['onPress'];\n onClickWhileStopped: UseSelectionDragOptions['onClickWhileStopped'];\n}\n\n/**\n * The scrolling frame with the parts in their places, the two layout values\n * and the selection drag. Returns two sibling elements in a fragment; the root\n * wraps them in its `DevicePixelRatioProvider`.\n *\n * It makes the calling root render on its own state (a drag in progress) and\n * on play and stop (the drag reads `isPlaying`), on a zoom and on a change of\n * the view settings or the theme. None of that renders a part by itself: both\n * layout values are memoized, and the part elements are the root's children.\n */\nexport function useWaveformFrame({\n className,\n viewOptions,\n parts,\n displayDuration,\n rows,\n playlistState,\n controlsWidth,\n onScrollContainer,\n onPress,\n onClickWhileStopped,\n}: WaveformFrameOptions): ReactElement {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { setScrollContainer } = usePlaybackControls();\n const { sampleRate } = usePlaylistView();\n const { waveHeight, barWidth, barGap, roundedBars, progressBarWidth } = viewOptions;\n // The strip exists when a part is drawn in it: rendering the timescale (or\n // the loop region) is the one switch, and the timescale part says how tall.\n const timeScaleHeight = parts.timescaleHeight;\n const { samplesPerPixel } = usePlaylistZoom();\n\n const handleScrollContainerRef = useCallback(\n (element: HTMLDivElement | null) => {\n onScrollContainer?.(element);\n setScrollContainer(element);\n },\n [onScrollContainer, setScrollContainer]\n );\n\n const tracksFullWidth = Math.floor((displayDuration * sampleRate) / samplesPerPixel);\n\n const {\n isSelecting,\n handleMouseDown,\n preview: selectionPreview,\n automaticScrollRef,\n } = useSelectionDrag({ samplesPerPixel, sampleRate, onPress, onClickWhileStopped });\n\n // The one publication of what a view draws with (#689): the options of\n // `<WaveformViewOptions>`, resolved by the root, with the zoom, the sample\n // rate and the strip height. Memoized so that its readers (every channel,\n // the timescale, the playhead) are not re-rendered by a render of the root\n // that changed none of it.\n const playlistInfo = useMemo<PlaylistInfo>(\n () => ({\n samplesPerPixel,\n sampleRate,\n waveHeight,\n timeScaleHeight,\n barWidth,\n barGap,\n roundedBars,\n progressBarWidth,\n }),\n [\n samplesPerPixel,\n sampleRate,\n waveHeight,\n timeScaleHeight,\n barWidth,\n barGap,\n roundedBars,\n progressBarWidth,\n ]\n );\n\n const extent = useMemo<WaveformExtentValue>(\n () => ({ displayDuration, tracksFullWidth }),\n [displayDuration, tracksFullWidth]\n );\n\n return (\n <>\n <AutomaticScrollFlag flagRef={automaticScrollRef} />\n <PlaylistInfoContext value={playlistInfo}>\n <WaveformExtentContext value={extent}>\n <WaveformRowsContext value={rows}>\n <RootSeesRecordingPreviewContext\n value={parts.tracksOptions.recordingState !== undefined}\n >\n <SelectionPreviewContext value={selectionPreview}>\n <Playlist\n className={className}\n theme={theme}\n backgroundColor={\n theme.playlistBackgroundColor || waveformColorToCss(theme.waveOutlineColor)\n }\n timescaleBackgroundColor={theme.timescaleBackgroundColor}\n timescaleWidth={tracksFullWidth}\n tracksWidth={tracksFullWidth}\n controlsWidth={controlsWidth}\n onTracksMouseDown={handleMouseDown}\n scrollContainerRef={handleScrollContainerRef}\n isSelecting={isSelecting}\n data-playlist-state={playlistState}\n trackControlsSlots={parts.controls}\n timescaleGapHeight={timeScaleHeight > 0 ? timeScaleHeight + 1 : 0}\n timescale={parts.timescale ?? undefined}\n >\n {parts.content}\n </Playlist>\n </SelectionPreviewContext>\n </RootSeesRecordingPreviewContext>\n </WaveformRowsContext>\n </WaveformExtentContext>\n </PlaylistInfoContext>\n </>\n );\n}\n","import { createContext, memo, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { createValueSource, type ValueSource } from '@waveform-playlist/core';\nimport {\n useIsPlaying,\n usePlaybackControls,\n usePlaylistSettings,\n} from '../contexts/playlistContexts';\nimport { useWindowDrag, clampedOffsetX } from './useWindowDrag';\n\n/** A time range in seconds, `start` before `end`. */\nexport interface SelectionRange {\n start: number;\n end: number;\n}\n\n/**\n * The range being drawn by a drag DURING PLAYBACK, or `null`. It is not the\n * selection yet: it becomes one when the button is released. Published by the\n * view that owns the drag (`useSelectionDrag`) and read by the selection\n * highlight, which shows it in place of the selection while it is set.\n *\n * A source and not state: it changes on every pointer move, and only the\n * highlight should follow it. Internal: not exported from the package.\n */\nexport const SelectionPreviewContext = createContext<ValueSource<SelectionRange | null> | null>(\n null\n);\n\n/** A range shorter than this, in seconds, is a click. */\nconst MIN_RANGE_SECONDS = 0.1;\n\nexport interface UseSelectionDragOptions {\n samplesPerPixel: number;\n sampleRate: number;\n /**\n * Called for every primary-button press, before the drag begins, with the\n * time under the pointer, the pointer's offset from the top of the pressed\n * element, and whether playback is running.\n */\n onPress?: (press: { time: number; offsetY: number; isPlaying: boolean }) => void;\n /** What a click (no drag) does with its time while playback is stopped. */\n onClickWhileStopped: (time: number) => void;\n}\n\nexport interface SelectionDrag {\n /** True from the press to the release. */\n isSelecting: boolean;\n /** For the `mousedown` of the element the drag starts on (the click overlay). */\n handleMouseDown: (event: React.MouseEvent<HTMLDivElement>) => void;\n /** For `<SelectionPreviewContext value>`. The same object for the life of the component. */\n preview: ValueSource<SelectionRange | null>;\n /** For `<AutomaticScrollFlag flagRef>`, which the caller must render (`useWaveformFrame` does). */\n automaticScrollRef: React.RefObject<boolean>;\n}\n\n/**\n * Keeps `flagRef` equal to the provider's automatic-scroll setting. Renders\n * nothing.\n *\n * The drag needs the setting only when an event arrives. Read with\n * `usePlaylistSettings()` in a root of the view, a toggle of the setting would\n * render that root and its frame for a value they never draw. This component\n * is the one that follows the setting; the frame renders it and nothing else\n * changes.\n * A layout effect: only a committed value, and in place before any event that\n * follows the commit. Memoized: its one prop is a ref that never changes, so a\n * render of the view does not render it.\n */\nexport const AutomaticScrollFlag = memo(function AutomaticScrollFlag({\n flagRef,\n}: {\n flagRef: React.RefObject<boolean>;\n}) {\n const { isAutomaticScroll } = usePlaylistSettings();\n useLayoutEffect(() => {\n flagRef.current = isAutomaticScroll;\n });\n return null;\n});\n\n/**\n * The selection drag of a waveform view, the same under either provider.\n *\n * **While playback is stopped** the selection follows the pointer: the press\n * collapses it at the pressed time, every move sets the ordered range from\n * the press to the pointer, and the release leaves that range (or, for a\n * click, calls `onClickWhileStopped`).\n *\n * **While playback is running nothing is committed before the release.**\n * `setSelection` restarts a running play, so writing the selection on the\n * press and on each move would restart playback under the pointer; until\n * 2026-11 the press did exactly that, moves were ignored, and no range could\n * be drawn during playback. Now the press changes nothing and the release\n * calls `setSelection` once. What the release commits depends on the\n * automatic scroll (maintainer's rules, 2026-11-12):\n *\n * - **Automatic scroll off:** the moves publish the range to `preview` (the\n * highlight shows it, playback carries on). The release sets that range,\n * which the provider plays from its start to its end (open-ended under the\n * multitrack provider with looping on); a range shorter than 0.1 s is not\n * previewed and is a click: playback moves to where the press landed.\n * - **Automatic scroll on:** no range can be drawn. The view scrolls to keep\n * the playhead in sight, so the audio moves under a still pointer and the\n * time under it at the release is not the time at the press. A press and\n * its release are one seek, to the time captured at the press, however far\n * the pointer travelled; moves are ignored.\n *\n * The drag is followed on the window (`useWindowDrag`): the pointer may leave\n * the element and the button may be released anywhere; positions outside it\n * clamp to its ends. When the drag ends with no release (the window lost\n * focus, or the `mouseup` was lost), a preview is dropped and playback is untouched; while stopped the\n * selection stays as the last move left it.\n *\n * A press made while playing whose release comes after playback has stopped\n * follows the stopped rules at the release. With the pointer under 0.1 s from\n * the press it is a click that collapses the selection at the press (the\n * press itself did not, because playback was running); further away, the\n * range becomes the selection, unplayed.\n */\nexport function useSelectionDrag({\n samplesPerPixel,\n sampleRate,\n onPress,\n onClickWhileStopped,\n}: UseSelectionDragOptions): SelectionDrag {\n const { isPlaying } = useIsPlaying();\n const { setSelection } = usePlaybackControls();\n const [isSelecting, setIsSelecting] = useState(false);\n // Kept current by <AutomaticScrollFlag>, read only inside the handlers.\n const automaticScrollRef = useRef(false);\n\n const previewHandle = useMemo(() => createValueSource<SelectionRange | null>(null), []);\n // The time under the pointer where the drag began.\n const pressTimeRef = useRef(0);\n // This drag has written the selection (the press while stopped, or a move\n // while stopped). False for a drag that has so far only run during playback.\n const wroteSelectionRef = useRef(false);\n // The element the drag began on, for pointer positions while the pointer is\n // somewhere else.\n const dragElementRef = useRef<HTMLDivElement | null>(null);\n\n const timeAt = (clientX: number): number | null => {\n const element = dragElementRef.current;\n const x = element ? clampedOffsetX(element, clientX) : null;\n return x === null ? null : (x * samplesPerPixel) / sampleRate;\n };\n\n /** From where the press landed to `time`, in order. The anchor is the press,\n * never the selection's start: that stops being the anchor as soon as the\n * pointer passes to the left of it (#733). */\n const rangeTo = (time: number): SelectionRange => ({\n start: Math.min(pressTimeRef.current, time),\n end: Math.max(pressTimeRef.current, time),\n });\n\n const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {\n // Primary button only: a right-click opens the context menu and its\n // release may never be delivered.\n if (event.button !== 0) return;\n const rect = event.currentTarget.getBoundingClientRect();\n // Never before the start of the timeline, whatever the event says.\n const time = Math.max(0, ((event.clientX - rect.left) * samplesPerPixel) / sampleRate);\n\n onPress?.({ time, offsetY: event.clientY - rect.top, isPlaying });\n\n pressTimeRef.current = time;\n dragElementRef.current = event.currentTarget;\n setIsSelecting(true);\n wroteSelectionRef.current = !isPlaying;\n if (!isPlaying) setSelection(time, time);\n };\n\n const handleDragMove = (event: MouseEvent) => {\n if (isPlaying && automaticScrollRef.current) {\n // Also when the setting was switched on under a drag that had already\n // drawn a range: it is withdrawn.\n previewHandle.publish(null);\n return;\n }\n const moveTime = timeAt(event.clientX);\n if (moveTime === null) return;\n const range = rangeTo(moveTime);\n\n if (isPlaying) {\n previewHandle.publish(range.end - range.start < MIN_RANGE_SECONDS ? null : range);\n return;\n }\n\n // Stopped. Also reached when playback stopped (or ended) under a drag\n // that began while it ran: from here it is an ordinary drag.\n previewHandle.publish(null);\n wroteSelectionRef.current = true;\n setSelection(range.start, range.end);\n };\n\n const handleDragEnd = (event: MouseEvent | null) => {\n setIsSelecting(false);\n previewHandle.publish(null);\n\n // The window lost focus mid-drag: there is no release position.\n if (event === null) return;\n\n // Where the press landed: what a click during playback seeks to.\n const pressTime = pressTimeRef.current;\n\n if (isPlaying && automaticScrollRef.current) {\n setSelection(pressTime, pressTime);\n return;\n }\n\n const endTime = timeAt(event.clientX);\n if (endTime === null) return;\n const range = rangeTo(endTime);\n const isClick = range.end - range.start < MIN_RANGE_SECONDS;\n\n if (isPlaying) {\n if (isClick) setSelection(pressTime, pressTime);\n else setSelection(range.start, range.end);\n return;\n }\n\n if (!isClick) {\n setSelection(range.start, range.end);\n } else if (wroteSelectionRef.current) {\n onClickWhileStopped(range.start);\n } else {\n // Pressed while playing, and playback has stopped since: the press did\n // not collapse the selection, so the click does (an older highlighted\n // range would otherwise stay selected, and Play would play it).\n setSelection(pressTime, pressTime);\n }\n };\n\n useWindowDrag(isSelecting, handleDragMove, handleDragEnd);\n\n return { isSelecting, handleMouseDown, preview: previewHandle.source, automaticScrollRef };\n}\n","import { useEffect, useLayoutEffect, useRef } from 'react';\n\n// Page text selection is switched off while any drag is active. Counted, so\n// that two components dragging at once cannot restore each other's 'none'.\nlet activeDrags = 0;\nlet userSelectBeforeDrags = '';\n// Safari only knows the prefixed property.\nlet webkitUserSelectBeforeDrags = '';\n\nfunction suspendTextSelection(): () => void {\n const root = document.documentElement;\n if (activeDrags === 0) {\n userSelectBeforeDrags = root.style.userSelect;\n webkitUserSelectBeforeDrags = root.style.webkitUserSelect;\n root.style.userSelect = 'none';\n root.style.webkitUserSelect = 'none';\n }\n activeDrags++;\n return () => {\n activeDrags--;\n if (activeDrags === 0) {\n root.style.userSelect = userSelectBeforeDrags;\n root.style.webkitUserSelect = webkitUserSelectBeforeDrags;\n }\n };\n}\n\n/**\n * Follows a mouse drag that began on an element for as long as the primary\n * button is held, wherever the pointer goes.\n *\n * An element's own `mousemove` / `mouseup` handlers stop running when the\n * pointer leaves it, so a drag tracked with them stalls outside the element\n * and, after a release outside, stays \"active\" with no button held. While\n * `active`, this listens on the window instead (capture phase, so a\n * `stopPropagation()` elsewhere on the page cannot hide the release):\n *\n * - `onMove` for every `mousemove` with the primary button held;\n * - `onEnd` for the primary button's `mouseup`, with the event;\n * - `onEnd(null)` when the drag ended without a release position: the window\n * lost focus (`blur`: the `mouseup` goes to another application), or a move\n * arrives with the primary button no longer held (the `mouseup` was lost).\n *\n * Text selection on the page is switched off while `active`.\n *\n * The caller starts the drag in its `onMouseDown` (primary button only) and\n * sets `active` false in `onEnd`. The latest callbacks are called; changing\n * them does not re-subscribe.\n */\nexport function useWindowDrag(\n active: boolean,\n onMove: (event: MouseEvent) => void,\n onEnd: (event: MouseEvent | null) => void\n): void {\n const callbacksRef = useRef({ onMove, onEnd });\n // Layout effect: the callbacks of a render are in place before any event\n // that follows its commit.\n useLayoutEffect(() => {\n callbacksRef.current = { onMove, onEnd };\n });\n\n useEffect(() => {\n if (!active) return;\n const move = (event: MouseEvent) => {\n if ((event.buttons & 1) === 0) {\n callbacksRef.current.onEnd(null);\n return;\n }\n callbacksRef.current.onMove(event);\n };\n const up = (event: MouseEvent) => {\n // Another button released while the primary one is still held.\n if (event.button !== 0) return;\n callbacksRef.current.onEnd(event);\n };\n const blur = () => callbacksRef.current.onEnd(null);\n // The press began on the element, so the browser would extend a text\n // selection across the page as the pointer travels over it. Switched off\n // for the length of the drag only (not with `preventDefault` on the press,\n // which would also stop the press from taking focus off a focused control).\n const resumeTextSelection = suspendTextSelection();\n window.addEventListener('mousemove', move, true);\n window.addEventListener('mouseup', up, true);\n window.addEventListener('blur', blur);\n return () => {\n resumeTextSelection();\n window.removeEventListener('mousemove', move, true);\n window.removeEventListener('mouseup', up, true);\n window.removeEventListener('blur', blur);\n };\n }, [active]);\n}\n\n/**\n * The horizontal position of a pointer inside `element`, in pixels from its\n * left edge, clamped to the element: a pointer to the left of it gives 0, one\n * to the right gives its width. `null` when the element is no longer in the\n * document (its rectangle would be all zeros).\n */\nexport function clampedOffsetX(element: Element, clientX: number): number | null {\n if (!element.isConnected) return null;\n const rect = element.getBoundingClientRect();\n return Math.min(Math.max(clientX - rect.left, 0), rect.width);\n}\n","/**\n * What a root of the view works out once and its parts read\n * (#685). Internal: not exported from the package.\n *\n * Two values, by what changes them. The extent changes with the timeline's\n * length and the zoom; the rows value changes with every clip edit (it holds\n * one `{ id, kind }` per track and their peaks, and the row heights follow from them). The timescale, the loop region and the\n * annotation row read the extent only, so a trim that leaves the length alone\n * does not render them.\n */\nimport { createContext, use } from 'react';\nimport type { RenderMode, TrackKind } from '@waveform-playlist/core';\nimport type { TrackClipPeaks } from '../WaveformPlaylistContext';\nimport type { TrackLayout } from '../utils/trackOrderPreview';\nimport type { SpectrogramTrackHelpers } from './TrackRows';\n\nexport interface WaveformExtentValue {\n /** Length of the drawn timeline in seconds (at least the audio's). */\n displayDuration: number;\n /** The same length in pixels at the current zoom. */\n tracksFullWidth: number;\n}\n\n/** What the view needs to know of a track to draw its row. */\nexport interface WaveformRow {\n id: string;\n kind: TrackKind;\n}\n\nexport interface WaveformRowsValue {\n /**\n * One entry per row, in timeline order, and the peaks of each (same index),\n * as the root read them from its provider. The parts take them from here and\n * do not read a provider's track value themselves: the multitrack timeline\n * value also changes with things no part draws (`isReady`), and a part that\n * read it would render for those too;\n * and no part then needs a hook only one provider serves.\n */\n rows: ReadonlyArray<WaveformRow>;\n peaksDataArray: TrackClipPeaks[];\n showClipHeaders: boolean;\n trackHeightById: ReadonlyMap<string, number>;\n trackLayout: TrackLayout;\n animateTrackLayout: boolean;\n /** Render mode per track id (spectrogram override, else the track's own). */\n renderModeById: ReadonlyMap<string, RenderMode>;\n spectrogramHelpersById: ReadonlyMap<string, SpectrogramTrackHelpers>;\n /** Stable: reads the tracks through a ref. */\n selectTrack: (trackIndex: number) => void;\n /** Opens the spectrogram settings of a track (the modal is the root's). */\n setSettingsModalTrackId: (id: string | null) => void;\n /** Channels of the take being recorded (already 1 when `mono`), else 0. */\n recordingChannelCount: number;\n /** The row being dragged to a new position, else null. */\n dragSourceTrackId: string | null;\n}\n\n/**\n * Where in the root a part is being rendered: the timescale strip, the\n * controls column, or the scrolling tracks area (the default: everything the\n * root does not recognise lands there). Read only for the development\n * warning of a part that ended up in the wrong place, which happens when it\n * is wrapped in another component: the root sorts its children by type.\n */\nexport type WaveformPartPlace = 'timescale' | 'controls' | 'tracks';\nexport const WaveformPartPlaceContext = createContext<WaveformPartPlace>('tracks');\n\n/**\n * Whether the root found a recording-preview marker in its tracks part. Read\n * by the tracks part alone, for the development warning of a tracks part the\n * root cannot see into (one wrapped in another component). A value of its own\n * and not a field of the rows value: the controls part reads that one, and\n * must not render because the marker came or went.\n */\nexport const RootSeesRecordingPreviewContext = createContext(false);\n\nexport const WaveformExtentContext = createContext<WaveformExtentValue | null>(null);\nexport const WaveformRowsContext = createContext<WaveformRowsValue | null>(null);\n\nfunction required<T>(value: T | null, part: string): T {\n if (value === null) {\n throw new Error(`${part} must be rendered inside the waveform root`);\n }\n return value;\n}\n\nexport const useWaveformExtent = (part: string) => required(use(WaveformExtentContext), part);\nexport const useWaveformRows = (part: string) => required(use(WaveformRowsContext), part);\n","/**\n * The parts of the view (#685), exported from the package: a consumer\n * composes them inside `WaveformRoot` (or, the ones its provider can serve,\n * inside `MediaElementWaveformRoot`). `Waveform`, `WaveformEditor` and\n * `MediaElementWaveform` are ready-made compositions of them.\n *\n * A part reads what it draws from the provider's contexts and from the root's\n * two layout values (waveformLayoutContext.ts); its props are the options of\n * that part alone. The root sorts its children into the three places a\n * playlist has (the timescale strip, the controls column, the scrolling\n * tracks area) by part type, see `sortWaveformParts`.\n *\n * A part is the component that draws, not a wrapper that forwards to one:\n * the tracks part is in TrackRows.tsx, the controls in\n * TrackControlsColumn.tsx, the overlays in VisualizationOverlays.tsx. The\n * parts with no children are memoized, except the playhead: the component\n * that composes them usually re-renders with the tracks (it holds them), and\n * a part whose props did not change should not follow.\n */\nimport React, { use, type ReactNode } from 'react';\nimport { SmartScale } from '@waveform-playlist/ui-components';\nimport {\n WaveformTracks,\n scanTracksParts,\n type TracksMarkers,\n type WaveformTracksProps,\n} from './TrackRows';\nimport {\n DEFAULT_TRACK_CONTROLS_WIDTH,\n WaveformTrackControls,\n type WaveformTrackControlsProps,\n} from './TrackControlsColumn';\nimport { WaveformLoopRegion } from './VisualizationOverlays';\nimport { useWaveformExtent, WaveformPartPlaceContext } from './waveformLayoutContext';\nimport { warnMisplacedPart } from './partWarnings';\nimport { WaveformViewOptions } from './WaveformViewOptions';\n\nexport {\n WaveformTracks,\n WaveformClipHeaders,\n WaveformFades,\n WaveformRecordingPreview,\n scanTracksParts,\n} from './TrackRows';\nexport { WaveformTrackControls } from './TrackControlsColumn';\n\nexport interface WaveformTimescaleProps {\n /** Custom tick label. `label` is already formatted for the scale mode. */\n renderTick?: (label: string, pixelPosition: number) => ReactNode;\n /**\n * Height in pixels of the timescale strip. The root reads it from the\n * element, as it reads the width of the controls part: the strip is the\n * root's own, above the scrolling area. Default: 30\n */\n height?: number;\n}\n\n/** Height in pixels of the timescale strip when the timescale part gives none. */\nexport const DEFAULT_TIMESCALE_HEIGHT = 30;\n\n/** The time ruler, as long as the root's timeline. */\nexport const WaveformTimescale = React.memo(function WaveformTimescale({\n renderTick,\n}: WaveformTimescaleProps) {\n // `height` is read by the root (`sortWaveformParts`), which draws the strip.\n const { displayDuration } = useWaveformExtent('The timescale');\n if (use(WaveformPartPlaceContext) !== 'timescale') {\n warnMisplacedPart(\n '<WaveformTimescale> is drawn among the tracks, not in the timescale strip: the root ' +\n 'recognises a part by its element type, so it must be a child of the root (a fragment ' +\n 'is fine), not wrapped in another component.'\n );\n }\n return <SmartScale durationMs={displayDuration * 1000} renderTick={renderTick} />;\n});\n\nexport { WaveformLoopRegion, WaveformPlayhead, WaveformSelection } from './VisualizationOverlays';\n\nexport interface SortedWaveformParts {\n /** Drawn in the timescale strip, in order. */\n timescale: ReactNode[];\n /** Drawn in the controls column, in order. */\n controls: ReactNode[];\n /**\n * Drawn in the scrolling tracks area, in order: one entry per child, `null`\n * for a child that is drawn elsewhere or not at all.\n */\n content: ReactNode[];\n /** The per-clip parts of the tracks part (all off when there is none). */\n tracksOptions: TracksMarkers;\n /** Width of the controls column in pixels, from the controls part; 0 without one. */\n controlsWidth: number;\n /** Height of the timescale strip in pixels, from the timescale part; 0 without a strip. */\n timescaleHeight: number;\n}\n\nconst TIMESCALE_PARTS: ReadonlySet<unknown> = new Set([WaveformTimescale, WaveformLoopRegion]);\nconst CONTROLS_PARTS: ReadonlySet<unknown> = new Set([WaveformTrackControls]);\n\n/**\n * Sorts the root's children into the places a playlist has. Fragments are\n * looked through; anything that is not a known part (the consumer's own\n * element, or a part wrapped in another component) goes to the tracks area.\n *\n * The elements are returned as they were given (no clone, no new key), so a\n * render of the root that received the same children hands React the same\n * elements and the parts are skipped. Call it from a `useMemo` on `children`.\n * The elements have no keys of their own: render the tracks-area and controls\n * lists as the children of one element (spread, not an array), and give the\n * strip's parts a key by kind (`useWaveformParts` does both).\n */\nexport function sortWaveformParts(children: ReactNode): SortedWaveformParts {\n const sorted: SortedWaveformParts = {\n timescale: [],\n controls: [],\n content: [],\n tracksOptions: { showClipHeaders: false, showFades: false, recordingState: undefined },\n controlsWidth: 0,\n timescaleHeight: 0,\n };\n let timescaleHeightGiven = false;\n let tracksParts = 0;\n const visit = (node: ReactNode) => {\n React.Children.forEach(node, (child) => {\n if (React.isValidElement(child)) {\n if (child.type === React.Fragment) {\n visit((child.props as { children?: ReactNode }).children);\n return;\n }\n if (TIMESCALE_PARTS.has(child.type)) {\n // The first timescale part says how tall the strip is; a strip that\n // holds only a loop region is the default height.\n if (child.type === WaveformTimescale && !timescaleHeightGiven) {\n timescaleHeightGiven = true;\n const { height } = child.props as WaveformTimescaleProps;\n // `null` (plain JavaScript) means \"not given\", like `undefined`.\n const given = height !== undefined && height !== null;\n if (given && !(height > 0)) {\n warnMisplacedPart(\n '<WaveformTimescale height> must be a positive number of pixels: ' +\n String(height) +\n ' is replaced by ' +\n DEFAULT_TIMESCALE_HEIGHT +\n '. Leave the part out to have no timescale.'\n );\n }\n sorted.timescaleHeight = given && height > 0 ? height : DEFAULT_TIMESCALE_HEIGHT;\n } else if (sorted.timescaleHeight === 0) {\n sorted.timescaleHeight = DEFAULT_TIMESCALE_HEIGHT;\n }\n sorted.timescale.push(child);\n sorted.content.push(null);\n return;\n }\n if (CONTROLS_PARTS.has(child.type)) {\n // The first controls part says how wide the column is.\n if (sorted.controls.length === 0) {\n const { width } = child.props as WaveformTrackControlsProps;\n // `null` (plain JavaScript) means \"not given\", like `undefined`.\n const given = width !== undefined && width !== null;\n if (given && !(width > 0)) {\n warnMisplacedPart(\n '<WaveformTrackControls width> must be a positive number of pixels: with ' +\n String(width) +\n ' no controls column is drawn. Leave the part out to have none.'\n );\n }\n // Not a positive number: no column, and 0 for whoever reads the width.\n sorted.controlsWidth = !given ? DEFAULT_TRACK_CONTROLS_WIDTH : width > 0 ? width : 0;\n }\n sorted.controls.push(child);\n sorted.content.push(null);\n return;\n }\n if (child.type === WaveformViewOptions) {\n // A root reads the options above itself: these do nothing for it,\n // and the parts inside them are wrapped, so not recognised either.\n warnMisplacedPart(\n '<WaveformViewOptions> inside a waveform root does nothing for that root: a root ' +\n 'reads the options above it. Put <WaveformViewOptions> around the root.'\n );\n }\n if (child.type === WaveformTracks) {\n tracksParts++;\n sorted.tracksOptions = scanTracksParts((child.props as WaveformTracksProps).children);\n }\n }\n // Every child keeps one position in the tracks area, also one that is\n // drawn elsewhere or not at all (`{flag && <Part />}`): the parts after\n // it are then not remounted when it comes or goes.\n // (`Children.forEach` already hands over `null` for `false` and `undefined`.)\n sorted.content.push(child);\n });\n };\n visit(children);\n if (sorted.controls.length > 1) {\n warnMisplacedPart(\n 'A waveform root has more than one <WaveformTrackControls>: each draws a panel for every ' +\n 'track in the one controls column, which is as wide as the first says.'\n );\n }\n if (tracksParts > 1) {\n warnMisplacedPart(\n 'A waveform root has more than one <WaveformTracks>: each draws every row, and the row ' +\n 'heights follow the per-clip parts of the last one.'\n );\n }\n return sorted;\n}\n","import React, {\n createContext,\n useCallback,\n use,\n useMemo,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { warnMisplacedPart } from './partWarnings';\nimport {\n Track as TrackComponent,\n Clip,\n ClipPlaceholderBody,\n SpectrogramLabels,\n useTheme,\n usePlaylistInfo,\n waveformColorToCss,\n type WaveformPlaylistTheme,\n} from '@waveform-playlist/ui-components';\nimport {\n resolveRecordingOffsetSamples,\n type Peaks,\n type RenderMode,\n type TrackKind,\n type SpectrogramConfig,\n} from '@waveform-playlist/core';\nimport { type ClipPeaks, type TrackClipPeaks } from '../WaveformPlaylistContext';\nimport {\n useEngineRefs,\n usePlaylistView,\n usePlaylistZoom,\n useSelectedRow,\n} from '../contexts/playlistContexts';\nimport {\n SpectrogramIntegrationContext,\n type SpectrogramIntegration,\n} from '../SpectrogramIntegrationContext';\nimport {\n RootSeesRecordingPreviewContext,\n useWaveformExtent,\n useWaveformRows,\n} from './waveformLayoutContext';\nimport { useClipInteraction } from '../contexts/ClipInteractionContext';\nimport { usePreviewedClipPeaks } from '../hooks/useTrimPreviewView';\nimport { ChannelWithProgress } from './ChannelWithProgress';\nimport {\n TrackRowPositioner,\n TracksLayout,\n getTrackChannelCount,\n type WaveformRecordingState,\n} from './visualizationLayout';\n\ntype FrequencyScaleFn = (f: number, minF: number, maxF: number) => number;\n\n/**\n * What every clip of the view is drawn with and no row uses: set once by the\n * tracks part, read by each clip (#685). A context and not props, so the\n * options do not travel through the row. The value changes only when one of\n * its fields does (a per-clip part comes or goes, the spectrogram integration\n * changes), and then every clip renders, as it must.\n */\ninterface ClipDisplayValue {\n gainScaledWaveforms: boolean;\n showFades: boolean;\n selectTrack: (trackIndex: number) => void;\n registerSpectrogramCanvas: SpectrogramIntegration['registerSpectrogramCanvas'] | undefined;\n unregisterSpectrogramCanvas: SpectrogramIntegration['unregisterSpectrogramCanvas'] | undefined;\n}\n\nconst ClipDisplayContext = createContext<ClipDisplayValue | null>(null);\n\n/** What a row uses itself and hands each of its clips. */\ninterface RowDisplayOptions {\n samplesPerPixel: number;\n sampleRate: number;\n showClipHeaders: boolean;\n}\n\ninterface ClipViewProps extends RowDisplayOptions {\n clip: ClipPeaks;\n trackId: string;\n trackIndex: number;\n clipIndex: number;\n isSelected: boolean;\n renderMode: RenderMode;\n}\n\n/**\n * One clip with its channels.\n *\n * Memoized (#693): `clip` keeps its identity while nothing about the clip\n * changed (see utils/derivePeaks.ts) and everything else is a primitive or a\n * stable callback, so an edit to one clip re-renders that clip only. Each\n * `Clip` runs three `useDraggable` hooks, which is what made re-rendering all\n * of them per pointer move expensive. While a trim of this clip is dragged it\n * also follows the trim preview, and draws the previewed geometry (#812); a\n * move of that drag renders this clip's view and no other. Its spectrogram\n * canvases register with the range drawn, so the spectrogram follows too.\n */\nconst ClipView = React.memo(function ClipView({\n clip: committedClip,\n trackId,\n trackIndex,\n clipIndex,\n isSelected,\n renderMode,\n samplesPerPixel,\n sampleRate,\n showClipHeaders,\n}: ClipViewProps) {\n // Always present: a clip is only ever rendered by the tracks part.\n const {\n gainScaledWaveforms,\n showFades,\n selectTrack,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n } = use(ClipDisplayContext) as ClipDisplayValue;\n // The one source of both options (#690): set by `ClipInteractionProvider`\n // or `ClipInteractionOptions` above, never passed down as props.\n const { enabled: interactiveClips, touchOptimized } = useClipInteraction();\n const clip = usePreviewedClipPeaks(committedClip, trackId);\n const peaksData = clip.peaks;\n const width = peaksData.length;\n // A placeholder with no peaks (only its duration is known) has nothing\n // for its channels to draw: its body shows the clip's extent, also in a\n // view without clip headers. A placeholder drawn from peaks gets none.\n const drawsBody = clip.isPlaceholder && width === 0;\n\n // Pressing a clip selects its track, except when the press starts a drag.\n const handleMouseDown = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n const target = e.target as HTMLElement;\n if (target.closest('[role=\"button\"][aria-roledescription=\"draggable\"]')) {\n return;\n }\n selectTrack(trackIndex);\n },\n [selectTrack, trackIndex]\n );\n\n return (\n <Clip\n clipId={clip.clipId}\n trackIndex={trackIndex}\n clipIndex={clipIndex}\n trackName={clip.trackName}\n startSample={clip.startSample}\n durationSamples={clip.durationSamples}\n samplesPerPixel={samplesPerPixel}\n showHeader={showClipHeaders}\n disableHeaderDrag={!interactiveClips}\n isPlaceholder={clip.isPlaceholder}\n isSelected={isSelected}\n trackId={trackId}\n fadeIn={clip.fadeIn}\n fadeOut={clip.fadeOut}\n sampleRate={sampleRate}\n showFades={showFades}\n touchOptimized={touchOptimized}\n onMouseDown={handleMouseDown}\n >\n {drawsBody && <ClipPlaceholderBody isSelected={isSelected} />}\n {peaksData.data.map((channelPeaks: Peaks, channelIndex: number) => (\n <ChannelWithProgress\n key={`${clip.clipId}-${channelIndex}`}\n index={channelIndex}\n data={channelPeaks}\n bits={peaksData.bits}\n length={width}\n isSelected={isSelected}\n gain={gainScaledWaveforms ? (clip.gain ?? 1) : 1}\n clipStartSample={clip.startSample}\n clipDurationSamples={clip.durationSamples}\n renderMode={renderMode}\n midiNotes={clip.midiNotes}\n clipSampleRate={clip.sampleRate}\n clipOffsetSeconds={\n clip.offsetSamples != null ? clip.offsetSamples / (clip.sampleRate || sampleRate) : 0\n }\n samplesPerPixel={samplesPerPixel}\n spectrogramClipId={clip.clipId}\n spectrogramOnCanvasRegister={registerSpectrogramCanvas}\n spectrogramOnCanvasUnregister={unregisterSpectrogramCanvas}\n // The range this clip is drawn for (the preview's while a trim of\n // it is dragged): its spectrogram canvases register with it.\n spectrogramOffsetSamples={clip.offsetSamples}\n spectrogramDurationSamples={clip.durationSamples}\n />\n ))}\n </Clip>\n );\n});\n\ninterface RecordingPreviewClipProps {\n recordingState: WaveformRecordingState;\n trackId: string;\n trackIndex: number;\n clipIndex: number;\n isSelected: boolean;\n samplesPerPixel: number;\n sampleRate: number;\n showClipHeaders: boolean;\n mono: boolean;\n}\n\n/**\n * The live preview of the take being recorded into a track.\n *\n * Strips leading-silence peaks so the visible preview matches audible content.\n * The recorder runs at real time, but the user's first reaction lands\n * ~outputLatency+lookAhead seconds into the buffer (they hadn't heard the\n * backing track yet). Without this, the playhead — which uses audible time —\n * would appear behind the right edge of the recorded waveform. Mirrors\n * useIntegratedRecording's finalization compensation (shared\n * `resolveRecordingOffsetSamples`) and dawcore's preview-skip pattern.\n * `getLookAhead()` reads from the same engine the playhead's animation loop\n * uses — keeps the two in lockstep.\n */\nconst RecordingPreviewClip: React.FC<RecordingPreviewClipProps> = ({\n recordingState,\n trackId,\n trackIndex,\n clipIndex,\n isSelected,\n samplesPerPixel,\n sampleRate,\n showClipHeaders,\n mono,\n}) => {\n const { getLookAhead, getOutputLatency } = useEngineRefs();\n // The one place that follows the take frame by frame (#695).\n // Called as methods (not destructured), so a source written as a class works.\n const source = recordingState.progress;\n const subscribe = useCallback((onChange: () => void) => source.subscribe(onChange), [source]);\n const getSnapshot = useCallback(() => source.getSnapshot(), [source]);\n const progress = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const durationSamples = Math.floor(progress.duration * sampleRate);\n\n const latencyOffsetSamples = resolveRecordingOffsetSamples({\n overrideSeconds: recordingState.latencyOffset,\n outputLatency: getOutputLatency(),\n lookAhead: getLookAhead(),\n sampleRate,\n });\n const latencyPixels = Math.floor(latencyOffsetSamples / samplesPerPixel);\n const skipPeakElements = latencyPixels * 2; // each pixel is a min/max pair\n const previewDuration = Math.max(0, durationSamples - latencyOffsetSamples);\n const previewChannels = (mono ? progress.peaks.slice(0, 1) : progress.peaks).map(\n (channelPeaks) =>\n skipPeakElements > 0 && skipPeakElements < channelPeaks.length\n ? channelPeaks.subarray(skipPeakElements)\n : channelPeaks\n );\n\n // Nothing to draw until the first peaks arrive.\n if (!(progress.peaks[0]?.length > 0)) return null;\n\n return (\n <Clip\n clipId=\"recording-preview\"\n trackIndex={trackIndex}\n clipIndex={clipIndex}\n trackName=\"Recording...\"\n startSample={recordingState.startSample}\n durationSamples={previewDuration}\n samplesPerPixel={samplesPerPixel}\n showHeader={showClipHeaders}\n disableHeaderDrag={true}\n isSelected={isSelected}\n trackId={trackId}\n >\n {previewChannels.map((channelPeaks, chIdx) => (\n <ChannelWithProgress\n key={`${trackId}-recording-${chIdx}`}\n index={chIdx}\n data={channelPeaks}\n bits={recordingState.bits}\n length={Math.floor(channelPeaks.length / 2)}\n isSelected={isSelected}\n clipStartSample={recordingState.startSample}\n clipDurationSamples={previewDuration}\n />\n ))}\n </Clip>\n );\n};\n\ninterface TrackRowProps extends RowDisplayOptions {\n trackId: string;\n trackIndex: number;\n trackClipPeaks: TrackClipPeaks;\n top: number;\n animate: boolean;\n width: number;\n isSelected: boolean;\n isDragSource: boolean;\n /** Audio or MIDI: a MIDI track is drawn as a piano roll. */\n kind: TrackKind;\n renderMode: RenderMode;\n numChannels: number;\n waveHeight: number;\n mono: boolean;\n /** Set only on the track being recorded into. */\n recordingState: WaveformRecordingState | undefined;\n /** Set only for a spectrogram track whose config asks for labels. */\n spectrogramConfig: SpectrogramConfig | undefined;\n frequencyScaleFn: FrequencyScaleFn | undefined;\n}\n\n/**\n * One track row: its background, spectrogram labels, clips and (while\n * recording into it) the live preview.\n *\n * Memoized (#693): `trackClipPeaks` keeps its identity while no clip of the\n * track changed, and the rest are primitives and stable callbacks.\n */\nconst TrackRow = React.memo(function TrackRow({\n trackId,\n trackIndex,\n trackClipPeaks,\n top,\n animate,\n width,\n isSelected,\n isDragSource,\n kind,\n renderMode,\n numChannels,\n waveHeight,\n mono,\n recordingState,\n spectrogramConfig,\n frequencyScaleFn,\n samplesPerPixel,\n sampleRate,\n showClipHeaders,\n}: TrackRowProps) {\n const theme = useTheme() as WaveformPlaylistTheme;\n\n return (\n <TrackRowPositioner\n $top={top}\n $animate={animate}\n data-track-row=\"\"\n data-track-id={trackId}\n data-track-kind={kind}\n data-selected={isSelected ? 'true' : undefined}\n data-track-drag-source={isDragSource ? 'true' : undefined}\n >\n <TrackComponent\n numChannels={numChannels}\n backgroundColor={\n kind === 'midi'\n ? theme.pianoRollBackgroundColor || '#1a1a2e'\n : waveformColorToCss(theme.waveOutlineColor)\n }\n offset={0}\n width={width}\n hasClipHeaders={showClipHeaders}\n trackId={trackId}\n isSelected={isSelected}\n >\n {renderMode !== 'waveform' && spectrogramConfig?.labels && frequencyScaleFn && (\n <SpectrogramLabels\n waveHeight={waveHeight}\n numChannels={numChannels}\n frequencyScaleFn={frequencyScaleFn}\n minFrequency={spectrogramConfig.minFrequency ?? 0}\n maxFrequency={spectrogramConfig.maxFrequency ?? sampleRate / 2}\n labelsColor={spectrogramConfig.labelsColor}\n labelsBackground={spectrogramConfig.labelsBackground}\n renderMode={renderMode as 'spectrogram' | 'both'}\n hasClipHeaders={showClipHeaders}\n />\n )}\n {trackClipPeaks.map((clip, clipIndex) => (\n <ClipView\n key={clip.clipId}\n clip={clip}\n trackId={trackId}\n trackIndex={trackIndex}\n clipIndex={clipIndex}\n isSelected={isSelected}\n renderMode={renderMode}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n showClipHeaders={showClipHeaders}\n />\n ))}\n {recordingState?.isRecording && (\n <RecordingPreviewClip\n key={`${trackId}-recording`}\n recordingState={recordingState}\n trackId={trackId}\n trackIndex={trackIndex}\n clipIndex={trackClipPeaks.length}\n isSelected={isSelected}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n showClipHeaders={showClipHeaders}\n mono={mono}\n />\n )}\n </TrackComponent>\n </TrackRowPositioner>\n );\n});\n\nexport interface SpectrogramTrackHelpers {\n colorLUT: Uint8Array;\n frequencyScaleFn: FrequencyScaleFn;\n config: SpectrogramConfig | undefined;\n}\n\nconst MARKER_OUTSIDE_TRACKS = (name: string) =>\n `<${name}> does nothing here: it must be a child of <WaveformTracks> (a fragment is fine), ` +\n 'not wrapped in another component and not a child of the root.';\n\n/**\n * Marker: clips get a header. With clip interaction enabled the header is also\n * what a clip is dragged by, and the trim handles come with it. It adds to the\n * height of every row, which is why the root must know of it before anything\n * is drawn: it renders nothing itself.\n */\nexport const WaveformClipHeaders: React.FC = () => {\n // A marker is read from the children of the tracks part and never rendered\n // there: when this runs, it was put somewhere else.\n warnMisplacedPart(MARKER_OUTSIDE_TRACKS('WaveformClipHeaders'));\n return null;\n};\n\n/** Marker: clips show their fade-in and fade-out curves. Renders nothing itself. */\nexport const WaveformFades: React.FC = () => {\n warnMisplacedPart(MARKER_OUTSIDE_TRACKS('WaveformFades'));\n return null;\n};\n\nexport interface WaveformRecordingPreviewProps {\n recordingState: WaveformRecordingState;\n}\n\n/**\n * Marker: the take being recorded is drawn into its track as it grows. The\n * preview clip is drawn by that track's row; this renders nothing itself.\n */\nexport const WaveformRecordingPreview: React.FC<WaveformRecordingPreviewProps> = () => {\n warnMisplacedPart(MARKER_OUTSIDE_TRACKS('WaveformRecordingPreview'));\n return null;\n};\n\nexport interface TracksMarkers {\n showClipHeaders: boolean;\n showFades: boolean;\n recordingState: WaveformRecordingState | undefined;\n}\n\n/**\n * Which per-clip parts are among the children of the tracks part. Looks\n * through fragments; a part wrapped in another component is not seen.\n */\nexport function scanTracksParts(children: ReactNode): TracksMarkers {\n const found: TracksMarkers = {\n showClipHeaders: false,\n showFades: false,\n recordingState: undefined,\n };\n const visit = (node: ReactNode) => {\n React.Children.forEach(node, (child) => {\n if (!React.isValidElement(child)) return;\n if (child.type === WaveformClipHeaders) found.showClipHeaders = true;\n else if (child.type === WaveformFades) found.showFades = true;\n else if (child.type === WaveformRecordingPreview) {\n found.recordingState = (child.props as WaveformRecordingPreviewProps).recordingState;\n } else if (child.type === React.Fragment) {\n visit((child.props as { children?: ReactNode }).children);\n } else {\n warnMisplacedPart(\n '<WaveformTracks> ignores a child that is not <WaveformClipHeaders>, <WaveformFades> or ' +\n '<WaveformRecordingPreview>. A marker wrapped in another component is not seen: ' +\n 'render it directly (a fragment is fine).'\n );\n }\n });\n };\n visit(children);\n return found;\n}\n\nexport interface WaveformTracksProps {\n /** Draw each clip's waveform scaled by its gain. */\n gainScaled?: boolean;\n /**\n * `WaveformClipHeaders`, `WaveformFades`, `WaveformRecordingPreview`: markers that\n * switch a per-clip part on. Nothing else is rendered from here.\n */\n children?: ReactNode;\n}\n\n/**\n * All track rows: the tracks part of the view (#685).\n *\n * It takes the rows, their peaks and the layout from the root's rows value\n * (not from a provider's track value, see waveformLayoutContext.ts) and the\n * selected row from a context both providers serve (`useSelectedRow`), so it\n * draws under either provider. It is\n * deliberately free of the time selection, the cursor and the annotation\n * state: those change on every pointer move of a selection drag and\n * throughout playback, and nothing in a track row depends on them. Read one\n * of them here and every row is back on that path (#693).\n *\n * It is not memoized: its children are new elements whenever the component\n * that composes the view renders. That costs this component's own render; the\n * rows below are memoized and get primitives, stable callbacks and the\n * identity-stable pieces of the peaks.\n */\nexport const WaveformTracks: React.FC<WaveformTracksProps> = ({ gainScaled = false, children }) => {\n const rows = useWaveformRows('The tracks');\n const { tracksFullWidth: width } = useWaveformExtent('The tracks');\n const { selectedTrackId } = useSelectedRow();\n const { sampleRate, mono } = usePlaylistView();\n // Published by the root from `<WaveformViewOptions>` (#689).\n const { waveHeight } = usePlaylistInfo();\n const { samplesPerPixel } = usePlaylistZoom();\n const spectrogram = use(SpectrogramIntegrationContext);\n const rootSeesRecordingPreview = use(RootSeesRecordingPreviewContext);\n const scanned = scanTracksParts(children);\n const { showFades, recordingState } = scanned;\n const {\n rows: rowList,\n peaksDataArray,\n dragSourceTrackId,\n trackLayout,\n renderModeById,\n spectrogramHelpersById,\n recordingChannelCount,\n } = rows;\n\n if (scanned.showClipHeaders !== rows.showClipHeaders) {\n warnMisplacedPart(\n '<WaveformTracks> and its root disagree about <WaveformClipHeaders>, so the rows have the ' +\n 'wrong height: the root reads the per-clip parts from a <WaveformTracks> that is its ' +\n 'own child (a fragment is fine), not one wrapped in another component, and from the ' +\n 'last one when there are several.'\n );\n }\n if ((recordingState !== undefined) !== rootSeesRecordingPreview) {\n warnMisplacedPart(\n '<WaveformTracks> and its root disagree about <WaveformRecordingPreview>, so the timeline ' +\n 'does not grow with the take: the root reads the per-clip parts from a <WaveformTracks> ' +\n 'that is its own child (a fragment is fine), not one wrapped in another component, and ' +\n 'from the last one when there are several.'\n );\n }\n const { selectTrack } = rows;\n const registerSpectrogramCanvas = spectrogram?.registerSpectrogramCanvas;\n const unregisterSpectrogramCanvas = spectrogram?.unregisterSpectrogramCanvas;\n const clipDisplay = useMemo<ClipDisplayValue>(\n () => ({\n gainScaledWaveforms: gainScaled,\n showFades,\n selectTrack,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n }),\n [gainScaled, showFades, selectTrack, registerSpectrogramCanvas, unregisterSpectrogramCanvas]\n );\n\n return (\n <ClipDisplayContext value={clipDisplay}>\n <TracksLayout $height={trackLayout.totalHeight}>\n {peaksDataArray.map((trackClipPeaks, trackIndex) => {\n const track = rowList[trackIndex];\n if (!track) return null;\n\n const isArmed =\n recordingState?.isRecording === true && recordingState.trackId === track.id;\n const recordingChannels = isArmed ? recordingChannelCount : 0;\n const helpers = spectrogramHelpersById.get(track.id);\n\n return (\n <TrackRow\n key={track.id}\n trackId={track.id}\n trackIndex={trackIndex}\n trackClipPeaks={trackClipPeaks}\n top={trackLayout.topById.get(track.id) ?? 0}\n animate={rows.animateTrackLayout}\n width={width}\n isSelected={track.id === selectedTrackId}\n isDragSource={track.id === dragSourceTrackId}\n kind={track.kind}\n renderMode={renderModeById.get(track.id) ?? 'waveform'}\n numChannels={getTrackChannelCount(trackClipPeaks, recordingChannels)}\n waveHeight={waveHeight}\n mono={mono}\n recordingState={isArmed ? recordingState : undefined}\n spectrogramConfig={helpers?.config}\n frequencyScaleFn={helpers?.frequencyScaleFn}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n showClipHeaders={rows.showClipHeaders}\n />\n );\n })}\n </TracksLayout>\n </ClipDisplayContext>\n );\n};\n","import React, { createContext, use, useMemo } from 'react';\n\n/** What the clips below are told about interaction. */\nexport interface ClipInteractionContextValue {\n /** Clips can be dragged and trimmed. */\n enabled: boolean;\n /**\n * Touch handling below: clips widen their trim handles, and a touch on an\n * annotation edge must be held (250 ms) before it drags.\n */\n touchOptimized: boolean;\n}\n\nconst NO_CLIP_INTERACTION: ClipInteractionContextValue = { enabled: false, touchOptimized: false };\n\nconst ClipInteractionContext = createContext<ClipInteractionContextValue>(NO_CLIP_INTERACTION);\n\nexport interface ClipInteractionOptionsProps {\n /** Clips below can be dragged and trimmed. Left out: inherited (false at the top). */\n enabled?: boolean;\n /**\n * Touch handling below: clips get wider trim handles, and a touch on an\n * annotation edge must be held (250 ms) before it drags, so a swipe is not\n * taken for a drag. Left out: inherited (false at the top).\n */\n touchOptimized?: boolean;\n children: React.ReactNode;\n}\n\n/**\n * The one source of the clip interaction options (#690). Every clip below\n * reads them from here; `<Waveform>` takes neither as a prop.\n *\n * `ClipInteractionProvider` renders this for you. Use it directly when you\n * wire up your own `DragDropProvider`, or nested inside a\n * `ClipInteractionProvider` to change one option for part of the tree: an\n * option you leave out keeps the value from above.\n */\nexport const ClipInteractionOptions: React.FC<ClipInteractionOptionsProps> = ({\n enabled: enabledProp,\n touchOptimized: touchOptimizedProp,\n children,\n}) => {\n const inherited = use(ClipInteractionContext);\n const enabled = enabledProp ?? inherited.enabled;\n const touchOptimized = touchOptimizedProp ?? inherited.touchOptimized;\n // Two booleans in, one object out: the value changes only when one of them\n // does, however often the parent renders.\n const value = useMemo(() => ({ enabled, touchOptimized }), [enabled, touchOptimized]);\n return <ClipInteractionContext value={value}>{children}</ClipInteractionContext>;\n};\n\n/** The options for the clip that calls it. */\nexport function useClipInteraction(): ClipInteractionContextValue {\n return use(ClipInteractionContext);\n}\n\n/** True when clips here can be dragged and trimmed. */\nexport function useClipInteractionEnabled(): boolean {\n return use(ClipInteractionContext).enabled;\n}\n","import React, { useId, useRef, useEffect } from 'react';\nimport styled from 'styled-components';\nimport {\n clipPixelWidth as computeClipPixelWidth,\n type MidiNoteData,\n} from '@waveform-playlist/core';\nimport {\n SmartChannel,\n type SmartChannelProps,\n useTheme,\n usePlaylistInfo,\n type WaveformPlaylistTheme,\n waveformColorToCss,\n} from '@waveform-playlist/ui-components';\nimport {\n useCurrentTime,\n usePlaylistView,\n usePlaylistZoom,\n usePlaybackRefs,\n useIsPlaying,\n} from '../contexts/playlistContexts';\n\nconst ChannelWrapper = styled.div`\n position: relative;\n`;\n\ninterface BackgroundProps {\n readonly $color: string;\n readonly $height: number;\n readonly $top: number;\n readonly $width: number;\n}\n\nconst Background = styled.div.attrs<BackgroundProps>((props) => ({\n style: {\n top: `${props.$top}px`,\n width: `${props.$width}px`,\n height: `${props.$height}px`,\n background: props.$color,\n },\n}))<BackgroundProps>`\n position: absolute;\n left: 0;\n z-index: 0;\n /* Force GPU compositing layer to prevent gradient flickering during scroll */\n transform: translateZ(0);\n backface-visibility: hidden;\n`;\n\ninterface ProgressOverlayProps {\n readonly $color: string;\n readonly $height: number;\n readonly $top: number;\n readonly $width: number;\n}\n\nconst ProgressOverlay = styled.div.attrs<ProgressOverlayProps>((props) => ({\n style: {\n top: `${props.$top}px`,\n height: `${props.$height}px`,\n width: `${props.$width}px`,\n background: props.$color,\n transform: 'scaleX(0)',\n },\n}))<ProgressOverlayProps>`\n position: absolute;\n left: 0;\n pointer-events: none;\n z-index: 1;\n transform-origin: left;\n /* scaleX changes are composite-only (GPU) — no layout reflow per frame */\n will-change: transform;\n`;\n\nconst ChannelContainer = styled.div`\n position: relative;\n z-index: 2;\n`;\n\nexport interface ChannelWithProgressProps extends SmartChannelProps {\n /** Start sample of the clip containing this channel (for progress calculation) */\n clipStartSample: number;\n /** Duration in samples of the clip */\n clipDurationSamples: number;\n /** MIDI note data for piano-roll rendering */\n midiNotes?: MidiNoteData[];\n /** Sample rate of the clip (for MIDI note positioning) */\n clipSampleRate?: number;\n /** Clip offset in seconds (for MIDI note positioning) */\n clipOffsetSeconds?: number;\n}\n\ninterface ClipProgressProps {\n clipStartSample: number;\n clipDurationSamples: number;\n color: string;\n height: number;\n top: number;\n}\n\n/** Fraction of the clip that lies before `time`, 0 to 1. */\nfunction playedRatio(\n time: number,\n sampleRate: number,\n clipStartSample: number,\n clipDurationSamples: number\n): number {\n const currentSample = time * sampleRate;\n if (currentSample <= clipStartSample) return 0;\n if (currentSample >= clipStartSample + clipDurationSamples) return 1;\n return (currentSample - clipStartSample) / clipDurationSamples;\n}\n\n/**\n * The played-portion overlay of one channel. It is the only part of a channel\n * that follows the cursor, so it alone subscribes to the provider's contexts\n * (#693): a seek, or a selection whose start moves, re-renders these\n * small overlays and not the channels (and their canvases' React trees) around\n * them. It reads shared hooks only, so it works under either provider (#688).\n */\nconst ClipProgress: React.FC<ClipProgressProps> = ({\n clipStartSample,\n clipDurationSamples,\n color,\n height,\n top,\n}) => {\n const progressRef = useRef<HTMLDivElement>(null);\n const callbackId = useId();\n const { currentTimeRef, visualTimeRef, registerFrameCallback, unregisterFrameCallback } =\n usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only: the effect below reads the refs.\n useCurrentTime();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n\n // Use shared helper to compute clip pixel width (must match Clip.tsx sizing)\n // peaksData.length may be shorter than the clip when audio is shorter than configured duration\n const clipPixelWidth = computeClipPixelWidth(\n clipStartSample,\n clipDurationSamples,\n samplesPerPixel\n );\n\n // Register per-frame callback during playback — no own rAF loop\n useEffect(() => {\n if (isPlaying) {\n registerFrameCallback(callbackId, ({ visualTime, sampleRate: sr }) => {\n if (progressRef.current) {\n const ratio = playedRatio(visualTime, sr, clipStartSample, clipDurationSamples);\n // scaleX is composite-only — no layout reflow, GPU-accelerated\n progressRef.current.style.transform = `scaleX(${ratio})`;\n }\n });\n }\n return () => unregisterFrameCallback(callbackId);\n }, [\n isPlaying,\n clipStartSample,\n clipDurationSamples,\n callbackId,\n registerFrameCallback,\n unregisterFrameCallback,\n ]);\n\n // Also update when not playing (for seeks, stops, etc.). Reads visualTimeRef\n // so the static progress fill matches the playhead's audible position. No\n // dependency array on purpose: `useCurrentTime()` re-renders this component\n // whenever the resting position changes.\n useEffect(() => {\n if (!isPlaying && progressRef.current) {\n const currentTime = visualTimeRef.current ?? currentTimeRef.current ?? 0;\n const ratio = playedRatio(currentTime, sampleRate, clipStartSample, clipDurationSamples);\n progressRef.current.style.transform = `scaleX(${ratio})`;\n }\n });\n\n return (\n <ProgressOverlay\n ref={progressRef}\n $color={color}\n $height={height}\n $top={top}\n $width={clipPixelWidth}\n />\n );\n};\n\n/**\n * SmartChannel wrapper that adds an animated progress overlay showing the\n * played portion of the waveform. Used under either provider: the rows of\n * the tracks part render it in both views. The channel itself reads no\n * playback state; its `ClipProgress` child does.\n */\nexport const ChannelWithProgress: React.FC<ChannelWithProgressProps> = ({\n clipStartSample,\n clipDurationSamples,\n midiNotes,\n clipSampleRate,\n clipOffsetSeconds,\n ...smartChannelProps\n}) => {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { waveHeight } = usePlaylistInfo();\n\n const progressColor = theme?.waveProgressColor || 'rgba(0, 0, 0, 0.1)';\n\n // Get the draw mode from theme (defaults to 'inverted')\n const drawMode = theme?.waveformDrawMode || 'inverted';\n\n // A selected channel without a selected colour in the theme falls back to\n // the unselected one. (The MediaElement view's one row is always the\n // selected one.)\n const selected = smartChannelProps.isSelected;\n const backgroundColor =\n drawMode === 'inverted'\n ? (selected && theme?.selectedWaveFillColor) || theme?.waveFillColor || 'white'\n : (selected && theme?.selectedWaveOutlineColor) || theme?.waveOutlineColor || 'grey';\n\n // A clip with notes is a MIDI clip and is drawn as a piano roll; the render\n // mode applies to audio clips only (black background for a spectrogram).\n const isPianoRollMode = midiNotes != null;\n const isSpectrogramMode =\n !isPianoRollMode &&\n (smartChannelProps.renderMode === 'spectrogram' || smartChannelProps.renderMode === 'both');\n const isBothMode = !isPianoRollMode && smartChannelProps.renderMode === 'both';\n const spectrogramBackground = theme?.spectrogramBackgroundColor ?? '#000';\n const backgroundCss = isSpectrogramMode\n ? spectrogramBackground\n : isPianoRollMode\n ? theme?.pianoRollBackgroundColor || '#1a1a2e'\n : waveformColorToCss(backgroundColor);\n\n // In \"both\" mode each half (spectrogram + waveform) is waveHeight/2 so the track\n // container stays the same height as a single-mode track.\n const halfHeight = Math.floor(waveHeight / 2);\n const effectiveHeight = waveHeight;\n const effectiveTop = isBothMode\n ? smartChannelProps.index * waveHeight\n : smartChannelProps.index * waveHeight;\n\n // In \"both\" mode, the waveform portion needs its own (non-black) background\n const waveformBackgroundCss = waveformColorToCss(backgroundColor);\n\n return (\n <ChannelWrapper>\n {/* Background layer - color depends on draw mode */}\n {isBothMode ? (\n <>\n {/* Spectrogram portion: the theme's spectrogram background */}\n <Background\n $color={spectrogramBackground}\n $height={halfHeight}\n $top={effectiveTop}\n $width={smartChannelProps.length}\n />\n {/* Waveform portion: themed background */}\n <Background\n $color={waveformBackgroundCss}\n $height={halfHeight}\n $top={effectiveTop + halfHeight}\n $width={smartChannelProps.length}\n />\n </>\n ) : (\n <Background\n $color={backgroundCss}\n $height={effectiveHeight}\n $top={effectiveTop}\n $width={smartChannelProps.length}\n />\n )}\n {/* Progress overlay - shows played portion with progress color (skip for piano-roll) */}\n {!isPianoRollMode && (\n <ClipProgress\n clipStartSample={clipStartSample}\n clipDurationSamples={clipDurationSamples}\n color={progressColor}\n height={effectiveHeight}\n top={effectiveTop}\n />\n )}\n {/* Waveform canvas with transparent background */}\n <ChannelContainer>\n <SmartChannel\n {...smartChannelProps}\n transparentBackground\n midiNotes={midiNotes}\n sampleRate={clipSampleRate}\n clipOffsetSeconds={clipOffsetSeconds}\n />\n </ChannelContainer>\n </ChannelWrapper>\n );\n};\n","import React, { use, useMemo, useRef, useState, type ReactNode } from 'react';\nimport type { RenderMode, TrackKind } from '@waveform-playlist/core';\nimport { useTheme, type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport { warnMisplacedPart } from './partWarnings';\nimport {\n usePlaylistMixer,\n useEditorControls,\n useRecordingArm,\n useSelectedTrackId,\n useTrackReorderPreview,\n} from '../contexts/playlistContexts';\nimport { SpectrogramIntegrationContext } from '../SpectrogramIntegrationContext';\nimport { useWaveformRows, WaveformPartPlaceContext } from './waveformLayoutContext';\nimport { DefaultTrackControls } from './DefaultTrackControls';\nimport { ControlSlot, TracksLayout } from './visualizationLayout';\nimport { useStableTemplate } from '../utils/stableTemplate';\nimport {\n TrackContext,\n TrackControlsSharedContext,\n TrackSlotWiringContext,\n type TrackContextValue,\n type TrackControlsShared,\n type TrackSlotWiring,\n} from './trackContext';\n\n/** Width of the controls column when the part does not say. */\nexport const DEFAULT_TRACK_CONTROLS_WIDTH = 200;\n\nexport interface WaveformTrackControlsProps {\n /**\n * Width of the controls column in pixels. Default 200. The root reads it\n * from the element (the column is its own, beside the scrolling area), so it\n * must be on the part itself.\n */\n width?: number;\n /**\n * The control panel of a track, as a template: it is rendered once per\n * track, inside that track's context, which `useTrack()` and the built-in\n * pieces (`<TrackName />`, `<TrackMuteButton />`, …) read. Default:\n * `<DefaultTrackControls />`.\n */\n children?: ReactNode;\n}\n\n/** What the part renders for a track when it has no children. */\nconst DEFAULT_TEMPLATE = <DefaultTrackControls />;\n\n/** Drop-shadow for the floating (fully opaque) drag-source controls row. */\nconst DRAG_SOURCE_SHADOW = '0 4px 12px rgba(0, 0, 0, 0.35)';\n\n/** Fills the slot; the element a reorder drag moves. */\nconst SLOT_BODY_STYLE = { height: '100%' } as const;\n\ninterface TrackControlsSlotProps {\n trackId: string;\n index: number;\n kind: TrackKind;\n name: string;\n muted: boolean;\n soloed: boolean;\n volume: number;\n pan: number;\n isSelected: boolean;\n isFirst: boolean;\n isLast: boolean;\n renderMode: RenderMode;\n hasSpectrogram: boolean;\n isRecordingArmed: boolean;\n height: number;\n top: number;\n animate: boolean;\n template: ReactNode;\n}\n\n/**\n * One track's slot in the controls column: the height-synced box, the track's\n * context around the template, and the click that selects the track.\n *\n * Memoized, and every prop is a primitive or the template: the column renders\n * on each mixer change (it reads the mixer state), and only the slot whose\n * track changed renders with it. The template is the same object for every\n * slot and across renders (see `useStableTemplate`), so inside a slot that\n * does render React skips every element of it and only the components that\n * read the track's context follow.\n */\nfunction TrackControlsSlotImpl({\n trackId,\n index,\n kind,\n name,\n muted,\n soloed,\n volume,\n pan,\n isSelected,\n isFirst,\n isLast,\n renderMode,\n hasSpectrogram,\n isRecordingArmed,\n height,\n top,\n animate,\n template,\n}: TrackControlsSlotProps) {\n const {\n setTrackMute,\n setTrackSolo,\n setTrackVolume,\n setTrackPan,\n reorderTrack,\n setSelectedTrackId,\n } = useEditorControls();\n const theme = useTheme() as WaveformPlaylistTheme;\n const shared = use(TrackControlsSharedContext);\n\n // The position is read when an action runs, so the actions do not change\n // with it.\n const indexRef = useRef(index);\n indexRef.current = index;\n\n const actions = useMemo(\n () => ({\n setMuted: (value: boolean) => setTrackMute(trackId, value),\n setSoloed: (value: boolean) => setTrackSolo(trackId, value),\n setVolume: (value: number) => setTrackVolume(trackId, value),\n setPan: (value: number) => setTrackPan(trackId, value),\n select: () => setSelectedTrackId(trackId),\n // The engine clamps the target and ignores a move to the same place.\n moveUp: () => reorderTrack(trackId, indexRef.current - 1),\n moveDown: () => reorderTrack(trackId, indexRef.current + 1),\n setRenderMode: (mode: RenderMode) => shared?.setTrackRenderMode(trackId, mode),\n openSpectrogramSettings: () => shared?.openSpectrogramSettings(trackId),\n }),\n [\n trackId,\n setTrackMute,\n setTrackSolo,\n setTrackVolume,\n setTrackPan,\n setSelectedTrackId,\n reorderTrack,\n shared,\n ]\n );\n\n const value = useMemo<TrackContextValue>(\n () => ({\n id: trackId,\n kind,\n index,\n name: name || `Track ${index + 1}`,\n muted,\n soloed,\n volume,\n pan,\n renderMode,\n isSelected,\n isFirst,\n isLast,\n hasSpectrogram,\n isRecordingArmed,\n ...actions,\n }),\n [\n trackId,\n kind,\n index,\n name,\n muted,\n soloed,\n volume,\n pan,\n renderMode,\n isSelected,\n isFirst,\n isLast,\n hasSpectrogram,\n isRecordingArmed,\n actions,\n ]\n );\n\n // For a reorder handle inside the panel (`useTrackReorderHandle`).\n const elementRef = useRef<HTMLDivElement | null>(null);\n const [isDragSource, setDragSource] = useState(false);\n const wiring = useMemo<TrackSlotWiring>(\n () => ({ elementRef, setDragSource, handleCount: { current: 0 } }),\n []\n );\n\n return (\n <ControlSlot\n $height={height}\n $top={top}\n $animate={animate}\n $isSelected={isSelected}\n onClick={actions.select}\n >\n <div\n ref={elementRef}\n data-track-controls={trackId}\n style={\n isDragSource\n ? {\n ...SLOT_BODY_STYLE,\n boxShadow: DRAG_SOURCE_SHADOW,\n // Opaque background for the floating (top-layer, popover-based)\n // drag-source row — without it the row underneath shows through.\n // onDragStart selects the dragged track, so its slot always shows\n // the selected-track background while lifted.\n background: theme.selectedTrackControlsBackground,\n }\n : SLOT_BODY_STYLE\n }\n >\n <TrackSlotWiringContext value={wiring}>\n <TrackContext value={value}>{template}</TrackContext>\n </TrackSlotWiringContext>\n </div>\n </ControlSlot>\n );\n}\n\nconst TrackControlsSlot = React.memo(TrackControlsSlotImpl);\n\n/**\n * The control panels of all tracks, one height-synced slot per track, for the\n * ControlsColumn outside the scroll area: the track-controls part of the view\n * (#685). Its children are the panel of ONE track, a template it renders once\n * per track inside that track's context (#687); without children the panel is\n * `<DefaultTrackControls />`.\n *\n * Memoized (#693): it takes the rows and the layout from the root's rows\n * value, reads the selected track itself, and no time selection, cursor or\n * annotation state, so a selection drag or an active-annotation change during\n * playback does not re-render the panels. It reads the mixer state itself\n * (#768), so a volume or pan step renders this column, the slot of that track\n * and the pieces of that track, and not the root above it.\n */\nfunction WaveformTrackControlsImpl({ children }: WaveformTrackControlsProps) {\n const {\n rows: tracks,\n renderModeById,\n trackLayout,\n trackHeightById,\n animateTrackLayout,\n setSettingsModalTrackId,\n } = useWaveformRows('The track controls');\n if (use(WaveformPartPlaceContext) !== 'controls') {\n warnMisplacedPart(\n '<WaveformTrackControls> is drawn among the tracks, not in the controls column: the root ' +\n 'recognises a part by its element type, so it must be a child of the root (a fragment ' +\n 'is fine), not wrapped in another component.'\n );\n }\n const { selectedTrackId } = useSelectedTrackId();\n // The track a take is recorded onto (#812): its slot alone renders when a take starts or ends.\n const { armedTrackId } = useRecordingArm();\n const { trackReorderEpoch } = useTrackReorderPreview();\n const spectrogram = use(SpectrogramIntegrationContext);\n const { trackStates } = usePlaylistMixer();\n\n // `null` and `undefined` both mean \"not given\".\n const template = useStableTemplate(children ?? DEFAULT_TEMPLATE);\n\n // The spectrogram integration's value changes with every per-track\n // override; the slots and the pieces get functions that read the latest\n // one, in a value that changes only when a menu comes or goes.\n const spectrogramRef = useRef(spectrogram);\n spectrogramRef.current = spectrogram;\n const menuAvailable = Boolean(spectrogram?.renderMenuItems);\n const shared = useMemo<TrackControlsShared>(\n () => ({\n menuAvailable,\n menuItems: (args) => spectrogramRef.current?.renderMenuItems?.(args) ?? [],\n setTrackRenderMode: (trackId, mode) =>\n spectrogramRef.current?.setTrackRenderMode(trackId, mode),\n openSpectrogramSettings: (trackId) => {\n if (spectrogramRef.current) setSettingsModalTrackId(trackId);\n },\n }),\n [menuAvailable, setSettingsModalTrackId]\n );\n\n return (\n <TrackControlsSharedContext value={shared}>\n <TracksLayout $height={trackLayout.totalHeight}>\n {tracks.map((track, trackIndex) => {\n // One entry per track, also while its audio loads (#812): a\n // change made then is kept.\n const state = trackStates[trackIndex];\n return (\n // key includes trackReorderEpoch: forces a remount after every\n // track-reorder drag, discarding @dnd-kit sortable-plugin DOM\n // corruption (see bumpTrackReorderEpoch's doc comment in\n // WaveformPlaylistContext). Stays at `-0` — a no-op suffix — for\n // consumers that never render a reorder handle.\n <TrackControlsSlot\n key={`${track.id}-${trackReorderEpoch}`}\n trackId={track.id}\n index={trackIndex}\n kind={track.kind}\n name={state.name}\n muted={state.muted}\n soloed={state.soloed}\n volume={state.volume}\n pan={state.pan}\n isSelected={track.id === selectedTrackId}\n isFirst={trackIndex === 0}\n isLast={trackIndex === tracks.length - 1}\n renderMode={renderModeById.get(track.id) ?? 'waveform'}\n hasSpectrogram={spectrogram !== null && track.kind !== 'midi'}\n isRecordingArmed={track.id === armedTrackId}\n height={trackHeightById.get(track.id) ?? 0}\n top={trackLayout.topById.get(track.id) ?? 0}\n animate={animateTrackLayout}\n template={template}\n />\n );\n })}\n </TracksLayout>\n </TrackControlsSharedContext>\n );\n}\n\nexport const WaveformTrackControls = React.memo(WaveformTrackControlsImpl);\n","import React, { type ReactNode } from 'react';\nimport styled from 'styled-components';\nimport { ButtonGroup, Controls, Header } from '@waveform-playlist/ui-components';\nimport {\n TrackMenuButton,\n TrackMuteButton,\n TrackName,\n TrackPanSlider,\n TrackSoloButton,\n TrackVolumeSlider,\n} from './TrackControlPieces';\n\n/**\n * The frame of the default panel. It makes room on both sides when a\n * `<TrackReorderGrip />` is rendered beside it (the grip sits at the right\n * edge of the slot, over the panel).\n */\nconst Frame = styled(Controls)`\n *:has(> [data-track-reorder-grip]) > & {\n padding-left: 18px;\n padding-right: 18px;\n }\n`;\n\nconst HEADER_STYLE = { justifyContent: 'center', position: 'relative' } as const;\nconst MENU_ANCHOR_STYLE = { position: 'absolute', right: 0, top: 0 } as const;\n\n/**\n * The default control panel of a track: its name, the track menu (under a\n * `<SpectrogramProvider>`, for an audio track), mute, solo, volume and pan.\n * It is what `<WaveformTrackControls />` renders when it has no children\n * (#687). It has no remove button and no reorder grip: render\n * `<TrackRemoveButton />` or `<TrackReorderGrip />` beside it for those (both\n * place themselves at an edge of the slot), or compose a panel from the\n * pieces.\n *\n * Its children are drawn inside the panel, below the pan slider: the place\n * for one more control of your own. An element rendered BESIDE the panel is\n * outside it, and the panel fills the slot, so that element is only visible\n * when it positions itself, as the remove button and the grip do.\n *\n * It reads no context itself: the pieces read the track.\n */\nexport interface DefaultTrackControlsProps {\n /** Drawn inside the panel, below the pan slider. */\n children?: ReactNode;\n}\n\nfunction DefaultTrackControlsImpl({ children }: DefaultTrackControlsProps) {\n return (\n <Frame>\n <Header style={HEADER_STYLE}>\n <TrackName />\n <span style={MENU_ANCHOR_STYLE}>\n <TrackMenuButton />\n </span>\n </Header>\n <ButtonGroup>\n <TrackMuteButton />\n <TrackSoloButton />\n </ButtonGroup>\n <TrackVolumeSlider />\n <TrackPanSlider />\n {children}\n </Frame>\n );\n}\n\nexport const DefaultTrackControls = React.memo(DefaultTrackControlsImpl);\n","/**\n * The pieces of a track's control panel (#687). Each is bound to the track\n * whose panel it is rendered in (`useTrack()`), takes no prop for the track,\n * and is drawn by being rendered among the children of\n * `<WaveformTrackControls>`.\n */\nimport React, { use } from 'react';\nimport {\n Button,\n CloseButton,\n ReorderRail,\n Slider,\n SliderWrapper,\n TrackMenu,\n VolumeDownIcon,\n VolumeUpIcon,\n} from '@waveform-playlist/ui-components';\nimport { TrackControlsSharedContext, useTrack } from './trackContext';\nimport { useTrackReorderHandle } from '../hooks/useTrackReorderHandle';\n\nconst NAME_STYLE = {\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n // Room for a remove button on the left and the track menu on the right.\n padding: '0 24px',\n display: 'block',\n} as const;\n\n/** The track's name, on one line, cut off with an ellipsis. */\nexport const TrackName: React.FC = () => {\n const { name } = useTrack();\n return (\n <span data-track-name=\"\" style={NAME_STYLE}>\n {name}\n </span>\n );\n};\n\n/**\n * Mutes and unmutes the track. Disabled while a take is recorded onto the\n * track (`useTrack().isRecordingArmed`): the track is muted for the take and\n * its mute from before is written back when the take ends (#812).\n */\nexport const TrackMuteButton: React.FC = () => {\n const { muted, setMuted, isRecordingArmed } = useTrack();\n return (\n <Button\n $variant={muted ? 'danger' : 'outline'}\n aria-pressed={muted}\n disabled={isRecordingArmed}\n onClick={() => setMuted(!muted)}\n >\n Mute\n </Button>\n );\n};\n\n/** Solos and unsolos the track. */\nexport const TrackSoloButton: React.FC = () => {\n const { soloed, setSoloed } = useTrack();\n return (\n <Button\n $variant={soloed ? 'info' : 'outline'}\n aria-pressed={soloed}\n onClick={() => setSoloed(!soloed)}\n >\n Solo\n </Button>\n );\n};\n\n/** The track's volume, 0 to 1. */\nexport const TrackVolumeSlider: React.FC = () => {\n const { volume, setVolume } = useTrack();\n return (\n <SliderWrapper>\n <VolumeDownIcon />\n <Slider\n min=\"0\"\n max=\"1\"\n step=\"0.01\"\n value={volume}\n aria-label=\"Volume\"\n onChange={(e) => setVolume(parseFloat(e.target.value))}\n />\n <VolumeUpIcon />\n </SliderWrapper>\n );\n};\n\n/** The track's pan, -1 (left) to 1 (right). */\nexport const TrackPanSlider: React.FC = () => {\n const { pan, setPan } = useTrack();\n return (\n <SliderWrapper>\n <span>L</span>\n <Slider\n min=\"-1\"\n max=\"1\"\n step=\"0.01\"\n value={pan}\n aria-label=\"Pan\"\n onChange={(e) => setPan(parseFloat(e.target.value))}\n />\n <span>R</span>\n </SliderWrapper>\n );\n};\n\n/**\n * The track's menu: how the track is drawn (waveform, spectrogram, both) and\n * its spectrogram settings. Draws nothing without a `<SpectrogramProvider>`\n * and nothing for a MIDI track, which is always a piano roll.\n */\nexport const TrackMenuButton: React.FC = () => {\n const { renderMode, hasSpectrogram, setRenderMode, openSpectrogramSettings } = useTrack();\n const shared = use(TrackControlsSharedContext);\n if (!shared || !shared.menuAvailable || !hasSpectrogram) return null;\n return (\n <TrackMenu\n items={(onClose) =>\n shared.menuItems({\n renderMode,\n onRenderModeChange: setRenderMode,\n onOpenSettings: openSpectrogramSettings,\n onClose,\n })\n }\n />\n );\n};\n\nexport interface TrackRemoveButtonProps {\n /** Called with the track's id. Removing the track from your `tracks` is yours to do. */\n onRemove: (trackId: string) => void;\n}\n\n// The primitive is absolutely positioned at its container's top left corner.\n// One pixel in, where it sat inside the bordered default panel.\nconst REMOVE_ANCHOR_STYLE = { position: 'absolute', left: 1, top: 1 } as const;\n\n/**\n * A close button at the top left corner of the track's slot. A click calls\n * `onRemove` with the track's id and does not select the track.\n */\nexport const TrackRemoveButton: React.FC<TrackRemoveButtonProps> = ({ onRemove }) => {\n const { id } = useTrack();\n return (\n <span style={REMOVE_ANCHOR_STYLE}>\n <CloseButton\n onClick={(e) => {\n e.stopPropagation();\n onRemove(id);\n }}\n />\n </span>\n );\n};\n\nconst GRIP_ANCHOR_STYLE = {\n position: 'absolute',\n right: 3,\n top: '50%',\n transform: 'translateY(-50%)',\n} as const;\n\n/**\n * A drag grip with a move-up and a move-down button, at the right edge of the\n * track's slot. The buttons work with no other setup; dragging needs a\n * `ClipInteractionProvider` above the view. The default panel makes room for\n * it. Neither the grip nor the buttons select the track.\n */\nexport const TrackReorderGrip: React.FC = () => {\n const { isFirst, isLast, moveUp, moveDown } = useTrack();\n const { handleRef } = useTrackReorderHandle();\n return (\n <span data-track-reorder-grip=\"\" style={GRIP_ANCHOR_STYLE}>\n <ReorderRail\n gripRef={handleRef as React.Ref<HTMLButtonElement>}\n onGripClick={(e) => e.stopPropagation()}\n upDisabled={isFirst}\n downDisabled={isLast}\n onMoveUp={(e) => {\n e.stopPropagation();\n moveUp();\n }}\n onMoveDown={(e) => {\n e.stopPropagation();\n moveDown();\n }}\n />\n </span>\n );\n};\n","/**\n * The per-track context of the track controls (#687).\n *\n * `<WaveformTrackControls>` renders its children once per track; around each\n * copy it provides that track's value, which `useTrack()` reads. A value\n * changes only when something about ITS track changes, so a volume step on one\n * track renders the pieces of that track and of no other.\n *\n * This file imports no provider and no engine.\n */\nimport { createContext, use, type RefObject } from 'react';\nimport type { RenderMode, TrackKind } from '@waveform-playlist/core';\nimport type { TrackMenuItem } from '@waveform-playlist/ui-components';\n\n/** What `useTrack()` returns: one track's identity, mixer state and bound actions. */\nexport interface TrackContextValue {\n /** The track's id. */\n id: string;\n /** `'audio'` or `'midi'`. */\n kind: TrackKind;\n /** The track's position in the list of tracks, from 0. Changes on a reorder. */\n index: number;\n\n /** The track's name, or \"Track N\" (N is the position, from 1) when it has none and while it is loading. */\n name: string;\n muted: boolean;\n soloed: boolean;\n /** 0 to 1. */\n volume: number;\n /** -1 (left) to 1 (right). */\n pan: number;\n /** How the track is drawn. Always `'waveform'` for a MIDI track. */\n renderMode: RenderMode;\n\n /** Whether this is the selected track. */\n isSelected: boolean;\n isFirst: boolean;\n isLast: boolean;\n /**\n * True for an audio track under a `<SpectrogramProvider>`: `setRenderMode`\n * and `openSpectrogramSettings` then do something.\n */\n hasSpectrogram: boolean;\n /**\n * True while a take is being recorded onto this track (`setRecordingActive`,\n * `useRecordingSession`). The track is muted for the take and its mute from\n * before is written back when the take ends, so a change made meanwhile does\n * not stay: the built-in `<TrackMuteButton />` is disabled while this is\n * true, and an app's own mute control can do the same.\n */\n isRecordingArmed: boolean;\n\n // Actions. Each keeps its identity while the track's slot is mounted and a\n // track menu neither becomes available nor stops being so.\n setMuted: (muted: boolean) => void;\n setSoloed: (soloed: boolean) => void;\n setVolume: (volume: number) => void;\n setPan: (pan: number) => void;\n /** Makes this the selected track. */\n select: () => void;\n /** Moves the track one position up. Nothing happens for the first track. */\n moveUp: () => void;\n /** Moves the track one position down. Nothing happens for the last track. */\n moveDown: () => void;\n /** Nothing happens without a `<SpectrogramProvider>`. */\n setRenderMode: (mode: RenderMode) => void;\n /** Opens the spectrogram settings of this track. Nothing happens without a `<SpectrogramProvider>`. */\n openSpectrogramSettings: () => void;\n}\n\nexport const TrackContext = createContext<TrackContextValue | null>(null);\n\n/**\n * The track whose control panel the calling component is part of. For the\n * children of `<WaveformTrackControls>`, which renders them once per track.\n */\nexport function useTrack(): TrackContextValue {\n const value = use(TrackContext);\n if (value === null) {\n throw new Error(\n 'useTrack must be used within <WaveformTrackControls>: it reads the track whose control ' +\n 'panel is being drawn, so the component that calls it (a built-in piece such as ' +\n '<TrackMuteButton />, or your own) must be among the children of ' +\n '<WaveformTrackControls>. Elsewhere, use usePlaylistMixer() and the setters of ' +\n 'useEditorControls(), which take a track id.'\n );\n }\n return value;\n}\n\n/** What the items of a track menu are built from (the spectrogram integration's). */\nexport interface TrackMenuItemsArgs {\n renderMode: RenderMode;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n}\n\n/**\n * Internal: what the controls part hands every slot and piece. The functions\n * read the spectrogram integration through a ref, so the value changes only\n * when a menu becomes available or stops being so.\n */\nexport interface TrackControlsShared {\n /** Whether the spectrogram integration offers menu items. */\n menuAvailable: boolean;\n menuItems: (args: TrackMenuItemsArgs) => TrackMenuItem[];\n setTrackRenderMode: (trackId: string, mode: RenderMode) => void;\n openSpectrogramSettings: (trackId: string) => void;\n}\n\nexport const TrackControlsSharedContext = createContext<TrackControlsShared | null>(null);\n\n/**\n * Internal: the wiring between a slot and the reorder handle inside it. The\n * slot's element is the item that is dragged; the handle says when it is.\n * Stable for the life of the slot.\n */\nexport interface TrackSlotWiring {\n elementRef: RefObject<HTMLDivElement | null>;\n setDragSource: (isDragSource: boolean) => void;\n /** How many reorder handles are mounted in the slot (one is right). */\n handleCount: { current: number };\n}\n\nexport const TrackSlotWiringContext = createContext<TrackSlotWiring | null>(null);\n","import { use, useEffect } from 'react';\nimport { useSortable } from '@dnd-kit/react/sortable';\nimport { RestrictToVerticalAxis } from '@dnd-kit/abstract/modifiers';\nimport { Feedback } from '@dnd-kit/dom';\nimport type { Plugins } from '@dnd-kit/abstract';\nimport { createDragPopoverHealer } from '../utils/dragPopoverHealer';\nimport { warnOnce } from '../components/partWarnings';\nimport { TrackSlotWiringContext, useTrack } from '../components/trackContext';\n\nexport interface TrackReorderHandle {\n /** Attach to the element the track is dragged by (a grip). */\n handleRef: (element: Element | null) => void;\n /** True while this track is the one being dragged. */\n isDragSource: boolean;\n}\n\nconst MOVE_FEEDBACK = Feedback.configure({ feedback: 'move' });\nconst withMoveFeedback = (defaults: Plugins): Plugins => [...defaults, MOVE_FEEDBACK];\n\n/**\n * Makes the track whose control panel the caller is part of a vertical\n * sortable item in the ambient `DragDropProvider` (`ClipInteractionProvider`),\n * dragged by the element `handleRef` is attached to (#687; it replaces\n * `SortableTrackControls`). `<TrackReorderGrip />` is this hook with the\n * built-in grip; call it yourself for a grip of your own. Once per panel: two\n * calls for one track register the same sortable id twice.\n *\n * The item that moves is the slot `<WaveformTrackControls>` draws around the\n * panel, not an element of the caller. The per-source modifiers REPLACE the\n * provider's clip modifiers for this operation, so track drags are\n * vertical-only and skip clip collision and snap. Data kind 'track-reorder'\n * is the discriminator the shared drag handlers branch on.\n */\nexport function useTrackReorderHandle(): TrackReorderHandle {\n const { id, index } = useTrack();\n const wiring = use(TrackSlotWiringContext);\n const { ref, handleRef, isDragSource } = useSortable({\n id: `track-reorder-${id}`,\n index,\n group: 'playlist-tracks',\n type: 'track',\n accept: ['track'],\n data: { kind: 'track-reorder', trackId: id },\n modifiers: [RestrictToVerticalAxis],\n // Per-entity Feedback config (@dnd-kit 0.5+ moved `feedback` out of the\n // hook options into `plugins`). The FUNCTION form extends the sortable's\n // default plugins — a bare array would silently drop\n // OptimisticSortingPlugin, which drives the live `sortable.index` that\n // drag-commit reads (covered by trackReorderHandleFeedbackPlugins.test).\n //\n // feedback: 'move' (NOT 'none' — see below) disables the Feedback\n // plugin's placeholder/clone splicing for this sortable while KEEPING its\n // dragOperation.shape computation alive. That plugin does raw,\n // React-bypassing DOM surgery on ANY pointer movement during an activated\n // drag (insertAdjacentElement to splice in a placeholder, then\n // `placeholder.replaceWith(element)` on drop) — confirmed via\n // MutationObserver instrumentation to relocate the React-owned row 6\n // times during a single one-slot drag, leaving its final parent/sibling\n // different from what React's fiber tree still believes. That desync is\n // permanent for the session: every later React-driven reorder (button OR\n // drag) computes the correct data but silently fails to update the DOM\n // for these rows. The placeholder splice is created only when\n // `feedback !== 'move'` (@dnd-kit/dom Feedback.ts) — 'move' keeps the\n // dragged element in the live DOM (no clone/placeholder) while still\n // running the *unconditional* `dragOperation.shape = ...` assignment.\n // `feedback: 'none'` looked like the boundary-trim precedent (Clip.tsx /\n // AnnotationBox.tsx) but is wrong here: 'none' bails out of Feedback's\n // render function BEFORE dragOperation.shape is ever set, and shape is\n // the ONLY input CollisionObserver.computeCollisions() checks — with\n // 'none', collision (and therefore sortable.index) never updates, so\n // drag-based reordering silently never commits. Boundary trims don't hit\n // this because they're plain useDraggable (no collision-based commit) —\n // sortables need shape. `isDragSource` is a reactive signal, unaffected\n // either way. See browser/CLAUDE.md \"Track Reordering\".\n plugins: withMoveFeedback,\n });\n\n // The sortable item is the slot's element, which the part owns: it is\n // handed to dnd-kit here, after the commit that mounted it. Not in a layout\n // effect: a child's layout effects run before React attaches its parent's\n // ref, so the slot's element would still be null on the first mount (tried:\n // no drag started at all).\n useEffect(() => {\n if (!wiring) return undefined;\n ref(wiring.elementRef.current);\n return () => ref(null);\n }, [ref, wiring]);\n\n // One handle per panel: a second one registers the same sortable id again.\n useEffect(() => {\n if (!wiring) return undefined;\n const { handleCount } = wiring;\n handleCount.current += 1;\n if (handleCount.current > 1) {\n warnOnce(\n 'A track control panel has more than one reorder handle (<TrackReorderGrip /> or ' +\n 'useTrackReorderHandle()): each registers the track as the same sortable item. ' +\n 'Render one per panel.'\n );\n }\n return () => {\n handleCount.current -= 1;\n };\n }, [wiring]);\n\n // The slot draws itself lifted (opaque, with a shadow) while it is dragged.\n useEffect(() => {\n if (!wiring) return undefined;\n wiring.setDragSource(isDragSource);\n return () => wiring.setDragSource(false);\n }, [isDragSource, wiring]);\n\n // `feedback: 'move'` opts out of dnd-kit's placeholder — and with it the\n // plugin's own popover-recovery MutationObserver, which is only created\n // when a placeholder exists. OptimisticSortingPlugin's mid-drag\n // insertAdjacentElement splices force-dismiss the top-layer popover\n // (eventlessly, per spec), leaving the dragged row UA-hidden\n // (`[popover]:not(:popover-open) { display: none }`) for the rest of the\n // drag. Run our own healer while this row is the drag source.\n useEffect(() => {\n const element = wiring?.elementRef.current;\n if (!isDragSource || !element) return undefined;\n return createDragPopoverHealer(element);\n }, [isDragSource, wiring]);\n\n return { handleRef, isDragSource };\n}\n","/**\n * Keeps a dnd-kit drag-feedback element visible for the duration of a drag.\n *\n * @dnd-kit/dom's Feedback plugin promotes the dragged element into the\n * browser top layer via the Popover API (`popover=\"manual\"` + showPopover()).\n * During a sortable drag, OptimisticSortingPlugin reorders rows with\n * `insertAdjacentElement` — a remove + reinsert that force-dismisses the\n * popover with NO toggle events (per spec, removal-dismissal fires none).\n * A dismissed `[popover]` element falls under the UA rule\n * `[popover]:not(:popover-open) { display: none }`, so the dragged row\n * vanishes the moment it crosses a collision boundary. dnd-kit's own\n * recovery MutationObserver is only created when a placeholder exists\n * (`feedback !== 'move'`), so `feedback: 'move'` sortables never recover.\n *\n * This observer mirrors that upstream recovery for the 'move' case: on any\n * childList mutation, if the element is connected but its popover was\n * dismissed, re-show it. MutationObserver callbacks run as microtasks, so\n * the heal lands in the same frame as the splice — no visible flicker.\n */\nexport function createDragPopoverHealer(element: HTMLElement): () => void {\n if (typeof element.showPopover !== 'function') {\n // Browser without the Popover API: dnd-kit falls back to plain\n // fixed-position feedback, which DOM splices cannot dismiss.\n return () => {};\n }\n const heal = () => {\n if (!element.isConnected || !element.hasAttribute('popover')) return;\n let open = false;\n try {\n open = element.matches(':popover-open');\n } catch {\n // Selector unsupported (older engines): treat as closed and let\n // showPopover's own InvalidStateError guard below settle it.\n }\n if (open) return;\n try {\n element.showPopover();\n } catch {\n // InvalidStateError (already open / mid-toggle) — nothing to heal.\n }\n };\n const observer = new MutationObserver(heal);\n observer.observe(element.ownerDocument.body, {\n childList: true,\n subtree: true,\n });\n return () => observer.disconnect();\n}\n","/**\n * Keeps a template of React elements while a new one says the same thing\n * (#687).\n *\n * `<WaveformTrackControls>` renders its children once per track. Children\n * written inline are new element objects on every render of the component\n * that composes the view, which usually holds the tracks and renders on every\n * move of a trim: handed on as they are, they rendered every piece of every\n * track each time (measured with a prototype on the multi-clip example: 237 components per\n * trim move against 83). Two elements describe the same thing when their\n * type, key and props are equal, so the previous template can stand in for an\n * equal new one, and React then skips everything below it.\n */\nimport { isValidElement, useRef, type ReactNode } from 'react';\n\nfunction sameStyle(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n const one = a as Record<string, unknown>;\n const other = b as Record<string, unknown>;\n const keys = Object.keys(one);\n return (\n keys.length === Object.keys(other).length && keys.every((k) => Object.is(one[k], other[k]))\n );\n}\n\n/**\n * Whether two templates describe the same elements: the same types and keys,\n * and props that are identical (`Object.is`), except `children` (compared the\n * same way, recursively) and `style` (compared one level deep, because a\n * style object is usually written inline). A function or an object written\n * inline as any other prop makes the templates differ.\n */\nexport function sameTemplate(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => sameTemplate(item, b[index]));\n }\n if (isValidElement(a) && isValidElement(b)) {\n if (a.type !== b.type || a.key !== b.key) return false;\n const one = a.props as Record<string, unknown>;\n const other = b.props as Record<string, unknown>;\n const keys = Object.keys(one);\n if (keys.length !== Object.keys(other).length) return false;\n return keys.every((key) => {\n if (!(key in other)) return false;\n if (key === 'children') return sameTemplate(one[key], other[key]);\n if (key === 'style') return sameStyle(one[key], other[key]);\n return Object.is(one[key], other[key]);\n });\n }\n return false;\n}\n\n/**\n * The template to render: the previous one while `template` is equal to it by\n * `sameTemplate`, else `template`.\n *\n * The ref is written during render. That is safe here: whatever it holds is a\n * template some render was given, and it is only ever used in place of one\n * that is equal to it.\n */\nexport function useStableTemplate(template: ReactNode): ReactNode {\n const kept = useRef(template);\n if (!sameTemplate(kept.current, template)) {\n kept.current = template;\n }\n return kept.current;\n}\n","/**\n * The parts of the visualization that follow selection, cursor, loop and\n * annotation state. They are small siblings of the track rows (#693): these\n * re-render on every pointer move of a selection drag and on every\n * active-annotation change during playback, and the rows do not.\n *\n * `WaveformSelection` and `WaveformPlayhead` read shared hooks only and are\n * rendered under both providers (#688). The loop region is multitrack only.\n * (The annotation boxes are `WaveformAnnotationBoxes.tsx`, for both providers.)\n */\nimport React, { use, useSyncExternalStore } from 'react';\nimport {\n Selection,\n TimescaleLoopRegion,\n useTheme,\n type RenderPlayheadFunction,\n type WaveformPlaylistTheme,\n} from '@waveform-playlist/ui-components';\nimport {\n useCurrentTime,\n useSelection,\n usePlaylistView,\n usePlaylistZoom,\n usePlaybackRefs,\n useLoop,\n useIsPlaying,\n useEditorControls,\n} from '../contexts/playlistContexts';\nimport { AnimatedPlayhead } from './AnimatedPlayhead';\nimport { useWaveformExtent, WaveformPartPlaceContext } from './waveformLayoutContext';\nimport { warnMisplacedPart } from './partWarnings';\nimport { SelectionPreviewContext, type SelectionRange } from '../hooks/useSelectionDrag';\n\nconst subscribeToNothing = () => () => {};\nconst noPreview = (): SelectionRange | null => null;\n\n/**\n * The highlighted selection range. Renders nothing for a collapsed selection.\n * While a drag is drawing a range during playback it shows that range.\n * Memoized (it takes no props): a render of the view around it (play, pause,\n * a press) is not its concern, only the selection, the zoom, the view settings\n * and the theme are.\n */\nexport const WaveformSelection: React.FC = React.memo(function WaveformSelection() {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { selectionStart, selectionEnd } = useSelection();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n // The range a drag is drawing during playback (see useSelectionDrag). It is\n // not the selection yet, and it is shown in its place until the release.\n // Called as methods (not detached), so a source written as a class works.\n const previewSource = use(SelectionPreviewContext);\n const preview = useSyncExternalStore(\n previewSource ? (onChange) => previewSource.subscribe(onChange) : subscribeToNothing,\n previewSource ? () => previewSource.getSnapshot() : noPreview,\n previewSource ? () => previewSource.getSnapshot() : noPreview\n );\n\n const start = preview ? preview.start : Math.min(selectionStart, selectionEnd);\n const end = preview ? preview.end : Math.max(selectionStart, selectionEnd);\n if (start === end) return null;\n\n return (\n <Selection\n startPosition={(start * sampleRate) / samplesPerPixel}\n endPosition={(end * sampleRate) / samplesPerPixel}\n color={theme.selectionColor}\n />\n );\n});\n\n/**\n * Wrapper that isolates the custom playhead's hooks from its parent.\n * Calling renderPlayhead() directly would merge its hooks into the parent,\n * causing \"Rendered more hooks\" errors if renderPlayhead is conditionally provided.\n * It reads shared hooks only, so it serves both providers.\n */\nconst CustomPlayhead: React.FC<{\n renderPlayhead: RenderPlayheadFunction;\n color: string;\n samplesPerPixel: number;\n sampleRate: number;\n}> = ({ renderPlayhead, color, samplesPerPixel, sampleRate }) => {\n const { currentTimeRef, visualTimeRef } = usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only, so a seek while stopped moves a custom\n // playhead: the position below comes from the refs.\n useCurrentTime();\n\n // Use visualTimeRef so the initial position matches the audible output\n // (the default playhead and the progress fill are drawn from it too).\n const visualTime = visualTimeRef.current ?? currentTimeRef.current ?? 0;\n\n return renderPlayhead({\n position: (visualTime * sampleRate) / samplesPerPixel,\n color,\n isPlaying,\n currentTimeRef,\n visualTimeRef,\n samplesPerPixel,\n sampleRate,\n }) as React.ReactElement;\n};\n\nexport interface WaveformPlayheadProps {\n /** Custom playhead render function. Receives position (pixels) and color from theme. */\n renderPlayhead?: RenderPlayheadFunction;\n}\n\n/**\n * The playhead: shown while playing, and at rest when no range is selected.\n * The same under either provider.\n */\nexport const WaveformPlayhead: React.FC<WaveformPlayheadProps> = ({ renderPlayhead }) => {\n const theme = useTheme() as WaveformPlaylistTheme;\n const { isPlaying } = useIsPlaying();\n const { selectionStart, selectionEnd } = useSelection();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n\n if (!isPlaying && selectionStart !== selectionEnd) return null;\n\n return renderPlayhead ? (\n <CustomPlayhead\n renderPlayhead={renderPlayhead}\n color={theme.playheadColor}\n samplesPerPixel={samplesPerPixel}\n sampleRate={sampleRate}\n />\n ) : (\n <AnimatedPlayhead color={theme.playheadColor} />\n );\n};\n\n/**\n * The draggable loop region in the timescale, bounded by the root's timeline.\n * Renders nothing while looping is off. Memoized: it takes no props.\n */\nexport const WaveformLoopRegion = React.memo(function WaveformLoopRegion() {\n const { tracksFullWidth: maxPosition } = useWaveformExtent('The loop region');\n if (use(WaveformPartPlaceContext) !== 'timescale') {\n warnMisplacedPart(\n '<WaveformLoopRegion> is drawn among the tracks, not in the timescale strip: the root ' +\n 'recognises a part by its element type, so it must be a child of the root (a fragment ' +\n 'is fine), not wrapped in another component.'\n );\n }\n const theme = useTheme() as WaveformPlaylistTheme;\n const { isLoopEnabled, loopStart, loopEnd } = useLoop();\n const { setLoopRegion } = useEditorControls();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n\n if (!isLoopEnabled) return null;\n\n return (\n <TimescaleLoopRegion\n startPosition={(Math.min(loopStart, loopEnd) * sampleRate) / samplesPerPixel}\n endPosition={(Math.max(loopStart, loopEnd) * sampleRate) / samplesPerPixel}\n markerColor={theme.loopMarkerColor}\n regionColor={theme.loopRegionColor}\n minPosition={0}\n maxPosition={maxPosition}\n onLoopRegionChange={(startPixels, endPixels) => {\n const startSeconds = (startPixels * samplesPerPixel) / sampleRate;\n const endSeconds = (endPixels * samplesPerPixel) / sampleRate;\n setLoopRegion(startSeconds, endSeconds);\n }}\n />\n );\n});\n","import React, { useRef, useEffect, useId } from 'react';\nimport styled from 'styled-components';\nimport { usePlaylistInfo } from '@waveform-playlist/ui-components';\nimport {\n useCurrentTime,\n usePlaylistView,\n usePlaylistZoom,\n usePlaybackRefs,\n useIsPlaying,\n} from '../contexts/playlistContexts';\n\nconst PlayheadLine = styled.div.attrs<{ $color: string; $width: number }>((props) => ({\n style: {\n width: `${props.$width}px`,\n background: props.$color,\n },\n}))<{ $color: string; $width: number }>`\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n z-index: 100; /* Below sticky controls (z-index: 101) so playhead is hidden when scrolled behind controls */\n pointer-events: none;\n will-change: transform;\n`;\n\ninterface AnimatedPlayheadProps {\n color?: string;\n}\n\n/**\n * The default playhead, under either provider. During playback the provider's\n * animation loop moves it (a registered frame callback, no loop of its own);\n * at rest it is placed after each render.\n */\nexport const AnimatedPlayhead: React.FC<AnimatedPlayheadProps> = ({ color = '#ff0000' }) => {\n const playheadRef = useRef<HTMLDivElement>(null);\n // Per instance: two visualizations under one provider each have a playhead,\n // and the registry keeps one callback per id.\n const frameCallbackId = useId();\n\n const { currentTimeRef, visualTimeRef, registerFrameCallback, unregisterFrameCallback } =\n usePlaybackRefs();\n const { isPlaying } = useIsPlaying();\n // Subscribed for the re-render only: the resting-position effect below\n // reads the refs.\n useCurrentTime();\n const { sampleRate } = usePlaylistView();\n // The view option, published by the root (#689).\n const { progressBarWidth } = usePlaylistInfo();\n const { samplesPerPixel } = usePlaylistZoom();\n\n // Register per-frame callback during playback\n useEffect(() => {\n if (isPlaying) {\n registerFrameCallback(\n frameCallbackId,\n ({ visualTime, sampleRate: sr, samplesPerPixel: spp }) => {\n if (playheadRef.current) {\n const px = (visualTime * sr) / spp;\n playheadRef.current.style.transform = `translate3d(${px}px, 0, 0)`;\n }\n }\n );\n }\n return () => unregisterFrameCallback(frameCallbackId);\n }, [isPlaying, frameCallbackId, registerFrameCallback, unregisterFrameCallback]);\n\n // Update position when not playing (seeks, stops, etc.) — no rAF needed.\n // Reads visualTimeRef so the static playhead lines up with audible output\n // (the pause/seek paths sync visualTimeRef when they update currentTimeRef).\n useEffect(() => {\n if (!isPlaying && playheadRef.current) {\n const time = visualTimeRef.current ?? currentTimeRef.current ?? 0;\n const position = (time * sampleRate) / samplesPerPixel;\n playheadRef.current.style.transform = `translate3d(${position}px, 0, 0)`;\n }\n });\n\n return <PlayheadLine ref={playheadRef} $color={color} $width={progressBarWidth} data-playhead />;\n};\n","/**\n * The options that only affect how a view draws (#689): row height, bar\n * style, playhead width, and whether a multitrack timeline fills its\n * container. One home for them, read by the root of each view below.\n *\n * It is a context and not props of a root or a part because several\n * components draw with these values (the root lays the rows out, the channels\n * draw the bars, the playhead takes its width) and because one set of options\n * often serves several views: ten players on a page, each under its own\n * provider, are styled by one `<WaveformViewOptions>` above them all.\n */\nimport React, { createContext, use, useMemo, type ReactNode } from 'react';\nimport {\n DEFAULT_BAR_GAP,\n DEFAULT_BAR_WIDTH,\n DEFAULT_WAVE_HEIGHT,\n} from '@waveform-playlist/ui-components';\nimport { warnOnce } from './partWarnings';\n\nexport interface WaveformViewOptionsValue {\n /** Height in pixels of one channel of a track. Default: 80 */\n waveHeight?: number;\n /** Width in pixels of a waveform bar. Default: 1 */\n barWidth?: number;\n /** Space in pixels between two bars. Default: 0 */\n barGap?: number;\n /** Draw bars with rounded caps (radius `barWidth / 2`). Default: false */\n roundedBars?: boolean;\n /** Width in pixels of the playhead line. Default: `barWidth + barGap` */\n progressBarWidth?: number;\n /**\n * Draw the timeline at least as wide as its scroll container when the audio\n * is shorter. `WaveformRoot` only: a MediaElement timeline is as long as\n * its audio. Default: false\n */\n fillViewport?: boolean;\n}\n\nexport interface WaveformViewOptionsProps extends WaveformViewOptionsValue {\n children?: ReactNode;\n}\n\nconst NO_OPTIONS: WaveformViewOptionsValue = {};\n\n/** INTERNAL: what the nearest `<WaveformViewOptions>` says, inherited props included. */\nconst WaveformViewOptionsContext = createContext<WaveformViewOptionsValue>(NO_OPTIONS);\n\n/**\n * Sets view options for every waveform root below it, under either provider.\n * It may sit above the provider, and above several.\n *\n * A prop that is left out is taken from the `<WaveformViewOptions>` above\n * (`??`, so `0` and `false` are values), and from the defaults when there is\n * none: nest one to change a single option for part of the tree. A nested one\n * cannot return an option to its default: write the value.\n *\n * It goes ABOVE a root. A root reads the options above itself, so one written\n * among a root's children does nothing for that root (and warns).\n */\nexport const WaveformViewOptions: React.FC<WaveformViewOptionsProps> = ({\n children,\n waveHeight: ownWaveHeight,\n barWidth: ownBarWidth,\n barGap: ownBarGap,\n roundedBars: ownRoundedBars,\n progressBarWidth: ownProgressBarWidth,\n fillViewport: ownFillViewport,\n}) => {\n const above = use(WaveformViewOptionsContext);\n const waveHeight = ownWaveHeight ?? above.waveHeight;\n const barWidth = ownBarWidth ?? above.barWidth;\n const barGap = ownBarGap ?? above.barGap;\n const roundedBars = ownRoundedBars ?? above.roundedBars;\n const progressBarWidth = ownProgressBarWidth ?? above.progressBarWidth;\n const fillViewport = ownFillViewport ?? above.fillViewport;\n // Memoized on the six values: the component that renders this usually\n // holds the tracks and renders whenever they change.\n const value = useMemo<WaveformViewOptionsValue>(\n () => ({ waveHeight, barWidth, barGap, roundedBars, progressBarWidth, fillViewport }),\n [waveHeight, barWidth, barGap, roundedBars, progressBarWidth, fillViewport]\n );\n return <WaveformViewOptionsContext value={value}>{children}</WaveformViewOptionsContext>;\n};\n\n/** INTERNAL: every option with a value, as a root draws with them. */\nexport interface ResolvedViewOptions {\n waveHeight: number;\n barWidth: number;\n barGap: number;\n roundedBars: boolean;\n progressBarWidth: number;\n fillViewport: boolean;\n}\n\nconst isPositive = (value: number) => value > 0;\n\n/**\n * INTERNAL: the options a root draws with. Called by the two roots only; what\n * is drawn below a root reads the resolved values from ui-components'\n * `PlaylistInfoContext`, where the root publishes them once (memoized there).\n *\n * Values that cannot be drawn are replaced, with one development warning per\n * message: a row height or a bar width that is not above 0 becomes the\n * default, a gap that is no number becomes the default, a gap that would put\n * the next bar less than one pixel on is raised until the step is one pixel,\n * and a playhead width that is not above 0 becomes the bar and its gap.\n */\nexport function useResolvedViewOptions(): ResolvedViewOptions {\n const options = use(WaveformViewOptionsContext);\n let waveHeight = options.waveHeight ?? DEFAULT_WAVE_HEIGHT;\n let barWidth = options.barWidth ?? DEFAULT_BAR_WIDTH;\n let barGap = options.barGap ?? DEFAULT_BAR_GAP;\n const roundedBars = options.roundedBars ?? false;\n const fillViewport = options.fillViewport ?? false;\n\n if (!isPositive(waveHeight)) {\n warnOnce(\n `<WaveformViewOptions waveHeight> must be a positive number of pixels: ${String(waveHeight)} ` +\n `is replaced by ${DEFAULT_WAVE_HEIGHT}.`\n );\n waveHeight = DEFAULT_WAVE_HEIGHT;\n }\n if (!isPositive(barWidth)) {\n warnOnce(\n `<WaveformViewOptions barWidth> must be a positive number of pixels: ${String(barWidth)} ` +\n `is replaced by ${DEFAULT_BAR_WIDTH}.`\n );\n barWidth = DEFAULT_BAR_WIDTH;\n }\n if (Number.isNaN(barGap)) {\n warnOnce(\n `<WaveformViewOptions barGap> must be a number of pixels: ${String(barGap)} is replaced by ` +\n `${DEFAULT_BAR_GAP}.`\n );\n barGap = DEFAULT_BAR_GAP;\n }\n if (!(barWidth + barGap >= 1)) {\n const raised = 1 - barWidth;\n warnOnce(\n `<WaveformViewOptions barGap> of ${String(barGap)} with a bar ${barWidth} px wide puts the ` +\n `next bar less than one pixel on, which cannot be drawn: the gap is ${raised}.`\n );\n barGap = raised;\n }\n // As wide as a bar and its gap unless a width is given.\n let progressBarWidth = options.progressBarWidth ?? barWidth + barGap;\n if (!isPositive(progressBarWidth)) {\n warnOnce(\n `<WaveformViewOptions progressBarWidth> must be a positive number of pixels: ` +\n `${String(progressBarWidth)} is replaced by the bar and its gap, ${barWidth + barGap}. ` +\n 'Leave <WaveformPlayhead> out to draw no playhead.'\n );\n progressBarWidth = barWidth + barGap;\n }\n\n // A new object on every call: the roots read its fields, and the frame\n // memoizes what it publishes on those values, so nothing follows its identity.\n return { waveHeight, barWidth, barGap, roundedBars, progressBarWidth, fillViewport };\n}\n","import React, { use } from 'react';\nimport { DragDropProvider } from '@dnd-kit/react';\nimport { RestrictToHorizontalAxis } from '@dnd-kit/abstract/modifiers';\nimport { useTheme, type WaveformPlaylistTheme } from '@waveform-playlist/ui-components';\nimport {\n useActiveAnnotation,\n useAnnotationOptions,\n useAnnotations,\n usePlaybackControls,\n usePlaylistView,\n usePlaylistZoom,\n} from '../contexts/playlistContexts';\nimport { AnnotationIntegrationContext } from '../AnnotationIntegrationContext';\nimport { useClipInteraction } from '../contexts/ClipInteractionContext';\nimport { useAnnotationDragHandlers } from '../hooks/useAnnotationDragHandlers';\nimport { useAnnotationsWithPreview } from '../hooks/useAnnotationsWithPreview';\nimport { useDragSensors } from '../hooks/useDragSensors';\nimport type { GetAnnotationBoxLabelFn } from '../types/annotations';\nimport { AnnotationBoxes } from './AnnotationBoxes';\nimport { useWaveformExtent } from './waveformLayoutContext';\n\n/** An edge moves along time only. */\nconst HORIZONTAL_ONLY = [RestrictToHorizontalAxis];\n\n/** Height in pixels of the row of annotation boxes when `height` is not given. */\nexport const DEFAULT_ANNOTATION_BOXES_HEIGHT = 30;\n\nexport interface WaveformAnnotationBoxesProps {\n /**\n * The label of a box, from the annotation and its index. Default: the\n * annotation's id. Pass a function that keeps its identity (defined outside\n * the component, or memoized): a new one renders every box.\n */\n getLabel?: GetAnnotationBoxLabelFn;\n /** Height of the row in pixels. Default: 30. */\n height?: number;\n}\n\n/**\n * The row of annotation boxes: a part of either root (`WaveformRoot`,\n * `MediaElementWaveformRoot`), as wide as the root's timeline. Needs the\n * annotation integration (`<AnnotationProvider>`); draws nothing without it\n * or without annotations.\n *\n * It wires the drag of a box's edges itself (#686): its own\n * `DragDropProvider` around the row, the moves shown through the provider's\n * preview, one write to the annotation store on release. The edges can be dragged\n * while the provider's `editable` option is on; `linkEndpoints` and\n * `continuousPlay` come from the same place (`useAnnotationOptions()`). The\n * touch setting of the drag is `ClipInteractionOptions`' `touchOptimized`.\n * The box colour is the theme's `annotationBoxBorder`.\n *\n * It is the one part of the view that reads the annotations and the active\n * annotation, so an annotation boundary during playback renders this and not\n * the waveform (#744). Memoized: a render of the component that composes the\n * view does not render it while its props keep their identity.\n */\nexport const WaveformAnnotationBoxes = React.memo(function WaveformAnnotationBoxes({\n getLabel,\n height = DEFAULT_ANNOTATION_BOXES_HEIGHT,\n}: WaveformAnnotationBoxesProps) {\n // An edge can be dragged as far as the timeline is drawn, not only as far as\n // there is audio: annotations may mark what is not recorded yet (chords, a\n // lyric sheet), on an empty timeline or past the end of a take (maintainer's\n // choice, #686). Under the MediaElement root the two lengths are the same.\n const { tracksFullWidth: width, displayDuration } = useWaveformExtent('The annotation boxes');\n const integration = use(AnnotationIntegrationContext);\n const { annotations } = useAnnotations();\n const { editable, linkEndpoints } = useAnnotationOptions();\n const { activeAnnotationId } = useActiveAnnotation();\n const { annotationStore, annotationPreview, playAnnotation } = usePlaybackControls();\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n const { touchOptimized } = useClipInteraction();\n const theme = useTheme() as Partial<WaveformPlaylistTheme>;\n // While an edge is dragged, the boxes follow the drag.\n const shownAnnotations = useAnnotationsWithPreview(annotations, annotationPreview);\n const sensors = useDragSensors({ touchOptimized });\n\n const { onDragStart, onDragMove, onDragEnd } = useAnnotationDragHandlers({\n store: annotationStore,\n preview: annotationPreview,\n samplesPerPixel,\n sampleRate,\n duration: displayDuration,\n linkEndpoints,\n });\n\n // Nothing to draw: mount no drag provider either.\n if (annotations.length === 0 || !integration) return null;\n\n return (\n <DragDropProvider\n sensors={sensors}\n onDragStart={onDragStart}\n onDragMove={onDragMove}\n onDragEnd={onDragEnd}\n modifiers={HORIZONTAL_ONLY}\n >\n <AnnotationBoxes\n annotations={shownAnnotations}\n activeAnnotationId={activeAnnotationId}\n editable={editable}\n width={width}\n height={height}\n color={theme.annotationBoxBorder}\n sampleRate={sampleRate}\n samplesPerPixel={samplesPerPixel}\n getLabel={getLabel}\n onSelect={playAnnotation}\n />\n </DragDropProvider>\n );\n});\n","import { createContext, use } from 'react';\nimport { installCommand } from './utils/installCommand';\nimport type {\n AnnotationData,\n AnnotationAction,\n AnnotationStore,\n AnnotationActionOptions,\n RenderAnnotationItemProps,\n} from '@waveform-playlist/core';\n\n/**\n * Props the browser package passes to the AnnotationText component.\n * Mirrors what `AnnotationList` actually uses.\n */\nexport interface AnnotationTextIntegrationProps {\n annotations: readonly AnnotationData[];\n activeAnnotationId?: string;\n shouldScrollToActive?: boolean;\n scrollActivePosition?: ScrollLogicalPosition;\n scrollActiveContainer?: 'nearest' | 'all';\n editable?: boolean;\n controls?: AnnotationAction[];\n annotationListConfig?: AnnotationActionOptions;\n height?: number;\n /** A click on a row (not in a field being edited, not on an action button). */\n onAnnotationClick?: (annotation: AnnotationData) => void;\n /** Where the list's edits are written: the provider's annotation store. */\n store?: AnnotationStore;\n renderAnnotationItem?: (props: RenderAnnotationItemProps) => React.ReactNode;\n}\n\n/**\n * Props the browser package passes to the AnnotationBox component.\n * Mirrors what `WaveformAnnotationBoxes` actually uses.\n */\nexport interface AnnotationBoxIntegrationProps {\n annotationId: string;\n annotationIndex: number;\n startPosition: number;\n endPosition: number;\n label?: string;\n color?: string;\n isActive?: boolean;\n onClick?: () => void;\n editable?: boolean;\n}\n\n/**\n * Props the browser package passes to the AnnotationBoxesWrapper component.\n * Mirrors what `WaveformAnnotationBoxes` actually uses.\n */\nexport interface AnnotationBoxesWrapperIntegrationProps {\n children?: React.ReactNode;\n height?: number;\n width?: number;\n}\n\n/**\n * Interface for annotation integration provided by @waveform-playlist/annotations.\n *\n * The browser package defines what its views need, and the optional annotations\n * package provides it via <AnnotationProvider>.\n */\nexport interface AnnotationIntegration {\n // Parser functions\n parseAeneas: (data: unknown) => AnnotationData;\n serializeAeneas: (annotation: AnnotationData) => unknown;\n\n // The components browser's own views draw (typed with the props it passes).\n // The checkboxes and the download button are not here: the app renders\n // those itself, from @waveform-playlist/annotations.\n AnnotationText: React.ComponentType<AnnotationTextIntegrationProps>;\n AnnotationBox: React.ComponentType<AnnotationBoxIntegrationProps>;\n AnnotationBoxesWrapper: React.ComponentType<AnnotationBoxesWrapperIntegrationProps>;\n}\n\nexport const AnnotationIntegrationContext = createContext<AnnotationIntegration | null>(null);\n\nexport const AnnotationIntegrationProvider = AnnotationIntegrationContext.Provider;\n\n/**\n * Hook to access annotation integration provided by @waveform-playlist/annotations.\n * Throws if used without <AnnotationProvider> wrapping the component tree.\n *\n * Follows the Kent C. Dodds pattern:\n * https://kentcdodds.com/blog/how-to-use-react-context-effectively\n */\nexport function useAnnotationIntegration(): AnnotationIntegration {\n const context = use(AnnotationIntegrationContext);\n if (!context) {\n throw new Error(\n 'useAnnotationIntegration must be used within <AnnotationProvider>. ' +\n 'Install @waveform-playlist/annotations (' +\n installCommand('@waveform-playlist/annotations') +\n ') and wrap your app with <AnnotationProvider>. ' +\n 'See: https://naomiaro.github.io/waveform-playlist/docs/react/guides/annotations'\n );\n }\n return context;\n}\n","import React, { use } from 'react';\nimport {\n AnnotationIntegrationContext,\n type AnnotationBoxIntegrationProps,\n} from '../AnnotationIntegrationContext';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport type { GetAnnotationBoxLabelFn } from '../types/annotations';\n\ninterface AnnotationBoxItemProps {\n AnnotationBox: React.ComponentType<AnnotationBoxIntegrationProps>;\n annotation: AnnotationData;\n index: number;\n startPosition: number;\n endPosition: number;\n label: string;\n color: string | undefined;\n isActive: boolean;\n editable: boolean;\n onSelect: (annotation: AnnotationData) => void;\n}\n\n/**\n * One annotation box. Memoized: the active annotation changes at every\n * annotation boundary during playback, and only the box that stops being\n * active and the box that becomes active have a changed prop (#740).\n */\nconst AnnotationBoxItem = React.memo(function AnnotationBoxItem({\n AnnotationBox,\n annotation,\n index,\n startPosition,\n endPosition,\n label,\n color,\n isActive,\n editable,\n onSelect,\n}: AnnotationBoxItemProps) {\n return (\n <AnnotationBox\n annotationId={annotation.id}\n annotationIndex={index}\n startPosition={startPosition}\n endPosition={endPosition}\n label={label}\n color={color}\n isActive={isActive}\n onClick={() => onSelect(annotation)}\n editable={editable}\n />\n );\n});\n\nexport interface AnnotationBoxesProps {\n annotations: readonly AnnotationData[];\n activeAnnotationId: string | null;\n /** Whether the box edges can be dragged. */\n editable: boolean;\n /** Width of the row in pixels (the full timeline width). */\n width: number;\n /** Height of the row in pixels. */\n height: number;\n /** Border colour of a box that is not active. Without it, the box's own default. */\n color: string | undefined;\n sampleRate: number;\n samplesPerPixel: number;\n /** Label for a box. Default: the annotation's id. */\n getLabel?: GetAnnotationBoxLabelFn;\n /**\n * Called with the annotation of a clicked box. It is a prop of every\n * memoized box, so it must keep its identity across renders in which only\n * the active annotation changed.\n */\n onSelect: (annotation: AnnotationData) => void;\n}\n\n/**\n * The row of annotation boxes under the waveform (#744). The caller\n * (`WaveformAnnotationBoxes`) reads the provider and passes the values in;\n * drag-and-drop (`DragDropProvider`) is the caller's too. Renders nothing without the\n * annotation integration or without annotations.\n */\nexport const AnnotationBoxes: React.FC<AnnotationBoxesProps> = ({\n annotations,\n activeAnnotationId,\n editable,\n width,\n height,\n color,\n sampleRate,\n samplesPerPixel,\n getLabel,\n onSelect,\n}) => {\n const annotationIntegration = use(AnnotationIntegrationContext);\n\n if (annotations.length === 0 || !annotationIntegration) return null;\n\n const { AnnotationBox, AnnotationBoxesWrapper } = annotationIntegration;\n\n return (\n <AnnotationBoxesWrapper height={height} width={width}>\n {annotations.map((annotation, index) => (\n <AnnotationBoxItem\n key={annotation.id}\n AnnotationBox={AnnotationBox}\n annotation={annotation}\n index={index}\n startPosition={(annotation.start * sampleRate) / samplesPerPixel}\n endPosition={(annotation.end * sampleRate) / samplesPerPixel}\n label={getLabel ? getLabel(annotation, index) : annotation.id}\n color={color}\n isActive={annotation.id === activeAnnotationId}\n editable={editable}\n onSelect={onSelect}\n />\n ))}\n </AnnotationBoxesWrapper>\n );\n};\n","import React, { use, useMemo } from 'react';\nimport type { AnnotationAction, RenderAnnotationItemProps } from '@waveform-playlist/core';\nimport { AnnotationIntegrationContext } from '../AnnotationIntegrationContext';\nimport {\n useActiveAnnotation,\n useAnnotationOptions,\n useAnnotations,\n usePlaybackControls,\n} from '../contexts/playlistContexts';\nimport { useAnnotationsWithPreview } from '../hooks/useAnnotationsWithPreview';\nimport { warnOnce } from './partWarnings';\nimport { installCommand } from '../utils/installCommand';\n\nexport interface AnnotationListProps {\n /** Height of the list in pixels. Without it the list is at most 200 px high. */\n height?: number;\n /**\n * Buttons shown on each row while the provider's `editable` option is on\n * (delete, split, …). An action is called with the annotation, its index,\n * the annotations and `{ linkEndpoints, continuousPlay }` as the provider\n * has them. Pass an array that keeps its identity: a new one renders every\n * row.\n */\n actions?: AnnotationAction[];\n /**\n * Where the active annotation is put when the list scrolls to it during\n * playback, or `'none'` for a list that does not follow. Default: `'center'`.\n */\n scrollActivePosition?: ScrollLogicalPosition | 'none';\n /** Which containers scroll: only the list (`'nearest'`), or the page too (`'all'`). Default: `'nearest'`. */\n scrollActiveContainer?: 'nearest' | 'all';\n /**\n * Draws a row, in place of the default one: called with\n * `{ annotation, index, isActive, onClick, formatTime }`. Define the\n * function outside the component (or memoize it): one written inline is a\n * new function on every render of your component and renders every row.\n */\n children?: (item: RenderAnnotationItemProps) => React.ReactNode;\n}\n\n/**\n * The annotation text list, for both providers (#686). Render it anywhere\n * under the provider: below the view, in a sidebar, more than once. It reads\n * everything from the provider (the annotations, the active one, the\n * `editable` / `linkEndpoints` / `continuousPlay` options) and writes edits\n * to the provider's annotation store. A click on a row plays the\n * annotation, as a click on its box does.\n *\n * Needs the annotation integration (`<AnnotationProvider>` from\n * `@waveform-playlist/annotations`). Without it, and without annotations, it\n * draws nothing.\n *\n * It renders at every annotation boundary during playback, and the rows are\n * memoized, so everything it hands down except the active annotation keeps\n * its identity across such a render.\n */\nexport const AnnotationList: React.FC<AnnotationListProps> = ({\n height,\n actions,\n scrollActivePosition = 'center',\n scrollActiveContainer = 'nearest',\n children,\n}) => {\n const integration = use(AnnotationIntegrationContext);\n const { annotations } = useAnnotations();\n const { editable, linkEndpoints, continuousPlay } = useAnnotationOptions();\n const { activeAnnotationId } = useActiveAnnotation();\n const { annotationStore, annotationPreview, playAnnotation } = usePlaybackControls();\n // While an edge is dragged, the times in the list follow it.\n const shownAnnotations = useAnnotationsWithPreview(annotations, annotationPreview);\n\n // The fourth argument of an action. Memoized: it is a dependency of a\n // handler given to every memoized row.\n const actionOptions = useMemo(\n () => ({ linkEndpoints, continuousPlay }),\n [linkEndpoints, continuousPlay]\n );\n\n if (annotations.length === 0) return null;\n\n if (!integration) {\n warnOnce(\n '<AnnotationList> draws nothing without the annotation components: ' +\n 'install @waveform-playlist/annotations (' +\n installCommand('@waveform-playlist/annotations') +\n ') and render <AnnotationProvider> above it. ' +\n 'See: https://naomiaro.github.io/waveform-playlist/docs/react/guides/annotations'\n );\n return null;\n }\n\n const { AnnotationText } = integration;\n const follows = scrollActivePosition !== 'none';\n\n return (\n <AnnotationText\n annotations={shownAnnotations}\n activeAnnotationId={activeAnnotationId ?? undefined}\n shouldScrollToActive={follows}\n scrollActivePosition={follows ? scrollActivePosition : undefined}\n scrollActiveContainer={scrollActiveContainer}\n editable={editable}\n controls={editable ? actions : undefined}\n annotationListConfig={actionOptions}\n height={height}\n onAnnotationClick={playAnnotation}\n store={annotationStore}\n renderAnnotationItem={children}\n />\n );\n};\n","import React from 'react';\nimport { WaveformRoot } from './WaveformRoot';\nimport {\n WaveformClipHeaders,\n WaveformFades,\n WaveformLoopRegion,\n WaveformPlayhead,\n WaveformSelection,\n WaveformTimescale,\n WaveformTrackControls,\n WaveformTracks,\n} from './waveformParts';\nimport { WaveformAnnotationBoxes } from './WaveformAnnotationBoxes';\nimport { AnnotationList } from './AnnotationList';\n\n/**\n * The props of the two ready-made multitrack views: `className`. What the\n * view is made of is not an option here, and neither are the options of its\n * parts (#686 moved the annotation ones onto `WaveformAnnotationBoxes` and\n * `AnnotationList`). For anything else, compose the parts inside\n * `WaveformRoot`.\n */\nexport interface WaveformProps {\n className?: string;\n}\n\nexport type WaveformEditorProps = WaveformProps;\n\n// The parts that take no option are the same elements on every render: a\n// render of the composition then hands the root children it has seen, and\n// React skips every one of them (the tracks part included, which is not\n// memoized because a consumer's children usually are new).\nconst TIMESCALE = <WaveformTimescale />;\nconst LOOP_REGION = <WaveformLoopRegion />;\nconst TRACK_CONTROLS = <WaveformTrackControls />;\nconst TRACKS = <WaveformTracks />;\nconst TRACKS_WITH_HEADERS_AND_FADES = (\n <WaveformTracks>\n <WaveformClipHeaders />\n <WaveformFades />\n </WaveformTracks>\n);\nconst SELECTION = <WaveformSelection />;\nconst PLAYHEAD = <WaveformPlayhead />;\nconst ANNOTATION_BOXES = <WaveformAnnotationBoxes />;\n// Draws nothing while there are no annotations.\nconst ANNOTATION_LIST = <AnnotationList />;\n\ninterface CompositionProps extends WaveformProps {\n tracks: React.ReactElement;\n}\n\n/** Not a component: called by the two below, so neither gains a layer. */\nfunction composeWaveform({ tracks, className }: CompositionProps) {\n return (\n <>\n <WaveformRoot className={className}>\n {TIMESCALE}\n {LOOP_REGION}\n {TRACK_CONTROLS}\n {tracks}\n {ANNOTATION_BOXES}\n {SELECTION}\n {PLAYHEAD}\n </WaveformRoot>\n {ANNOTATION_LIST}\n </>\n );\n}\n\n/**\n * The multitrack view, ready-made: the timescale, the loop region, the track\n * controls (200 px), the tracks, the annotation boxes, the selection and the\n * playhead, with the annotation text list below when there are annotations.\n *\n * It is a composition of the public parts with no options for them. To leave\n * a part out, give one an option (`renderTick`, a column width, a label for\n * the annotation boxes, a height or actions for the annotation list), compose the\n * panel of a track (a remove button, a reorder grip, your own control) or\n * add your own element, write the composition yourself:\n *\n * ```tsx\n * <WaveformRoot>\n * <WaveformTimescale />\n * <WaveformLoopRegion />\n * <WaveformTrackControls />\n * <WaveformTracks />\n * <WaveformAnnotationBoxes />\n * <WaveformSelection />\n * <WaveformPlayhead />\n * </WaveformRoot>\n * <AnnotationList />\n * ```\n */\nexport const Waveform: React.FC<WaveformProps> = (props) =>\n composeWaveform({ ...props, tracks: TRACKS });\n\n/**\n * `Waveform` with clip headers and fade curves: `<WaveformTracks>` holds\n * `<WaveformClipHeaders />` and `<WaveformFades />`. Inside a\n * `ClipInteractionProvider` the header is what a clip is dragged by, and the\n * trim handles come with it.\n */\nexport const WaveformEditor: React.FC<WaveformEditorProps> = (props) =>\n composeWaveform({ ...props, tracks: TRACKS_WITH_HEADERS_AND_FADES });\n","import React, { useCallback, useMemo, type ReactNode } from 'react';\nimport { DevicePixelRatioProvider, CLIP_HEADER_HEIGHT } from '@waveform-playlist/ui-components';\nimport type { RenderMode } from '@waveform-playlist/core';\nimport {\n MEDIA_ELEMENT_TRACK_ID,\n useMediaElementTrack,\n usePlaybackControls,\n} from '../contexts/playlistContexts';\nimport { computeTrackLayout } from '../utils/trackOrderPreview';\nimport type { TrackClipPeaks } from '../WaveformPlaylistContext';\nimport type { SpectrogramTrackHelpers } from './TrackRows';\nimport { getTrackChannelCount } from './visualizationLayout';\nimport type { WaveformRow, WaveformRowsValue } from './waveformLayoutContext';\nimport { useWaveformFrame, useWaveformParts } from './waveformFrame';\nimport { useResolvedViewOptions } from './WaveformViewOptions';\nimport { warnMisplacedPart } from './partWarnings';\n\n// A MediaElement player has one audio track and nothing a row can be asked to\n// do: module constants, so the rows value changes only with the peaks, the\n// wave height and the clip-headers marker.\nconst ONE_ROW: ReadonlyArray<WaveformRow> = [{ id: MEDIA_ELEMENT_TRACK_ID, kind: 'audio' }];\n// The peaks of a row with no clip: what is drawn when the provider has none.\nconst ONE_EMPTY_ROW: TrackClipPeaks[] = [[]];\nconst NO_RENDER_MODES: ReadonlyMap<string, RenderMode> = new Map();\nconst NO_SPECTROGRAM_HELPERS: ReadonlyMap<string, SpectrogramTrackHelpers> = new Map();\nconst nothing = () => {};\n\nexport interface MediaElementWaveformRootProps {\n className?: string;\n /** The parts, and anything else to draw over the track. */\n children?: ReactNode;\n}\n\n/**\n * The root of the MediaElement view (#685), exported from the package.\n *\n * The counterpart of `WaveformRoot` for `MediaElementPlaylistProvider`: it\n * works out what only this provider knows (the timeline is as long as the\n * audio; there is one row, empty when its peaks could not be extracted) and hands it to\n * the shared frame. The parts are the multitrack view's.\n *\n * It renders on what the frame follows (a drag in progress, play and stop, a\n * zoom, the view settings, the theme), when the track or its peaks change, when the\n * player becomes ready, and whenever the component that composes it renders.\n * The root's render never renders a part; a part renders when a value it\n * reads changes. See `WaveformRoot`.\n *\n * No controls column is drawn: there is no controls part for this provider.\n */\nexport const MediaElementWaveformRoot: React.FC<MediaElementWaveformRootProps> = ({\n className,\n children,\n}) => {\n const { setSelection } = usePlaybackControls();\n const { duration, peaksDataArray } = useMediaElementTrack();\n // `fillViewport` is not read here: this timeline is as long as its audio.\n const viewOptions = useResolvedViewOptions();\n const { waveHeight } = viewOptions;\n\n const parts = useWaveformParts(children);\n if (parts.controls) {\n warnMisplacedPart(\n '<WaveformTrackControls> draws nothing inside <MediaElementWaveformRoot>: a MediaElement ' +\n 'player has one track and no mixer. Remove it.'\n );\n }\n const { showClipHeaders } = parts.tracksOptions;\n\n const rows = useMemo<WaveformRowsValue>(() => {\n // No peaks: they could not be extracted (the provider logged it). The row\n // is drawn all the same, one channel tall and with no clip in it, so the\n // timeline keeps its height and can be clicked.\n const rowList = ONE_ROW;\n const rowPeaks = peaksDataArray.length > 0 ? peaksDataArray : ONE_EMPTY_ROW;\n const trackHeightById = new Map<string, number>();\n rowList.forEach((row, index) => {\n const channels = getTrackChannelCount(rowPeaks[index], 0);\n trackHeightById.set(\n row.id,\n waveHeight * channels + (showClipHeaders ? CLIP_HEADER_HEIGHT : 0)\n );\n });\n return {\n rows: rowList,\n peaksDataArray: rowPeaks,\n showClipHeaders,\n trackHeightById,\n trackLayout: computeTrackLayout(\n rowList.map((row) => row.id),\n trackHeightById\n ),\n animateTrackLayout: false,\n renderModeById: NO_RENDER_MODES,\n spectrogramHelpersById: NO_SPECTROGRAM_HELPERS,\n selectTrack: nothing,\n setSettingsModalTrackId: nothing,\n recordingChannelCount: 0,\n dragSourceTrackId: null,\n };\n }, [peaksDataArray, waveHeight, showClipHeaders]);\n\n // A click while stopped collapses the selection at its time, which moves\n // the cursor.\n const collapseSelectionAt = useCallback(\n (time: number) => setSelection(time, time),\n [setSelection]\n );\n\n const frame = useWaveformFrame({\n className,\n viewOptions,\n parts,\n displayDuration: duration,\n rows,\n // The waveform is drawn from the provider's first render: it does not\n // wait for the player (`useMediaElementTrack().isReady` is that).\n playlistState: 'ready',\n controlsWidth: 0,\n onClickWhileStopped: collapseSelectionAt,\n });\n\n return <DevicePixelRatioProvider>{frame}</DevicePixelRatioProvider>;\n};\n","import React from 'react';\nimport { MediaElementWaveformRoot } from './MediaElementWaveformRoot';\nimport {\n WaveformPlayhead,\n WaveformSelection,\n WaveformTimescale,\n WaveformTracks,\n} from './waveformParts';\nimport { WaveformAnnotationBoxes } from './WaveformAnnotationBoxes';\nimport { AnnotationList } from './AnnotationList';\n\n/**\n * `className`. What the view is made of is not an option here, and neither\n * are the options of its parts: compose the parts inside\n * `MediaElementWaveformRoot` for anything else.\n */\nexport interface MediaElementWaveformProps {\n className?: string;\n}\n\n// The same elements on every render, so a render of the composition does not\n// render these parts (see Waveform.tsx).\nconst TIMESCALE = <WaveformTimescale />;\nconst TRACKS = <WaveformTracks />;\nconst SELECTION = <WaveformSelection />;\nconst PLAYHEAD = <WaveformPlayhead />;\nconst ANNOTATION_BOXES = <WaveformAnnotationBoxes />;\n// Draws nothing while there are no annotations.\nconst ANNOTATION_LIST = <AnnotationList />;\n\n/**\n * The view of `MediaElementPlaylistProvider`, ready-made: the timescale, the\n * one track, the annotation boxes, the selection and the playhead, with the\n * annotation text list below when there are annotations.\n *\n * It is a composition of the public parts with no options for them. To leave\n * the timescale out, show fades, use your own playhead or give the\n * annotation boxes or the annotation list an option, write the composition\n * yourself:\n *\n * ```tsx\n * <MediaElementWaveformRoot>\n * <WaveformTimescale />\n * <WaveformTracks>\n * <WaveformFades />\n * </WaveformTracks>\n * <WaveformAnnotationBoxes />\n * <WaveformSelection />\n * <WaveformPlayhead renderPlayhead={…} />\n * </MediaElementWaveformRoot>\n * <AnnotationList />\n * ```\n */\nexport const MediaElementWaveform: React.FC<MediaElementWaveformProps> = ({ className }) => (\n <>\n <MediaElementWaveformRoot className={className}>\n {TIMESCALE}\n {TRACKS}\n {ANNOTATION_BOXES}\n {SELECTION}\n {PLAYHEAD}\n </MediaElementWaveformRoot>\n {ANNOTATION_LIST}\n </>\n);\n","import React from 'react';\nimport type { KeyboardShortcut } from '@waveform-playlist/core';\nimport { usePlaybackShortcuts } from '../hooks/usePlaybackShortcuts';\nimport { useClipSplitting } from '../hooks/useClipSplitting';\nimport { useAnnotationKeyboardControls } from '../hooks/useAnnotationKeyboardControls';\nimport {\n useActiveAnnotation,\n usePlaylistZoom,\n usePlaylistTimeline,\n useAnnotations,\n useAnnotationOptions,\n usePlaybackControls,\n useEditorControls,\n} from '../contexts/playlistContexts';\n\nexport interface KeyboardShortcutsProps {\n /** Enable default playback shortcuts (Space, Escape, 0). Defaults to false. */\n playback?: boolean;\n /** Enable clip splitting shortcut ('s' key). Defaults to false. */\n clipSplitting?: boolean;\n /** Enable annotation keyboard controls (arrow nav, boundary editing). Defaults to false. */\n annotations?: boolean;\n /** Enable undo/redo shortcuts (Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z). Defaults to false. */\n undo?: boolean;\n /** Additional shortcuts appended to the defaults. */\n additionalShortcuts?: KeyboardShortcut[];\n}\n\n/**\n * Self-closing component that sets up keyboard shortcuts for the playlist.\n * Must be rendered inside a WaveformPlaylistProvider.\n *\n * @example\n * ```tsx\n * <WaveformPlaylistProvider arrangement={arrangement} {...}>\n * <KeyboardShortcuts playback clipSplitting />\n * <Waveform />\n * </WaveformPlaylistProvider>\n * ```\n */\nexport const KeyboardShortcuts: React.FC<KeyboardShortcutsProps> = ({\n playback = false,\n clipSplitting = false,\n annotations = false,\n undo: undoEnabled = false,\n additionalShortcuts = [],\n}) => {\n // Clip splitting setup\n const { samplesPerPixel } = usePlaylistZoom();\n const { duration } = usePlaylistTimeline();\n const { annotations: annotationList } = useAnnotations();\n const { linkEndpoints, continuousPlay } = useAnnotationOptions();\n const { activeAnnotationId } = useActiveAnnotation();\n const { annotationStore, setActiveAnnotationId, scrollContainerRef, play } =\n usePlaybackControls();\n const { undo, redo } = useEditorControls();\n\n const { splitClipAtPlayhead } = useClipSplitting({ samplesPerPixel });\n\n // Build additional shortcuts from enabled features\n const allAdditional: KeyboardShortcut[] = [];\n\n if (clipSplitting) {\n allAdditional.push({\n key: 's',\n action: splitClipAtPlayhead,\n description: 'Split clip at playhead',\n preventDefault: true,\n });\n }\n\n if (undoEnabled) {\n allAdditional.push(\n { key: 'z', ctrlKey: true, shiftKey: false, action: undo, description: 'Undo' },\n { key: 'z', metaKey: true, shiftKey: false, action: undo, description: 'Undo' },\n { key: 'z', ctrlKey: true, shiftKey: true, action: redo, description: 'Redo' },\n { key: 'z', metaKey: true, shiftKey: true, action: redo, description: 'Redo' }\n );\n }\n\n if (additionalShortcuts.length > 0) {\n allAdditional.push(...additionalShortcuts);\n }\n\n // Playback shortcuts (or just additional if playback is off)\n usePlaybackShortcuts({\n enabled: playback || allAdditional.length > 0,\n ...(playback ? { additionalShortcuts: allAdditional } : { shortcuts: allAdditional }),\n });\n\n // Annotation keyboard controls\n useAnnotationKeyboardControls({\n store: annotationStore,\n activeAnnotationId,\n onActiveAnnotationChange: setActiveAnnotationId,\n duration,\n linkEndpoints,\n continuousPlay,\n scrollContainerRef,\n onPlay: play,\n enabled: annotations && annotationList.length > 0,\n });\n\n return null;\n};\n","import { useEffect } from 'react';\nimport { useEditorControls } from '../contexts/playlistContexts';\n\nexport interface RecordingSessionOptions {\n /** True while a take is being recorded. */\n isRecording: boolean;\n /** The track being recorded into, or null when there is none. */\n trackId: string | null | undefined;\n}\n\n/**\n * Tells the playlist that a take is being recorded into a track, for as long\n * as `isRecording` is true (#685). The provider then keeps playback running\n * past the end of the audio and mutes the armed track in the arrangement for\n * the take, so what it already holds does not play under a punch-in that\n * replaces it (#812: the mixer shows the track muted, its built-in Mute\n * button is disabled and `useTrack().isRecordingArmed` is true). The mute\n * from before the take is written back when the take ends, the track changes\n * or the component unmounts, whatever was set in between; the provider also\n * writes it back in its own cleanup (its unmount or an `<Activity>` hide)\n * while a track is still armed. An `<Activity>` hide of the component ends\n * the session the same way, and the reveal starts it again from the track's\n * mute at that moment.\n *\n * Call it in the component that calls `useIntegratedRecording`, under\n * `WaveformPlaylistProvider`. `<WaveformRecordingPreview>` only draws the\n * take: without this hook the armed track is not muted.\n *\n * A handler that starts playback together with the recording should also call\n * `setRecordingActive(true, trackId)` (from `useEditorControls()`) before\n * `play()`: this effect runs after the render that follows, which is too late\n * for the first animation frame. `play()` does nothing before the playlist's\n * first ready (`usePlaylistTimeline().isReady`), so a take started during the\n * first load records without playback.\n */\nexport function useRecordingSession({ isRecording, trackId }: RecordingSessionOptions): void {\n const { setRecordingActive } = useEditorControls();\n const armedTrackId = trackId ?? null;\n useEffect(() => {\n if (!isRecording) return undefined;\n setRecordingActive(true, armedTrackId);\n return () => setRecordingActive(false);\n }, [isRecording, armedTrackId, setRecordingActive]);\n}\n","import React, { useCallback, useMemo, useRef } from 'react';\nimport { flushSync } from 'react-dom';\nimport { DragDropProvider } from '@dnd-kit/react';\nimport { RestrictToHorizontalAxis } from '@dnd-kit/abstract/modifiers';\nimport type { Modifiers } from '@dnd-kit/abstract';\nimport {\n samplesToTicks,\n ticksToSamples,\n snapToGrid,\n ticksPerBeat,\n ticksPerBar,\n} from '@waveform-playlist/core';\nimport { useBeatsAndBars, getScaleInfo } from '@waveform-playlist/ui-components';\n\nimport {\n usePlaylistView,\n usePlaylistZoom,\n usePlaylistTimeline,\n useEditorControls,\n} from '../contexts/playlistContexts';\nimport { useClipDragHandlers } from '../hooks/useClipDragHandlers';\nimport { useDragSensors } from '../hooks/useDragSensors';\nimport { ClipCollisionModifier } from '../modifiers/ClipCollisionModifier';\nimport { SnapToGridModifier } from '../modifiers/SnapToGridModifier';\nimport { ClipInteractionOptions, useClipInteraction } from '../contexts/ClipInteractionContext';\n\nexport interface ClipInteractionProviderProps {\n /** Enable snap-to-grid for clip moves and boundary trims. When true,\n * auto-detects beats snapping from BeatsAndBarsProvider context\n * (if present with scaleMode=\"beats\" and snapTo!=\"off\"), otherwise\n * falls back to timescale-based snapping. Default: false. */\n snap?: boolean;\n /** Touch-friendly interaction: drag sensors that wait 250ms on touch (so a\n * swipe still scrolls) and wider clip trim handles. Left out: inherited from\n * a `ClipInteractionOptions` or `ClipInteractionProvider` above (false at\n * the top). */\n touchOptimized?: boolean;\n children: React.ReactNode;\n}\n\nexport const ClipInteractionProvider: React.FC<ClipInteractionProviderProps> = ({\n snap = false,\n touchOptimized: touchOptimizedProp,\n children,\n}) => {\n // One value for the sensors and for the handles (which `ClipInteractionOptions`\n // below resolves the same way): the prop, else what is set above.\n const inherited = useClipInteraction();\n const touchOptimized = touchOptimizedProp ?? inherited.touchOptimized;\n const { sampleRate } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n const { tracks } = usePlaylistTimeline();\n const { setSelectedTrackId, reorderTrack, bumpTrackReorderEpoch, setTrackDragPreview } =\n useEditorControls();\n const beatsAndBars = useBeatsAndBars();\n\n // Derive snap mode from context: beats if provider is in beats mode with snap enabled,\n // timescale otherwise, off when snap prop is false.\n const useBeatsSnap =\n snap &&\n beatsAndBars != null &&\n beatsAndBars.scaleMode === 'beats' &&\n beatsAndBars.snapTo !== 'off';\n const useTimescaleSnap = snap && !useBeatsSnap;\n\n // Build snapSamplePosition for boundary trim snapping\n const snapSamplePosition = useMemo(() => {\n if (useBeatsSnap && beatsAndBars) {\n const { bpm, timeSignature, snapTo } = beatsAndBars;\n const gridTicks = snapTo === 'bar' ? ticksPerBar(timeSignature) : ticksPerBeat(timeSignature);\n return (samplePos: number) => {\n const ticks = samplesToTicks(samplePos, bpm, sampleRate);\n const snapped = snapToGrid(ticks, gridTicks);\n return ticksToSamples(snapped, bpm, sampleRate);\n };\n }\n if (useTimescaleSnap) {\n const gridSamples = Math.round((getScaleInfo(samplesPerPixel).smallStep / 1000) * sampleRate);\n return (samplePos: number) => Math.round(samplePos / gridSamples) * gridSamples;\n }\n return undefined;\n }, [useBeatsSnap, useTimescaleSnap, beatsAndBars, sampleRate, samplesPerPixel]);\n\n // The modifiers and the track selection on drag start read the loaded\n // tracks through this ref, so their identity does not change when tracks\n // do: keyed on tracks, the modifiers array handed to DragDropProvider would\n // be rebuilt by any clip operation, also one that lands mid-drag.\n const tracksRef = useRef(tracks);\n tracksRef.current = tracks;\n const getTracks = useCallback(() => tracksRef.current, []);\n\n // Sensors\n const sensors = useDragSensors({ touchOptimized });\n\n // Drag handlers\n const {\n onDragStart: handleDragStart,\n onDragMove,\n onDragEnd,\n } = useClipDragHandlers({ samplesPerPixel, snapSamplePosition });\n\n // True from the start of a track-reorder drag to its end. dnd-kit can send\n // one more dragover AFTER the dragend of a canceled drag (the sorting\n // plugin putting the item back): seen with Escape mid-drag once the slot's\n // element was registered from the reorder handle's effect (#687), where it\n // set the preview again for good. A preview without a drag is never wanted.\n const trackReorderDragActiveRef = React.useRef(false);\n\n // Wrap onDragStart to auto-select track\n const onDragStart = React.useCallback(\n (event: Parameters<typeof handleDragStart>[0]) => {\n const data = event.operation?.source?.data as\n | { kind?: string; trackId?: string; trackIndex?: number }\n | undefined;\n if (data?.kind === 'track-reorder') {\n trackReorderDragActiveRef.current = true;\n if (data.trackId) setSelectedTrackId(data.trackId);\n return; // clip handler guards also skip this kind\n }\n const trackIndex = data?.trackIndex;\n const track = trackIndex !== undefined ? tracksRef.current[trackIndex] : undefined;\n if (track) {\n setSelectedTrackId(track.id);\n }\n handleDragStart(event);\n },\n [handleDragStart, setSelectedTrackId]\n );\n\n // Publish the live track-reorder preview. dnd-kit fires dragover on every\n // collision change; OptimisticSortingPlugin has already updated\n // source.sortable.index by then. Functional set with an equality guard so\n // repeated dragovers at the same index don't re-render the playlist.\n const handleDragOver = React.useCallback(\n (event: { operation: { source?: { data?: unknown } | null } }) => {\n const data = event.operation.source?.data as { kind?: string; trackId?: string } | undefined;\n if (data?.kind !== 'track-reorder' || !data.trackId) return;\n if (!trackReorderDragActiveRef.current) return;\n const sortable = (\n event.operation.source as unknown as {\n sortable?: { index: number; initialIndex: number };\n }\n ).sortable;\n if (!sortable) return;\n const trackId = data.trackId;\n const toIndex = sortable.index;\n setTrackDragPreview((prev) =>\n prev && prev.trackId === trackId && prev.toIndex === toIndex ? prev : { trackId, toIndex }\n );\n },\n [setTrackDragPreview]\n );\n\n // Wrap onDragEnd: track-reorder sources commit via reorderTrack, clip sources\n // flow through to the existing move/trim handler unchanged.\n const handleDragEnd = React.useCallback(\n (event: Parameters<typeof onDragEnd>[0]) => {\n const data = event.operation.source?.data as { kind?: string; trackId?: string } | undefined;\n if (data?.kind === 'track-reorder') {\n trackReorderDragActiveRef.current = false;\n const sortable = (\n event.operation.source as unknown as {\n sortable?: { index: number; initialIndex: number };\n }\n ).sortable;\n const trackId = data.trackId;\n const moves =\n !event.canceled && trackId && sortable && sortable.index !== sortable.initialIndex;\n // ONE commit for the three: the reorder, the cleared preview and the\n // epoch. dnd-kit calls this inside `startTransition`, where the two\n // state updates would wait as transition updates while the reorder\n // (the arrangement, read with `useSyncExternalStore`) renders at\n // once: React would first move the slots under their old keys, which\n // is what the epoch is there to avoid, and remount them a commit\n // later. `flushSync` renders all three together.\n flushSync(() => {\n // Unconditional, regardless of canceled/committed: @dnd-kit/react's\n // sortable plugins can splice React-owned DOM nodes (Feedback's\n // placeholder, OptimisticSortingPlugin's reorder()) during the drag\n // that just ended, desyncing React's fiber tree from the true DOM.\n // Bumping this forces the view's track-controls part to remount the\n // track-controls slots, healing the corruption before the next\n // reorder (drag or button) needs to touch the DOM. See\n // bumpTrackReorderEpoch's doc comment in WaveformPlaylistContext.\n bumpTrackReorderEpoch();\n // The columns go straight from the previewed layout to the\n // committed one, with no frame in between.\n setTrackDragPreview(null);\n if (moves) reorderTrack(trackId, sortable.index);\n });\n return;\n }\n onDragEnd(event);\n },\n [onDragEnd, reorderTrack, bumpTrackReorderEpoch, setTrackDragPreview]\n );\n\n // Build modifiers array\n const modifiers = useMemo(() => {\n const mods: Modifiers = [RestrictToHorizontalAxis];\n\n if (useBeatsSnap && beatsAndBars) {\n mods.push(\n SnapToGridModifier.configure({\n mode: 'beats',\n snapTo: beatsAndBars.snapTo,\n bpm: beatsAndBars.bpm,\n timeSignature: beatsAndBars.timeSignature,\n samplesPerPixel,\n sampleRate,\n })\n );\n } else if (useTimescaleSnap) {\n mods.push(\n SnapToGridModifier.configure({\n mode: 'timescale',\n gridSamples: Math.round((getScaleInfo(samplesPerPixel).smallStep / 1000) * sampleRate),\n samplesPerPixel,\n })\n );\n }\n\n mods.push(ClipCollisionModifier.configure({ tracks: getTracks, samplesPerPixel }));\n return mods;\n }, [useBeatsSnap, useTimescaleSnap, beatsAndBars, getTracks, samplesPerPixel, sampleRate]);\n\n return (\n <ClipInteractionOptions enabled touchOptimized={touchOptimized}>\n <DragDropProvider\n sensors={sensors}\n onDragStart={onDragStart}\n onDragMove={onDragMove}\n onDragOver={handleDragOver}\n onDragEnd={handleDragEnd}\n modifiers={modifiers}\n >\n {children}\n </DragDropProvider>\n </ClipInteractionOptions>\n );\n};\n","import {\n Modifier,\n configurator,\n type DragDropManager,\n type DragOperation,\n} from '@dnd-kit/abstract';\nimport { constrainClipDrag } from '@waveform-playlist/engine';\nimport type { ClipTrack, AudioClip } from '@waveform-playlist/core';\nimport { sortedClipsOf } from '../utils/sortedClips';\n\ninterface ClipCollisionOptions {\n /**\n * The tracks to check against, or a function returning them. Pass a function\n * (reading a ref, say) to keep the configured modifier's identity stable while\n * tracks change, so the modifiers array handed to DragDropProvider is not\n * rebuilt on every edit.\n */\n tracks: readonly ClipTrack[] | (() => readonly ClipTrack[]);\n samplesPerPixel: number;\n}\n\n/**\n * Modifier that constrains clip drag movement to prevent overlaps.\n *\n * For clip move operations: constrains horizontal transform to valid positions\n * using the engine's collision detection.\n *\n * For boundary trim operations: returns zero transform because the trim is\n * shown by the trim preview, which draws the clip at its previewed geometry,\n * not by a CSS translate.\n */\nexport class ClipCollisionModifier extends Modifier<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n DragDropManager<any, any>,\n ClipCollisionOptions\n> {\n apply(operation: DragOperation): { x: number; y: number } {\n const { transform, source } = operation;\n\n if (!source?.data || !this.options) return transform;\n\n // `clipIndex` is a position in the drawn row, not in `track.clips`: the clip\n // is found by its id.\n const { boundary, trackIndex, clipId } = source.data as {\n boundary?: 'left' | 'right';\n trackIndex: number;\n clipId: string;\n };\n\n // Boundary trims: zero transform (the trim preview draws the clip)\n if (boundary) return { x: 0, y: 0 };\n\n const { samplesPerPixel } = this.options;\n const tracks =\n typeof this.options.tracks === 'function' ? this.options.tracks() : this.options.tracks;\n const track = tracks[trackIndex];\n if (!track) return transform;\n\n const clip = track.clips.find((c: AudioClip) => c.id === clipId);\n if (!clip) return transform;\n\n // Convert pixel delta to samples, constrain, convert back\n const deltaSamples = transform.x * samplesPerPixel;\n const sortedClips = sortedClipsOf(track.clips);\n const sortedIndex = sortedClips.findIndex((c: AudioClip) => c.id === clip.id);\n const constrainedDelta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);\n\n return { x: constrainedDelta / samplesPerPixel, y: 0 };\n }\n\n static configure = configurator(ClipCollisionModifier);\n}\n","import {\n Modifier,\n configurator,\n type DragDropManager,\n type DragOperation,\n} from '@dnd-kit/abstract';\nimport {\n ticksPerBeat,\n ticksPerBar,\n ticksToSamples,\n samplesToTicks,\n snapToGrid,\n} from '@waveform-playlist/core';\nimport type { BeatsAndBarsSnapTo } from '@waveform-playlist/ui-components';\n\ninterface SnapToGridBeatsOptions {\n mode: 'beats';\n snapTo: BeatsAndBarsSnapTo;\n bpm: number;\n timeSignature: [number, number];\n samplesPerPixel: number;\n sampleRate: number;\n}\n\ninterface SnapToGridTimescaleOptions {\n mode: 'timescale';\n gridSamples: number;\n samplesPerPixel: number;\n}\n\ntype SnapToGridOptions = SnapToGridBeatsOptions | SnapToGridTimescaleOptions;\n\n/**\n * dnd-kit modifier that quantizes clip drag movement to a grid.\n *\n * Two modes:\n * - \"beats\": Snaps to beat/bar grid using PPQN tick space for exact musical timing.\n * - \"timescale\": Snaps to a sample-based grid derived from timescale markers.\n *\n * Designed to compose with ClipCollisionModifier — snap first,\n * then collision constrains the snapped position.\n */\nexport class SnapToGridModifier extends Modifier<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n DragDropManager<any, any>,\n SnapToGridOptions\n> {\n apply(operation: DragOperation): { x: number; y: number } {\n const { transform, source } = operation;\n\n if (!this.options || !source?.data) return transform;\n\n // Don't snap boundary trims — snapping for trims is handled in the drag handler\n const { boundary, startSample } = source.data as {\n boundary?: 'left' | 'right';\n startSample?: number;\n };\n if (boundary) return transform;\n\n const { samplesPerPixel } = this.options;\n\n // Snap the absolute position (not just the delta) so clips land exactly\n // on grid lines even if they started off-grid.\n if (this.options.mode === 'timescale') {\n const { gridSamples } = this.options;\n if (startSample !== undefined) {\n const proposedPosition = startSample + transform.x * samplesPerPixel;\n const snappedPosition = Math.round(proposedPosition / gridSamples) * gridSamples;\n return { x: (snappedPosition - startSample) / samplesPerPixel, y: 0 };\n }\n // Fallback: snap delta (no startSample available)\n const deltaSamples = transform.x * samplesPerPixel;\n const snappedSamples = Math.round(deltaSamples / gridSamples) * gridSamples;\n return { x: snappedSamples / samplesPerPixel, y: 0 };\n }\n\n // Beats mode\n const { snapTo, bpm, timeSignature, sampleRate } = this.options;\n\n if (snapTo === 'off') return transform;\n\n const gridTicks = snapTo === 'bar' ? ticksPerBar(timeSignature) : ticksPerBeat(timeSignature);\n\n if (startSample !== undefined) {\n // Snap absolute position in tick space\n const proposedSamples = startSample + transform.x * samplesPerPixel;\n const proposedTicks = samplesToTicks(proposedSamples, bpm, sampleRate);\n const snappedTicks = snapToGrid(proposedTicks, gridTicks);\n const snappedSamples = ticksToSamples(snappedTicks, bpm, sampleRate);\n return { x: (snappedSamples - startSample) / samplesPerPixel, y: 0 };\n }\n\n // Fallback: snap delta (no startSample available)\n const deltaSamples = transform.x * samplesPerPixel;\n const deltaTicks = samplesToTicks(deltaSamples, bpm, sampleRate);\n const snappedTicks = snapToGrid(deltaTicks, gridTicks);\n const snappedSamples = ticksToSamples(snappedTicks, bpm, sampleRate);\n\n return { x: snappedSamples / samplesPerPixel, y: 0 };\n }\n\n static configure = configurator(SnapToGridModifier);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAC,gBAAe,8BAA6B,qBAAoB,4BAA2B,gBAAe,uBAAsB,kBAAiB,yBAAwB,kCAAiC,iDAAgD,4CAA2C,2DAA0D,8BAA6B,6CAA4C,gCAA+B,+CAA8C,OAAQ,iBAAgB,aAAY,qBAAoB,qBAAoB,4BAA2B,MAAO,gBAAe,kCAAiC,gDAA+C;;;ACAnsB;AAAA,EACE,YAAAA;AAAA,EACA,aAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,UAAAC;AAAA,EACA,eAAAC;AAAA,EACA,WAAAC;AAAA,OAEK;AACP,SAAS,qBAAqB;;;ACO9B,SAAS,kBACP,SACqD;AACrD,SACE,WAAW,QACX,OAAQ,QAA6C,sBAAsB;AAE/E;AAQO,SAAS,4BACd,SACAC,QACM;AACN,MAAI,CAAC,kBAAkB,OAAO,EAAG;AACjC,UAAQ,kBAAkBA,MAAK;AACjC;;;ACrCA,SAAS,aAAa,gBAA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A,QACjD,CAAC;AACD;AAAA,MACF;AACA,gBAAU,KAAK;AAAA,IACjB;AAAA,IACA,CAAC,WAAW,cAAc,uBAAuB,mBAAmB;AAAA,EACtE;AAGA,QAAM,YAAYT,UAAQ,MAAM;AAC9B,UAAM,OAAkB,CAACU,yBAAwB;AAEjD,QAAI,gBAAgB,cAAc;AAChC,WAAK;AAAA,QACH,mBAAmB,UAAU;AAAA,UAC3B,MAAM;AAAA,UACN,QAAQ,aAAa;AAAA,UACrB,KAAK,aAAa;AAAA,UAClB,eAAe,aAAa;AAAA,UAC5B;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,WAAW,kBAAkB;AAC3B,WAAK;AAAA,QACH,mBAAmB,UAAU;AAAA,UAC3B,MAAM;AAAA,UACN,aAAa,KAAK,MAAO,aAAa,eAAe,EAAE,YAAY,MAAQ,UAAU;AAAA,UACrF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAEA,SAAK,KAAK,sBAAsB,UAAU,EAAE,QAAQ,WAAW,gBAAgB,CAAC,CAAC;AACjF,WAAO;AAAA,EACT,GAAG,CAAC,cAAc,kBAAkB,cAAc,WAAW,iBAAiB,UAAU,CAAC;AAEzF,SACE,gBAAAX,MAAC,0BAAuB,SAAO,MAAC,gBAC9B,0BAAAA;AAAA,IAACY;AAAA,IAAA;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA,YAAY;AAAA,MACZ,WAAW;AAAA,MACX;AAAA,MAEC;AAAA;AAAA,EACH,GACF;AAEJ;","names":["useState","useEffect","useLayoutEffect","useRef","useCallback","useMemo","cache","formatTime","useState","useCallback","useState","useCallback","useRef","useState","useCallback","useRef","useState","useCallback","useRef","useState","useCallback","useRef","cache","React","useCallback","useCallback","useRef","useCallback","useCallback","useEffect","useRef","useRef","useEffect","useCallback","_a","useCallback","useCallback","useMemo","useEffect","useSyncExternalStore","useMemo","useSyncExternalStore","useCallback","useEffect","useCallback","useEffect","useRef","useState","useEffect","useRef","useCallback","useState","useRef","useCallback","useEffect","useState","useMemo","useSyncExternalStore","useMemo","useSyncExternalStore","useRef","useState","useMemo","useSyncExternalStore","useCallback","useMemo","useRef","useState","useSyncExternalStore","useState","NO_ANNOTATIONS","noSubscription","noAnnotations","useMemo","useSyncExternalStore","useRef","useCallback","useCallback","useRef","useCallback","useRef","useState","useMemo","useRef","useMemo","useRef","useState","createValueSource","WaveformData","WaveformData","bits","emptyPeaks","useState","createValueSource","useRef","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","useState","useCallback","useRef","useEffect","useLayoutEffect","useMemo","useMemo","useRef","useSyncExternalStore","isLoadingClip","isLoadingClip","useMemo","useSyncExternalStore","useRef","useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect","useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","createValueSource","useRef","useState","createValueSource","useCallback","armedTrackId","useEffect","useSyncExternalStore","useMemo","useEffect","useRef","useRef","useEffect","useMemo","useState","useRef","useCallback","useLayoutEffect","useEffect","useState","useEffect","useLayoutEffect","useRef","useCallback","useMemo","ThemeProvider","installHint","jsx","useState","useRef","useCallback","useLayoutEffect","useMemo","useEffect","ThemeProvider","useCallback","jsx","useCallback","BaseControlButton","jsx","BaseControlButton","useRef","useEffect","jsx","useRef","useEffect","_a","use","useLayoutEffect","useRef","useState","useMemo","useCallback","useEffect","useState","useCallback","useSyncExternalStore","useCallback","useMemo","useSyncExternalStore","subscribeToNothing","useMemo","useCallback","_a","preview","useSyncExternalStore","trackKind","createContext","use","createContext","use","styled","React","Fragment","useCallback","useMemo","useTheme","waveformColorToCss","createContext","memo","useLayoutEffect","useMemo","useRef","useState","createValueSource","useEffect","useLayoutEffect","useRef","createContext","memo","AutomaticScrollFlag","useLayoutEffect","useState","useRef","useMemo","createValueSource","createContext","use","React","use","React","createContext","useCallback","use","useMemo","useSyncExternalStore","useTheme","usePlaylistInfo","waveformColorToCss","createContext","use","useMemo","jsx","useId","useRef","useEffect","styled","jsx","styled","useRef","useId","useEffect","_a","jsx","jsxs","createContext","React","ClipView","use","useCallback","useSyncExternalStore","TrackRow","useTheme","waveformColorToCss","usePlaylistInfo","useMemo","React","use","useMemo","useRef","useState","useTheme","React","styled","use","createContext","use","use","useEffect","use","useEffect","jsx","jsxs","use","jsx","jsxs","styled","React","useRef","jsx","useTheme","use","useRef","useMemo","value","useState","React","React","use","useSyncExternalStore","useTheme","useRef","useEffect","useId","styled","usePlaylistInfo","jsx","styled","useRef","useId","usePlaylistInfo","useEffect","jsx","subscribeToNothing","React","WaveformSelection","useTheme","use","useSyncExternalStore","WaveformLoopRegion","createContext","use","useMemo","jsx","createContext","use","useMemo","jsx","React","WaveformTimescale","use","Fragment","jsx","jsxs","React","useMemo","useTheme","useCallback","waveformColorToCss","jsx","jsxs","use","useMemo","_a","_b","_c","_d","_e","_f","_g","useState","useCallback","useLayoutEffect","useRef","trackKind","React","use","useTheme","createContext","use","createContext","use","React","use","jsx","React","AnnotationBoxItem","use","jsx","React","WaveformAnnotationBoxes","use","useTheme","use","useMemo","jsx","use","useMemo","Fragment","jsx","jsxs","useCallback","useMemo","DevicePixelRatioProvider","CLIP_HEADER_HEIGHT","jsx","useMemo","CLIP_HEADER_HEIGHT","useCallback","DevicePixelRatioProvider","Fragment","jsx","jsxs","TIMESCALE","TRACKS","SELECTION","PLAYHEAD","ANNOTATION_BOXES","ANNOTATION_LIST","useEffect","useEffect","React","useCallback","useMemo","useRef","flushSync","DragDropProvider","RestrictToHorizontalAxis","samplesToTicks","ticksToSamples","snapToGrid","ticksPerBeat","ticksPerBar","Modifier","configurator","deltaSamples","snappedSamples","snappedTicks","jsx","useMemo","ticksPerBar","ticksPerBeat","samplesToTicks","snapToGrid","ticksToSamples","useRef","useCallback","React","flushSync","RestrictToHorizontalAxis","DragDropProvider"]}