@dawcore/components 0.0.39-next.18 → 0.0.39-next.19

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","<define:__INSTALL_SPECS__>","../src/elements/daw-annotation.ts","../src/elements/daw-annotation-track.ts","../src/elements/daw-annotation-list.ts","../src/utils/annotation-playing.ts","../src/elements/daw-clip.ts","../src/interactions/element-links.ts","../src/elements/daw-track.ts","../src/types.ts","../src/utils/track-mix.ts","../src/elements/daw-waveform.ts","../src/utils/peak-rendering.ts","../src/utils/viewport.ts","../src/elements/daw-piano-roll.ts","../src/elements/daw-playhead.ts","../src/elements/daw-transport.ts","../src/elements/daw-play-button.ts","../src/elements/daw-transport-button.ts","../src/utils/transport-capability.ts","../src/elements/daw-pause-button.ts","../src/elements/daw-stop-button.ts","../src/elements/daw-editor.ts","../src/workers/peaksWorker.ts","../src/workers/waveformDataUtils.ts","../src/workers/peakPipeline.ts","../src/elements/daw-ruler.ts","../src/utils/time-format.ts","../src/utils/smart-scale.ts","../src/utils/musical-tick-cache.ts","../src/elements/daw-track-controls.ts","../src/elements/daw-grid.ts","../src/styles/theme.ts","../src/controllers/viewport-controller.ts","../src/controllers/audio-resume-controller.ts","../src/utils/install-command.ts","../src/controllers/recording-controller.ts","../src/controllers/annotation-controller.ts","../src/controllers/spectrogram-controller.ts","../src/interactions/pointer-handler.ts","../src/interactions/constants.ts","../src/interactions/clip-pointer-handler.ts","../src/interactions/annotation-drag.ts","../src/interactions/track-reorder-handler.ts","../src/utils/time-display-format.ts","../src/interactions/abort.ts","../src/interactions/file-loader.ts","../src/interactions/midi-loader.ts","../src/interactions/recording-clip.ts","../src/interactions/split-handler.ts","../src/interactions/clip-peak-sync.ts","../src/interactions/track-entry.ts","../src/interactions/load-announcer.ts","../src/interactions/arrangement-view.ts","../src/interactions/arrangement-swap.ts","../src/interactions/drag-watch.ts","../src/interactions/clip-rehome.ts","../src/effects/effects-chain-controller.ts","../src/effects/optional-modules.ts","../src/effects/effects-manager.ts","../src/effects/effect-registry.ts","../src/interactions/export-audio.ts","../src/interactions/peaks-loader.ts","../src/controllers/scroll-sync-controller.ts","../src/controllers/animation-controller.ts","../src/controllers/playback-animation-controller.ts","../src/elements/daw-selection.ts","../src/elements/daw-record-button.ts","../src/elements/daw-keyboard-shortcuts.ts","../src/elements/daw-spectrogram.ts","../src/elements/daw-time-display.ts","../src/elements/daw-time-format.ts","../src/elements/daw-player.ts"],"sourcesContent":["import './elements/daw-annotation';\nimport './elements/daw-annotation-track';\nimport './elements/daw-annotation-list';\nimport './elements/daw-clip';\nimport './elements/daw-track';\nimport './elements/daw-waveform';\nimport './elements/daw-piano-roll';\nimport './elements/daw-playhead';\nimport './elements/daw-transport';\nimport './elements/daw-play-button';\nimport './elements/daw-pause-button';\nimport './elements/daw-stop-button';\nimport './elements/daw-editor';\nimport './elements/daw-ruler';\nimport './elements/daw-grid';\nimport './elements/daw-selection';\nimport './elements/daw-track-controls';\nimport './elements/daw-record-button';\nimport './elements/daw-keyboard-shortcuts';\nimport './elements/daw-spectrogram';\nimport './elements/daw-time-display';\nimport './elements/daw-time-format';\nimport './elements/daw-player';\n\nexport { DawAnnotationElement } from './elements/daw-annotation';\nexport { DawAnnotationTrackElement } from './elements/daw-annotation-track';\nexport { DawAnnotationListElement } from './elements/daw-annotation-list';\nexport { DawClipElement } from './elements/daw-clip';\nexport { DawTrackElement } from './elements/daw-track';\nexport { DawWaveformElement } from './elements/daw-waveform';\nexport type { WaveformSegment } from './elements/daw-waveform';\nexport { DawPianoRollElement } from './elements/daw-piano-roll';\nexport { DawPlayheadElement } from './elements/daw-playhead';\nexport { DawTransportElement } from './elements/daw-transport';\nexport { DawTransportButton } from './elements/daw-transport-button';\nexport { DawPlayButtonElement } from './elements/daw-play-button';\nexport { DawPauseButtonElement } from './elements/daw-pause-button';\nexport { DawStopButtonElement } from './elements/daw-stop-button';\nexport { DawEditorElement } from './elements/daw-editor';\nexport { DawRulerElement } from './elements/daw-ruler';\nexport { DawGridElement } from './elements/daw-grid';\nexport { DawSelectionElement } from './elements/daw-selection';\nexport { DawTrackControlsElement } from './elements/daw-track-controls';\nexport { DawRecordButtonElement } from './elements/daw-record-button';\nexport { DawKeyboardShortcutsElement } from './elements/daw-keyboard-shortcuts';\nexport { DawSpectrogramElement } from './elements/daw-spectrogram';\nexport { DawTimeDisplayElement } from './elements/daw-time-display';\nexport { DawTimeFormatElement } from './elements/daw-time-format';\nexport { DawPlayerElement } from './elements/daw-player';\nexport { SpectrogramController } from './controllers/spectrogram-controller';\nexport type {\n PlaybackShortcutMap,\n SplittingShortcutMap,\n UndoShortcutMap,\n} from './elements/daw-keyboard-shortcuts';\n\nexport { AudioResumeController } from './controllers/audio-resume-controller';\nexport { ANNOTATION_LANE_HEIGHT } from './controllers/annotation-controller';\nexport { RecordingController } from './controllers/recording-controller';\nexport type { RecordingOptions, RecordingSession } from './controllers/recording-controller';\nexport { PlaybackAnimationController } from './controllers/playback-animation-controller';\nexport type {\n PlayheadLike,\n PlaybackAnimationOptions,\n} from './controllers/playback-animation-controller';\nexport {\n TIME_DISPLAY_FORMATS,\n isTimeDisplayFormat,\n formatDisplayTime,\n parseDisplayTime,\n} from './utils/time-display-format';\nexport type { TimeDisplayFormat } from './utils/time-display-format';\nexport {\n resolveTransportTarget,\n targetSupports,\n warnOnce,\n warnUnsupportedOnce,\n} from './utils/transport-capability';\n\nexport type {\n TrackDescriptor,\n TrackWithId,\n ClipDescriptor,\n DomClipDescriptor,\n DropClipDescriptor,\n TrackRenderMode,\n TrackConfig,\n ClipConfig,\n EditorCallOptions,\n} from './types';\nexport { isDomClip } from './types';\nexport type { PointerEngineContract } from './interactions/pointer-handler';\nexport { ClipPointerHandler } from './interactions/clip-pointer-handler';\nexport type { ClipPointerHost, ClipEngineContract } from './interactions/clip-pointer-handler';\nexport { splitAtPlayhead } from './interactions/split-handler';\nexport type { SplitHost, SplitEngineContract } from './interactions/split-handler';\n\nexport type {\n DawEventMap,\n DawEvent,\n DawSelectionDetail,\n DawSeekDetail,\n DawTrackSelectDetail,\n DawTrackConnectedDetail,\n DawTrackIdDetail,\n DawTrackUpdateDetail,\n DawTrackErrorDetail,\n DawFilesLoadErrorDetail,\n DawErrorDetail,\n DawTrackControlDetail,\n DawTrackRemoveDetail,\n DawRecordingStartDetail,\n DawRecordingCompleteDetail,\n DawRecordingClipAddDetail,\n DawRecordingErrorDetail,\n DawClipConnectedDetail,\n DawClipUpdateDetail,\n DawClipIdDetail,\n DawClipErrorDetail,\n DawClipMoveDetail,\n DawClipTrimDetail,\n DawClipSplitDetail,\n DawEffectAddDetail,\n DawEffectRemoveDetail,\n DawEffectChangeDetail,\n DawEffectBypassDetail,\n DawEffectReorderDetail,\n DawEffectErrorDetail,\n DawAnnotationConnectedDetail,\n DawAnnotationUpdateDetail,\n DawAnnotationSelectDetail,\n DawAnnotationTrackConnectedDetail,\n DawTimeUpdateDetail,\n DawTimeFormatChangeDetail,\n LoadFilesResult,\n} from './events';\n\n// Effects. The registry (registerEffect, prepareEffect, …) and the definition\n// types live in @waveform-playlist/core, shared with the React hooks.\nexport type { EffectState, SerializedEffectEntry } from './effects/types';\nexport type { ExportOptions, ExportAudioHost } from './interactions/export-audio';\n","{\"@dawcore/faust\":\"@dawcore/faust@^0.0.2-next.1\",\"@dawcore/midi\":\"@dawcore/midi@^0.0.6-next.12\",\"@dawcore/transport\":\"@dawcore/transport@^0.0.16-next.11\",\"@dawcore/wam\":\"@dawcore/wam@^0.0.5-next.0\",\"@waveform-playlist/core\":\"@waveform-playlist/core@^13.0.0-next.11\",\"@waveform-playlist/engine\":\"@waveform-playlist/engine@^14.0.0-next.9\",\"@waveform-playlist/worklets\":\"@waveform-playlist/worklets@^13.0.1-next.0\",\"@waveform-playlist/playout\":\"@waveform-playlist/playout@^13.0.0-next.11\"}","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { AnnotationData } from '@waveform-playlist/core';\n\n/** Valid tick value: finite non-negative integer. */\nfunction isValidTick(value: number): boolean {\n return Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * Declarative annotation data element (light DOM). Its `start`/`end`\n * attributes and text content ARE the single source of truth — the editor's\n * annotation lane and <daw-annotation-list> both derive from them.\n */\n@customElement('daw-annotation')\nexport class DawAnnotationElement extends LitElement {\n /** Start time in seconds. Reflected — attribute writes drive both views. */\n @property({ type: Number, noAccessor: true, reflect: true })\n get start(): number {\n return this._start;\n }\n set start(value: number) {\n if (!Number.isFinite(value) || value < 0) {\n console.warn('[dawcore] daw-annotation start ' + String(value) + ' is invalid — ignored');\n return;\n }\n const old = this._start;\n this._start = value;\n this.requestUpdate('start', old);\n }\n private _start = 0;\n\n /** End time in seconds. Reflected. */\n @property({ type: Number, noAccessor: true, reflect: true })\n get end(): number {\n return this._end;\n }\n set end(value: number) {\n if (!Number.isFinite(value) || value < 0) {\n console.warn('[dawcore] daw-annotation end ' + String(value) + ' is invalid — ignored');\n return;\n }\n const old = this._end;\n this._end = value;\n this.requestUpdate('end', old);\n }\n private _end = 0;\n\n /** Musical start position (ticks). Authoritative when end-tick is also set —\n * start/end seconds become a derived cache the host editor keeps fresh\n * (clip startTick pattern). */\n @property({ type: Number, noAccessor: true, reflect: true, attribute: 'start-tick' })\n get startTick(): number | null {\n return this._startTick;\n }\n set startTick(value: number | null) {\n const old = this._startTick;\n if (value === null) {\n this._startTick = null;\n this.requestUpdate('startTick', old);\n return;\n }\n if (!isValidTick(value)) {\n console.warn(\n '[dawcore] daw-annotation start-tick ' + String(value) + ' is invalid — ignored'\n );\n return;\n }\n this._startTick = value;\n this.requestUpdate('startTick', old);\n }\n private _startTick: number | null = null;\n\n /** Musical end position (ticks). See startTick. */\n @property({ type: Number, noAccessor: true, reflect: true, attribute: 'end-tick' })\n get endTick(): number | null {\n return this._endTick;\n }\n set endTick(value: number | null) {\n const old = this._endTick;\n if (value === null) {\n this._endTick = null;\n this.requestUpdate('endTick', old);\n return;\n }\n if (!isValidTick(value)) {\n console.warn('[dawcore] daw-annotation end-tick ' + String(value) + ' is invalid — ignored');\n return;\n }\n this._endTick = value;\n this.requestUpdate('endTick', old);\n }\n private _endTick: number | null = null;\n\n /** Tick-based iff BOTH tick attributes are set (authority rule). */\n get isTickBased(): boolean {\n return this._startTick !== null && this._endTick !== null;\n }\n\n private _warnedHalfTick = false;\n\n private readonly _generatedId = 'annotation-' + crypto.randomUUID();\n\n /** Stable identity: the id attribute when present, else a generated UUID. */\n get annotationId(): string {\n return this.id || this._generatedId;\n }\n\n toAnnotationData(): AnnotationData {\n const text = this.textContent?.trim() ?? '';\n const data: AnnotationData = {\n id: this.annotationId,\n start: this.start,\n end: this.end,\n lines: text.length > 0 ? text.split('\\n') : [''],\n };\n if (this.isTickBased) {\n data.startTick = this._startTick as number;\n data.endTick = this._endTick as number;\n }\n return data;\n }\n\n // Light DOM — data container only.\n createRenderRoot() {\n return this;\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Data element — its light-DOM text must not render through a host's\n // bare <slot> (e.g. <daw-editor>'s, or a bare <daw-annotation> used\n // outside a track). Views (editor lane, <daw-annotation-list>) present\n // it instead.\n this.style.display = 'none';\n // Deferred so ancestor listeners (editor / annotation track) register first\n // when parsed all-at-once — same pattern as <daw-clip>.\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-annotation-connected', {\n bubbles: true,\n composed: true,\n detail: { annotationId: this.annotationId, element: this },\n })\n );\n }, 0);\n }\n\n private _hasRendered = false;\n\n updated(changed: PropertyValues) {\n // Exactly one tick attribute set is a half-configured state — warn once.\n const halfTick = (this._startTick !== null) !== (this._endTick !== null);\n if (halfTick && !this._warnedHalfTick) {\n this._warnedHalfTick = true;\n console.warn(\n '[dawcore] daw-annotation \"' +\n this.annotationId +\n '\": only one of start-tick/end-tick is set — treated as seconds-based until both are present'\n );\n }\n if (!this._hasRendered) {\n this._hasRendered = true;\n return;\n }\n if (\n changed.has('start') ||\n changed.has('end') ||\n changed.has('startTick') ||\n changed.has('endTick')\n ) {\n this.dispatchEvent(\n new CustomEvent('daw-annotation-update', {\n bubbles: true,\n composed: true,\n detail: { annotationId: this.annotationId },\n })\n );\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-annotation': DawAnnotationElement;\n }\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport {\n updateAnnotationBoundaries,\n resolveAnnotationShortcuts,\n matchesKeyBinding,\n keyBelongsToFocusedControl,\n ANNOTATION_LINK_THRESHOLD_TICKS,\n annotationMinDurationTicks,\n} from '@waveform-playlist/core';\nimport type {\n AnnotationData,\n AnnotationShortcutMap,\n AnnotationShortcutAction,\n KeyBinding,\n} from '@waveform-playlist/core';\nimport type { DawAnnotationElement } from './daw-annotation';\n\n/** Structural view of the host editor — only what this element touches. */\ninterface AnnotationHostEditor extends HTMLElement {\n play(startTime?: number, endTime?: number): Promise<void>;\n seekTo(time: number): void;\n _annotationClampDuration: number;\n _secondsToTicks(seconds: number): number;\n _ticksToSeconds(ticks: number): number;\n ppqn: number;\n}\n\n/**\n * Write boundary-math results back to the <daw-annotation> elements — only\n * edges that actually differ from the element's CURRENT values, so no\n * spurious daw-annotation-update events fire. Targets are resolved by\n * annotation id and diffed against the live element (#609): the math's input\n * snapshot can be ordered differently than the live sorted children mid-drag,\n * so index-paired comparisons are never trustworthy.\n */\nexport function applyBoundaryResults(\n elements: DawAnnotationElement[],\n after: AnnotationData[]\n): void {\n const byId = new Map(elements.map((el) => [el.annotationId, el]));\n for (const next of after) {\n const el = byId.get(next.id);\n if (!el) continue;\n if (el.start !== next.start) el.start = next.start;\n if (el.end !== next.end) el.end = next.end;\n }\n}\n\n/**\n * Tick-space sibling of applyBoundaryResults: `after` carries TICK values in\n * start/end. Id-resolved targets diffed against the element's CURRENT values\n * (#609). A tick-based element gets rounded integer ticks PLUS a re-derived\n * seconds cache in the same write pass; a seconds-based element (converted in\n * for mixed-track link math) gets seconds back in ITS authoritative unit and\n * never gains tick attributes.\n */\nexport function applyTickBoundaryResults(\n elements: DawAnnotationElement[],\n after: AnnotationData[],\n ticksToSeconds: (ticks: number) => number\n): void {\n const byId = new Map(elements.map((el) => [el.annotationId, el]));\n for (const next of after) {\n const el = byId.get(next.id);\n if (!el) continue;\n if (el.isTickBased) {\n const startTick = Math.round(next.start);\n const endTick = Math.round(next.end);\n if (el.startTick !== startTick) {\n el.startTick = startTick;\n el.start = ticksToSeconds(startTick);\n }\n if (el.endTick !== endTick) {\n el.endTick = endTick;\n el.end = ticksToSeconds(endTick);\n }\n } else {\n const start = ticksToSeconds(next.start);\n const end = ticksToSeconds(next.end);\n if (el.start !== start) el.start = start;\n if (el.end !== end) el.end = end;\n }\n }\n}\n\n/** Map an annotation element into tick-space AnnotationData: tick-based\n * elements use their authoritative ticks; seconds-based neighbors are\n * converted so mixed-track link/collision math runs in one unit space. */\nexport function tickSpaceData(\n el: DawAnnotationElement,\n editor: { _secondsToTicks(seconds: number): number }\n): AnnotationData {\n const base = el.toAnnotationData();\n if (el.isTickBased) {\n return { ...base, start: base.startTick as number, end: base.endTick as number };\n }\n return {\n ...base,\n start: editor._secondsToTicks(base.start),\n end: editor._secondsToTicks(base.end),\n };\n}\n\n/**\n * Declarative annotation track (light DOM). Children are <daw-annotation>\n * elements — their attributes are the single source of truth. This element\n * owns the ephemeral selection state and the programmatic API; the host\n * <daw-editor> renders the timeline lane, <daw-annotation-list> renders the\n * text panel.\n */\n@customElement('daw-annotation-track')\nexport class DawAnnotationTrackElement extends LitElement {\n @property({ type: Boolean, reflect: true }) editable = false;\n @property({ type: Boolean, reflect: true, attribute: 'link-endpoints' }) linkEndpoints = false;\n @property({ type: Boolean, reflect: true, attribute: 'continuous-play' }) continuousPlay = false;\n @property({ type: Boolean, reflect: true, attribute: 'keyboard-controls' })\n keyboardControls = false;\n /** Lane box label mode: 'text' (default) | 'id' (sonnet-style: explicit id\n * attribute, else 1-based position) | 'none' (pure region bars). The list\n * always shows full text — this only affects the timeline lane. */\n @property({ reflect: true, attribute: 'box-label' }) boxLabel: 'text' | 'id' | 'none' = 'text';\n /** Display label for the editor's controls-column lane row (mirrors\n * <daw-track name>). Empty = blank spacer (opt-in, no layout change). */\n @property({ reflect: true }) name = '';\n\n // --- Selection (ephemeral UI state — deliberately NOT DOM data) ---\n\n private _activeAnnotationId: string | null = null;\n\n get activeAnnotationId(): string | null {\n return this._activeAnnotationId;\n }\n\n set activeAnnotationId(value: string | null) {\n if (value !== null && !this.annotationElements.some((el) => el.annotationId === value)) {\n console.warn(\n '[dawcore] daw-annotation-track: unknown annotation id \"' + value + '\" — selection ignored'\n );\n return;\n }\n if (value === this._activeAnnotationId) return;\n this._activeAnnotationId = value;\n const active = this._activeElement();\n this.dispatchEvent(\n new CustomEvent('daw-annotation-select', {\n bubbles: true,\n composed: true,\n detail: { annotation: active ? active.toAnnotationData() : null },\n })\n );\n }\n\n // --- Child access ---\n\n /** Child annotation elements, sorted by start time. */\n get annotationElements(): DawAnnotationElement[] {\n return Array.from(this.querySelectorAll<DawAnnotationElement>(':scope > daw-annotation')).sort(\n (a, b) => a.start - b.start\n );\n }\n\n get annotations(): AnnotationData[] {\n return this.annotationElements.map((el) => el.toAnnotationData());\n }\n\n // --- Navigation methods (spec API) ---\n\n selectNext(): void {\n this._selectByOffset(1, 0);\n }\n\n selectPrevious(): void {\n this._selectByOffset(-1, -1);\n }\n\n selectFirst(): void {\n const list = this.annotationElements;\n if (list.length > 0) this.activeAnnotationId = list[0].annotationId;\n }\n\n selectLast(): void {\n const list = this.annotationElements;\n if (list.length > 0) this.activeAnnotationId = list[list.length - 1].annotationId;\n }\n\n clearSelection(): void {\n this.activeAnnotationId = null;\n }\n\n /** offset: +1 next / -1 previous; noSelectionIndex: 0 → first, -1 → last. */\n private _selectByOffset(offset: number, noSelectionIndex: number): void {\n const list = this.annotationElements;\n if (list.length === 0) return;\n const currentIndex = list.findIndex((el) => el.annotationId === this._activeAnnotationId);\n const nextIndex =\n currentIndex === -1\n ? (noSelectionIndex + list.length) % list.length\n : (currentIndex + offset + list.length) % list.length;\n this.activeAnnotationId = list[nextIndex].annotationId;\n }\n\n // --- Playback (spec API) ---\n\n playActive(): void {\n const active = this._activeElement();\n if (!active) return;\n const editor = this._hostEditor();\n if (!editor) {\n console.warn(\n '[dawcore] <daw-annotation-track> playActive: no parent <daw-editor> — call ignored'\n );\n return;\n }\n const data = active.toAnnotationData();\n void editor.play(data.start, this.continuousPlay ? undefined : data.end);\n }\n\n // --- Boundary editing (spec API) ---\n\n moveStartBoundary(deltaMs: number): void {\n this._moveBoundary(deltaMs, true);\n }\n\n moveEndBoundary(deltaMs: number): void {\n this._moveBoundary(deltaMs, false);\n }\n\n private _moveBoundary(deltaMs: number, isStart: boolean): void {\n if (!this.editable) {\n console.warn(\n '[dawcore] daw-annotation-track: boundary editing requires the editable attribute'\n );\n return;\n }\n const elements = this.annotationElements;\n const index = elements.findIndex((el) => el.annotationId === this._activeAnnotationId);\n if (index === -1) return;\n const active = elements[index];\n\n if (active.isTickBased) {\n const editor = this._hostEditor();\n if (!editor) {\n console.warn(\n '[dawcore] daw-annotation-track: tick-based boundary edits need a parent <daw-editor> for tempo conversion — call ignored'\n );\n return;\n }\n // Tick space: siblings converted in; ms delta converted at the edge's\n // local tempo (correct under variable-tempo callbacks).\n const tickData = elements.map((el) => tickSpaceData(el, editor));\n const edgeTick = isStart ? tickData[index].start : tickData[index].end;\n const edgeSeconds = editor._ticksToSeconds(edgeTick);\n const deltaTicks =\n editor._secondsToTicks(edgeSeconds + deltaMs / 1000) - editor._secondsToTicks(edgeSeconds);\n const clamp = this._timelineDuration();\n const updated = updateAnnotationBoundaries(\n {\n annotationIndex: index,\n newTime: edgeTick + deltaTicks,\n isDraggingStart: isStart,\n annotations: tickData,\n duration: clamp === Infinity ? Infinity : editor._secondsToTicks(clamp),\n linkEndpoints: this.linkEndpoints,\n },\n {\n linkThreshold: ANNOTATION_LINK_THRESHOLD_TICKS,\n minDuration: annotationMinDurationTicks(editor.ppqn),\n }\n );\n applyTickBoundaryResults(elements, updated, (t) => editor._ticksToSeconds(t));\n return;\n }\n\n const data = elements.map((el) => el.toAnnotationData());\n const edge = isStart ? data[index].start : data[index].end;\n const updated = updateAnnotationBoundaries({\n annotationIndex: index,\n newTime: edge + deltaMs / 1000,\n isDraggingStart: isStart,\n annotations: data,\n duration: this._timelineDuration(),\n linkEndpoints: this.linkEndpoints,\n });\n applyBoundaryResults(elements, updated);\n }\n\n private _timelineDuration(): number {\n return this._hostEditor()?._annotationClampDuration ?? Infinity;\n }\n\n private _activeElement(): DawAnnotationElement | null {\n if (this._activeAnnotationId === null) return null;\n return (\n this.annotationElements.find((el) => el.annotationId === this._activeAnnotationId) ?? null\n );\n }\n\n private _hostEditor(): AnnotationHostEditor | null {\n return this.closest('daw-editor') as AnnotationHostEditor | null;\n }\n\n // --- Keyboard remapping (accessor pair: cache invalidation on set) ---\n\n private _annotationShortcuts: AnnotationShortcutMap | null = null;\n private _resolvedShortcuts: Array<{\n action: AnnotationShortcutAction;\n binding: KeyBinding;\n }> | null = null;\n\n get annotationShortcuts(): AnnotationShortcutMap | null {\n return this._annotationShortcuts;\n }\n set annotationShortcuts(value: AnnotationShortcutMap | null) {\n this._annotationShortcuts = value;\n this._resolvedShortcuts = null;\n }\n\n private _shortcutEntries(): Array<{ action: AnnotationShortcutAction; binding: KeyBinding }> {\n if (!this._resolvedShortcuts) {\n this._resolvedShortcuts = resolveAnnotationShortcuts(this._annotationShortcuts);\n }\n return this._resolvedShortcuts;\n }\n\n private static readonly _boundaryActions: ReadonlySet<AnnotationShortcutAction> = new Set([\n 'moveStartEarlier',\n 'moveStartLater',\n 'moveEndEarlier',\n 'moveEndLater',\n ]);\n\n // Capture phase: runs before <daw-keyboard-shortcuts>' bubble-phase listener,\n // giving annotation shortcuts deterministic priority (spec rule).\n private _onKeyDownCapture = (e: KeyboardEvent): void => {\n if (!this.keyboardControls) return;\n if (e.repeat) return;\n // <daw-editor>'s drag cancel (a window capture listener, so it runs\n // first) prevented this Escape: it cancelled a drag and does nothing\n // else, so the selection stays (#848).\n if (e.key === 'Escape' && e.defaultPrevented) return;\n // Same rule as the editor shortcuts: a key the focused control uses itself\n // (text entry, Escape in a modal dialog, Space/Enter on a focused button)\n // is not a shortcut. Reads the composed path, so it\n // sees controls inside shadow roots that `e.target` hides at `document`.\n if (keyBelongsToFocusedControl(e)) return;\n const match = this._shortcutEntries().find((entry) => matchesKeyBinding(e, entry.binding));\n if (!match) return;\n\n const hasSelection = this._activeAnnotationId !== null;\n // Escape with no selection falls through so a second press reaches the\n // editor's stop shortcut (spec two-press rule).\n if (match.action === 'clearSelection' && !hasSelection) return;\n // Boundary editing requires editable + a selection; don't eat keys otherwise.\n if (DawAnnotationTrackElement._boundaryActions.has(match.action)) {\n if (!this.editable || !hasSelection) return;\n }\n if (match.action === 'playActive' && !hasSelection) return;\n\n e.preventDefault();\n // stopImmediatePropagation (not stopPropagation): multiple\n // <daw-annotation-track keyboard-controls> elements each register their\n // own capture listener on `document`, and stopPropagation does NOT stop\n // sibling listeners on the same node — only stopImmediatePropagation\n // does (it also implies stopPropagation). Without it, one keypress would\n // act on every annotation track at once. This makes a consumed key act\n // on exactly the first-registered track (DOM order) and also prevents\n // bubble-phase editor shortcuts from firing. Unconsumed keys (Escape\n // with no selection, gated boundary keys) still fall through everywhere\n // via the early returns above.\n e.stopImmediatePropagation();\n try {\n this._runShortcutAction(match.action);\n } catch (err) {\n console.warn('[dawcore] Annotation shortcut failed (key=' + e.key + '): ' + String(err));\n this.dispatchEvent(\n new CustomEvent('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'annotation-shortcut', key: e.key, error: err },\n })\n );\n }\n };\n\n private _runShortcutAction(action: AnnotationShortcutAction): void {\n switch (action) {\n case 'selectPrevious':\n this.selectPrevious();\n break;\n case 'selectNext':\n this.selectNext();\n break;\n case 'selectFirst':\n this.selectFirst();\n break;\n case 'selectLast':\n this.selectLast();\n break;\n case 'clearSelection':\n this.clearSelection();\n break;\n case 'moveStartEarlier':\n this.moveStartBoundary(-10);\n break;\n case 'moveStartLater':\n this.moveStartBoundary(10);\n break;\n case 'moveEndEarlier':\n this.moveEndBoundary(-10);\n break;\n case 'moveEndLater':\n this.moveEndBoundary(10);\n break;\n case 'playActive':\n this.playActive();\n break;\n }\n }\n\n // --- Lifecycle ---\n\n private _childObserver: MutationObserver | null = null;\n\n createRenderRoot() {\n return this;\n }\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n // Data element — its light-DOM text must not render through a host's\n // bare <slot> (e.g. <daw-editor>'s). Views (editor lane,\n // <daw-annotation-list>) present it instead.\n this.style.display = 'none';\n // Upgrade-property dance: a remap assigned before element definition\n // created an own property shadowing the accessor — re-route it.\n if (Object.prototype.hasOwnProperty.call(this, 'annotationShortcuts')) {\n const value = (this as Record<string, unknown>)['annotationShortcuts'];\n delete (this as Record<string, unknown>)['annotationShortcuts'];\n this.annotationShortcuts = value as AnnotationShortcutMap | null;\n }\n this._listeners?.abort();\n this._listeners = new AbortController();\n document.addEventListener('keydown', this._onKeyDownCapture, {\n capture: true, // capture phase\n signal: this._listeners.signal,\n });\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-annotation-track-connected', {\n bubbles: true,\n composed: true,\n detail: { element: this },\n })\n );\n }, 0);\n // Clear selection when the active annotation element is removed.\n this._childObserver = new MutationObserver(() => {\n if (\n this._activeAnnotationId !== null &&\n !this.annotationElements.some((el) => el.annotationId === this._activeAnnotationId)\n ) {\n this.activeAnnotationId = null;\n }\n });\n this._childObserver.observe(this, { childList: true });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n this._childObserver?.disconnect();\n this._childObserver = null;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-annotation-track': DawAnnotationTrackElement;\n }\n}\n","import { LitElement, html, css, nothing } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { ticksToBarBeat } from '@waveform-playlist/core';\nimport type { AnnotationData, MeterEntry } from '@waveform-playlist/core';\nimport type { DawAnnotationTrackElement } from './daw-annotation-track';\nimport type { DawAnnotationElement } from './daw-annotation';\nimport type { DawAnnotationSelectDetail, DawTimeUpdateDetail } from '../events';\nimport { computePlayingAnnotationId } from '../utils/annotation-playing';\n\n/**\n * m:ss.mmm for annotation timestamps (finer than the ruler's m:ss). Milliseconds\n * that round up to 1000 carry into the seconds, so 59.9996 s is `1:00.000`,\n * never `0:59.1000`. A negative, `NaN` or infinite time is 0.\n */\nfunction formatAnnotationTime(seconds: number): string {\n const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;\n const floor = Math.floor(safe);\n const rounded = Math.round((safe - floor) * 1000);\n const whole = rounded === 1000 ? floor + 1 : floor;\n const ms = rounded === 1000 ? 0 : rounded;\n const s = whole % 60;\n const m = (whole - s) / 60;\n return m + ':' + String(s).padStart(2, '0') + '.' + String(ms).padStart(3, '0');\n}\n\n/** Structural view of the host editor — only what bars-mode formatting touches. */\ninterface AnnotationListHostEditor extends HTMLElement {\n _secondsToTicks(seconds: number): number;\n _meterEntries: MeterEntry[];\n ppqn: number;\n}\n\n/**\n * Scrollable text panel over a <daw-annotation-track>'s children — the same\n * <daw-annotation> elements the editor lane renders (single source of truth).\n * Linked via the `for` attribute (id of the track element).\n */\n@customElement('daw-annotation-list')\nexport class DawAnnotationListElement extends LitElement {\n @property() for = '';\n\n /** `'time'` (default): m:ss.mmm clock times, unchanged. `'bars'`: B.b – B.b\n * bar.beat ranges resolved via the host editor's meter map — falls back\n * to time display (and warns once) when no `<daw-editor>` ancestor is\n * found via `this.track?.closest('daw-editor')`. */\n @property({ type: String, attribute: 'time-display', reflect: true })\n timeDisplay: 'time' | 'bars' = 'time';\n\n /** Suppress re-render while a row's text is being edited. */\n @state() private _editingId: string | null = null;\n\n private _activeId: string | null = null;\n /** Playback-following highlight, separate from `_activeId` (selection) so\n * playback never disturbs selection/keyboard editing. Driven by\n * daw-timeupdate, cleared on daw-stop, retained on pause. */\n private _playingId: string | null = null;\n private _observer: MutationObserver | null = null;\n private _observedTrack: DawAnnotationTrackElement | null = null;\n private _warnedMissing = false;\n /** Warn once per resolved `for` target when bars mode can't find a host\n * editor — reset alongside `_warnedMissing` on `for` change so a\n * retargeted list can warn again for its new target. */\n private _warnedNoEditorForBars = false;\n /** Set around `_cancelEdit`'s `span.blur()` so the resulting synchronous\n * blur event doesn't re-enter `_commitEdit` (cancel already restores the\n * text and clears `_editingId` itself). */\n private _cancelling = false;\n\n static styles = css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: block;\n max-height: var(--daw-annotation-list-max-height, 240px);\n overflow-y: auto;\n background: var(--daw-annotation-list-background, #16213e);\n color: var(--daw-annotation-text-color, #e0d4c8);\n font-family: system-ui, sans-serif;\n font-size: 13px;\n }\n .annotation-row {\n display: flex;\n gap: 10px;\n align-items: baseline;\n padding: 6px 10px;\n border-bottom: 1px solid rgba(255, 255, 255, 0.06);\n cursor: pointer;\n }\n .annotation-row.playing {\n background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.12));\n box-shadow: inset 2px 0 0 var(--daw-annotation-box-border, #c49a6c);\n }\n .annotation-row.active {\n background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.25));\n }\n .annotation-row-times {\n font-variant-numeric: tabular-nums;\n font-size: 11px;\n opacity: 0.7;\n white-space: nowrap;\n }\n .annotation-row-text {\n flex: 1;\n min-width: 0;\n }\n .annotation-row-text[contenteditable='true'] {\n cursor: text;\n outline-offset: 2px;\n }\n .annotation-row-text:empty::before {\n content: '—';\n opacity: 0.4;\n }\n `;\n\n get track(): DawAnnotationTrackElement | null {\n if (!this.for) return null;\n const el = document.getElementById(this.for);\n if (!el || el.tagName !== 'DAW-ANNOTATION-TRACK') {\n if (!this._warnedMissing) {\n console.warn(\n el\n ? '[dawcore] <daw-annotation-list for=\"' +\n this.for +\n '\"> target is not a <daw-annotation-track>'\n : '[dawcore] <daw-annotation-list for=\"' + this.for + '\"> target not found'\n );\n this._warnedMissing = true;\n }\n return null;\n }\n return el as DawAnnotationTrackElement;\n }\n\n protected willUpdate(changed: Map<string, unknown>): void {\n // Allow a retargeted list to warn again for its new `for` value.\n if (changed.has('for')) {\n this._warnedMissing = false;\n this._warnedNoEditorForBars = false;\n }\n }\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('daw-annotation-select', this._onSelect as EventListener, { signal });\n document.addEventListener('daw-timeupdate', this._onTimeUpdate as EventListener, { signal });\n document.addEventListener('daw-stop', this._onStop as EventListener, { signal });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n this._observer?.disconnect();\n this._observer = null;\n this._observedTrack = null;\n }\n\n protected shouldUpdate(): boolean {\n // Never clobber an in-progress text edit with a re-render.\n return this._editingId === null;\n }\n\n protected updated(): void {\n this._ensureObserver();\n this._syncRowText();\n }\n\n /**\n * Text content is set imperatively, NOT bound as a Lit expression.\n * contenteditable mutates the span's DOM directly as the user types —\n * that ejects lit-html's ChildPart marker comments for any binding at\n * that position, so a later Lit-driven re-render of the same row throws\n * \"ChildPart has no parentNode\". Keeping the span's children entirely\n * outside Lit's diffing sidesteps the crash; the (soon-to-commit) edited\n * row is skipped via the _editingId check.\n */\n private _syncRowText(): void {\n const annotations = this.track?.annotations ?? [];\n const spans = this.shadowRoot?.querySelectorAll<HTMLElement>('.annotation-row-text') ?? [];\n spans.forEach((span) => {\n const id = span.dataset.id;\n if (id === undefined || id === this._editingId) return;\n const a = annotations.find((x) => x.id === id);\n if (!a) return;\n const text = a.lines.join(' ');\n if (span.textContent !== text) span.textContent = text;\n });\n }\n\n /** (Re)attach the MutationObserver when the resolved track changes. */\n private _ensureObserver(): void {\n const track = this.track;\n if (track === this._observedTrack) return;\n this._observer?.disconnect();\n this._observedTrack = track;\n if (!track) return;\n this._observer = new MutationObserver(() => this.requestUpdate());\n this._observer.observe(track, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n attributeFilter: ['start', 'end', 'id', 'editable'],\n });\n }\n\n private _onSelect = (e: CustomEvent<DawAnnotationSelectDetail>): void => {\n if (e.target !== this.track) return;\n this._activeId = e.detail.annotation?.id ?? null;\n this.requestUpdate();\n void this.updateComplete.then(() => {\n const row = this.shadowRoot?.querySelector('.annotation-row.active');\n // happy-dom lacks scrollIntoView — guard.\n (row as HTMLElement | null)?.scrollIntoView?.({ block: 'center' });\n });\n };\n\n /**\n * Update only on annotation-boundary crossings, not per animation frame.\n * `shouldUpdate()` suppresses the resulting render while a row is being\n * edited (`_editingId`) — intentional, not bypassed here. A boundary\n * crossed mid-edit is caught up on the NEXT crossing after the edit ends;\n * the highlight is briefly stale in that window, which is acceptable\n * (edits are rare and short-lived relative to playback).\n */\n private _onTimeUpdate = (e: CustomEvent<DawTimeUpdateDetail>): void => {\n if (e.target !== this.track?.closest('daw-editor')) return;\n const playingId = computePlayingAnnotationId(this.track?.annotations ?? [], e.detail.time);\n if (playingId === this._playingId) return;\n this._playingId = playingId;\n this.requestUpdate();\n void this.updateComplete.then(() => {\n const row = this.shadowRoot?.querySelector('.annotation-row.playing');\n // happy-dom lacks scrollIntoView — guard.\n (row as HTMLElement | null)?.scrollIntoView?.({ block: 'center' });\n });\n };\n\n private _onStop = (e: Event): void => {\n if (e.target !== this.track?.closest('daw-editor')) return;\n if (this._playingId === null) return;\n this._playingId = null;\n this.requestUpdate();\n };\n\n private _onRowClick(a: AnnotationData): void {\n const track = this.track;\n if (!track) return;\n track.activeAnnotationId = a.id;\n const editor = track.closest('daw-editor') as { seekTo?: (t: number) => void } | null;\n editor?.seekTo?.(a.start);\n }\n\n /** Formats a row's times span per `timeDisplay`. `'bars'` resolves the\n * host editor once (shared across all rows in a render) and falls back\n * to time display, warning once, when no editor is found. */\n private _formatTimes(a: AnnotationData, editor: AnnotationListHostEditor | null): string {\n if (this.timeDisplay === 'bars') {\n if (editor) {\n const isTickBased = a.startTick !== undefined && a.endTick !== undefined;\n const startTick = isTickBased ? (a.startTick as number) : editor._secondsToTicks(a.start);\n const endTick = isTickBased ? (a.endTick as number) : editor._secondsToTicks(a.end);\n const start = ticksToBarBeat(startTick, editor._meterEntries, editor.ppqn);\n const end = ticksToBarBeat(endTick, editor._meterEntries, editor.ppqn);\n return start.bar + '.' + start.beat + ' – ' + end.bar + '.' + end.beat;\n }\n if (!this._warnedNoEditorForBars) {\n console.warn(\n '[dawcore] <daw-annotation-list for=\"' +\n this.for +\n '\" time-display=\"bars\"> found no parent <daw-editor> — falling back to time display'\n );\n this._warnedNoEditorForBars = true;\n }\n }\n return formatAnnotationTime(a.start) + ' – ' + formatAnnotationTime(a.end);\n }\n\n private _annotationElement(id: string): DawAnnotationElement | null {\n return this.track?.annotationElements.find((el) => el.annotationId === id) ?? null;\n }\n\n private _commitEdit(a: AnnotationData, span: HTMLElement): void {\n // A cancel-triggered blur (span.blur() in _cancelEdit) must not commit —\n // cancel already restored the text and cleared _editingId itself.\n if (this._cancelling) return;\n this._editingId = null;\n const el = this._annotationElement(a.id);\n if (el) el.textContent = span.textContent?.trim() ?? '';\n this.requestUpdate();\n }\n\n private _cancelEdit(a: AnnotationData, span: HTMLElement): void {\n this._editingId = null;\n span.textContent = a.lines.join('\\n');\n this._cancelling = true;\n try {\n span.blur();\n } finally {\n this._cancelling = false;\n }\n this.requestUpdate();\n }\n\n render() {\n const track = this.track;\n const annotations = track?.annotations ?? [];\n const editable = track?.editable ?? false;\n const editor =\n this.timeDisplay === 'bars'\n ? ((track?.closest('daw-editor') as AnnotationListHostEditor | null) ?? null)\n : null;\n return html`\n ${annotations.map(\n (a) => html`\n <div\n class=\"annotation-row ${a.id === this._activeId ? 'active' : ''} ${a.id ===\n this._playingId\n ? 'playing'\n : ''}\"\n @click=${(e: Event) => {\n // Ignore clicks that land on the text span while this row is\n // ALREADY the active/selected one and mid-edit — avoids\n // re-seeking (jumping the playhead back to the row's start)\n // on every cursor-repositioning click while typing.\n //\n // Must NOT also fire on the very first click into an unselected\n // row's contenteditable text: browsers dispatch `focus` before\n // `click`, so `_editingId` is already `a.id` by the time this\n // handler runs even though `_onRowClick` (which sets it) never\n // ran yet. Gating on `_activeId === a.id` too lets that first\n // click through. (Not reproducible via `row.click()` in tests —\n // the DOM method skips the native focus-then-click sequence.)\n if (this._editingId === a.id && this._activeId === a.id) return;\n e.stopPropagation();\n this._onRowClick(a);\n }}\n >\n <span class=\"annotation-row-times\"> ${this._formatTimes(a, editor)} </span>\n <span\n class=\"annotation-row-text\"\n data-id=${a.id}\n contenteditable=${editable ? 'true' : nothing}\n @focus=${() => {\n if (editable) this._editingId = a.id;\n }}\n @blur=${(e: Event) => this._commitEdit(a, e.target as HTMLElement)}\n @keydown=${(e: KeyboardEvent) => {\n if (!editable) return;\n e.stopPropagation(); // never leak into shortcut handlers\n if (e.key === 'Enter') {\n e.preventDefault();\n (e.target as HTMLElement).blur(); // blur commits\n } else if (e.key === 'Escape') {\n this._cancelEdit(a, e.target as HTMLElement);\n }\n }}\n ></span>\n </div>\n `\n )}\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-annotation-list': DawAnnotationListElement;\n }\n}\n","import type { AnnotationData } from '@waveform-playlist/core';\n\n/**\n * Playing annotation = first annotation (in start-sorted order) where\n * `start <= time < end`. Returns `null` when `time` falls in a gap between\n * annotations (or before/after all of them).\n *\n * Shared by <daw-annotation-list> and AnnotationController so the lane and\n * the list agree on identical playback-highlight semantics. Seconds domain\n * only — callers pass the view's already-derived seconds cache, which is\n * correct for tick-based annotations too (AnnotationController.deriveSecondsCaches\n * keeps it fresh).\n */\nexport function computePlayingAnnotationId(\n annotations: readonly AnnotationData[],\n time: number\n): string | null {\n const match = annotations.find((a) => a.start <= time && time < a.end);\n return match?.id ?? null;\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { MidiNoteData } from '@waveform-playlist/core';\nimport {\n detachedWarning,\n linkHostOf,\n setCustomState,\n type ClipLinkValues,\n} from '../interactions/element-links';\n\n@customElement('daw-clip')\nexport class DawClipElement extends LitElement {\n @property() src = '';\n @property({ attribute: 'peaks-src' }) peaksSrc = '';\n // --- Live properties (#848): the arrangement's values while the clip is in\n // it; the declaration (attributes, a set before entry) otherwise. Setting\n // one is a request to the arrangement (an undo step) and never writes the\n // attribute. ---\n\n /** Timeline position in seconds. */\n @property({ type: Number, noAccessor: true })\n get start(): number {\n return this._linked('start');\n }\n set start(value: number) {\n this._request('start', value);\n }\n @property({ type: Number, noAccessor: true })\n get duration(): number {\n return this._linked('duration');\n }\n set duration(value: number) {\n this._request('duration', value);\n }\n @property({ type: Number, noAccessor: true })\n get offset(): number {\n return this._linked('offset');\n }\n set offset(value: number) {\n this._request('offset', value);\n }\n @property({ type: Number, noAccessor: true })\n get gain(): number {\n return this._linked('gain');\n }\n set gain(value: number) {\n this._request('gain', value);\n }\n @property({ noAccessor: true })\n get name(): string {\n return this._linked('name');\n }\n set name(value: string) {\n this._request('name', value ?? '');\n }\n @property() color = '';\n @property({ type: Number, attribute: 'fade-in' }) fadeIn = 0;\n @property({ type: Number, attribute: 'fade-out' }) fadeOut = 0;\n @property({ attribute: 'fade-type' }) fadeType = 'linear';\n\n /** MIDI notes — JS property only, not reflected (note arrays are too large for attributes). */\n @property({ attribute: false, noAccessor: true })\n get midiNotes(): MidiNoteData[] | null {\n return this._linked('midiNotes');\n }\n set midiNotes(value: MidiNoteData[] | null) {\n this._request('midiNotes', value ?? null);\n }\n\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n @property({ type: Number, attribute: 'midi-channel', noAccessor: true })\n get midiChannel(): number | null {\n return this._linked('midiChannel');\n }\n set midiChannel(value: number | null) {\n if (\n value !== null &&\n (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15)\n ) {\n console.warn('[dawcore] daw-clip midi-channel ' + value + ' is out of range 0-15 — ignored');\n return;\n }\n this._request('midiChannel', value);\n }\n\n /** MIDI program (GM instrument 0-127). Used by SoundFontToneTrack. */\n @property({ type: Number, attribute: 'midi-program', noAccessor: true })\n get midiProgram(): number | null {\n return this._linked('midiProgram');\n }\n set midiProgram(value: number | null) {\n if (\n value !== null &&\n (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127)\n ) {\n console.warn('[dawcore] daw-clip midi-program ' + value + ' is out of range 0-127 — ignored');\n return;\n }\n this._request('midiProgram', value);\n }\n\n /** What the page declared: the attributes, and a property set before the clip entered. */\n private _declared: ClipLinkValues = {\n start: 0,\n duration: 0,\n offset: 0,\n gain: 1,\n name: '',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n };\n private _fromAttribute = false;\n private _internals: ElementInternals | null = this.attachInternals?.() ?? null;\n\n attributeChangedCallback(name: string, old: string | null, value: string | null): void {\n // An attribute is the declaration, whatever the link state.\n this._fromAttribute = true;\n try {\n super.attributeChangedCallback(name, old, value);\n } finally {\n this._fromAttribute = false;\n }\n }\n\n private get _trackId(): string {\n return (this.closest('daw-track') as { trackId?: string } | null)?.trackId ?? '';\n }\n\n private _linked<K extends keyof ClipLinkValues>(key: K): ClipLinkValues[K] {\n const host = linkHostOf(this);\n const trackId = this._trackId;\n const live =\n host && trackId && host._clipLinkState(trackId, this.clipId) === 'live'\n ? host._clipValues(trackId, this.clipId)\n : null;\n return live ? live[key] : this._declared[key];\n }\n\n private _request<K extends keyof ClipLinkValues>(key: K, value: ClipLinkValues[K]): void {\n const old = this._linked(key);\n const host = linkHostOf(this);\n const trackId = this._trackId;\n const state = host && trackId ? host._clipLinkState(trackId, this.clipId) : 'pending';\n if (this._fromAttribute || state === 'pending') {\n this._declared = { ...this._declared, [key]: value };\n }\n if (state === 'live') {\n host!._requestClipChange(trackId, this.clipId, { [key]: value } as Partial<ClipLinkValues>);\n } else if (state === 'detached') {\n const label = '<daw-clip> of track \"' + trackId + '\"';\n console.warn(detachedWarning(label, key + ' = ' + String(value), host!._detachedReason()));\n }\n this.requestUpdate(key, old);\n }\n\n /** @internal Shown as `:state(detached)` (#848). */\n _setDetached(detached: boolean): void {\n setCustomState(this._internals, 'detached', detached);\n }\n\n readonly clipId = crypto.randomUUID();\n\n // Light DOM — no visual rendering, just a data container\n createRenderRoot() {\n return this;\n }\n\n /**\n * A move with `Node.moveBefore()` (#848; modern-web-guidance\n * `custom-elements`): the browser calls this instead of\n * `disconnectedCallback` → `connectedCallback`, so the element stays\n * connected, and Lit's disconnect and connect do not run. It announces\n * itself again, as a connect does, so the editor sees its new place: a\n * clip in another track, a track back in an editor (#848; a real-Chromium\n * check found both missed with an empty hook).\n */\n connectedMoveCallback(): void {\n this._announceConnected();\n }\n\n connectedCallback() {\n super.connectedCallback();\n this._announceConnected();\n }\n\n /** Tell the editor this element is here (a connect or a moveBefore() move). */\n private _announceConnected(): void {\n // Defer dispatch so:\n // 1. The editor's connectedCallback (which registers the daw-clip-connected\n // listener) has time to run when parsed all-at-once.\n // 2. The parent's deferred daw-track-connected event fires first; the\n // editor reads the <daw-clip> children when the track enters, so this\n // event is the late-append signal (and, from connectedMoveCallback,\n // the signal of a move into another track).\n // _onClipConnected adds the clip to the descriptor of a track that has not\n // entered the arrangement yet, and appends it to an entered track as a\n // loading clip (a loaded one for MIDI) (#848).\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-clip-connected', {\n bubbles: true,\n composed: true,\n detail: { clipId: this.clipId, element: this },\n })\n );\n }, 0);\n }\n\n // Removal is detected by the editor's MutationObserver — detached elements\n // cannot bubble events to ancestors.\n\n private _hasRendered = false;\n\n updated(changed: PropertyValues) {\n if (!this._hasRendered) {\n this._hasRendered = true;\n return;\n }\n const clipProps = [\n 'src',\n 'peaksSrc',\n 'start',\n 'duration',\n 'offset',\n 'gain',\n 'name',\n 'fadeIn',\n 'fadeOut',\n 'fadeType',\n 'midiNotes',\n 'midiChannel',\n 'midiProgram',\n ];\n if (clipProps.some((p) => changed.has(p as keyof this))) {\n // Resolve parent <daw-track> at dispatch time so consumers don't need\n // to walk closest('daw-track') themselves. trackId may be empty if the\n // clip is mounted outside a track (developer error).\n const trackEl = this.closest('daw-track') as { trackId?: string } | null;\n this.dispatchEvent(\n new CustomEvent('daw-clip-update', {\n bubbles: true,\n composed: true,\n detail: { trackId: trackEl?.trackId ?? '', clipId: this.clipId },\n })\n );\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-clip': DawClipElement;\n }\n}\n","/**\n * How `<daw-track>` and `<daw-clip>` are linked to the arrangement the editor\n * plays (#848 PR 3): by id. An element is\n *\n * - pending: not in an editor, or registered and not entered yet. Its\n * properties are its own declaration (the attributes, and any property set\n * before entry, which is the value the track enters with);\n * - live: the arrangement holds its id. Properties read the arrangement, and\n * setting one (or changing its attribute) is a request to it, one undo step;\n * - detached: the editor took it, and the arrangement no longer holds its id\n * (an Undo of its arrival, a removal made on the arrangement, a refusal).\n * Properties read the declaration; a change does nothing, with a warning.\n * The element carries the custom state `detached` (`:state(detached)`).\n *\n * Attributes are never written by the editor.\n */\nimport type { MidiNoteData, PanLaw, TrackKind } from '@waveform-playlist/core';\n\nexport type LinkState = 'pending' | 'live' | 'detached';\n\n/** The `<daw-track>` properties read from the arrangement while live. */\nexport interface TrackLinkValues {\n volume: number;\n pan: number;\n muted: boolean;\n soloed: boolean;\n /** `'auto'` until the track's first decoded audio decides it (#684). */\n panLaw: PanLaw;\n name: string;\n}\n\n/** The `<daw-clip>` properties read from the arrangement while live. */\nexport interface ClipLinkValues {\n start: number;\n duration: number;\n offset: number;\n gain: number;\n name: string;\n midiNotes: MidiNoteData[] | null;\n midiChannel: number | null;\n midiProgram: number | null;\n}\n\n/** What the elements ask the editor that holds them. */\nexport interface ElementLinkHost {\n _trackLinkState(trackId: string): LinkState;\n _clipLinkState(trackId: string, clipId: string): LinkState;\n /** The live values; null when the track is not live. */\n _trackValues(trackId: string): TrackLinkValues | null;\n _clipValues(trackId: string, clipId: string): ClipLinkValues | null;\n _requestTrackChange(trackId: string, partial: Partial<TrackLinkValues>): void;\n _requestClipChange(trackId: string, clipId: string, partial: Partial<ClipLinkValues>): void;\n /** The track's position in the arrangement, -1 when it is not there. */\n _trackIndex(trackId: string): number;\n /** The kind of a track the arrangement holds, null when it holds none. */\n _trackKind(trackId: string): TrackKind | null;\n /** Why an element of this editor is detached, for the warning. */\n _detachedReason(): string;\n}\n\n/** The editor an element belongs to, when it is in one that links elements. */\nexport function linkHostOf(el: Element): ElementLinkHost | null {\n const editor = el.closest('daw-editor') as unknown as Partial<ElementLinkHost> | null;\n return editor && typeof editor._trackLinkState === 'function'\n ? (editor as ElementLinkHost)\n : null;\n}\n\n/** An element that can show it is detached. */\nexport interface DetachableElement {\n _setDetached(detached: boolean): void;\n}\n\n/**\n * Set or clear the `detached` state on every registered track element and\n * its clip elements.\n */\nexport function refreshLinkStates(\n host: ElementLinkHost,\n trackEls: Iterable<[string, Element & DetachableElement]>\n): void {\n for (const [trackId, trackEl] of trackEls) {\n trackEl._setDetached(host._trackLinkState(trackId) === 'detached');\n for (const clipEl of trackEl.querySelectorAll('daw-clip')) {\n const clip = clipEl as unknown as Element & DetachableElement & { clipId: string };\n clip._setDetached(host._clipLinkState(trackId, clip.clipId) === 'detached');\n }\n }\n}\n\n/** The warning for a change on a detached element. */\nexport function detachedWarning(element: string, change: string, reason: string): string {\n return (\n '[dawcore] ' +\n element +\n ' is detached (' +\n reason +\n '): ' +\n change +\n ' changes nothing. Remove the element and insert it again to declare a new one.'\n );\n}\n\n/** Set a custom state on an element's internals; happy-dom and older browsers have none. */\nexport function setCustomState(\n internals: ElementInternals | null,\n name: string,\n on: boolean\n): void {\n const states = internals?.states as unknown as Set<string> | undefined;\n if (!states) return;\n if (on) states.add(name);\n else states.delete(name);\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { PanLaw, RenderMode, SpectrogramConfig, TrackKind } from '@waveform-playlist/core';\nimport type { EffectState as TrackEffectState, SerializedEffectEntry } from '../effects/types';\nimport { normalizeRenderMode } from '../types';\nimport type { DawTrackUpdateDetail } from '../events';\nimport {\n detachedWarning,\n linkHostOf,\n setCustomState,\n type TrackLinkValues,\n} from '../interactions/element-links';\nimport { declaredPanLaw } from '../utils/track-mix';\n\n/** The properties whose change the editor hears about (`daw-track-update`). */\nconst TRACK_PROPS: readonly string[] = [\n 'volume',\n 'pan',\n 'panLaw',\n 'muted',\n 'soloed',\n 'src',\n 'name',\n 'kind',\n 'renderMode',\n 'spectrogramConfig',\n];\n\n/** Structural view of the editor's public per-track effects API (keyed by\n * trackId) — avoids a value-import cycle between daw-track and daw-editor.\n * These are the same methods consumers can call directly on <daw-editor> for\n * element-less (drag-dropped / programmatic) tracks; the element just supplies\n * its own trackId. */\ninterface TrackEffectsDelegate {\n addTrackEffect(trackId: string, type: string, params?: Record<string, number>): string;\n trackEffects(trackId: string): TrackEffectState[];\n removeTrackEffect(trackId: string, effectId: string): void;\n setTrackEffectParams(trackId: string, effectId: string, params: Record<string, number>): void;\n setTrackEffectBypassed(trackId: string, effectId: string, bypassed: boolean): void;\n moveTrackEffect(trackId: string, effectId: string, newIndex: number): void;\n addTrackWamPlugin(trackId: string, url: string, initialState?: unknown): Promise<string>;\n addTrackFaustEffect(\n trackId: string,\n dspCode: string,\n options?: { name?: string }\n ): Promise<string>;\n openTrackEffectGui(\n trackId: string,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement>;\n closeTrackEffectGui(trackId: string, effectId: string): void;\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]>;\n setTrackEffectsState(trackId: string, entries: SerializedEffectEntry[]): Promise<void>;\n}\n\n@customElement('daw-track')\nexport class DawTrackElement extends LitElement {\n @property() src = '';\n\n // --- Live properties (#848): the arrangement's values while the track is\n // in it; the declaration (attributes, a set before entry) otherwise. ---\n\n /** The track's name: the arrangement's, or as declared. Setting it renames the track (an undo step). */\n @property({ noAccessor: true })\n get name(): string {\n return this._linked('name');\n }\n set name(value: string) {\n this._request('name', value ?? '');\n }\n @property({ type: Number, noAccessor: true })\n get volume(): number {\n return this._linked('volume');\n }\n set volume(value: number) {\n this._request('volume', value);\n }\n @property({ type: Number, noAccessor: true })\n get pan(): number {\n return this._linked('pan');\n }\n set pan(value: number) {\n this._request('pan', value);\n }\n /**\n * The track's pan law (#684): `'mono'` (equal power, −3 dB per side at\n * centre) or `'stereo'` (unity at centre, panning folds one channel into\n * the other). `pan-law` declares the law the track enters with; without\n * it the track's first decoded audio decides, and the track then keeps\n * that law whatever clips follow. Live: reads the arrangement's value\n * (`'auto'` while the track has no audio), and the editor writes no\n * attribute. Setting `'mono'` or `'stereo'` on an entered track is a\n * request (an undo step); `'auto'` there changes nothing.\n */\n @property({ attribute: 'pan-law', noAccessor: true })\n get panLaw(): PanLaw {\n return this._linked('panLaw');\n }\n set panLaw(value: PanLaw) {\n this._request('panLaw', declaredPanLaw(value));\n }\n /** The stored mute (a take's mute is not shown here). */\n @property({ type: Boolean, noAccessor: true })\n get muted(): boolean {\n return this._linked('muted');\n }\n set muted(value: boolean) {\n this._request('muted', Boolean(value));\n }\n @property({ type: Boolean, noAccessor: true })\n get soloed(): boolean {\n return this._linked('soloed');\n }\n set soloed(value: boolean) {\n this._request('soloed', Boolean(value));\n }\n\n /** The track's position in the arrangement the editor plays; -1 when it is not there. */\n get index(): number {\n return linkHostOf(this)?._trackIndex(this.trackId) ?? -1;\n }\n\n /** What the page declared: the attributes, and a property set before the track entered. */\n private _declared: TrackLinkValues = {\n name: '',\n volume: 1,\n pan: 0,\n panLaw: 'auto',\n muted: false,\n soloed: false,\n };\n private _fromAttribute = false;\n private _internals: ElementInternals | null = this.attachInternals?.() ?? null;\n\n attributeChangedCallback(name: string, old: string | null, value: string | null): void {\n // An attribute is the declaration, whatever the link state.\n this._fromAttribute = true;\n try {\n super.attributeChangedCallback(name, old, value);\n } finally {\n this._fromAttribute = false;\n }\n }\n\n private _linked<K extends keyof TrackLinkValues>(key: K): TrackLinkValues[K] {\n const host = linkHostOf(this);\n const live =\n host?._trackLinkState(this.trackId) === 'live' ? host._trackValues(this.trackId) : null;\n return live ? live[key] : this._declared[key];\n }\n\n private _request<K extends keyof TrackLinkValues>(key: K, value: TrackLinkValues[K]): void {\n const old = this._linked(key);\n const host = linkHostOf(this);\n const state = host?._trackLinkState(this.trackId) ?? 'pending';\n if (this._fromAttribute || state === 'pending') {\n this._declared = { ...this._declared, [key]: value };\n }\n if (state === 'live') {\n host!._requestTrackChange(this.trackId, { [key]: value } as Partial<TrackLinkValues>);\n } else if (state === 'detached') {\n const label = '<daw-track name=\"' + this._declared.name + '\">';\n console.warn(detachedWarning(label, key + ' = ' + String(value), host!._detachedReason()));\n }\n this.requestUpdate(key, old);\n }\n\n /** @internal Shown as `:state(detached)` (#848). */\n _setDetached(detached: boolean): void {\n setCustomState(this._internals, 'detached', detached);\n }\n\n /**\n * What the track holds: `'audio'` (default) or `'midi'`. Every `<daw-clip>`\n * child must be of this kind (#756). Set it before the track enters: the\n * editor reads it then. Live (#848): once the track has entered, it reads\n * the track's kind, which cannot change; a later change keeps the attribute\n * (the page's declaration) and warns.\n */\n @property({ reflect: true, noAccessor: true })\n get kind(): TrackKind {\n const host = linkHostOf(this);\n const live =\n host?._trackLinkState(this.trackId) === 'live' ? host._trackKind(this.trackId) : null;\n return live ?? this._kind;\n }\n set kind(value: TrackKind) {\n const host = linkHostOf(this);\n const live =\n host?._trackLinkState(this.trackId) === 'live' ? host._trackKind(this.trackId) : null;\n if (live && value !== live) {\n console.warn(\n '[dawcore] <daw-track> \"' +\n (this._declared.name || 'Untitled') +\n '\": kind cannot change after the track has loaded (still \"' +\n live +\n '\"). Remove the track and add one of the other kind.'\n );\n // The attribute is the page's declaration: it keeps what was written.\n if (!this._fromAttribute) return;\n }\n if (value !== 'audio' && value !== 'midi') {\n console.warn(\n '[dawcore] <daw-track kind=\"' +\n String(value) +\n \"\\\"> is not a track kind ('audio' or 'midi'); keeping \\\"\" +\n this._kind +\n '\"'\n );\n return;\n }\n const old = this._kind;\n this._kind = value;\n this.requestUpdate('kind', old);\n }\n private _kind: TrackKind = 'audio';\n\n // Custom getter/setter so we can warn-and-fallback on 'both' (dawcore\n // doesn't yet support rendering waveform + spectrogram simultaneously).\n @property({ attribute: 'render-mode', noAccessor: true })\n get renderMode(): RenderMode {\n return this._renderMode;\n }\n set renderMode(value: RenderMode) {\n const old = this._renderMode;\n // From markup the value is any string, and null when the attribute is\n // removed.\n let next = normalizeRenderMode(value);\n if (next === 'both') {\n console.warn(\n '[dawcore] <daw-track render-mode=\"both\"> is not yet supported; falling back to \\'spectrogram\\''\n );\n next = 'spectrogram';\n }\n this._renderMode = next;\n this.requestUpdate('renderMode', old);\n }\n private _renderMode: RenderMode = 'waveform';\n\n @property({ attribute: false }) spectrogramConfig: SpectrogramConfig | null = null;\n\n readonly trackId = crypto.randomUUID();\n\n // Light DOM so <daw-clip> children are queryable.\n createRenderRoot() {\n return this;\n }\n\n // --- Effects API (delegates to the owning <daw-editor>) ---\n\n addEffect(type: string, params?: Record<string, number>): string {\n return this._effectsEditor().addTrackEffect(this.trackId, type, params);\n }\n\n /** Load a WAM plugin (via the optional @dawcore/wam peer) into this track's chain. */\n addWamPlugin(url: string, initialState?: unknown): Promise<string> {\n return this._effectsEditor().addTrackWamPlugin(this.trackId, url, initialState);\n }\n\n /**\n * Compile Faust DSP source in the browser (via the optional @dawcore/faust\n * peer) and add the resulting WAM to this track's chain. Compile errors\n * keep their Faust line/column diagnostics and leave the chain untouched.\n */\n addFaustEffect(dspCode: string, options?: { name?: string }): Promise<string> {\n return this._effectsEditor().addTrackFaustEffect(this.trackId, dspCode, options);\n }\n\n /** Snapshot this track's chain in its persisted form (see dawcore README). */\n getEffectsState(): Promise<SerializedEffectEntry[]> {\n const editor = this.closest('daw-editor') as TrackEffectsDelegate | null;\n return editor?.getTrackEffectsState(this.trackId) ?? Promise.resolve([]);\n }\n\n /** Replace this track's chain with a persisted snapshot. */\n setEffectsState(entries: SerializedEffectEntry[]): Promise<void> {\n return this._effectsEditor().setTrackEffectsState(this.trackId, entries);\n }\n\n /**\n * Open (lazily creating) the GUI for one of this track's effects into a\n * consumer-provided container. Closing hides without interrupting audio;\n * the element is cached for reopen. See <daw-editor>.openEffectGui.\n */\n openEffectGui(effectId: string, container: HTMLElement): Promise<HTMLElement> {\n return this._effectsEditor().openTrackEffectGui(this.trackId, effectId, container);\n }\n\n /** Hide an effect's GUI (cached for reopen — never destroys). */\n closeEffectGui(effectId: string): void {\n this._effectsEditor().closeTrackEffectGui(this.trackId, effectId);\n }\n\n removeEffect(effectId: string): void {\n this._effectsEditor().removeTrackEffect(this.trackId, effectId);\n }\n\n setEffectParams(effectId: string, params: Record<string, number>): void {\n this._effectsEditor().setTrackEffectParams(this.trackId, effectId, params);\n }\n\n setEffectBypassed(effectId: string, bypassed: boolean): void {\n this._effectsEditor().setTrackEffectBypassed(this.trackId, effectId, bypassed);\n }\n\n moveEffect(effectId: string, newIndex: number): void {\n this._effectsEditor().moveTrackEffect(this.trackId, effectId, newIndex);\n }\n\n get effects(): TrackEffectState[] {\n const editor = this.closest('daw-editor') as TrackEffectsDelegate | null;\n return editor?.trackEffects(this.trackId) ?? [];\n }\n\n private _effectsEditor(): TrackEffectsDelegate {\n const editor = this.closest('daw-editor') as TrackEffectsDelegate | null;\n if (!editor) {\n throw new Error(\n '[waveform-playlist] <daw-track> effects API requires the track to be inside a <daw-editor>'\n );\n }\n return editor;\n }\n\n /**\n * A move with `Node.moveBefore()` (#848; modern-web-guidance\n * `custom-elements`): the browser calls this instead of\n * `disconnectedCallback` → `connectedCallback`, so the element stays\n * connected, and Lit's disconnect and connect do not run. It announces\n * itself again, as a connect does, so the editor sees its new place: a\n * clip in another track, a track back in an editor (#848; a real-Chromium\n * check found both missed with an empty hook).\n */\n connectedMoveCallback(): void {\n this._announceConnected();\n }\n\n connectedCallback() {\n super.connectedCallback();\n this._announceConnected();\n }\n\n /** Tell the editor this element is here (a connect or a moveBefore() move). */\n private _announceConnected(): void {\n // Defer so the editor's connectedCallback (which registers the\n // daw-track-connected listener) has time to run. Without this,\n // tracks parsed before the editor would fire events with no listener.\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-track-connected', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId, element: this },\n })\n );\n }, 0);\n }\n\n // Track removal is detected by the editor's MutationObserver,\n // not by dispatching from disconnectedCallback (detached elements\n // cannot bubble events to ancestors).\n\n private _hasRendered = false;\n\n updated(changed: PropertyValues) {\n // Skip the initial render — all properties appear in `changed` on first\n // update, but the editor handles initial state via daw-track-connected.\n if (!this._hasRendered) {\n this._hasRendered = true;\n return;\n }\n\n // The names go in the event (#843): the editor's _onTrackUpdate takes\n // kind, renderMode, spectrogramConfig and src only when they are among\n // them. The mix and the name do not go through this event: their setters\n // ask the editor directly (#848).\n const trackChanged = TRACK_PROPS.filter((p) => changed.has(p as keyof this));\n\n if (trackChanged.length > 0) {\n const detail: DawTrackUpdateDetail = { trackId: this.trackId, changed: trackChanged };\n this.dispatchEvent(\n new CustomEvent('daw-track-update', {\n bubbles: true,\n composed: true,\n detail,\n })\n );\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-track': DawTrackElement;\n }\n}\n","import type {\n FadeType,\n MidiNoteData,\n PanLaw,\n RenderMode,\n SpectrogramConfig,\n TrackKind,\n} from '@waveform-playlist/core';\n\n// dawcore's name for core's `RenderMode` (the same type).\nexport type TrackRenderMode = RenderMode;\n\nexport interface TrackDescriptor {\n name: string;\n src: string;\n volume: number;\n pan: number;\n /** The pan law: `'auto'` until the track's first decoded audio decides it (#684). */\n panLaw: PanLaw;\n muted: boolean;\n soloed: boolean;\n /** What the track holds: audio clips or MIDI clips, never both (#756). */\n kind: TrackKind;\n /** How an audio track is drawn. A MIDI track is drawn as a piano roll from\n * its `kind`; its `renderMode` is always `'waveform'` and means nothing. */\n renderMode: TrackRenderMode;\n spectrogramConfig?: SpectrogramConfig | null;\n clips: ClipDescriptor[];\n}\n\n/**\n * A render mode from untyped input (an attribute string, a config object from\n * JavaScript). A missing value is `'waveform'`. Anything that is not a render\n * mode is `'waveform'` with a warning; the former `'piano-roll'` gets a hint.\n */\nexport function normalizeRenderMode(value: unknown): TrackRenderMode {\n if (value === null || value === undefined) return 'waveform';\n if (value === 'waveform' || value === 'spectrogram' || value === 'both') return value;\n console.warn(\n '[dawcore] render-mode=\"' +\n String(value) +\n '\" is not a render mode (waveform or spectrogram); using waveform.' +\n (value === 'piano-roll'\n ? ' A piano roll is how a MIDI track is drawn: set kind=\"midi\" on the track.'\n : '')\n );\n return 'waveform';\n}\n\n/**\n * The render mode a track descriptor carries, given its kind. Render modes are\n * for audio tracks; a MIDI track always carries `'waveform'`, so that a\n * `render-mode=\"spectrogram\"` left on it does not start the spectrogram\n * pipeline for a track with no audio.\n */\nexport function trackDescriptorRenderMode(\n kind: TrackKind,\n requested: TrackRenderMode\n): TrackRenderMode {\n return kind === 'midi' ? 'waveform' : requested;\n}\n\n/** The mixer fields of a `TrackDescriptor`. */\nexport type TrackMixFields = 'volume' | 'pan' | 'muted' | 'soloed' | 'panLaw';\n\n/**\n * What `<daw-editor>` stores per track (internal, not exported from the\n * package): a `TrackDescriptor` without its mix. The mix is the arrangement's\n * (#843); `editor.tracks` fills the mix fields in from it.\n */\nexport type StoredTrackDescriptor = Omit<TrackDescriptor, TrackMixFields>;\n\n/**\n * What `<daw-editor>` keeps per track that the arrangement has no field for\n * (internal, #848): how the track is drawn, the `<daw-track src>` shorthand\n * as declared, and each clip's `peaks-src`. Names, times, gains and the mix\n * are read from the arrangement; nothing here is written back to it.\n */\nexport interface TrackExtras {\n kind: TrackKind;\n renderMode: TrackRenderMode;\n spectrogramConfig?: SpectrogramConfig | null;\n /** The `<daw-track src>` shorthand as declared ('' when none). */\n src: string;\n /** A clip's `peaks-src`, by clip id. */\n peaksSrc: ReadonlyMap<string, string>;\n}\n\n/** A `TrackDescriptor` plus its `trackId` — the shape returned by `editor.tracks`\n * so consumers can map a track's name to the `trackId` the per-track APIs\n * (`addTrackEffect`, `removeTrack`, `updateTrack`, …) are keyed by. */\nexport type TrackWithId = TrackDescriptor & { trackId: string };\n\n/**\n * Common fields shared by all clip descriptors regardless of source.\n */\ninterface BaseClipDescriptor {\n src: string;\n peaksSrc: string;\n start: number;\n duration: number;\n offset: number;\n gain: number;\n name: string;\n fadeIn: number;\n fadeOut: number;\n fadeType: FadeType;\n midiNotes: MidiNoteData[] | null;\n midiChannel: number | null;\n midiProgram: number | null;\n}\n\n/**\n * A clip descriptor sourced from a `<daw-clip>` DOM element. `clipId` is\n * always set — `<daw-clip>.clipId` is a `crypto.randomUUID()` generated at\n * construction. The arrangement clip's id is this id (`buildArrangementTrack`,\n * `_loadAndAppendClip`), so the DOM and the arrangement name the same clip.\n */\nexport interface DomClipDescriptor extends BaseClipDescriptor {\n kind: 'dom';\n clipId: string;\n}\n\n/**\n * A clip descriptor synthesized from a non-DOM source — file drops, the\n * `<daw-track src>` shorthand fallback, or recording-clip insertion. There\n * is no DOM element to align with.\n *\n * `clipId` is the arrangement clip's id: set at creation for a recorded take\n * (#659), and written in when a dropped file or the shorthand enters the\n * arrangement (#848). Pass it to `editor.updateClip()` / `removeClip()` to\n * address the clip.\n */\nexport interface DropClipDescriptor extends BaseClipDescriptor {\n kind: 'drop';\n clipId?: string;\n /** A dropped file the clip loads (`src` is then ''): a File cannot be an attribute (#848). */\n file?: File;\n}\n\nexport type ClipDescriptor = DomClipDescriptor | DropClipDescriptor;\n\n/**\n * Type predicate for the `'dom'` discriminator. Use to narrow a\n * `ClipDescriptor` to `DomClipDescriptor` (which has `clipId`) without\n * inline `c.kind === 'dom'` repetition.\n */\nexport function isDomClip(desc: ClipDescriptor): desc is DomClipDescriptor {\n return desc.kind === 'dom';\n}\n\n/**\n * Options of `addTrack`, `addClip` and `loadFiles` (#848). `signal` cancels\n * the call: it rejects with the signal's `reason`, and what it added is\n * taken out for good (see each method), with no undo step left. A Redo list\n * its arrival cleared stays cleared, as after any edit. A signal already\n * aborted rejects at once and adds nothing.\n */\nexport interface EditorCallOptions {\n signal?: AbortSignal;\n}\n\n/**\n * Public input shape for `editor.addTrack(config)`. All fields optional —\n * defaults match the declarative `<daw-track>` defaults.\n */\nexport interface TrackConfig {\n name?: string;\n volume?: number;\n pan?: number;\n /**\n * The pan law (#684): `'mono'` or `'stereo'`. In `addTrack` it is the law\n * the track enters with (default: decided by its first decoded audio); in\n * `updateTrack` it sets the law of an entered track. `'auto'` there, or a\n * value that is not a law, changes nothing.\n */\n panLaw?: PanLaw;\n muted?: boolean;\n soloed?: boolean;\n /**\n * What the track holds. Default `'audio'`, or `'midi'` when `midi` is given.\n * Every clip must be of this kind: a clip of the other kind is not added and\n * is reported through `daw-clip-error`. Creation-only: ignored by `updateTrack`.\n */\n kind?: TrackKind;\n /** How an audio track is drawn. Ignored for a MIDI track (a piano roll). */\n renderMode?: TrackRenderMode;\n spectrogramConfig?: SpectrogramConfig | null;\n clips?: ClipConfig[];\n /**\n * Convenience: makes the track a MIDI track (`kind: 'midi'`) with a single\n * `<daw-clip>` child holding these notes. Equivalent to passing\n * `{ kind: 'midi', clips: [{ midiNotes, midiChannel, midiProgram }] }`.\n *\n * Creation-only — ignored by `updateTrack`. To modify notes after the\n * track is built, use `editor.updateClip(trackId, clipId, { midiNotes })` or\n * mutate the `<daw-clip>` element's `midiNotes` property directly.\n */\n midi?: {\n notes: MidiNoteData[];\n channel?: number;\n program?: number;\n };\n}\n\n/**\n * Public input shape for clips passed via `TrackConfig.clips` or\n * `editor.addClip(trackId, config)`. `src` is optional to support MIDI clips\n * with no audio source. Other fields default to the matching `<daw-clip>`\n * attribute defaults.\n */\nexport interface ClipConfig {\n src?: string;\n peaksSrc?: string;\n start?: number;\n duration?: number;\n offset?: number;\n gain?: number;\n name?: string;\n fadeIn?: number;\n fadeOut?: number;\n fadeType?: FadeType;\n midiNotes?: MidiNoteData[];\n midiChannel?: number;\n midiProgram?: number;\n}\n","/**\n * A track's mix (volume, pan, pan law, mute, solo) as `<daw-editor>` reads it (#843).\n * The arrangement owns the mix of every track it holds; until a track enters\n * it, the editor holds the values the track will start with (the seed).\n */\nimport { isDecidedPanLaw } from '@waveform-playlist/core';\nimport type { ClipTrack, PanLaw } from '@waveform-playlist/core';\nimport type { TrackMixerValues } from '@waveform-playlist/engine';\n\nexport const DEFAULT_TRACK_MIX: Readonly<TrackMixerValues> = Object.freeze({\n volume: 1,\n pan: 0,\n muted: false,\n soloed: false,\n panLaw: 'auto',\n});\n\n/** A pan law from anywhere (an attribute, plain JS): `'mono'`, `'stereo'`, and `'auto'` for everything else. */\nexport function toPanLaw(value: unknown): PanLaw {\n return isDecidedPanLaw(value) ? value : 'auto';\n}\n\n/**\n * A pan law the page gave (#684), with one warning for a value that is not\n * one: `'mono'`, `'stereo'`, `'auto'` (also for none, or an empty attribute).\n */\nexport function declaredPanLaw(value: unknown): PanLaw {\n if (value == null || value === '' || value === 'auto' || isDecidedPanLaw(value)) {\n return toPanLaw(value);\n }\n console.warn(\n '[dawcore] <daw-track pan-law> must be \"mono\", \"stereo\" or \"auto\", got ' + JSON.stringify(value)\n );\n return 'auto';\n}\n\n/** The mix fields of an engine track (the projection: `muted` includes a take's mute). */\nexport function mixOfTrack(track: ClipTrack): TrackMixerValues {\n return {\n volume: track.volume,\n pan: track.pan,\n muted: track.muted,\n soloed: track.soloed,\n panLaw: toPanLaw(track.panLaw),\n };\n}\n\n/** The mix a `<daw-track>` element (or anything with the four fields) asks for. */\nexport function mixOfElement(el: TrackMixerValues): TrackMixerValues {\n return {\n volume: el.volume,\n pan: el.pan,\n muted: el.muted,\n soloed: el.soloed,\n panLaw: toPanLaw(el.panLaw),\n };\n}\n\n/**\n * The fields of `mix` whose names are in `names` (a `daw-track-update`'s\n * `changed` list): the mixer properties an update changed, and no other.\n */\nexport function pickMix(mix: TrackMixerValues, names: Iterable<string>): Partial<TrackMixerValues> {\n const named = new Set(names);\n return {\n ...(named.has('volume') && { volume: mix.volume }),\n ...(named.has('pan') && { pan: mix.pan }),\n ...(named.has('muted') && { muted: mix.muted }),\n ...(named.has('soloed') && { soloed: mix.soloed }),\n ...(named.has('panLaw') && { panLaw: mix.panLaw }),\n };\n}\n\n/** `track` with `mix` written over its mixer fields (a new object). */\nexport function withMix(track: ClipTrack, mix: TrackMixerValues): ClipTrack {\n return { ...track, ...mixOfElement(mix) };\n}\n\n/** A control's value as a number within [min, max]. */\nexport function clampNumber(value: unknown, min: number, max: number): number {\n return Math.max(min, Math.min(max, Number(value)));\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { Peaks, Bits } from '@waveform-playlist/core';\nimport {\n addBarToPath,\n aggregatePeaks,\n scalePeakByGain,\n calculateBarRects,\n type BarRect,\n} from '../utils/peak-rendering';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\n/** A segment mapping a peak-index range to a pixel range within the waveform. */\nexport interface WaveformSegment {\n /** Start position in the peaks array (fractional index). */\n peakStart: number;\n /** End position in the peaks array (fractional index). */\n peakEnd: number;\n /** Start pixel position within the waveform. */\n pixelStart: number;\n /** End pixel position within the waveform. */\n pixelEnd: number;\n}\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n/** Layout/data properties that require a full redraw when changed. */\nconst LAYOUT_PROPS = new Set([\n 'length',\n 'waveHeight',\n 'barWidth',\n 'barGap',\n 'roundedBars',\n 'segments',\n 'gain',\n]);\n\n/**\n * Group dirty peak indices by canvas chunk. Returns bar-pixel-aligned\n * min/max positions per chunk for correct clearRect coordinates,\n * including when barWidth > 1 or barGap > 0.\n */\nfunction groupDirtyByChunk(\n dirtyPixels: Set<number>,\n step: number,\n barWidth: number\n): Map<number, { min: number; max: number }> {\n const dirtyByChunk = new Map<number, { min: number; max: number }>();\n const mark = (chunkIdx: number, barPixel: number) => {\n const existing = dirtyByChunk.get(chunkIdx);\n if (existing) {\n dirtyByChunk.set(chunkIdx, {\n min: Math.min(existing.min, barPixel),\n max: Math.max(existing.max, barPixel),\n });\n } else {\n dirtyByChunk.set(chunkIdx, { min: barPixel, max: barPixel });\n }\n };\n for (const peakIdx of dirtyPixels) {\n // Map peak index to its bar's global pixel position\n const barPixel = Math.floor(peakIdx / step) * step;\n const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);\n mark(chunkIdx, barPixel);\n // A bar straddling the chunk boundary (barWidth+barGap not dividing\n // MAX_CANVAS_WIDTH) has pixels on the NEXT canvas too — mark that chunk\n // dirty for the same bar, or its clipped remainder is a permanent 1-2px\n // gap at every boundary. _drawChunk's loop is global-indexed, so the\n // next chunk draws the bar at a negative local x.\n const endChunkIdx = Math.floor((barPixel + barWidth - 1) / MAX_CANVAS_WIDTH);\n if (endChunkIdx !== chunkIdx) {\n mark(endChunkIdx, barPixel);\n }\n }\n return dirtyByChunk;\n}\n\n@customElement('daw-waveform')\nexport class DawWaveformElement extends LitElement {\n private _peaks: Peaks = new Int16Array(0);\n private _dirtyPixels: Set<number> = new Set();\n private _drawScheduled = false;\n private _rafId = 0;\n /** Chunk indices visible in the last draw pass — used to detect new chunks on scroll. */\n private _drawnChunks: Set<number> = new Set();\n\n set peaks(value: Peaks) {\n this._peaks = value;\n this._markAllDirty();\n this.requestUpdate();\n }\n\n get peaks(): Peaks {\n return this._peaks;\n }\n\n /**\n * Replace the internal peaks reference without marking all dirty.\n * Use with updatePeaks() for incremental recording updates where\n * appendPeaks() returns a new array but only the tail changed.\n */\n setPeaksQuiet(value: Peaks) {\n this._peaks = value;\n }\n\n get bits(): Bits {\n return this._peaks instanceof Int8Array ? 8 : 16;\n }\n\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) waveHeight = 128;\n @property({ type: Number, attribute: false }) barWidth = 1;\n @property({ type: Number, attribute: false }) barGap = 0;\n /** Draw bars with pill-shaped rounded caps (radius barWidth/2). */\n @property({ type: Boolean, attribute: false }) roundedBars = false;\n /** Linear gain applied to the DRAWN bars (clamped to the channel height).\n * Display-only — peaks are untouched, so changing it never regenerates\n * them. The editor feeds it a clip's gain under `gain-scaled-waveforms`. */\n @property({ type: Number, attribute: false }) gain = 1;\n /** Visible viewport start in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n /** Visible viewport end in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n /** This element's left offset on the timeline (for viewport intersection). */\n @property({ type: Number, attribute: false }) originX = 0;\n /** When set, draws per-segment with independent samples-per-pixel ratios. */\n @property({ attribute: false }) segments?: WaveformSegment[];\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n }\n .container {\n position: relative;\n }\n canvas {\n position: absolute;\n top: 0;\n }\n `;\n\n private _getVisibleChunkIndices(): number[] {\n return getVisibleChunkIndices(\n this.length,\n MAX_CANVAS_WIDTH,\n this.visibleStart,\n this.visibleEnd,\n this.originX\n );\n }\n\n /**\n * Mark a range of peak indices as dirty for incremental redraw.\n * The caller must have already updated the underlying peaks array.\n * Does NOT trigger a Lit re-render — bypasses Lit entirely.\n */\n updatePeaks(startIndex: number, endIndex: number) {\n const peakCount = Math.floor(this._peaks.length / 2);\n const clampedStart = Math.max(0, startIndex);\n const clampedEnd = Math.min(peakCount, endIndex);\n for (let i = clampedStart; i < clampedEnd; i++) {\n this._dirtyPixels.add(i);\n }\n this._scheduleDraw();\n }\n\n private _markAllDirty() {\n const peakCount = Math.floor(this._peaks.length / 2);\n for (let i = 0; i < peakCount; i++) {\n this._dirtyPixels.add(i);\n }\n this._scheduleDraw();\n }\n\n private _scheduleDraw() {\n if (!this._drawScheduled) {\n this._drawScheduled = true;\n this._rafId = requestAnimationFrame(() => {\n this._drawScheduled = false;\n this._drawDirty();\n });\n }\n }\n\n private _drawDirty() {\n if (this._dirtyPixels.size === 0 || this.length === 0 || this._peaks.length === 0) {\n this._dirtyPixels.clear();\n return;\n }\n\n const canvases = this.shadowRoot?.querySelectorAll('canvas');\n if (!canvases || canvases.length === 0) {\n // Don't clear _dirtyPixels — canvases may appear after Lit renders.\n // connectedCallback or updated() will reschedule the draw.\n return;\n }\n\n const step = this.barWidth + this.barGap;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const halfHeight = this.waveHeight / 2;\n const bits = this.bits;\n const waveColor =\n getComputedStyle(this).getPropertyValue('--daw-wave-color').trim() || '#c49a6c';\n\n this._drawnChunks.clear();\n\n if (this.segments) {\n // Segment mode: full redraw per chunk (segments have variable SPP)\n for (const canvas of canvases) {\n const chunkIdx = Number(canvas.dataset.index);\n this._drawnChunks.add(chunkIdx);\n this._drawSegments(canvas, chunkIdx, dpr, halfHeight, bits, waveColor);\n }\n } else {\n const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step, this.barWidth);\n for (const canvas of canvases) {\n const chunkIdx = Number(canvas.dataset.index);\n this._drawnChunks.add(chunkIdx);\n const range = dirtyByChunk.get(chunkIdx);\n if (!range) continue;\n this._drawChunk(canvas, chunkIdx, range, step, dpr, halfHeight, bits, waveColor);\n }\n }\n\n this._dirtyPixels.clear();\n }\n\n private _drawChunk(\n canvas: HTMLCanvasElement,\n chunkIdx: number,\n range: { min: number; max: number },\n step: number,\n dpr: number,\n halfHeight: number,\n bits: Bits,\n waveColor: string\n ) {\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n\n const globalOffset = chunkIdx * MAX_CANVAS_WIDTH;\n // range.min/max are bar-pixel-aligned global positions from groupDirtyByChunk\n const clearStart = Math.max(0, range.min - globalOffset);\n const clearEnd = range.max - globalOffset + this.barWidth;\n const clearWidth = clearEnd - clearStart;\n const firstBar = range.min;\n\n ctx.resetTransform();\n ctx.clearRect(clearStart * dpr, 0, clearWidth * dpr, canvas.height);\n ctx.scale(dpr, dpr);\n ctx.fillStyle = waveColor;\n\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, this.length - globalOffset);\n const regionEnd = Math.min(globalOffset + clearEnd, globalOffset + canvasWidth);\n\n // Rounded bars batch into one path with a single fill per region draw.\n const barRadius = this.roundedBars ? this.barWidth / 2 : null;\n if (barRadius !== null) ctx.beginPath();\n\n for (let bar = Math.max(0, firstBar); bar < regionEnd; bar += step) {\n const source = aggregatePeaks(this._peaks, bits, bar, bar + step);\n if (!source) continue;\n const peak = scalePeakByGain(source, this.gain);\n const rects = calculateBarRects(\n bar - globalOffset,\n this.barWidth,\n halfHeight,\n peak.min,\n peak.max,\n 'normal'\n );\n this._drawBarRects(ctx, rects, barRadius);\n }\n\n if (barRadius !== null) ctx.fill();\n }\n\n /** Draw bar rects: fillRect when radius is null, else add rounded bars to the current path. */\n private _drawBarRects(\n ctx: CanvasRenderingContext2D,\n rects: Array<BarRect>,\n radius: number | null\n ) {\n for (const r of rects) {\n if (radius === null) {\n ctx.fillRect(r.x, r.y, r.width, r.height);\n } else {\n addBarToPath(ctx, r, radius);\n }\n }\n }\n\n private _drawSegments(\n canvas: HTMLCanvasElement,\n chunkIdx: number,\n dpr: number,\n halfHeight: number,\n bits: Bits,\n waveColor: string\n ) {\n if (!this.segments) return;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n\n const globalOffset = chunkIdx * MAX_CANVAS_WIDTH;\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, this.length - globalOffset);\n\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.scale(dpr, dpr);\n ctx.fillStyle = waveColor;\n\n const step = Math.max(1, Math.round(this.barWidth + this.barGap));\n const barRadius = this.roundedBars ? this.barWidth / 2 : null;\n if (barRadius !== null) ctx.beginPath();\n\n for (const seg of this.segments) {\n // Skip segments outside this chunk\n if (seg.pixelEnd <= globalOffset || seg.pixelStart >= globalOffset + canvasWidth) continue;\n\n const localStart = Math.max(0, seg.pixelStart - globalOffset);\n const localEnd = Math.min(canvasWidth, seg.pixelEnd - globalOffset);\n const segPixelWidth = seg.pixelEnd - seg.pixelStart;\n const segPeakWidth = seg.peakEnd - seg.peakStart;\n if (segPixelWidth <= 0 || segPeakWidth <= 0) continue;\n\n // Per-segment peaks-per-pixel ratio\n const peaksPerPixel = segPeakWidth / segPixelWidth;\n\n for (let px = Math.floor(localStart); px < Math.ceil(localEnd); px += step) {\n // Map this pixel to a peak index range\n const pxInSeg = px + globalOffset - seg.pixelStart;\n const peakPos = seg.peakStart + pxInSeg * peaksPerPixel;\n const peakEnd = peakPos + step * peaksPerPixel;\n\n const source = aggregatePeaks(this._peaks, bits, Math.floor(peakPos), Math.ceil(peakEnd));\n if (!source) continue;\n const peak = scalePeakByGain(source, this.gain);\n\n const rects = calculateBarRects(\n px,\n this.barWidth,\n halfHeight,\n peak.min,\n peak.max,\n 'normal'\n );\n this._drawBarRects(ctx, rects, barRadius);\n }\n }\n\n if (barRadius !== null) ctx.fill();\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Reschedule draw if dirty pixels survived a disconnect/reconnect cycle\n if (this._dirtyPixels.size > 0) {\n this._scheduleDraw();\n }\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this._drawScheduled) {\n cancelAnimationFrame(this._rafId);\n this._drawScheduled = false;\n }\n // Keep _dirtyPixels — connectedCallback will reschedule if reconnected\n }\n\n render() {\n const indices = this._getVisibleChunkIndices();\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n\n return html`\n <div class=\"container\" style=\"width: ${this.length}px; height: ${this.waveHeight}px;\">\n ${indices.map((i) => {\n const width = Math.min(MAX_CANVAS_WIDTH, this.length - i * MAX_CANVAS_WIDTH);\n return html`\n <canvas\n data-index=${i}\n width=${width * dpr}\n height=${this.waveHeight * dpr}\n style=\"left: ${i * MAX_CANVAS_WIDTH}px; width: ${width}px; height: ${this\n .waveHeight}px;\"\n ></canvas>\n `;\n })}\n </div>\n `;\n }\n\n /** Mark peaks dirty only for chunks that weren't drawn in the previous frame. */\n private _markNewChunksDirty() {\n const currentIndices = this._getVisibleChunkIndices();\n const peakCount = Math.floor(this._peaks.length / 2);\n for (const chunkIdx of currentIndices) {\n if (!this._drawnChunks.has(chunkIdx)) {\n const start = chunkIdx * MAX_CANVAS_WIDTH;\n const end = Math.min(start + MAX_CANVAS_WIDTH, peakCount);\n for (let i = start; i < end; i++) {\n this._dirtyPixels.add(i);\n }\n }\n }\n if (this._dirtyPixels.size > 0) {\n this._scheduleDraw();\n }\n }\n\n updated(changedProperties: Map<string, unknown>) {\n // Layout/data changes require full redraw of all peaks\n const needsFullDirty = [...changedProperties.keys()].some((key) => LAYOUT_PROPS.has(key));\n if (needsFullDirty) {\n this._markAllDirty();\n return;\n }\n // Viewport-only changes: only draw newly visible chunks, skip already-drawn ones\n if (\n changedProperties.has('visibleStart') ||\n changedProperties.has('visibleEnd') ||\n changedProperties.has('originX')\n ) {\n this._markNewChunksDirty();\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-waveform': DawWaveformElement;\n }\n}\n","import type { Peaks, Bits } from '@waveform-playlist/core';\n\nexport type WaveformDrawMode = 'normal' | 'inverted';\n\n/**\n * Result of aggregating peaks over a range.\n *\n * Invariants (assumed from valid waveform input):\n * - min and max are normalized to [-1, 1] by dividing by 2^(bits-1)\n * - min <= max (min-of-mins, max-of-maxes — guaranteed by the interleaved min/max peak format)\n * - Values are finite (derived from integer typed arrays)\n *\n * Construct via aggregatePeaks() — do not create directly.\n */\nexport interface AggregatedPeak {\n min: number;\n max: number;\n}\n\n/**\n * Canvas fillRect parameters for a single waveform bar.\n * width >= 0 and height >= 0 when peak values are in [-1, 1] (guaranteed by\n * the interleaved min/max peak format normalization).\n */\nexport interface BarRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Aggregates peaks over a range of interleaved min/max pairs.\n * Finds min-of-mins and max-of-maxes, normalized by bit depth.\n *\n * @param data - Interleaved peak data [min0, max0, min1, max1, ...]\n * @param bits - Bit depth (8 or 16)\n * @param startIndex - First peak index (not array index — peak i is at data[i*2], data[i*2+1])\n * @param endIndex - One past the last peak index to include\n * @returns Normalized { min, max } or null if startIndex is out of bounds\n */\nexport function aggregatePeaks(\n data: Peaks,\n bits: Bits,\n startIndex: number,\n endIndex: number\n): AggregatedPeak | null {\n if (startIndex * 2 + 1 >= data.length) {\n return null;\n }\n\n const maxValue = 2 ** (bits - 1);\n let minPeak = data[startIndex * 2] / maxValue;\n let maxPeak = data[startIndex * 2 + 1] / maxValue;\n\n for (let p = startIndex + 1; p < endIndex; p++) {\n if (p * 2 + 1 >= data.length) break;\n const pMin = data[p * 2] / maxValue;\n const pMax = data[p * 2 + 1] / maxValue;\n if (pMin < minPeak) minPeak = pMin;\n if (pMax > maxPeak) maxPeak = pMax;\n }\n\n return { min: minPeak, max: maxPeak };\n}\n\nfunction clampToFullScale(value: number): number {\n return Math.max(-1, Math.min(1, value));\n}\n\n/**\n * Scales a drawn peak by a linear gain (a clip's gain), clamped to full\n * scale so a boosted bar never leaves its channel. Display-only: the\n * underlying peak data is untouched, so a gain change needs no peak\n * regeneration. A negative (phase-inverting) gain scales by magnitude; a\n * non-finite gain is ignored.\n *\n * @returns the same object at unity gain (the hot path allocates nothing)\n */\nexport function scalePeakByGain(peak: AggregatedPeak, gain: number): AggregatedPeak {\n if (gain === 1 || !Number.isFinite(gain)) {\n return peak;\n }\n const factor = Math.abs(gain);\n // Clamp BOTH values on BOTH sides. Zoomed in on low-frequency content a\n // bar's min is often positive (or its max negative): {min: 0.6, max: 0.9}\n // at gain 2 would otherwise leave min at 1.2, outside the channel.\n return {\n min: clampToFullScale(peak.min * factor),\n max: clampToFullScale(peak.max * factor),\n };\n}\n\n/**\n * Computes canvas fillRect parameters for a single waveform bar.\n *\n * @param x - Bar x position in canvas coordinates\n * @param barWidth - Width of the bar in pixels\n * @param halfHeight - Half the waveform height (center line y)\n * @param minPeak - Normalized min peak value (negative for below center)\n * @param maxPeak - Normalized max peak value (positive for above center)\n * @param drawMode - 'normal' draws the peak region, 'inverted' draws the non-peak regions\n * @returns Array of BarRect — 1 rect for 'normal', 2 rects for 'inverted'\n */\nexport function calculateBarRects(\n x: number,\n barWidth: number,\n halfHeight: number,\n minPeak: number,\n maxPeak: number,\n drawMode: WaveformDrawMode\n): BarRect[] {\n const min = Math.abs(minPeak * halfHeight);\n const max = Math.abs(maxPeak * halfHeight);\n\n if (drawMode === 'normal') {\n return [{ x, y: halfHeight - max, width: barWidth, height: max + min }];\n }\n\n // Inverted: draw areas WITHOUT audio (top gap + bottom gap)\n return [\n { x, y: 0, width: barWidth, height: halfHeight - max },\n { x, y: halfHeight + min, width: barWidth, height: halfHeight - min },\n ];\n}\n\n/**\n * Adds a bar to the current canvas path with pill-shaped rounded caps.\n * Falls back to square corners on canvases without roundRect\n * (Safari < 16.4, Firefox < 112) instead of throwing.\n *\n * The caller owns beginPath()/fill() so all bars of a chunk batch into a\n * single fill.\n *\n * @param ctx - Canvas context whose current path is being built\n * @param rect - Bar rect from calculateBarRects\n * @param radius - Corner radius (barWidth/2; roundRect spec-clamps on short bars)\n */\nexport function addBarToPath(ctx: CanvasRenderingContext2D, rect: BarRect, radius: number): void {\n if (typeof ctx.roundRect === 'function') {\n ctx.roundRect(rect.x, rect.y, rect.width, rect.height, radius);\n } else {\n ctx.rect(rect.x, rect.y, rect.width, rect.height);\n }\n}\n\n/**\n * Computes the first bar position (in global pixel coordinates) that could\n * affect a given canvas chunk.\n *\n * A bar at position X extends from X to X+barWidth-1, so we need bars where\n * barStart + barWidth > canvasStartGlobal.\n *\n * @param canvasStartGlobal - Global pixel offset of the canvas chunk\n * @param barWidth - Width of each bar in pixels\n * @param step - Bar stride (barWidth + barGap)\n * @returns The first bar's global position (always >= 0 when step >= barWidth; caller clamps to 0)\n */\nexport function calculateFirstBarPosition(\n canvasStartGlobal: number,\n barWidth: number,\n step: number\n): number {\n return Math.floor((canvasStartGlobal - barWidth + step) / step) * step;\n}\n","/**\n * Compute which canvas chunk indices are visible within a viewport range.\n *\n * @param totalWidth - Total pixel width of the content\n * @param chunkWidth - Width of each canvas chunk (e.g. 1000px)\n * @param visibleStart - Viewport start in pixels (relative to timeline origin)\n * @param visibleEnd - Viewport end in pixels (relative to timeline origin)\n * @param originX - Content's left offset on the timeline\n */\nexport function getVisibleChunkIndices(\n totalWidth: number,\n chunkWidth: number,\n visibleStart: number,\n visibleEnd: number,\n originX = 0\n): number[] {\n const totalChunks = Math.ceil(totalWidth / chunkWidth);\n const indices: number[] = [];\n for (let i = 0; i < totalChunks; i++) {\n const chunkStart = originX + i * chunkWidth;\n const chunkEnd = chunkStart + chunkWidth;\n if (chunkEnd > visibleStart && chunkStart < visibleEnd) {\n indices.push(i);\n }\n }\n return indices;\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { MidiNoteData } from '@waveform-playlist/core';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n/** Layout/data properties that require a full redraw when changed. */\nconst LAYOUT_PROPS = new Set([\n 'length',\n 'waveHeight',\n 'samplesPerPixel',\n 'sampleRate',\n 'clipOffsetSeconds',\n 'midiNotes',\n 'selected',\n]);\n\n@customElement('daw-piano-roll')\nexport class DawPianoRollElement extends LitElement {\n @property({ attribute: false }) midiNotes: MidiNoteData[] = [];\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) waveHeight = 128;\n @property({ type: Number, attribute: 'samples-per-pixel', noAccessor: true })\n get samplesPerPixel(): number {\n return this._samplesPerPixel;\n }\n set samplesPerPixel(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-piano-roll samplesPerPixel ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._samplesPerPixel;\n this._samplesPerPixel = value;\n this.requestUpdate('samplesPerPixel', old);\n }\n private _samplesPerPixel = 1024;\n\n @property({ type: Number, attribute: 'sample-rate', noAccessor: true })\n get sampleRate(): number {\n return this._sampleRate;\n }\n set sampleRate(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-piano-roll sampleRate ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._sampleRate;\n this._sampleRate = value;\n this.requestUpdate('sampleRate', old);\n }\n private _sampleRate = 48000;\n @property({ type: Number, attribute: false }) clipOffsetSeconds = 0;\n /** Visible viewport start in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n /** Visible viewport end in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n /** This element's left offset on the timeline (for viewport intersection). */\n @property({ type: Number, attribute: false }) originX = 0;\n @property({ type: Boolean, reflect: true }) selected = false;\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n }\n .container {\n position: relative;\n background: var(--daw-piano-roll-background, #1a1a2e);\n }\n canvas {\n position: absolute;\n top: 0;\n image-rendering: pixelated;\n image-rendering: crisp-edges;\n }\n `;\n\n private _rafHandle: number | null = null;\n\n private _scheduleDraw() {\n if (this._rafHandle !== null) return;\n this._rafHandle = requestAnimationFrame(() => {\n this._rafHandle = null;\n this._draw();\n });\n }\n\n willUpdate(_changed: PropertyValues) {\n this._scheduleDraw();\n }\n\n updated(changedProperties: Map<string, unknown>) {\n // Layout/data changes: willUpdate already scheduled a draw — nothing extra needed.\n const needsFullDraw = [...changedProperties.keys()].some((key) => LAYOUT_PROPS.has(key));\n if (needsFullDraw) return;\n // Viewport-only changes: new canvases may have mounted; schedule a draw so they get painted.\n if (\n changedProperties.has('visibleStart') ||\n changedProperties.has('visibleEnd') ||\n changedProperties.has('originX')\n ) {\n this._scheduleDraw();\n }\n }\n\n private _getPitchRange(): { minMidi: number; maxMidi: number } {\n if (this.midiNotes.length === 0) return { minMidi: 0, maxMidi: 127 };\n let min = 127;\n let max = 0;\n for (const note of this.midiNotes) {\n if (note.midi < min) min = note.midi;\n if (note.midi > max) max = note.midi;\n }\n return {\n minMidi: Math.max(0, min - 1),\n maxMidi: Math.min(127, max + 1),\n };\n }\n\n private _getNoteColor(): string {\n const cs = getComputedStyle(this);\n const note = cs.getPropertyValue('--daw-piano-roll-note-color').trim() || '#2a7070';\n const selectedColor =\n cs.getPropertyValue('--daw-piano-roll-selected-note-color').trim() || '#3d9e9e';\n return this.selected ? selectedColor : note;\n }\n\n private _draw() {\n if (!this.shadowRoot) return;\n const canvases = this.shadowRoot.querySelectorAll('canvas');\n if (canvases.length === 0) return;\n\n const { minMidi, maxMidi } = this._getPitchRange();\n const noteRange = maxMidi - minMidi + 1;\n const noteHeight = Math.max(2, this.waveHeight / noteRange);\n const pixelsPerSecond = this.sampleRate / this.samplesPerPixel;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const color = this._getNoteColor();\n\n for (const canvas of canvases) {\n // Read data-index (matching daw-waveform pattern)\n const chunkIdx = Number((canvas as HTMLCanvasElement).dataset.index);\n const chunkPixelStart = chunkIdx * MAX_CANVAS_WIDTH;\n const canvasWidth = (canvas as HTMLCanvasElement).width / dpr;\n\n const ctx = (canvas as HTMLCanvasElement).getContext('2d');\n if (!ctx) continue;\n\n ctx.resetTransform();\n ctx.clearRect(\n 0,\n 0,\n (canvas as HTMLCanvasElement).width,\n (canvas as HTMLCanvasElement).height\n );\n ctx.imageSmoothingEnabled = false;\n ctx.scale(dpr, dpr);\n\n const chunkStartTime = (chunkPixelStart * this.samplesPerPixel) / this.sampleRate;\n const chunkEndTime =\n ((chunkPixelStart + canvasWidth) * this.samplesPerPixel) / this.sampleRate;\n\n for (const note of this.midiNotes) {\n const noteStart = note.time - this.clipOffsetSeconds;\n const noteEnd = noteStart + note.duration;\n if (noteEnd <= chunkStartTime || noteStart >= chunkEndTime) continue;\n\n const x = noteStart * pixelsPerSecond - chunkPixelStart;\n const w = Math.max(2, note.duration * pixelsPerSecond);\n const y = ((maxMidi - note.midi) / noteRange) * this.waveHeight;\n\n const alpha = 0.3 + note.velocity * 0.7;\n ctx.fillStyle = color;\n ctx.globalAlpha = alpha;\n\n ctx.beginPath();\n ctx.roundRect(x, y, w, noteHeight, 1);\n ctx.fill();\n }\n ctx.globalAlpha = 1;\n }\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Reschedule draw if a RAF was pending during disconnect/reconnect cycle\n this._scheduleDraw();\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this._rafHandle !== null) {\n cancelAnimationFrame(this._rafHandle);\n this._rafHandle = null;\n }\n }\n\n render() {\n if (this.length <= 0)\n return html`<div class=\"container\" style=\"width: 0; height: ${this.waveHeight}px;\"></div>`;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const visibleIndices = getVisibleChunkIndices(\n this.length,\n MAX_CANVAS_WIDTH,\n this.visibleStart,\n this.visibleEnd,\n this.originX\n );\n // Wrap canvases in a .container div with explicit width/height,\n // matching daw-waveform's container pattern. Background is on .container (not :host)\n // so it has the correct measurable size.\n return html`\n <div class=\"container\" style=\"width: ${this.length}px; height: ${this.waveHeight}px;\">\n ${visibleIndices.map((i) => {\n const chunkLeft = i * MAX_CANVAS_WIDTH;\n const chunkWidth = Math.min(this.length - chunkLeft, MAX_CANVAS_WIDTH);\n // Use data-index (not data-chunk-idx) to match daw-waveform pattern\n return html`<canvas\n data-index=${i}\n width=${chunkWidth * dpr}\n height=${this.waveHeight * dpr}\n style=\"left: ${chunkLeft}px; width: ${chunkWidth}px; height: ${this.waveHeight}px;\"\n ></canvas>`;\n })}\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-piano-roll': DawPianoRollElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\n\n@customElement('daw-playhead')\nexport class DawPlayheadElement extends LitElement {\n private _line: HTMLElement | null = null;\n\n static styles = css`\n :host {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n pointer-events: none;\n z-index: 10;\n }\n div {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 1px;\n background: var(--daw-playhead-color, #d08070);\n will-change: transform;\n }\n `;\n\n render() {\n return html`<div></div>`;\n }\n\n firstUpdated() {\n this._line = this.shadowRoot!.querySelector('div');\n }\n\n /** Position the playhead line at an absolute pixel offset on the timeline.\n * The editor's PlaybackAnimationController drives this each frame — the\n * playhead owns no animation loop or time math of its own. */\n setPosition(px: number) {\n if (this._line) {\n this._line.style.transform = `translate3d(${px}px, 0, 0)`;\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-playhead': DawPlayheadElement;\n }\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\n\n@customElement('daw-transport')\nexport class DawTransportElement extends LitElement {\n @property() for = '';\n\n get target(): HTMLElement | null {\n return this.for ? document.getElementById(this.for) : null;\n }\n\n // Light DOM — button children stay in consumer's DOM.\n // No render() needed; light DOM elements don't use <slot>.\n createRenderRoot() {\n return this;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-transport': DawTransportElement;\n }\n}\n","import { html } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\n\n@customElement('daw-play-button')\nexport class DawPlayButtonElement extends DawTransportButton {\n @state() private _isRecording = false;\n private _targetRef: HTMLElement | null = null;\n /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */\n private _targetListeners: AbortController | null = null;\n private _onRecStart = () => {\n this._isRecording = true;\n };\n private _onRecEnd = () => {\n this._isRecording = false;\n };\n\n connectedCallback() {\n super.connectedCallback();\n // Defer so <daw-transport for=\"...\"> and the target editor are resolved\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this._ensureTargetListeners();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._cleanupListeners();\n }\n\n protected override updated() {\n // Re-resolve on every render (pointerenter triggers one via the base\n // class) — a target that upgrades/appears after the one-shot\n // connectedCallback rAF (or a swapped <daw-transport for>) would\n // otherwise never get the recording-state listeners: Play stays enabled\n // during recording (#573, same fix as daw-record-button).\n this._ensureTargetListeners();\n }\n\n private _ensureTargetListeners() {\n const target = this.target;\n if (target === this._targetRef) return;\n if (this._targetRef) {\n // Swapping away from a live target: recording state observed there is\n // stale — a replaced editor (framework remount reusing the id) never\n // fires the complete/error event that would clear it, wedging the\n // button. (A reconnect of the BUTTON has a null _targetRef and keeps\n // its state — the same editor may still be recording.)\n this._isRecording = false;\n }\n this._cleanupListeners();\n if (!target) return;\n this._targetRef = target;\n this._targetListeners = new AbortController();\n const { signal } = this._targetListeners;\n target.addEventListener('daw-recording-start', this._onRecStart, { signal });\n target.addEventListener('daw-recording-complete', this._onRecEnd, { signal });\n target.addEventListener('daw-recording-error', this._onRecEnd, { signal });\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetListeners?.abort();\n this._targetListeners = null;\n this._targetRef = null;\n }\n }\n\n render() {\n return html`\n <button part=\"button\" ?disabled=${this._isRecording} @click=${this._onClick}>\n <slot>Play</slot>\n </button>\n `;\n }\n\n private _onClick() {\n const target = this.target;\n if (!target) {\n console.warn(\n '[dawcore] <daw-play-button> has no target. Check <daw-transport for=\"...\"> references a valid <daw-editor> id.'\n );\n return;\n }\n target.play();\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-play-button': DawPlayButtonElement;\n }\n}\n","import { LitElement, css } from 'lit';\nimport {\n resolveTransportTarget,\n targetSupports,\n targetUndetermined,\n warnNoTargetOnce,\n warnUnsupportedOnce,\n} from '../utils/transport-capability';\n\n/**\n * Base class for transport button elements.\n * Finds target via closest <daw-transport>. Capability detection is\n * duck-typed (#474): subclasses declare requiredTargetMethods and render\n * `?disabled=${!this.targetSupported}`; targets lacking the methods get a\n * disabled control and a one-time console warning on interaction.\n */\nexport class DawTransportButton extends LitElement {\n /** Methods the transport target must implement for this control to be\n * enabled. Empty = works with any target. */\n protected static requiredTargetMethods: readonly string[] = [];\n\n protected get target(): any {\n return resolveTransportTarget(this);\n }\n\n private get _requiredMethods(): readonly string[] {\n return (this.constructor as typeof DawTransportButton).requiredTargetMethods;\n }\n\n /**\n * False when this control declares requirements its target doesn't meet.\n * An undetermined target (missing, or a not-yet-upgraded custom element)\n * gets the benefit of the doubt and stays enabled — click-time resolution\n * warns if it's still unusable.\n */\n protected get targetSupported(): boolean {\n const required = this._requiredMethods;\n if (required.length === 0) return true;\n const target = this.target;\n if (targetUndetermined(target)) return true;\n return targetSupports(target, required);\n }\n\n /** The host's capability listeners, one controller per connection. */\n private _capabilityListeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._capabilityListeners?.abort();\n this._capabilityListeners = new AbortController();\n const { signal } = this._capabilityListeners;\n // Disabled inner buttons swallow clicks — listen on the host so an\n // unsupported control still explains itself on first interaction.\n this.addEventListener('pointerdown', this._onCapabilityPointerDown, { signal });\n // A target that became resolvable since the last render should\n // re-evaluate before the click lands.\n this.addEventListener('pointerenter', this._onCapabilityPointerEnter, { signal });\n // The transport `for` id resolves after connect (target may upgrade\n // later) — re-render once it's resolvable so disabled state is accurate.\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this.requestUpdate();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._capabilityListeners?.abort();\n this._capabilityListeners = null;\n }\n\n private _onCapabilityPointerEnter = () => {\n this.requestUpdate();\n };\n\n private _onCapabilityPointerDown = () => {\n const target = this.target;\n if (!target) {\n // A control with requirements stays enabled when the target is missing\n // (benefit of the doubt) — without this warn, a bad <daw-transport for>\n // id would be silent. Controls with no requirements warn in their own\n // click handlers instead.\n if (this._requiredMethods.length > 0) {\n warnNoTargetOnce(this);\n }\n return;\n }\n if (!this.targetSupported) {\n warnUnsupportedOnce(this, this._requiredMethods);\n }\n };\n\n static styles: import('lit').CSSResultGroup = css`\n button {\n cursor: pointer;\n background: var(--daw-controls-background, #1a1a2e);\n color: var(--daw-controls-text, #e0d4c8);\n border: 1px solid currentColor;\n padding: 4px 8px;\n font: inherit;\n }\n button:hover {\n opacity: 0.8;\n }\n button:disabled {\n opacity: 0.4;\n cursor: default;\n }\n `;\n}\n","import type { DawTransportElement } from '../elements/daw-transport';\n\n/**\n * Transport target resolution + duck-typed capability detection.\n *\n * Transport controls never instanceof-check their target — they probe for the\n * methods they need (`typeof target[m] === 'function'`). This is what lets the\n * same controls drive <daw-editor>, the future <daw-player> (#454), or any\n * conforming element, and lets editor-only controls render disabled against a\n * player (#474, spec \"Transport Compatibility\").\n */\n\n/**\n * Resolve the target of the closest <daw-transport for=\"...\"> ancestor.\n * Walks light-DOM ancestors only (`closest` does not cross shadow boundaries).\n */\nexport function resolveTransportTarget(el: Element): HTMLElement | null {\n const transport = el.closest('daw-transport') as DawTransportElement | null;\n return transport?.target ?? null;\n}\n\n/** True when target exists and every named method is a function on it. */\nexport function targetSupports(target: unknown, methods: readonly string[]): boolean {\n if (!target) return false;\n return methods.every((m) => typeof (target as Record<string, unknown>)[m] === 'function');\n}\n\n/**\n * True when the target cannot be judged yet: it is missing entirely, or it is\n * a custom element that has not upgraded (its methods don't exist until the\n * definition loads). Capability-gated controls give these the benefit of the\n * doubt and stay enabled — click-time resolution warns if still unusable —\n * instead of latching disabled before the app finishes booting.\n */\nexport function targetUndetermined(target: HTMLElement | null): boolean {\n if (!target) return true;\n const name = target.localName;\n return name.includes('-') && customElements.get(name) === undefined;\n}\n\nconst warned = new WeakMap<Element, Set<string>>();\n\n/**\n * One-time console warning for a transport control.\n * Dedup is per element per message — distinct messages on the same element\n * each warn once, while repeats of the same message stay silent. A\n * missing-target warn and an unsupported-target warn no longer suppress each\n * other.\n */\nexport function warnOnce(element: Element, message: string): void {\n let messages = warned.get(element);\n if (!messages) {\n messages = new Set();\n warned.set(element, messages);\n }\n if (messages.has(message)) return;\n messages.add(message);\n console.warn(message);\n}\n\n/**\n * One-time canonical warning for a control whose transport target is missing.\n * Every no-target site uses this single sentence so the message-keyed\n * {@link warnOnce} dedup collapses pointerdown-time and click-time warns into\n * one warning total. An optional suffix appends extra element-specific\n * context after the canonical text (still one message key per suffix).\n */\nexport function warnNoTargetOnce(element: Element, suffix?: string): void {\n warnOnce(\n element,\n `[dawcore] <${element.tagName.toLowerCase()}> has no target. Check ` +\n '<daw-transport for=\"...\"> references a valid element id.' +\n (suffix ?? '')\n );\n}\n\n/**\n * One-time console warning explaining why a control is disabled.\n * Delegates to {@link warnOnce} — an element that already triggered a\n * missing-target warn will not warn again here.\n */\nexport function warnUnsupportedOnce(element: Element, methods: readonly string[]): void {\n warnOnce(\n element,\n `[dawcore] <${element.tagName.toLowerCase()}> is disabled: its transport target ` +\n `does not implement ${methods.join(', ')}. See the transport compatibility ` +\n 'table in the docs for which controls work with which targets.'\n );\n}\n","import { html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\n\n@customElement('daw-pause-button')\nexport class DawPauseButtonElement extends DawTransportButton {\n @state() private _isPaused = false;\n @state() private _isRecording = false;\n private _targetRef: HTMLElement | null = null;\n /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */\n private _targetListeners: AbortController | null = null;\n private _onRecStart = () => {\n this._isRecording = true;\n };\n private _onRecEnd = () => {\n this._isRecording = false;\n this._isPaused = false;\n };\n private _onRecPause = () => {\n this._isPaused = true;\n };\n private _onRecResume = () => {\n this._isPaused = false;\n };\n\n static override styles = [\n DawTransportButton.styles,\n css`\n button[data-paused] {\n background: rgba(255, 255, 255, 0.1);\n border-color: var(--daw-controls-text, #e0d4c8);\n }\n `,\n ];\n\n connectedCallback() {\n super.connectedCallback();\n // Defer so <daw-transport for=\"...\"> and the target editor are resolved\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this._ensureTargetListeners();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._cleanupListeners();\n }\n\n protected override updated() {\n // Re-resolve on every render (pointerenter triggers one via the base\n // class) — a target that upgrades/appears after the one-shot\n // connectedCallback rAF (or a swapped <daw-transport for>) would\n // otherwise never get the recording-state listeners: mid-recording,\n // Pause would pause only the transport while the worklet keeps\n // capturing (#573, same fix as daw-record-button).\n this._ensureTargetListeners();\n }\n\n private _ensureTargetListeners() {\n const target = this.target;\n if (target === this._targetRef) return;\n if (this._targetRef) {\n // Swapping away from a live target: recording/pause state observed\n // there is stale — a replaced editor never fires the events that\n // would clear it, wedging the button into togglePauseRecording\n // routing. (A reconnect of the BUTTON has a null _targetRef and\n // keeps its state.)\n this._isRecording = false;\n this._isPaused = false;\n }\n this._cleanupListeners();\n if (!target) return;\n this._targetRef = target;\n this._targetListeners = new AbortController();\n const { signal } = this._targetListeners;\n target.addEventListener('daw-recording-start', this._onRecStart, { signal });\n target.addEventListener('daw-recording-complete', this._onRecEnd, { signal });\n target.addEventListener('daw-recording-error', this._onRecEnd, { signal });\n target.addEventListener('daw-recording-pause', this._onRecPause, { signal });\n target.addEventListener('daw-recording-resume', this._onRecResume, { signal });\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetListeners?.abort();\n this._targetListeners = null;\n this._targetRef = null;\n }\n }\n\n render() {\n return html`\n <button part=\"button\" ?data-paused=${this._isPaused} @click=${this._onClick}>\n <slot>Pause</slot>\n </button>\n `;\n }\n\n private _onClick() {\n const target = this.target;\n if (!target) {\n console.warn(\n '[dawcore] <daw-pause-button> has no target. Check <daw-transport for=\"...\"> references a valid <daw-editor> id.'\n );\n return;\n }\n\n if (this._isRecording) {\n // Delegate to editor — events keep visual state in sync via\n // daw-recording-pause / daw-recording-resume.\n target.togglePauseRecording();\n } else {\n target.pause();\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-pause-button': DawPauseButtonElement;\n }\n}\n","import { html } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\n\n@customElement('daw-stop-button')\nexport class DawStopButtonElement extends DawTransportButton {\n render() {\n return html`\n <button part=\"button\" @click=${this._onClick}>\n <slot>Stop</slot>\n </button>\n `;\n }\n\n private _onClick() {\n const target = this.target;\n if (!target) {\n console.warn(\n '[dawcore] <daw-stop-button> has no target. Check <daw-transport for=\"...\"> references a valid <daw-editor> id.'\n );\n return;\n }\n // When recording: await stopRecording (which awaits the worklet's\n // done ack) BEFORE calling editor.stop(). Calling stop() in parallel\n // disrupts the audio thread mid-handshake — engine.stop() can pause\n // worklet rendering, which prevents the done message from arriving.\n // ALWAYS run stop() afterward (even if stopRecording rejected), so the\n // engine cleans up; wrap stop() in try/catch since it's synchronous\n // void and can throw.\n if (target.isRecording) {\n target\n .stopRecording()\n .catch((err: unknown) => {\n console.warn('[dawcore] stopRecording failed: ' + String(err));\n })\n .then(() => {\n try {\n target.stop();\n } catch (err) {\n console.warn('[dawcore] stop after stopRecording failed: ' + String(err));\n }\n });\n } else {\n try {\n target.stop();\n } catch (err) {\n console.warn('[dawcore] stop failed: ' + String(err));\n }\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-stop-button': DawStopButtonElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport type {\n ArrangementTrack,\n AudioClip,\n ClipTrack,\n FadeType,\n TrackKind,\n LoadingClip,\n Peaks,\n PeakData,\n SnapTo,\n MeterEntry,\n SpectrogramConfig,\n ColorMapValue,\n} from '@waveform-playlist/core';\nimport type {\n StoredTrackDescriptor,\n TrackExtras,\n TrackRenderMode,\n TrackWithId,\n ClipDescriptor,\n DomClipDescriptor,\n DropClipDescriptor,\n TrackConfig,\n EditorCallOptions,\n ClipConfig,\n} from '../types';\nimport { isDomClip, normalizeRenderMode, trackDescriptorRenderMode } from '../types';\nimport {\n createMixerGesture,\n clipPixelWidth,\n isDecidedPanLaw,\n isLoadingClip,\n trackKind,\n} from '@waveform-playlist/core';\nimport { PeakPipeline } from '../workers/peakPipeline';\nimport type { DawTrackElement } from './daw-track';\nimport type { DawClipElement } from './daw-clip';\nimport type { DawPlayheadElement } from './daw-playhead';\nimport type { WaveformSegment } from './daw-waveform';\n// Register the visual child elements this editor's template always renders.\n// The shadow template emits <daw-playhead>/<daw-waveform>/<daw-ruler> directly,\n// so the editor must guarantee they're defined. Without these side-effect\n// imports, importing daw-editor alone (not the package barrel) leaves the\n// elements un-upgraded — querySelector returns generic HTMLElements, and calls\n// like playhead.setPosition() throw \"is not a function\". (Module caching +\n// @customElement make this safe to import here and from the index barrel.)\nimport './daw-playhead';\nimport './daw-waveform';\nimport './daw-ruler';\nimport { createArrangement, EditorEngine } from '@waveform-playlist/engine';\nimport type {\n Arrangement,\n EngineState,\n MixerChangeOptions,\n PlayoutAdapter,\n TrackMixerValues,\n} from '@waveform-playlist/engine';\nimport {\n DEFAULT_TRACK_MIX,\n clampNumber,\n declaredPanLaw,\n mixOfElement,\n mixOfTrack,\n} from '../utils/track-mix';\nimport '../elements/daw-track-controls';\nimport '../elements/daw-grid';\nimport { hostStyles, clipStyles } from '../styles/theme';\nimport { ViewportController } from '../controllers/viewport-controller';\nimport { AudioResumeController } from '../controllers/audio-resume-controller';\nimport { RecordingController } from '../controllers/recording-controller';\nimport type { RecordingOptions } from '../controllers/recording-controller';\nimport { AnnotationController, ANNOTATION_LANE_HEIGHT } from '../controllers/annotation-controller';\nimport type { DawAnnotationTrackElement } from './daw-annotation-track';\nimport { SpectrogramController } from '../controllers/spectrogram-controller';\nimport { PointerHandler } from '../interactions/pointer-handler';\nimport { ClipPointerHandler } from '../interactions/clip-pointer-handler';\nimport { AnnotationDragHandler } from '../interactions/annotation-drag';\nimport { TrackReorderHandler } from '../interactions/track-reorder-handler';\nimport type {\n DawSelectionDetail,\n DawTrackIdDetail,\n DawTrackControlDetail,\n DawTrackUpdateDetail,\n DawTrackErrorDetail,\n DawTrackReorderDetail,\n DawTrackReorderGrabDetail,\n DawClipErrorDetail,\n DawClipIdDetail,\n DawRecordingErrorDetail,\n DawErrorDetail,\n DawTimeFormatChangeDetail,\n LoadFilesResult,\n} from '../events';\nimport {\n isTimeDisplayFormat,\n TIME_DISPLAY_FORMATS,\n type TimeDisplayFormat,\n} from '../utils/time-display-format';\nimport { loadFiles as loadFilesImpl } from '../interactions/file-loader';\nimport {\n loadMidiImpl,\n type MidiLoaderHost,\n type MidiLoadOptions,\n type MidiLoadResult,\n} from '../interactions/midi-loader';\nimport { addRecordedClip } from '../interactions/recording-clip';\nimport { splitAtPlayhead as performSplitAtPlayhead } from '../interactions/split-handler';\nimport { syncPeaksForChangedClips } from '../interactions/clip-peak-sync';\nimport {\n buildArrangementTrack,\n buildLoadingClip,\n buildMidiClip,\n clipKindError,\n clipSourceOf,\n entryIndex,\n isMidiDescriptor,\n validMidiNotes,\n} from '../interactions/track-entry';\nimport { LoadAnnouncer } from '../interactions/load-announcer';\nimport { clipSeconds, loadedTrack, mixOf } from '../interactions/arrangement-view';\nimport { normalizeHandedIn, swapArrangement } from '../interactions/arrangement-swap';\nimport { clipDragChanged, trackDragChanged } from '../interactions/drag-watch';\nimport { moveClipToTrack, trackHoldingClip } from '../interactions/clip-rehome';\nimport { abortError, isAbortError, PlaySignals, reasonOf } from '../interactions/abort';\nimport {\n refreshLinkStates,\n detachedWarning,\n type ClipLinkValues,\n type LinkState,\n type TrackLinkValues,\n} from '../interactions/element-links';\nimport { EffectsManager } from '../effects/effects-manager';\nimport { exportAudioImpl } from '../interactions/export-audio';\nimport type { ExportOptions } from '../interactions/export-audio';\nimport type { EffectState, SerializedEffectEntry } from '../effects/types';\nimport { loadWaveformDataFromUrl } from '../interactions/peaks-loader';\nimport { extractPeaks } from '../workers/waveformDataUtils';\nimport { ScrollSyncController } from '../controllers/scroll-sync-controller';\nimport { PlaybackAnimationController } from '../controllers/playback-animation-controller';\nimport { installCommand } from '../utils/install-command';\n\n/** Height of the ruler band — single source for the ruler element and the header row. */\nconst RULER_HEIGHT = 30;\n\n/**\n * A track registered and not in the arrangement yet (#848): a `<daw-track>`\n * (read when it enters, with clips `addClip()` gave it meanwhile), or a\n * declaration with no element (`addTrack()`, a dropped file) and its mix.\n */\ntype PendingEntry =\n | { element: DawTrackElement; extraClips: DropClipDescriptor[] }\n | { descriptor: StoredTrackDescriptor; mix: TrackMixerValues };\n\n/** The values a clip change is computed from: the live values with the request applied (#848). */\ntype ClipUpdateValues = ClipLinkValues & { src: string };\n\n/** What a row of the template reads about its track (#848: from the arrangement and the extras). */\ninterface RowInfo {\n name: string;\n kind: TrackKind;\n renderMode: TrackRenderMode;\n}\n\n/** The descriptor of a clip from `addTrack()` / `addClip()` config: no element, a new id. */\nfunction clipDescriptorOf(config: ClipConfig): DropClipDescriptor & { clipId: string } {\n return {\n kind: 'drop',\n clipId: crypto.randomUUID(),\n src: config.src ?? '',\n peaksSrc: config.peaksSrc ?? '',\n start: config.start ?? 0,\n duration: config.duration ?? 0,\n offset: config.offset ?? 0,\n gain: config.gain ?? 1,\n name: config.name ?? '',\n fadeIn: config.fadeIn ?? 0,\n fadeOut: config.fadeOut ?? 0,\n fadeType: config.fadeType ?? 'linear',\n midiNotes: config.midiNotes ?? null,\n midiChannel: config.midiChannel ?? null,\n midiProgram: config.midiProgram ?? null,\n };\n}\n\n/** The extras of a track entering with this declaration: every clip it takes, with its `peaks-src`. */\nfunction extrasOf(descriptor: StoredTrackDescriptor): TrackExtras {\n return {\n kind: descriptor.kind,\n renderMode: descriptor.renderMode,\n spectrogramConfig: descriptor.spectrogramConfig,\n src: descriptor.src,\n peaksSrc: new Map(\n descriptor.clips.flatMap((c) => (c.clipId ? [[c.clipId, c.peaksSrc] as const] : []))\n ),\n };\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst noAdapterError = (): string =>\n 'No PlayoutAdapter set on <daw-editor>. ' +\n 'Set editor.adapter before use.\\n\\n' +\n ' // Option 1: Native Web Audio (no Tone.js)\\n' +\n ' ' +\n installCommand('@dawcore/transport') +\n '\\n' +\n \" import { NativePlayoutAdapter } from '@dawcore/transport';\\n\" +\n ' editor.adapter = new NativePlayoutAdapter(new AudioContext());\\n\\n' +\n ' // Option 2: Tone.js (effects, MIDI synths)\\n' +\n ' ' +\n installCommand('@waveform-playlist/playout') +\n '\\n' +\n \" import { createToneAdapter } from '@waveform-playlist/playout';\\n\" +\n ' editor.adapter = createToneAdapter();';\n\n/** The outcome of `_settleEntry` for a track that entered. */\nconst ENTERED: unique symbol = Symbol('entered');\n\n@customElement('daw-editor')\nexport class DawEditorElement extends LitElement implements MidiLoaderHost {\n @property({ type: Number, attribute: 'samples-per-pixel', noAccessor: true })\n get samplesPerPixel(): number {\n return this._samplesPerPixel;\n }\n set samplesPerPixel(value: number) {\n const old = this._samplesPerPixel;\n if (!Number.isFinite(value) || value <= 0) return;\n const clamped =\n this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel\n ? this._minSamplesPerPixel\n : value;\n if (clamped !== value) {\n console.warn(\n '[dawcore] Zoom ' +\n value +\n ' spp clamped to the peak floor (' +\n this._minSamplesPerPixel +\n ' spp) — peaks for the loaded audio (worker-generated or pre-computed) ' +\n 'can only render at or above that scale'\n );\n }\n this._samplesPerPixel = clamped;\n this.requestUpdate('samplesPerPixel', old);\n }\n private _samplesPerPixel = 1024;\n\n /** Raise the zoom floor and re-clamp the LIVE samplesPerPixel when it's\n * now below the floor. Peaks can only be extracted at >= the floor scale —\n * the setter alone clamps only FUTURE sets, so without the re-clamp an\n * already-finer spp keeps sizing clip containers while the waveforms\n * render at the coarser scale: half/quarter width, misaligned against the\n * ruler and playhead. */\n _raiseZoomFloor(scale: number): void {\n if (!Number.isFinite(scale) || scale <= 0) return;\n if (scale > this._minSamplesPerPixel) {\n this._minSamplesPerPixel = scale;\n }\n if (this._samplesPerPixel < this._minSamplesPerPixel) {\n this.samplesPerPixel = this._minSamplesPerPixel; // setter warns + requestUpdate\n }\n }\n\n /** Recompute the floor from the surviving cached scales (track removal /\n * load cancellation / preview cleanup). Usually LOWERS the floor, freeing\n * finer zoom — but a buffer whose scale never raised the floor (or a mix\n * of scales) can raise it above the live spp, so re-clamp like\n * _raiseZoomFloor. Never mutate _minSamplesPerPixel directly. */\n private _recomputeZoomFloor(): void {\n this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);\n if (this._minSamplesPerPixel > 0 && this._samplesPerPixel < this._minSamplesPerPixel) {\n this.samplesPerPixel = this._minSamplesPerPixel;\n }\n }\n\n private _timeFormat: TimeDisplayFormat = 'hh:mm:ss.sss';\n\n /**\n * Time display format used by <daw-time-display> and (future, #463) the\n * selection inputs. Lives on the editor — the target element owns the\n * state, the transport controls reflect it (native-form style).\n */\n @property({ attribute: 'time-format', reflect: true, noAccessor: true })\n get timeFormat(): TimeDisplayFormat {\n return this._timeFormat;\n }\n set timeFormat(value: TimeDisplayFormat) {\n if (!isTimeDisplayFormat(value)) {\n console.warn(\n '[dawcore] timeFormat: invalid format \"' +\n String(value) +\n '\" ignored. Valid formats: ' +\n TIME_DISPLAY_FORMATS.join(', ')\n );\n // Self-heal the DOM: a rejected attribute value would otherwise stick\n // (reflection never runs for a rejected set), leaving attribute and\n // property permanently divergent.\n if (\n this.hasAttribute('time-format') &&\n this.getAttribute('time-format') !== this._timeFormat\n ) {\n this.setAttribute('time-format', this._timeFormat);\n }\n return;\n }\n if (value === this._timeFormat) return;\n const old = this._timeFormat;\n this._timeFormat = value;\n this.requestUpdate('timeFormat', old);\n this.dispatchEvent(\n new CustomEvent<DawTimeFormatChangeDetail>('daw-time-format-change', {\n bubbles: true,\n composed: true,\n detail: { format: value },\n })\n );\n }\n\n /** Set the time display format. Sugar over the `timeFormat` property. */\n setTimeFormat(format: TimeDisplayFormat): void {\n this.timeFormat = format;\n }\n\n @property({ type: Number, attribute: 'wave-height' }) waveHeight = 128;\n @property({ type: Boolean }) timescale = false;\n @property({ type: Boolean }) mono = false;\n @property({ type: Number, attribute: 'bar-width' }) barWidth = 1;\n @property({ type: Number, attribute: 'bar-gap' }) barGap = 0;\n @property({ type: Boolean, attribute: 'rounded-bars' }) roundedBars = false;\n @property({ type: Boolean, attribute: 'file-drop' }) fileDrop = false;\n @property({ type: Boolean, attribute: 'clip-headers' }) clipHeaders = false;\n /** Scale each clip's drawn waveform by its `gain` (clamped to the channel\n * height), so levelled clips look the way they sound. Off by default:\n * waveforms show source level. Draw-time only — no peak regeneration. */\n @property({ type: Boolean, attribute: 'gain-scaled-waveforms' }) gainScaledWaveforms = false;\n @property({ type: Number, attribute: 'clip-header-height' }) clipHeaderHeight = 20;\n @property({ type: Boolean, attribute: 'interactive-clips' }) interactiveClips = false;\n /**\n * Disable the end-of-timeline auto-stop — the transport rolls until an\n * explicit stop/pause (DAW style). Implies the fill-viewport layout.\n * Recording sessions suppress the auto-stop automatically, so recording\n * UIs usually want `fill-viewport` instead. Parity with the React\n * provider's `indefinitePlayback` prop.\n */\n @property({ type: Boolean, attribute: 'indefinite-playback' }) indefinitePlayback = false;\n /**\n * When true, the timeline fills the visible viewport even if total clip\n * duration is less (layout only — playback still auto-stops at the end).\n * Lets the ruler render before any audio is loaded — useful for empty\n * editors and recording UIs. In beats mode the 32-bar floor already\n * provides this; this attribute controls the temporal mode. Parity with\n * the React provider's `fillViewport` prop.\n */\n @property({ type: Boolean, attribute: 'fill-viewport' }) fillViewport = false;\n /**\n * Enable vertical track reordering UI: grip + move up/down buttons on each\n * track's controls. Reordering is purely organizational.\n */\n @property({ type: Boolean, attribute: 'track-reordering' }) trackReordering = false;\n /**\n * Default spectrogram FFT/render config inherited by tracks with\n * `render-mode=\"spectrogram\"` that do not set their own. Wired into the\n * orchestrator by `SpectrogramController` in Task 14.\n */\n @property({ attribute: false, noAccessor: true })\n get spectrogramConfig(): SpectrogramConfig | null {\n return this._spectrogramConfig;\n }\n set spectrogramConfig(value: SpectrogramConfig | null) {\n const old = this._spectrogramConfig;\n this._spectrogramConfig = value;\n this._spectrogramController?.setEditorConfig(value);\n this.requestUpdate('spectrogramConfig', old);\n }\n private _spectrogramConfig: SpectrogramConfig | null = null;\n\n /**\n * Default color map for spectrogram tracks. Tracks may override via\n * their own per-track property in a future iteration. Separate from\n * `spectrogramConfig` because `ColorMapValue` is not part of the\n * `SpectrogramConfig` shape.\n */\n @property({ attribute: false, noAccessor: true })\n get spectrogramColorMap(): ColorMapValue | null {\n return this._spectrogramColorMap;\n }\n set spectrogramColorMap(value: ColorMapValue | null) {\n const old = this._spectrogramColorMap;\n this._spectrogramColorMap = value;\n this._spectrogramController?.setEditorColorMap(value);\n this.requestUpdate('spectrogramColorMap', old);\n }\n private _spectrogramColorMap: ColorMapValue | null = null;\n\n private _ensureSpectrogramController(): SpectrogramController {\n if (!this._spectrogramController) {\n this._spectrogramController = new SpectrogramController(\n this,\n () =>\n new Worker(new URL('@dawcore/spectrogram/worker/spectrogram.worker', import.meta.url), {\n type: 'module',\n })\n );\n if (this._spectrogramConfig) {\n this._spectrogramController.setEditorConfig(this._spectrogramConfig);\n }\n if (this._spectrogramColorMap) {\n this._spectrogramController.setEditorColorMap(this._spectrogramColorMap);\n }\n }\n return this._spectrogramController;\n }\n\n /** Called by <daw-spectrogram> after transferControlToOffscreen. */\n _spectrogramRegisterCanvas(reg: {\n canvasId: string;\n canvas: OffscreenCanvas;\n clipId: string;\n trackId: string;\n channelIndex: number;\n chunkIndex: number;\n globalPixelOffset: number;\n widthPx: number;\n heightPx: number;\n }): void {\n this._ensureSpectrogramController().registerCanvas(reg);\n }\n\n /** Called by <daw-spectrogram> on chunk unmount / element disconnect. */\n _spectrogramUnregisterCanvas(canvasId: string): void {\n this._spectrogramController?.unregisterCanvas(canvasId);\n }\n\n /**\n * Forward a clip's AudioBuffer to the spectrogram controller if the parent\n * track is in spectrogram render-mode. Eagerly creates the controller via\n * `_ensureSpectrogramController` so the audio data is queued for the first\n * render — even if no canvases have been registered yet.\n */\n private _maybeRegisterSpectrogramClipAudio(trackId: string, clip: AudioClip): void {\n if (this._renderModeOf(trackId) !== 'spectrogram') return;\n // Read the buffer off the clip itself — `_clipBuffers` is mutated in-place\n // by `cleanupOrphanedClipData` during concurrent track loading and may\n // briefly miss this clip even though the clip object still holds the\n // buffer reference.\n const buffer = clip.audioBuffer ?? this._clipBuffers.get(clip.id);\n if (!buffer) return;\n const channelData: Float32Array[] = [];\n for (let i = 0; i < buffer.numberOfChannels; i++) {\n channelData.push(buffer.getChannelData(i));\n }\n this._ensureSpectrogramController().registerClipAudio({\n clipId: clip.id,\n trackId,\n channelData,\n sampleRate: buffer.sampleRate,\n durationSamples: clip.durationSamples,\n offsetSamples: clip.offsetSamples,\n });\n }\n @property({ type: String, attribute: 'scale-mode' })\n scaleMode: 'temporal' | 'beats' = 'temporal';\n @property({ type: Number, attribute: 'ticks-per-pixel', noAccessor: true })\n get ticksPerPixel(): number {\n return this._ticksPerPixel;\n }\n set ticksPerPixel(value: number) {\n const old = this._ticksPerPixel;\n if (!Number.isFinite(value) || value <= 0) return;\n this._ticksPerPixel = value;\n this.requestUpdate('ticksPerPixel', old);\n }\n private _ticksPerPixel = 24;\n @property({ type: Number, noAccessor: true })\n get bpm(): number {\n return this._bpm;\n }\n set bpm(value: number) {\n const old = this._bpm;\n if (!Number.isFinite(value) || value <= 0) return;\n this._bpm = value;\n // Forward to engine (which forwards to adapter's Transport) — unless the\n // consumer provided tick callbacks, in which case the external tempo map\n // is authoritative and bpm is display/grid-only (#407).\n if (this._engine && !this._hasTickCallbacks) {\n this._engine.setTempo(value);\n }\n this.requestUpdate('bpm', old);\n }\n private _bpm = 120;\n @property({ attribute: false })\n timeSignature: [number, number] = [4, 4];\n @property({ attribute: false })\n meterEntries?: MeterEntry[];\n /** MeterEntries for grid/ruler: explicit meterEntries if set, otherwise derived from timeSignature. */\n get _meterEntries(): MeterEntry[] {\n if (this.meterEntries && this.meterEntries.length > 0) return this.meterEntries;\n return [{ tick: 0, numerator: this.timeSignature[0], denominator: this.timeSignature[1] }];\n }\n @property({ type: Number, noAccessor: true })\n get ppqn(): number {\n return this._ppqn;\n }\n set ppqn(value: number) {\n const old = this._ppqn;\n if (!Number.isFinite(value) || value <= 0) return;\n this._ppqn = value;\n this.requestUpdate('ppqn', old);\n }\n private _ppqn = 960;\n @property({ type: String, attribute: 'snap-to' })\n snapTo: SnapTo = 'off';\n /** Optional tempo-aware conversion: seconds → PPQN ticks. When provided\n * together with ticksToSeconds, enables variable tempo AND makes `bpm`\n * display/grid-only (no engine/adapter tempo forwarding — #407). */\n @property({ attribute: false })\n secondsToTicks?: (seconds: number) => number;\n /** Optional tempo-aware conversion: PPQN ticks → seconds. Required alongside\n * secondsToTicks — see that property for the variable-tempo and bpm\n * display-only semantics enabled when both are set (#407). */\n @property({ attribute: false })\n ticksToSeconds?: (ticks: number) => number;\n /** True when the consumer provided BOTH tick conversion callbacks — the\n * external tempo map is authoritative and `bpm` is display/grid-only (#407). */\n get _hasTickCallbacks(): boolean {\n return !!(this.secondsToTicks && this.ticksToSeconds);\n }\n /**\n * Sample rate: the adapter's AudioContext rate. Without an adapter (after a\n * disconnect let it go), the rate of the loaded clips the arrangement holds,\n * else 48000. Decoded audio is at the context's rate, so the two agree.\n */\n get sampleRate(): number {\n return this._externalAdapter?.audioContext.sampleRate ?? this._loadedClipSampleRate() ?? 48000;\n }\n private _loadedClipSampleRate(): number | null {\n for (const track of this._arrangement.getTracks()) {\n for (const clip of track.clips) {\n if ('sampleRate' in clip && typeof clip.sampleRate === 'number') return clip.sampleRate;\n }\n }\n return null;\n }\n /**\n * The editor's own arrangement (#848): the one owner of the tracks, the\n * clips, the mix, the undo history and loading of what the `<daw-track>`\n * children declare. Made with the editor, kept across a disconnect.\n */\n readonly _ownArrangement: Arrangement = createArrangement();\n /** An arrangement the app handed in (`editor.arrangement`), played alone; null: the own one. */\n _handedIn: Arrangement | null = null;\n /** The arrangement played now: a handed-in one, else the editor's own. */\n get _arrangement(): Arrangement {\n return this._handedIn ?? this._ownArrangement;\n }\n /**\n * The arrangement the editor plays (#848 PR 3): one handed in by the app,\n * or else the editor's own, whose content the `<daw-track>` children\n * declare. Setting one plays it alone, like `video.srcObject`: the\n * children are not added to it and show `:state(detached)` while it is\n * set; `null` (or the editor's own) goes back to the own arrangement with\n * what it held. A swap keeps the adapter: playback stops, a new engine is\n * built on the new arrangement. Refused (with a warning) during a take.\n * The editor never disposes or clears an arrangement it was handed.\n * Throws a `TypeError` for a value that is not an arrangement.\n */\n get arrangement(): Arrangement {\n return this._arrangement;\n }\n set arrangement(value: Arrangement | null) {\n swapArrangement(this, normalizeHandedIn(value, this._ownArrangement));\n }\n /** Sends the load events, read from the arrangement played (#848; a new one per swap). */\n private _announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));\n /** Stops following the arrangement played (its sources and its tracks). */\n private _unfollow: () => void = () => {};\n constructor() {\n super();\n this._follow(this._ownArrangement);\n }\n /**\n * Follow the arrangement played: a source that fails changes no track,\n * only `sources` tells of it (the events, the failed look); the elements'\n * link states follow its tracks (a structural change only, not every\n * mixer frame).\n */\n private _follow(arrangement: Arrangement): void {\n this._unfollow();\n const stopSources = arrangement.sources.subscribe(() => {\n this._announceLoading();\n this.requestUpdate();\n });\n let tracksVersion = arrangement.tracksVersion;\n const stopTracks = arrangement.subscribe(() => {\n this._watchDrags();\n if (arrangement.tracksVersion === tracksVersion) return;\n tracksVersion = arrangement.tracksVersion;\n this._refreshLinkStates();\n });\n this._unfollow = () => {\n stopSources();\n stopTracks();\n };\n }\n /**\n * A change to the arrangement while a drag is in progress came from\n * elsewhere (a drag writes nothing until its release): cancel the drag\n * when it changed what is dragged (#848 P2, interactions/drag-watch.ts).\n */\n private _watchDrags(): void {\n const clip = this._clipPointer.draggedClip;\n if (clip && clipDragChanged(this._arrangement, clip)) this._pointer.cancelClipDrag();\n const track = this._trackReorderDrag.draggedTrack;\n if (track && trackDragChanged(this._arrangement, track)) this._trackReorderDrag.cancel();\n }\n // --- The swap (interactions/arrangement-swap.ts) ---\n /** @internal */\n _releaseEngine(): void {\n if (!this._engine) return;\n try {\n this._engine.dispose({ keepAdapter: true });\n } catch (err) {\n console.warn('[dawcore] Error releasing the engine: ' + String(err));\n }\n this._engine = null;\n }\n /** @internal */\n _disposeTrackChain(trackId: string): void {\n this._effectsManager?.disposeTrackChain(trackId);\n }\n /** @internal */\n _playArrangement(next: Arrangement | null): void {\n // The waits on the arrangement played until now end (D2): an addClip()\n // rejects, a loadFiles() wait ends as loaded, a peaks fetch is aborted.\n this._playSignals.swappedOut(\n this._arrangement,\n abortError('the arrangement was swapped out (editor.arrangement) before it finished')\n );\n this._handedIn = next;\n // A new load cycle: every track of the arrangement now played is announced.\n this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));\n this._follow(this._arrangement);\n this._currentTime = 0;\n this._stopPlayhead();\n this._recomputeDuration();\n this._refreshLinkStates();\n this._announceLoading();\n this.requestUpdate();\n }\n /** @internal */\n _buildEngineIfReady(): void {\n if (this._externalAdapter && this.isConnected && !this._engine) this._buildEngineReporting();\n }\n /**\n * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and\n * not yet in the arrangement: they enter at the next flush, once there is\n * an engine (#848).\n */\n private _entryQueue: string[] = [];\n private _entryFlushScheduled = false;\n /**\n * Clips an `addClip()` is waiting for, with their track and the way to\n * reject the call: a removal of the clip or of its track before the clip\n * loads settles it here, without a public event (#917).\n */\n private _awaitedClips = new Map<string, { trackId: string; reject: (error: unknown) => void }>();\n /** Reject the `addClip()` calls waiting for clips that match `which`. */\n private _rejectAwaitedClips(\n which: (clipId: string, trackId: string) => boolean,\n message: string\n ): void {\n for (const [clipId, awaited] of [...this._awaitedClips]) {\n if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));\n }\n }\n /** `.dat` peaks drawn for a clip still loading, by clip id (an editor-only render cache). */\n @state() _previewPeaks: Map<string, PeakData> = new Map();\n /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */\n private _previewWaveforms = new Map<string, import('waveform-data').default>();\n /**\n * Tracks registered and not in the arrangement yet, with their declaration\n * (#848): a `<daw-track>` is read when it enters (its clips and attributes\n * as they are then); a dropped file carries its descriptor. The one place a\n * track's state lives until it enters.\n */\n _pending: Map<string, PendingEntry> = new Map();\n /** What the arrangement has no field for, by track id (#848; render mode, `peaks-src`). */\n @state() _extras: Map<string, TrackExtras> = new Map();\n @state() _peaksData: Map<string, PeakData> = new Map();\n @state() _isPlaying = false;\n @state() _duration = 0;\n @state() _selectedTrackId: string | null = null;\n @state() _dragOver = false;\n // Not @state — updated directly to avoid 60fps Lit re-renders\n _selectionStartTime = 0;\n _selectionEndTime = 0;\n _currentTime = 0;\n // Bounded-playback watermark for the current play(start, end) call\n // (selection/annotation playback). Adapters with the engine's\n // onPlaybackEnded hook (Tone, and native since #636) report their\n // endTime self-stop through the engine's `stop` event; this watermark is\n // the fallback check in the _startPlayhead loop for adapters without the\n // hook, same pattern as the whole-track _duration check.\n _activePlayEndTime: number | null = null;\n @property({ attribute: false })\n set adapter(value: PlayoutAdapter | null) {\n if (value && value.audioContext.state === 'closed') {\n console.warn('[dawcore] Adapter AudioContext is already closed. Ignoring.');\n return;\n }\n if (this._engine) {\n console.warn(\n '[dawcore] adapter set after engine is built. ' +\n 'The engine will continue using the previous adapter.'\n );\n }\n if (this._effectsManager) {\n // Chains are wired into the previous adapter's transport/graph and\n // cannot be migrated. Sever them there BEFORE the swap so the old\n // graph is left clean; consumers re-add effects on the new adapter.\n console.warn(\n '[dawcore] adapter replaced — existing effect chains were disposed. ' +\n 'Re-add effects on the new adapter.'\n );\n this._effectsManager.disposeAll();\n this._effectsManager = null;\n }\n this._externalAdapter = value;\n // The engine is built as soon as the editor is connected with an adapter (#848).\n if (value && this.isConnected && !this._engine) this._buildEngineReporting();\n }\n get adapter(): PlayoutAdapter | null {\n return this._externalAdapter;\n }\n private _externalAdapter: PlayoutAdapter | null = null;\n\n // --- Effects (master chain; per-track chains delegated from <daw-track>) ---\n\n private _effectsManager: EffectsManager | null = null;\n\n private get _effects(): EffectsManager {\n if (!this._effectsManager) {\n this._effectsManager = new EffectsManager(() => this._externalAdapter, this);\n }\n return this._effectsManager;\n }\n\n /**\n * Run a registered effect type's async `prepare` hook (e.g. an\n * `audioWorklet.addModule`) on this editor's audio context. Await it before\n * the synchronous `addEffect`/`addTrackEffect` for effect types that define\n * one; `setEffectsState()` and `exportAudio()` run it themselves. Idempotent\n * per context, and a no-op for types without a hook.\n */\n prepareEffect(type: string): Promise<void> {\n return this._effects.prepareEffect(type);\n }\n\n /** Master effects chain — inserted between the master bus and the destination. */\n addEffect(type: string, params?: Record<string, number>): string {\n return this._effects.addMasterEffect(type, params);\n }\n\n removeEffect(effectId: string): void {\n this._effects.masterOp('remove', effectId);\n }\n\n setEffectParams(effectId: string, params: Record<string, number>): void {\n this._effects.masterOp('setParams', effectId, params);\n }\n\n setEffectBypassed(effectId: string, bypassed: boolean): void {\n this._effects.masterOp('setBypassed', effectId, bypassed);\n }\n\n moveEffect(effectId: string, newIndex: number): void {\n this._effects.masterOp('move', effectId, newIndex);\n }\n\n get effects(): EffectState[] {\n return this._effectsManager?.masterEffects() ?? [];\n }\n\n /** Load a WAM plugin (via the optional @dawcore/wam peer) into the master chain. */\n addWamPlugin(url: string, initialState?: unknown): Promise<string> {\n return this._effects.addMasterWamPlugin(url, initialState);\n }\n\n /**\n * Compile Faust DSP source in the browser (via the optional @dawcore/faust\n * peer) and add the resulting WAM to the master chain. Compile errors keep\n * their Faust line/column diagnostics and leave the chain untouched.\n */\n addFaustEffect(dspCode: string, options?: { name?: string }): Promise<string> {\n return this._effects.addMasterFaustEffect(dspCode, options);\n }\n\n /**\n * Open (lazily creating) the GUI for a master-chain effect into a\n * consumer-provided container. WAM plugins mount their own GUI; plugins\n * without one — and native effects — get the generic parameter panel from\n * @dawcore/wam. The element is cached: closeEffectGui hides it without\n * interrupting audio, reopening remounts the same element.\n */\n openEffectGui(effectId: string, container: HTMLElement): Promise<HTMLElement> {\n return this._effects.openMasterEffectGui(effectId, container);\n }\n\n /** Hide a master-chain effect's GUI (cached for reopen — never destroys). */\n closeEffectGui(effectId: string): void {\n this._effects.closeEffectGui(effectId);\n }\n\n /** Snapshot the master chain in its persisted form (see dawcore README). */\n getEffectsState(): Promise<SerializedEffectEntry[]> {\n return this._effectsManager?.getMasterEffectsState() ?? Promise.resolve([]);\n }\n\n /** Replace the master chain with a persisted snapshot. */\n setEffectsState(entries: SerializedEffectEntry[]): Promise<void> {\n return this._effects.setMasterEffectsState(entries);\n }\n\n /**\n * Render the session offline through all effect chains (per-track +\n * master), including WAM plugins (re-instantiated on the offline context\n * with their live state). Returns the rendered AudioBuffer.\n */\n exportAudio(options?: ExportOptions): Promise<AudioBuffer> {\n return exportAudioImpl(\n {\n effectiveSampleRate: this.effectiveSampleRate,\n duration: this._duration,\n tracks: this._loadedTracks(),\n masterVolume: this._engine?.getState().masterVolume ?? 1,\n getMasterEffectsState: () => this.getEffectsState(),\n getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId),\n },\n options\n );\n }\n\n // --- Per-track effects API (public, keyed by trackId) ---\n // Mirrors the master-chain methods above and the <daw-track> element methods,\n // but addresses a track by id so element-less tracks (drag-dropped, or\n // programmatic tracks the consumer doesn't hold an element for) can carry\n // their own insert chain. Effect events dispatch from the track's <daw-track>\n // element when one exists, else from the editor (see _trackEventTarget).\n\n /** Add a native registry effect to a track's chain. */\n addTrackEffect(trackId: string, type: string, params?: Record<string, number>): string {\n return this._effects.addTrackEffect(trackId, this._trackEventTarget(trackId), type, params);\n }\n\n /** Snapshot of a track's effect chain (empty array for an unknown track). */\n trackEffects(trackId: string): EffectState[] {\n return this._effectsManager?.trackEffects(trackId) ?? [];\n }\n\n removeTrackEffect(trackId: string, effectId: string): void {\n this._effects.trackOp(trackId, this._trackEventTarget(trackId), 'remove', effectId);\n }\n\n setTrackEffectParams(trackId: string, effectId: string, params: Record<string, number>): void {\n this._effects.trackOp(trackId, this._trackEventTarget(trackId), 'setParams', effectId, params);\n }\n\n setTrackEffectBypassed(trackId: string, effectId: string, bypassed: boolean): void {\n this._effects.trackOp(\n trackId,\n this._trackEventTarget(trackId),\n 'setBypassed',\n effectId,\n bypassed\n );\n }\n\n moveTrackEffect(trackId: string, effectId: string, newIndex: number): void {\n this._effects.trackOp(trackId, this._trackEventTarget(trackId), 'move', effectId, newIndex);\n }\n\n /** Load a WAM plugin (via the optional @dawcore/wam peer) into a track's chain. */\n addTrackWamPlugin(trackId: string, url: string, initialState?: unknown): Promise<string> {\n return this._effects.addTrackWamPlugin(\n trackId,\n this._trackEventTarget(trackId),\n url,\n initialState\n );\n }\n\n /** Compile Faust DSP (via the optional @dawcore/faust peer) into a track's chain. */\n addTrackFaustEffect(\n trackId: string,\n dspCode: string,\n options?: { name?: string }\n ): Promise<string> {\n return this._effects.addTrackFaustEffect(\n trackId,\n this._trackEventTarget(trackId),\n dspCode,\n options\n );\n }\n\n /** Open (lazily creating) the GUI for a track-chain effect into a container. */\n openTrackEffectGui(\n trackId: string,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement> {\n return this._effects.openTrackEffectGui(\n trackId,\n this._trackEventTarget(trackId),\n effectId,\n container\n );\n }\n\n /** Hide a track-chain effect's GUI (cached for reopen — never destroys). */\n closeTrackEffectGui(_trackId: string, effectId: string): void {\n this._effects.closeEffectGui(effectId);\n }\n\n /** Snapshot a track's chain in its persisted form (see dawcore README). */\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]> {\n return this._effectsManager?.getTrackEffectsState(trackId) ?? Promise.resolve([]);\n }\n\n /** Replace a track's chain from a persisted snapshot. */\n setTrackEffectsState(trackId: string, entries: SerializedEffectEntry[]): Promise<void> {\n return this._effects.setTrackEffectsState(trackId, this._trackEventTarget(trackId), entries);\n }\n\n /**\n * Event-dispatch source for a per-track effect op: the track's `<daw-track>`\n * element when one exists (so `daw-effect-*` bubble from it exactly as the\n * element-method path does), else the editor itself for element-less tracks\n * (drag-dropped / programmatic). Reads the `_trackElements` index the editor\n * already maintains across the track connect/remove lifecycle — O(1), and the\n * same resolution `removeTrack` uses — rather than re-querying the DOM per op.\n */\n private _trackEventTarget(trackId: string): EventTarget {\n return this._trackElements.get(trackId) ?? this;\n }\n\n get audioContext(): AudioContext {\n if (!this._externalAdapter) {\n throw new Error(noAdapterError());\n }\n return this._externalAdapter.audioContext;\n }\n _engine: EditorEngine | null = null;\n private _warnedMissingTicksToSeconds = false;\n private _warnedMissingSecondsToTicks = false;\n private _peaksCache = new Map<string, Promise<import('waveform-data').default>>();\n _clipBuffers = new Map<string, AudioBuffer>();\n _clipOffsets = new Map<string, { offsetSamples: number; durationSamples: number }>();\n _peakPipeline = new PeakPipeline();\n /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */\n private _minSamplesPerPixel = 0;\n private _trackElements = new Map<string, DawTrackElement>();\n private _childObserver: MutationObserver | null = null;\n private _audioResume = new AudioResumeController(this);\n @property({ attribute: 'eager-resume' })\n eagerResume?: string;\n private _recordingController = new RecordingController(this);\n private _annotations = new AnnotationController(this);\n /** Last engine BPM seen by the statechange handler — re-derives tick\n * annotation seconds caches only when it actually changes. */\n private _lastAnnotationBpm: number | null = null;\n // Closures (not direct references) — _timeToPixels/_getPlayhead are\n // declared later in the class body; class-field init order would read\n // `undefined` for a direct reference here.\n private _playbackAnimation = new PlaybackAnimationController(this, {\n timeToPixels: (time) => this._timeToPixels(time),\n getPlayhead: () => this._getPlayhead(),\n });\n /**\n * True while a seek-while-playing stop+play transition is in flight.\n * Suppresses the transient settle dispatch from the engine 'stop' handler\n * (which would otherwise leak a backward-jumping daw-timeupdate at the\n * play-start position). Non-private: pointer-handler's seek path sets it.\n */\n _inSeekTransition = false;\n /**\n * True while `stop()` (the public API) is actively calling `this._engine.stop()`.\n * Suppresses the engine 'stop' handler's own `daw-stop` dispatch — `stop()`\n * dispatches its own, and without this guard a consumer-initiated stop would\n * fire `daw-stop` twice. See the engine 'stop' handler for the counterpart\n * engine-initiated case this flag does NOT suppress.\n */\n private _inConsumerStop = false;\n private _spectrogramController: SpectrogramController | null = null;\n private _clipPointer = new ClipPointerHandler(this);\n private _annotationDrag = new AnnotationDragHandler(this);\n private _trackReorderDrag = new TrackReorderHandler(this);\n get _clipHandler() {\n return this.interactiveClips ? this._clipPointer : null;\n }\n get engine() {\n return this._engine;\n }\n get renderSamplesPerPixel() {\n return this._renderSpp;\n }\n /** Re-extract peaks for a clip at new offset/duration from cached WaveformData. */\n reextractClipPeaks(\n clipId: string,\n offsetSamples: number,\n durationSamples: number\n ): PeakData | null {\n const buf = this._clipBuffers.get(clipId);\n if (!buf) return null;\n const singleClipBuffers = new Map([[clipId, buf]]);\n const singleClipOffsets = new Map([[clipId, { offsetSamples, durationSamples }]]);\n const result = this._peakPipeline.reextractPeaks(\n singleClipBuffers,\n this._renderSpp,\n this.mono,\n singleClipOffsets\n );\n return result.get(clipId) ?? null;\n }\n\n /**\n * Returns true if the clip is a MIDI clip (has midiNotes).\n * Used by ClipPointerHandler to make trim handles inert for MIDI clips.\n * Returns false for unknown track/clip IDs (defensive).\n */\n isMidiClip(trackId: string, clipId: string): boolean {\n const clip = this._loadedClip(trackId, clipId);\n return clip?.midiNotes != null;\n }\n /** The arrangement's tracks as they are played: loaded clips, the current mix (#848). */\n _loadedTracks(): ClipTrack[] {\n const arrangement = this._arrangement;\n return arrangement\n .getTracks()\n .map((t) =>\n loadedTrack(\n t,\n arrangement.getMixer().get(t.id) ?? mixOfTrack(t as ClipTrack),\n arrangement.recordingTrackIds.has(t.id)\n )\n );\n }\n /** A loaded clip of a track of the arrangement, or undefined. */\n private _loadedClip(trackId: string, clipId: string): AudioClip | undefined {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n const clip = track?.clips.find((c) => c.id === clipId);\n return clip && !isLoadingClip(clip) ? clip : undefined;\n }\n\n private _pointer = new PointerHandler(this);\n private _viewport = (() => {\n const v = new ViewportController(this);\n v.scrollSelector = '.scroll-area';\n return v;\n })();\n private _scrollSync = (() => {\n const s = new ScrollSyncController(this);\n s.scrollSelector = '.scroll-area';\n // xTargetSelector, yTargetSelector, and wheelForwardSelector are kept\n // truthful by updated() — they start empty and are set before any scroll\n // is possible (updated() runs before paint on every reactive update).\n return s;\n })();\n\n static styles = [\n hostStyles,\n css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: flex;\n flex-direction: column;\n position: relative;\n background: var(--daw-background, #1a1a2e);\n overflow: hidden;\n }\n .header-row {\n display: flex;\n flex-shrink: 0;\n }\n .ruler-gap {\n flex-shrink: 0;\n width: var(--daw-controls-width, 180px);\n }\n .ruler-viewport {\n flex: 1;\n position: relative;\n overflow: hidden;\n cursor: text;\n }\n .ruler-content {\n will-change: transform;\n }\n .body {\n flex: 1;\n min-height: 0;\n display: flex;\n }\n .controls-viewport {\n flex-shrink: 0;\n width: var(--daw-controls-width, 180px);\n overflow: hidden;\n }\n .controls-column {\n will-change: transform;\n }\n .scroll-area {\n flex: 1;\n overflow: auto;\n overflow-anchor: none;\n min-height: var(--daw-min-height, 200px);\n }\n .timeline {\n position: relative;\n min-height: 100%;\n cursor: text;\n }\n .track-row {\n position: relative;\n box-sizing: border-box;\n background: var(--daw-track-background, #16213e);\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\n }\n .track-row.selected {\n background: rgba(99, 199, 95, 0.08);\n }\n .track-row[data-track-drag-source] {\n background: rgba(99, 199, 95, 0.08);\n }\n :host([scale-mode='beats']) .track-row {\n background: transparent;\n }\n :host([scale-mode='beats']) .clip-container {\n background: var(--daw-track-background, #16213e);\n }\n :host([scale-mode='beats']) .track-row.selected .clip-container {\n box-shadow: inset 0 0 0 1000px rgba(99, 199, 95, 0.06);\n }\n .timeline.drag-over {\n outline: 2px dashed var(--daw-selection-color, rgba(99, 199, 95, 0.3));\n outline-offset: -2px;\n }\n .annotation-lane {\n position: relative;\n box-sizing: border-box;\n border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));\n background: var(--daw-annotation-lane-background, rgba(0, 0, 0, 0.15));\n user-select: none;\n -webkit-user-drag: none;\n }\n .annotation-lane-spacer {\n box-sizing: border-box;\n border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));\n display: flex;\n align-items: center;\n overflow: hidden;\n }\n .annotation-lane-name {\n padding: 0 10px;\n font-size: 11px;\n color: var(--daw-controls-text, #e0d4c8);\n opacity: 0.8;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .annotation-box {\n position: absolute;\n top: 3px;\n bottom: 3px;\n overflow: hidden;\n display: flex;\n align-items: center;\n border: 1px solid var(--daw-annotation-box-border, #c49a6c);\n border-radius: 3px;\n background: var(--daw-annotation-box-background, rgba(196, 154, 108, 0.2));\n color: var(--daw-annotation-text-color, #e0d4c8);\n font-size: 11px;\n cursor: pointer;\n }\n .annotation-box.playing {\n box-shadow: inset 0 0 0 1px var(--daw-annotation-box-border, #c49a6c);\n background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.32));\n }\n .annotation-box.active {\n background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.45));\n }\n .annotation-box-text {\n padding: 0 6px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n pointer-events: none;\n }\n .annotation-boundary {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 6px;\n cursor: ew-resize;\n flex-shrink: 0;\n }\n .annotation-boundary[data-edge='start'] {\n left: 0;\n }\n .annotation-boundary[data-edge='end'] {\n right: 0;\n }\n `,\n clipStyles,\n ];\n\n get effectiveSampleRate(): number {\n return this.sampleRate;\n }\n /**\n * In beats mode, derive samplesPerPixel from ticksPerPixel so that\n * clip positions, waveforms, and the tick-space grid all align.\n */\n get _renderSpp(): number {\n if (this.scaleMode === 'beats') {\n // Round to integer — WaveformData.resample() uses integer scale math.\n const spp = Math.ceil(\n (60 * this.effectiveSampleRate * this.ticksPerPixel) / (this.ppqn * this.bpm)\n );\n // Floor at the peak pipeline's base scale so peaks can always be extracted.\n // Without this, fine zoom levels request a scale finer than what WaveformData\n // can resample to, causing blank waveforms.\n return this._minSamplesPerPixel > 0 ? Math.max(spp, this._minSamplesPerPixel) : spp;\n }\n return this.samplesPerPixel;\n }\n /** Convert seconds to ticks — uses callback if provided, otherwise single-BPM fallback. */\n _secondsToTicks(seconds: number): number {\n if (this.secondsToTicks) {\n if (!this.ticksToSeconds && !this._warnedMissingTicksToSeconds) {\n this._warnedMissingTicksToSeconds = true;\n console.warn(\n '[waveform-playlist] daw-editor: secondsToTicks is set but ticksToSeconds is missing. Both callbacks are required for variable tempo.'\n );\n }\n return this.secondsToTicks(seconds);\n }\n return (seconds * this.bpm * this.ppqn) / 60;\n }\n /** Convert ticks to seconds — uses callback if provided, otherwise single-BPM fallback. */\n _ticksToSeconds(ticks: number): number {\n if (this.ticksToSeconds) {\n if (!this.secondsToTicks && !this._warnedMissingSecondsToTicks) {\n this._warnedMissingSecondsToTicks = true;\n console.warn(\n '[waveform-playlist] daw-editor: ticksToSeconds is set but secondsToTicks is missing. Both callbacks are required for variable tempo.'\n );\n }\n return this.ticksToSeconds(ticks);\n }\n return (ticks * 60) / (this.bpm * this.ppqn);\n }\n /** Clamp limit for annotation boundary edits. indefinite-playback removes the\n * end-of-timeline bound — annotations may extend past the audio (DAW-style\n * unbounded timeline); the shared boundary math treats Infinity as \"no end cap\". */\n get _annotationClampDuration(): number {\n return this.indefinitePlayback ? Infinity : this._duration;\n }\n private get _totalWidth(): number {\n if (this.scaleMode === 'beats') {\n const contentTicks = this._secondsToTicks(this._duration);\n // Floor at 32 bars so the grid is always visible — DAW convention.\n const [num] = this.timeSignature;\n const minTicks = 32 * num * this.ppqn;\n return Math.ceil(Math.max(contentTicks, minTicks) / this.ticksPerPixel);\n }\n // Extend past the natural (clip-derived) duration to cover annotations\n // that reach beyond the audio — DAW-style unbounded timeline (temporal\n // mode only; beats-mode annotation extent is a documented limitation).\n const naturalDuration = Math.max(this._duration, this._annotations.maxAnnotationEndSeconds);\n const naturalWidth = Math.ceil(\n (naturalDuration * this.effectiveSampleRate) / this.samplesPerPixel\n );\n if (this.indefinitePlayback || this.fillViewport) {\n // Fill the visible viewport when natural duration is shorter — lets the\n // ruler render before any audio is loaded. ViewportController exposes\n // the scroll-area's clientWidth (updated on attach + ResizeObserver).\n return Math.max(naturalWidth, this._viewport.containerWidth);\n }\n return naturalWidth;\n }\n /** Grid height when no tracks exist — matches scroll area's rendered height. */\n private get _emptyGridHeight(): number {\n const scrollArea = this.shadowRoot?.querySelector('.scroll-area') as HTMLElement | null;\n return scrollArea?.clientHeight ?? 200;\n }\n _setSelectedTrackId(trackId: string | null) {\n this._selectedTrackId = trackId;\n }\n /**\n * Every track: those in the arrangement, in its order, then those still\n * waiting to enter (#848). A `<daw-track>` whose track an Undo took out of\n * the arrangement is not listed (its descriptor stays for a Redo).\n */\n get tracks(): TrackWithId[] {\n const listed = this._arrangement.getTracks().map((track) => this._listTrack(track));\n // While a handed-in arrangement is played, the page's tracks waiting for\n // the own one are not listed (P15).\n const queue = this._handedIn\n ? this._entryQueue.filter((id) => !this._trackElements.has(id))\n : this._entryQueue;\n const waiting = queue.flatMap((trackId) => {\n const descriptor = this._pendingDescriptor(trackId);\n return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];\n });\n return [...listed, ...waiting];\n }\n /** A track of the arrangement as `editor.tracks` lists it: everything read from the arrangement. */\n private _listTrack(track: ArrangementTrack): TrackWithId {\n const extras = this._extras.get(track.id);\n // Anywhere in the editor: after an Undo of a move a clip's element sits\n // in another track's element (#848).\n const clipEls = new Map<string, DawClipElement>(\n [...this.querySelectorAll('daw-clip')].map((el) => [\n (el as DawClipElement).clipId,\n el as DawClipElement,\n ])\n );\n const sr = this.effectiveSampleRate;\n const clips: ClipDescriptor[] = track.clips.map((clip) => {\n const el = clipEls.get(clip.id);\n const times = clipSeconds(clip, sr);\n const midi = isLoadingClip(clip) ? null : clip;\n const base = {\n src: typeof clip.src === 'string' ? clip.src : '',\n peaksSrc: extras?.peaksSrc.get(clip.id) ?? this._takenPeaksSrc(clip.id) ?? '',\n ...times,\n gain: clip.gain ?? 1,\n name: clip.name ?? '',\n fadeIn: el?.fadeIn ?? 0,\n fadeOut: el?.fadeOut ?? 0,\n fadeType: ((el?.fadeType as FadeType) ?? 'linear') as FadeType,\n midiNotes: midi?.midiNotes ?? null,\n midiChannel: midi?.midiChannel ?? null,\n midiProgram: midi?.midiProgram ?? null,\n };\n return el\n ? { kind: 'dom' as const, clipId: clip.id, ...base }\n : { kind: 'drop' as const, clipId: clip.id, ...base };\n });\n return {\n trackId: track.id,\n name: track.name ?? '',\n src: extras?.src ?? '',\n kind: trackKind(track),\n renderMode: this._renderModeOf(track.id),\n spectrogramConfig: extras?.spectrogramConfig ?? null,\n clips,\n ...this._mixOf(track.id),\n };\n }\n /** A pending track's declaration: its element's attributes and clips now, or its descriptor. */\n private _pendingDescriptor(trackId: string): StoredTrackDescriptor | null {\n const pending = this._pending.get(trackId);\n if (!pending) return null;\n if (!('element' in pending)) return pending.descriptor;\n const read = this._readTrackDescriptor(pending.element);\n return pending.extraClips.length > 0\n ? { ...read, clips: [...read.clips, ...pending.extraClips] }\n : read;\n }\n /** The extras a track of the arrangement takes when the editor has none for it. */\n private _defaultExtras(trackId: string): TrackExtras | null {\n const track = this._arrangementOf(trackId)\n .getTracks()\n .find((t) => t.id === trackId);\n if (!track) return null;\n const kind = trackKind(track);\n return {\n kind,\n renderMode: trackDescriptorRenderMode(kind, 'waveform'),\n src: '',\n peaksSrc: new Map(),\n };\n }\n /** How a track is drawn: its extras, else from its kind (an undo-restored track has none). */\n _renderModeOf(trackId: string): TrackRenderMode {\n const extras = this._extras.get(trackId);\n if (extras) return extras.renderMode;\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n return trackDescriptorRenderMode(track ? trackKind(track) : 'audio', 'waveform');\n }\n /**\n * A track's mix, from its one owner, the arrangement (#843), as the engine\n * plays it: its projection carries the take's mute, which `getMixer()`\n * leaves out (the stored mute comes back when the take ends). A track still\n * waiting to enter shows what its element declares.\n */\n _mixOf(trackId: string): TrackMixerValues {\n const mix = mixOf(this._arrangement, trackId);\n if (mix) return mix;\n const pending = this._pending.get(trackId);\n if (pending && 'mix' in pending) return pending.mix;\n const el = this._trackElements.get(trackId);\n return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;\n }\n // --- Element links (#848, interactions/element-links.ts) ---\n /** @internal */\n _trackLinkState(trackId: string): LinkState {\n // While a handed-in arrangement is set, the children are not played (P7).\n if (this._handedIn && this._trackElements.has(trackId)) return 'detached';\n if (this._isEntered(trackId)) return 'live';\n return this._extras.has(trackId) && !this._pending.has(trackId) ? 'detached' : 'pending';\n }\n /** @internal */\n _clipLinkState(trackId: string, clipId: string): LinkState {\n const track = this._trackLinkState(trackId);\n if (track !== 'live') return track;\n // Linked by id, wherever the element sits (#848: the editor moves no\n // element, so after an Undo of a move it is in another track's element).\n const held = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));\n if (held) return 'live';\n return this._extras.get(trackId)?.peaksSrc.has(clipId) ? 'detached' : 'pending';\n }\n /** @internal The stored mix (not a take's mute) and the name. */\n _trackValues(trackId: string): TrackLinkValues | null {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n const mix = this._arrangement.getMixer().get(trackId);\n if (!track || !mix) return null;\n return { ...mix, name: track.name ?? '' };\n }\n /** @internal */\n _clipValues(trackId: string, clipId: string): ClipLinkValues | null {\n const clip = this._arrangement\n .getTracks()\n .find((t) => t.id === this._clipHolderId(trackId, clipId))\n ?.clips.find((c) => c.id === clipId);\n if (!clip) return null;\n const midi = isLoadingClip(clip) ? null : clip;\n return {\n ...clipSeconds(clip, this.effectiveSampleRate),\n gain: clip.gain ?? 1,\n name: clip.name ?? '',\n midiNotes: midi?.midiNotes ?? null,\n midiChannel: midi?.midiChannel ?? null,\n midiProgram: midi?.midiProgram ?? null,\n };\n }\n /** @internal A property or attribute set on a live `<daw-track>`: one undo step per field kind. */\n _requestTrackChange(trackId: string, partial: Partial<TrackLinkValues>): void {\n const { name, ...mix } = partial;\n if (Object.keys(mix).length > 0) this._writeMixFields(trackId, mix, this._taskGesture(trackId));\n if (name !== undefined) this._renameTrack(trackId, name || 'Untitled');\n }\n /** One gesture id per track for the rest of this task: mix sets made together are one step (#843). */\n private _taskGestures = new Map<string, string>();\n private _taskGesture(trackId: string): string {\n let id = this._taskGestures.get(trackId);\n if (!id) {\n id = createMixerGesture().id;\n this._taskGestures.set(trackId, id);\n if (this._taskGestures.size === 1) queueMicrotask(() => this._taskGestures.clear());\n }\n return id;\n }\n /** @internal A property or attribute set on a live `<daw-clip>`: one undo step. */\n _requestClipChange(trackId: string, clipId: string, partial: Partial<ClipLinkValues>): void {\n const current = this._clipValues(trackId, clipId);\n if (!current) return;\n const holderId = this._clipHolderId(trackId, clipId);\n const clip = this._arrangement\n .getTracks()\n .find((t) => t.id === holderId)\n ?.clips.find((c) => c.id === clipId);\n const src = clip && typeof clip.src === 'string' ? clip.src : '';\n this._applyClipUpdate(holderId, clipId, { ...current, ...partial, src });\n }\n /**\n * The clips of an entering track that another track of the arrangement\n * holds (the page moved their `<daw-clip>` here while the track waited):\n * the track takes the held clip as it is, and `from` names what leaves\n * where. A held clip of the other kind is refused and stays.\n */\n private _takeOverMovedClips(\n trackId: string,\n track: ArrangementTrack\n ): {\n track: ArrangementTrack;\n from: Map<string, Set<string>>;\n movedIds: Set<string>;\n refused: Array<{ clipId: string; error: Error }>;\n } {\n const from = new Map<string, Set<string>>();\n const movedIds = new Set<string>();\n const refused: Array<{ clipId: string; error: Error }> = [];\n const others = this._arrangement.getTracks().filter((t) => t.id !== trackId);\n const kind = trackKind(track);\n const clips: ArrangementTrack['clips'] = [];\n for (const clip of track.clips) {\n const holder = others.find((t) => t.clips.some((c) => c.id === clip.id));\n const held = holder?.clips.find((c) => c.id === clip.id);\n if (!holder || !held) {\n clips.push(clip);\n continue;\n }\n const isMidi = 'midiNotes' in held && held.midiNotes != null;\n const error = clipKindError(track.name ?? '', kind, isMidi, held.name || held.id);\n if (error) {\n refused.push({ clipId: clip.id, error });\n continue;\n }\n clips.push(held);\n movedIds.add(clip.id);\n const ids = from.get(holder.id) ?? new Set<string>();\n from.set(holder.id, ids.add(clip.id));\n }\n return {\n track: movedIds.size || refused.length ? { ...track, clips } : track,\n from,\n movedIds,\n refused,\n };\n }\n /** Run `fn` as one undo step of each arrangement it changes. */\n private _inOneStep(arrangements: readonly Arrangement[], fn: () => void): void {\n for (const a of arrangements) a.beginTransaction();\n try {\n fn();\n } finally {\n for (const a of arrangements) a.commitTransaction();\n }\n }\n /** The `peaks-src` some track took for a clip element, if any. */\n private _takenPeaksSrc(clipId: string): string | undefined {\n for (const extras of this._extras.values()) {\n const peaksSrc = extras.peaksSrc.get(clipId);\n if (peaksSrc !== undefined) return peaksSrc;\n }\n return undefined;\n }\n /**\n * The arrangement whose history holds a track: the one that holds it now,\n * or else, for a page track, the own one (an Undo took it out there; a\n * handed-in arrangement may be played meanwhile), or else the one played.\n */\n private _historyOf(trackId: string, isPageTrack = this._trackElements.has(trackId)): Arrangement {\n const holder = this._arrangementOf(trackId);\n if (holder.getTracks().some((t) => t.id === trackId)) return holder;\n return isPageTrack ? this._ownArrangement : holder;\n }\n /** The track of the arrangement played that holds a clip: `trackId` when it does, or else the one that does. */\n private _clipHolderId(trackId: string, clipId: string): string {\n const tracks = this._arrangement.getTracks();\n if (tracks.some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId)))\n return trackId;\n return tracks.find((t) => t.clips.some((c) => c.id === clipId))?.id ?? trackId;\n }\n /** @internal */\n _trackKind(trackId: string): TrackKind | null {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n return track ? trackKind(track) : null;\n }\n /** @internal */\n _trackIndex(trackId: string): number {\n return this._arrangement.getTracks().findIndex((t) => t.id === trackId);\n }\n /** @internal */\n _detachedReason(): string {\n return this._handedIn\n ? 'a handed-in arrangement is set (editor.arrangement)'\n : 'its track or clip is not in the arrangement the editor plays';\n }\n /** Set or clear `:state(detached)` on every registered element (#848). */\n private _refreshLinkStates(): void {\n refreshLinkStates(this, this._trackElements);\n }\n /**\n * Change one mixer field of a track: the arrangement's setter with\n * `options` (an undo step; changes with one `gesture` id are one step). A\n * track that has not entered yet changes nothing.\n */\n private _writeMix<K extends keyof TrackMixerValues>(\n trackId: string,\n field: K,\n value: TrackMixerValues[K],\n options?: MixerChangeOptions\n ): void {\n const arrangement = this._arrangement;\n if (field === 'volume') arrangement.setTrackVolume(trackId, value as number, options);\n else if (field === 'pan') arrangement.setTrackPan(trackId, value as number, options);\n else if (field === 'muted') arrangement.setTrackMute(trackId, value as boolean, options);\n else if (field === 'soloed') arrangement.setTrackSolo(trackId, value as boolean, options);\n // A decided track does not go back to 'auto' (#684): only a law is a request.\n else if (field === 'panLaw' && isDecidedPanLaw(value)) {\n arrangement.setTrackPanLaw(trackId, value, options);\n }\n }\n /**\n * Change the given mixer fields of a track as ONE undo step (#843): all\n * of them carry one fresh gesture id. A field left out is not sent.\n */\n private _writeMixFields(\n trackId: string,\n mix: Partial<TrackMixerValues>,\n gesture: string = createMixerGesture().id\n ): void {\n const options: MixerChangeOptions = { gesture };\n if (mix.volume !== undefined) this._writeMix(trackId, 'volume', mix.volume, options);\n if (mix.pan !== undefined) this._writeMix(trackId, 'pan', mix.pan, options);\n if (mix.muted !== undefined) this._writeMix(trackId, 'muted', mix.muted, options);\n if (mix.soloed !== undefined) this._writeMix(trackId, 'soloed', mix.soloed, options);\n if (mix.panLaw !== undefined) this._writeMix(trackId, 'panLaw', mix.panLaw, options);\n }\n get selectedTrackId(): string | null {\n return this._selectedTrackId;\n }\n get selection(): { start: number; end: number } | null {\n if (this._selectionStartTime === 0 && this._selectionEndTime === 0) return null;\n return { start: this._selectionStartTime, end: this._selectionEndTime };\n }\n setSelection(start: number, end: number) {\n this._selectionStartTime = Math.min(start, end);\n this._selectionEndTime = Math.max(start, end);\n if (this._engine) {\n this._engine.setSelection(this._selectionStartTime, this._selectionEndTime);\n }\n this.requestUpdate();\n this.dispatchEvent(\n new CustomEvent<DawSelectionDetail>('daw-selection', {\n bubbles: true,\n composed: true,\n detail: { start: this._selectionStartTime, end: this._selectionEndTime },\n })\n );\n }\n // --- Lifecycle ---\n connectedCallback() {\n super.connectedCallback();\n if (this._connection.signal.aborted) this._connection = new AbortController();\n // Follow the arrangement played again (a disconnect let it go, #848),\n // and show what changed meanwhile (an Undo made while out of the page).\n this._follow(this._arrangement);\n this._refreshLinkStates();\n // Every listener of this connection goes with its signal (D8).\n const { signal } = this._connection;\n // Capture on window: runs before <daw-keyboard-shortcuts>' document listener.\n window.addEventListener('keydown', this._onDragEscape, { capture: true, signal });\n this.addEventListener('daw-track-connected', this._onTrackConnected as EventListener, {\n signal,\n });\n this.addEventListener('daw-track-update', this._onTrackUpdate as EventListener, { signal });\n this.addEventListener('daw-track-control', this._onTrackControl as EventListener, { signal });\n this.addEventListener('daw-track-remove', this._onTrackRemoveRequest as EventListener, {\n signal,\n });\n this.addEventListener('daw-clip-connected', this._onClipConnected as EventListener, {\n signal,\n });\n this.addEventListener(\n 'daw-annotation-track-connected',\n this._onAnnotationTrackConnected as EventListener,\n { signal }\n );\n this.addEventListener('daw-annotation-select', this._onAnnotationSelect as EventListener, {\n signal,\n });\n this.addEventListener('daw-track-reorder', this._onTrackReorder as EventListener, { signal });\n this.addEventListener('daw-track-reorder-grab', this._onTrackReorderGrab as EventListener, {\n signal,\n });\n // Detect track + clip removal via MutationObserver (detached elements can't\n // bubble events). A node present in BOTH removedNodes and addedNodes within\n // one batch is a MOVE (insertBefore fires remove+insert) — treated as a\n // reorder, never a teardown (#612).\n this._childObserver = new MutationObserver((mutations) => {\n const removedTracks = new Map<string, DawTrackElement>();\n const removedClips = new Set<DawClipElement>();\n // The clips that left inside a removed <daw-track>, by its id.\n const clipsOfRemoved = new Map<string, DawClipElement[]>();\n const addedTrackIds = new Set<string>();\n for (const mutation of mutations) {\n for (const node of mutation.addedNodes) {\n if (!(node instanceof HTMLElement)) continue;\n if (node.tagName === 'DAW-TRACK') {\n addedTrackIds.add((node as DawTrackElement).trackId);\n }\n node.querySelectorAll?.('daw-track').forEach((t) => {\n addedTrackIds.add((t as DawTrackElement).trackId);\n });\n }\n for (const node of mutation.removedNodes) {\n if (!(node instanceof HTMLElement)) continue;\n if (node.tagName === 'DAW-TRACK') {\n removedTracks.set((node as DawTrackElement).trackId, node as DawTrackElement);\n } else if (node.tagName === 'DAW-CLIP') {\n removedClips.add(node as DawClipElement);\n }\n node.querySelectorAll?.('daw-track').forEach((t) => {\n removedTracks.set((t as DawTrackElement).trackId, t as DawTrackElement);\n });\n node.querySelectorAll?.('daw-clip').forEach((c) => {\n removedClips.add(c as DawClipElement);\n });\n for (const t of node.tagName === 'DAW-TRACK'\n ? [node]\n : [...(node.querySelectorAll?.('daw-track') ?? [])]) {\n clipsOfRemoved.set((t as DawTrackElement).trackId, [\n ...t.querySelectorAll('daw-clip'),\n ] as DawClipElement[]);\n }\n }\n }\n const movedTrackIds = new Set<string>();\n for (const [trackId] of removedTracks) {\n if (addedTrackIds.has(trackId)) {\n movedTrackIds.add(trackId); // move, not removal\n continue;\n }\n // The track and what its children declared are one undo step: a\n // child may be the element of another track's clip (after an Undo\n // of a move), which goes with it (the maintainer's choice, #848).\n const children = (clipsOfRemoved.get(trackId) ?? []).filter((c) => !c.isConnected);\n // Only the arrangement that holds the track (a page track's children\n // declare clips of the same one): an app's open transaction on\n // another is left alone (review of #919).\n this._inOneStep([this._historyOf(trackId)], () => {\n this._onTrackRemoved(trackId);\n for (const clip of children) {\n removedClips.delete(clip);\n this._onClipRemovedFromDom(clip);\n }\n });\n }\n for (const clip of removedClips) {\n // A clip that moved with its track, or into another track of this\n // editor (its connected event moves it, #848), is still here. One\n // moved out of the editor goes.\n if (clip.isConnected && this.contains(clip)) continue;\n this._onClipRemovedFromDom(clip);\n }\n if (movedTrackIds.size > 0) this._placeMovedTracks(movedTrackIds);\n });\n this._childObserver.observe(this, { childList: true, subtree: true });\n // A <daw-track> the page removed while the editor was detached (the\n // observer was off): its track goes now, as the observer would have done\n // (#917; `_trackElements` is kept across a disconnect).\n for (const [trackId, el] of [...this._trackElements]) {\n if (!this.contains(el)) this._onTrackRemoved(trackId);\n }\n // ... and a <daw-clip> the page removed meanwhile: its clip goes (#848).\n // Present anywhere in the editor: an element may sit in another track's\n // element than the one holding its clip (an Undo of a move, #848).\n const present = new Set(\n [...this.querySelectorAll('daw-clip')].map((c) => (c as DawClipElement).clipId as string)\n );\n for (const [trackId] of this._trackElements) {\n for (const clipId of this._extras.get(trackId)?.peaksSrc.keys() ?? []) {\n if (present.has(clipId)) continue;\n // The track that holds the clip, which may be another one than the\n // element's (an Undo of a move, #848): the removal takes it from there.\n const holder = this._historyOf(trackId)\n .getTracks()\n .find((t) => t.clips.some((c) => c.id === clipId));\n if (holder) {\n this._removeClipFromTrack(holder.id, clipId);\n this._forgetClip(trackId, clipId);\n } else this._dropUnheldClip(trackId, clipId);\n }\n }\n if (this._externalAdapter && !this._engine) this._buildEngineReporting();\n }\n disconnectedCallback() {\n super.disconnectedCallback();\n // A removed editor does not follow its arrangement: a handed-in one would\n // keep it alive and run its listeners (review of #919).\n this._unfollow();\n this._unfollow = () => {};\n // The listeners of this connection go, and its waits end: a track's\n // load wait resolves (the track is kept and loads after a reparent).\n this._connection.abort(abortError('<daw-editor> was disconnected'));\n this._effectsManager?.disposeAll();\n this._effectsManager = null;\n // Before the engine is disposed: every pointer interaction ends here.\n this._cancelDrags(true);\n // No audio loads while detached (the decode context goes with the\n // engine). A dropped file whose track has entered is kept and counts as\n // loaded (the connection's abort above ended its wait): it loads after a\n // reparent, like the page's tracks (maintainer, #917). One not entered\n // yet is not added.\n for (const trackId of this._entryQueue) {\n const pending = this._pending.get(trackId);\n if (!pending || 'element' in pending || !this._entryWaiters.has(trackId)) continue;\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._entryQueue = this._entryQueue.filter((id) => id !== trackId);\n this._settleEntry(\n trackId,\n new Error('<daw-editor> was disconnected before the file entered')\n );\n }\n this._childObserver?.disconnect();\n this._childObserver = null;\n // `_trackElements` is kept (#917): the build on a fresh adapter can run\n // before the children's deferred reconnect, and its descriptor reconcile\n // must still see which tracks have an element.\n this._peaksCache.clear();\n // The worker goes; the pipeline makes a new one on its next use.\n this._peakPipeline.terminate();\n this._spectrogramController?.dispose();\n this._spectrogramController = null;\n this._lastSpectrogramViewport = null;\n const hadEngine = this._engine !== null;\n try {\n this._disposeEngine();\n } catch (err) {\n console.warn('[dawcore] Error disposing engine: ' + String(err));\n }\n // engine.dispose() disposed the CONSUMER's adapter. Some adapters\n // (NativePlayoutAdapter) leave the AudioContext open, so building on it\n // again would decode into a dead transport graph: waveforms, no audio.\n // The editor lets go of it; a fresh editor.adapter builds a new engine\n // on the kept arrangement (#848).\n if (hadEngine) {\n this._externalAdapter = null;\n }\n // The arrangement stays, as a moved <input> keeps its value (#848), and\n // so do the descriptors and the peak caches that draw it: the editor\n // shows its tracks while detached, and a fresh adapter plays them. The\n // children's reconnect finds their descriptors and enters nothing again.\n }\n willUpdate(changedProperties: Map<string, unknown>) {\n if (changedProperties.has('eagerResume')) {\n this._audioResume.target = this.eagerResume;\n }\n // Restart playhead animation when zoom or beats params change during playback\n if (\n (changedProperties.has('samplesPerPixel') ||\n changedProperties.has('ticksPerPixel') ||\n changedProperties.has('bpm') ||\n changedProperties.has('secondsToTicks')) &&\n this._isPlaying\n ) {\n this._startPlayhead();\n }\n // Re-extract peaks at new zoom level from cached WaveformData (near-instant).\n // For worker-generated peaks, baseScale (128) is finest; for pre-computed .dat\n // peaks (only cached when rates match), the file's scale is the limit.\n // In beats mode, _renderSpp changes when ticksPerPixel or bpm changes.\n // `mono` changes the derived peak data too (per-channel vs merged) —\n // without it here, toggling mono keeps the stale channel layout until\n // the next zoom change, then snaps mid-session.\n const peaksInputChanged =\n changedProperties.has('samplesPerPixel') ||\n changedProperties.has('ticksPerPixel') ||\n changedProperties.has('bpm') ||\n changedProperties.has('scaleMode') ||\n changedProperties.has('secondsToTicks') ||\n changedProperties.has('mono');\n if (peaksInputChanged && this._clipBuffers.size > 0) {\n const re = this._peakPipeline.reextractPeaks(\n this._clipBuffers,\n this._renderSpp,\n this.mono,\n this._clipOffsets\n );\n if (re.size > 0) {\n const next = new Map(this._peaksData);\n for (const [id, pd] of re) next.set(id, pd);\n this._peaksData = next;\n }\n }\n }\n\n /**\n * Cache of the last ViewportState forwarded to the spectrogram controller.\n * Lit's `updated()` fires on every reactive state change (`_isPlaying`,\n * `_selectedTrackId`, etc.) — most of which don't affect the spectrogram\n * viewport. Skip the cross-controller call when nothing changed.\n *\n * The orchestrator dedupes identical viewports too, so removing this cache\n * wouldn't change observable behavior — but it would push a fresh\n * `setViewport` call (with object allocation) into every Lit reactive\n * update for properties unrelated to the viewport.\n */\n private _lastSpectrogramViewport: {\n vs: number;\n ve: number;\n spp: number;\n } | null = null;\n\n protected updated(_changed: Map<string, unknown>): void {\n // Keep selectors truthful so the controller can distinguish \"intentionally\n // not rendered\" from \"selector broken\" (it warns on the latter when scrolled).\n this._scrollSync.xTargetSelector = this._showRuler ? '.ruler-content' : '';\n this._scrollSync.yTargetSelector = this._showControls ? '.controls-column' : '';\n this._scrollSync.wheelForwardSelector = [\n this._showControls ? '.controls-viewport' : '',\n this._showRuler ? '.ruler-viewport' : '',\n ]\n .filter(Boolean)\n .join(', ');\n // Re-applies transforms clobbered by the .ruler-content style binding —\n // Lit rewrites the style attribute (width) on _totalWidth changes, wiping\n // the imperatively-set transform. Must run before paint on every update.\n this._scrollSync.sync();\n // Forward viewport + zoom into the spectrogram controller on every update\n // so scroll, resize, and zoom all trigger orchestrator.setViewport.\n if (this._spectrogramController) {\n const vs = this._viewport.visibleStart;\n const ve = this._viewport.visibleEnd;\n const spp = this._renderSpp;\n if (Number.isFinite(vs) && Number.isFinite(ve)) {\n const prev = this._lastSpectrogramViewport;\n if (prev && prev.vs === vs && prev.ve === ve && prev.spp === spp) return;\n this._lastSpectrogramViewport = { vs, ve, spp };\n const span = ve - vs;\n const bufferPad = span * 0.25;\n this._spectrogramController.setViewport({\n visibleStartPx: vs,\n visibleEndPx: ve,\n bufferStartPx: Math.max(0, vs - bufferPad),\n bufferEndPx: ve + bufferPad,\n samplesPerPixel: spp,\n });\n }\n }\n }\n\n // --- Annotation Events ---\n private _onAnnotationTrackConnected = (e: CustomEvent<{ element: HTMLElement }>) => {\n this._annotations.handleTrackConnected(e.detail.element as DawAnnotationTrackElement);\n };\n private _onAnnotationSelect = (e: CustomEvent<{ annotation: { start: number } | null }>) => {\n const annotation = e.detail.annotation;\n if (!annotation) return;\n const scrollArea = this.shadowRoot?.querySelector('.scroll-area') as HTMLElement | null;\n if (!scrollArea) return;\n const px = Math.floor((annotation.start * this.effectiveSampleRate) / this._renderSpp);\n scrollArea.scrollLeft = Math.max(0, px - scrollArea.clientWidth / 2);\n };\n\n // --- Track Events ---\n private _onTrackConnected = (e: CustomEvent) => {\n const trackId = e.detail?.trackId;\n const trackEl = e.detail?.element;\n if (!trackId || !(trackEl instanceof HTMLElement)) {\n console.warn('[dawcore] Invalid daw-track-connected event detail: ' + String(e.detail));\n return;\n }\n // A DOM MOVE sends daw-track-connected again for the SAME trackId: an\n // insertBefore runs disconnectedCallback+connectedCallback, a\n // moveBefore() runs connectedMoveCallback, and both announce (#848). If the track is\n // already registered (loading or fully loaded), this is a reconnect from\n // a move, not a first-time registration: refresh the element mapping and\n // bail out WITHOUT re-reading the descriptor or entering it again. The\n // same holds when the EDITOR itself was reparented: the disconnect keeps\n // the arrangement and the descriptors (#848), so the children's\n // reconnect enters nothing again, also a track an Undo took out.\n if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n return;\n }\n // Its declaration is read when it enters (#848 PR 3).\n this._pending = new Map(this._pending).set(trackId, {\n element: trackEl as DawTrackElement,\n extraClips: [],\n });\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n // It enters the arrangement at the next flush, in DOM position (#848).\n this._queueEntry(trackId);\n };\n private _onTrackRemoved(trackId: string) {\n // Captured before the cleanup below — gates the outbound event so it only\n // fires for a track that was actually registered.\n const existed =\n this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId);\n // Detached (an Undo of its arrival): gone for good, also from the undo\n // and redo states (maintainer's choice, #848).\n const isPageTrack = this._trackElements.has(trackId);\n const history = this._historyOf(trackId, isPageTrack);\n const detached =\n this._extras.has(trackId) &&\n !this._pending.has(trackId) &&\n !history.getTracks().some((t) => t.id === trackId);\n const detachedClipIds = detached ? [...(this._extras.get(trackId)?.peaksSrc.keys() ?? [])] : [];\n // An addClip() waiting for a clip of this track would never settle (the\n // clip may not even have connected yet): reject it (#917).\n this._rejectAwaitedClips(\n (_, awaitedTrackId) => awaitedTrackId === trackId,\n 'the track of the clip was removed before the clip loaded'\n );\n this._entryQueue = this._entryQueue.filter((id) => id !== trackId);\n this._settleEntry(trackId, new Error('track \"' + trackId + '\" was removed before it entered'));\n // A page track removed while a handed-in arrangement is played is the own one's (P7).\n const holder = this._arrangementOf(trackId);\n const arrangementTrack = holder.getTracks().find((t) => t.id === trackId);\n const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];\n this._announcer.forget(trackId, clipIds);\n if (clipIds.some((id) => this._previewPeaks.has(id))) {\n const nextPreview = new Map(this._previewPeaks);\n for (const id of clipIds) nextPreview.delete(id);\n this._previewPeaks = nextPreview;\n }\n for (const id of clipIds) this._previewWaveforms.delete(id);\n this._trackElements.delete(trackId);\n this._effectsManager?.disposeTrackChain(trackId);\n // Clean up per-clip data before removing the track\n if (arrangementTrack) {\n const nextPeaks = new Map(this._peaksData);\n for (const clip of arrangementTrack.clips) {\n this._clipBuffers.delete(clip.id);\n this._clipOffsets.delete(clip.id);\n nextPeaks.delete(clip.id);\n this._spectrogramController?.unregisterClipAudio(clip.id);\n }\n this._peaksData = nextPeaks;\n }\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n const nextExtras = new Map(this._extras);\n nextExtras.delete(trackId);\n this._extras = nextExtras;\n // An undo step; the engine follows (incremental removal, playback goes on).\n if (arrangementTrack) holder.removeTrack(trackId);\n else if (detached) {\n history.removeTrack(trackId, { undoable: false });\n for (const id of detachedClipIds) {\n this._purgeClipCaches(id);\n this._previewWaveforms.delete(id);\n }\n }\n this._recomputeDuration();\n // Recompute zoom floor from remaining cached WaveformData scales\n this._recomputeZoomFloor();\n this._disposeSpectrogramControllerIfEmpty();\n // `existed` gate: the MutationObserver fires this for never-registered\n // <daw-track> churn too (element added+removed before its deferred\n // connect) — that must not rewind the user's cursor on an empty timeline.\n if (existed && this._arrangement.getTracks().length === 0) {\n if (this._engine) {\n // The editor rewinds to 0 when the last track goes away — the engine\n // must follow (engine.removeTrack never touches time), or the next\n // play() resumes from the stale position while the display shows 0.\n // Stop first if rolling: an empty timeline has nothing to play, and\n // without it isPlaying stays true with a dead playhead RAF. Suppress\n // the stop settle — the final resting position is 0, dispatched by\n // _stopPlayhead below.\n if (this._isPlaying) {\n this._withSeekSuppression(() => this._engine!.stop());\n // Announce like every other stop path — transport UIs key on\n // daw-play/daw-stop, and editor.stop() (the usual dispatcher) is\n // bypassed here.\n this.dispatchEvent(new CustomEvent('daw-stop', { bubbles: true, composed: true }));\n }\n this._engine.seek(0);\n }\n this._currentTime = 0;\n this._stopPlayhead();\n }\n // Outbound notification (symmetric with daw-track-ready) — fired after\n // the removal so handlers reading editor.tracks see it.\n // Only for a track that was registered, and never on a detached editor\n // (a bubbling/composed event can't reach ancestors — CLAUDE.md pattern #36).\n if (existed && this.isConnected) {\n this.dispatchEvent(\n new CustomEvent<DawTrackIdDetail>('daw-track-removed', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n }\n }\n private _onTrackUpdate = (e: CustomEvent<DawTrackUpdateDetail>) => {\n const trackId = e.detail?.trackId;\n if (!trackId) return;\n const trackEl = (e.target as HTMLElement).closest('daw-track') as DawTrackElement | null;\n if (!trackEl) return;\n // A track that has not entered is read when it enters; one an Undo took\n // out keeps what it had (#848).\n const old = this._extras.get(trackId);\n if (!old || !this._isEntered(trackId)) return;\n const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];\n // A `kind` change after entry is refused by the element itself (its\n // live property warns, #848).\n // Only what this update changed: an unrelated change (a volume) must\n // not put back a render mode or a config `updateTrack` gave the track.\n const next: TrackExtras = {\n ...old,\n ...(changed.includes('renderMode') && {\n renderMode: trackDescriptorRenderMode(old.kind, trackEl.renderMode),\n }),\n ...(changed.includes('spectrogramConfig') && {\n spectrogramConfig: trackEl.spectrogramConfig,\n }),\n ...(changed.includes('src') && { src: trackEl.src }),\n };\n this._extras = new Map(this._extras).set(trackId, next);\n // The mix and the name are not handled here: the element's setters ask\n // the arrangement directly (#848, element-links.ts).\n if (old.src !== next.src) this._replaceShorthandClips(trackId, trackEl);\n const loaded = this._loadedTracks().find((t) => t.id === trackId)?.clips ?? [];\n // Track switched into spectrogram mode — push existing clip audio into the controller.\n if (next.renderMode === 'spectrogram' && old.renderMode !== 'spectrogram') {\n for (const clip of loaded) this._maybeRegisterSpectrogramClipAudio(trackId, clip);\n }\n // Track switched OUT of spectrogram mode — drop clip audio.\n if (next.renderMode !== 'spectrogram' && old.renderMode === 'spectrogram') {\n if (this._spectrogramController) {\n for (const clip of loaded) this._spectrogramController.unregisterClipAudio(clip.id);\n }\n this._disposeSpectrogramControllerIfEmpty();\n }\n if (next.spectrogramConfig !== old.spectrogramConfig) {\n this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);\n }\n };\n /** The arrangement that holds a track: the one played, else the own one (a page track while handed in). */\n private _arrangementOf(trackId: string): Arrangement {\n const has = (a: Arrangement) => a.getTracks().some((t) => t.id === trackId);\n return has(this._arrangement) || !has(this._ownArrangement)\n ? this._arrangement\n : this._ownArrangement;\n }\n /** Rename a track in the arrangement (an undo step); the same name changes nothing. */\n private _renameTrack(trackId: string, name: string): void {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n if (!track || track.name === name) return;\n this._arrangement.updateTrack(trackId, (current) => ({ ...current, name }));\n }\n\n /** Drop the controller when no spectrogram tracks remain. */\n private _disposeSpectrogramControllerIfEmpty(): void {\n if (!this._spectrogramController) return;\n const stillNeeded = Array.from(this._extras.values()).some(\n (d) => d.renderMode === 'spectrogram'\n );\n if (!stillNeeded) {\n this._spectrogramController.dispose();\n this._spectrogramController = null;\n // A recreated controller diffs new viewports against this cache — a\n // stale entry suppresses the fresh orchestrator's initial setViewport\n // and every canvas stays black until a >=100px scroll or zoom change.\n this._lastSpectrogramViewport = null;\n }\n }\n\n private static _CONTROL_PROPS = new Set(['volume', 'pan', 'muted', 'soloed']);\n private _onTrackControl = (e: CustomEvent<Partial<DawTrackControlDetail>>) => {\n const { trackId, prop, value, gesture } = e.detail ?? {};\n if (!trackId || !prop || !DawEditorElement._CONTROL_PROPS.has(prop)) return;\n // Select the track when interacting with its controls\n if (this._selectedTrackId !== trackId) {\n this._setSelectedTrackId(trackId);\n if (this._engine) {\n this._engine.selectTrack(trackId);\n }\n this.dispatchEvent(\n new CustomEvent('daw-track-select', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n }\n if (this._isEntered(trackId)) {\n // Validated values to the arrangement's setters (also while the track\n // loads, #848). A slider's gesture id makes its drag one undo step\n // (#843); a control without one (mute, solo) is a step per event.\n const options: MixerChangeOptions | undefined =\n typeof gesture === 'string' ? { gesture } : undefined;\n if (prop === 'volume') this._writeMix(trackId, 'volume', clampNumber(value, 0, 1), options);\n if (prop === 'pan') this._writeMix(trackId, 'pan', clampNumber(value, -1, 1), options);\n if (prop === 'muted') this._writeMix(trackId, 'muted', Boolean(value), options);\n if (prop === 'soloed') this._writeMix(trackId, 'soloed', Boolean(value), options);\n }\n // Don't sync back to <daw-track> DOM element — avoids daw-track-update loop.\n // The arrangement holds the control values.\n };\n private _onTrackRemoveRequest = (e: CustomEvent) => {\n const { trackId } = e.detail ?? {};\n if (!trackId) return;\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n trackEl.remove(); // MutationObserver will trigger _onTrackRemoved\n } else {\n this._onTrackRemoved(trackId); // File-dropped tracks: no DOM element\n }\n };\n // --- Clip lifecycle ---\n private _onClipConnected = (e: CustomEvent) => {\n const detail = e.detail as { clipId: string; element: DawClipElement };\n const clipEl = detail.element;\n if (!(clipEl instanceof HTMLElement)) return;\n const trackEl = clipEl.closest('daw-track') as DawTrackElement | null;\n if (!trackEl) return;\n const trackId = trackEl.trackId;\n // Moved here from another track of this editor (#848, choice a): the\n // clip moves with it, one undo step.\n if (this._rehomeClip(trackId, clipEl)) return;\n // The arrangement that holds the track: the own one for a page track\n // while a handed-in arrangement is played (the children declare it, P7).\n const entered = this._arrangementOf(trackId)\n .getTracks()\n .some((t) => t.id === trackId);\n if (!entered && !this._pending.has(trackId) && this._trackLinkState(trackId) === 'detached') {\n // Added under a detached track (an Undo of its arrival): it never\n // enters, also after a Redo. It is taken, so it shows detached\n // (maintainer's choice, #848).\n this._takeClip(trackId, clipEl.clipId, clipEl.peaksSrc || '');\n console.warn(\n detachedWarning(\n '<daw-track> \"' + (trackEl.name || 'Untitled') + '\"',\n 'a <daw-clip> added to it',\n this._detachedReason()\n )\n );\n this._rejectAwaitedClips(\n (id) => id === clipEl.clipId,\n 'addClip: track \"' + trackId + '\" is detached'\n );\n this._refreshLinkStates();\n return;\n }\n if (!entered) {\n // Neither entered nor waiting to enter: an Undo took the track out\n // between an addClip() and this deferred connect, or the arrangement\n // refused it. Nothing will take the clip, so its addClip() is rejected\n // (#917). A track waiting to enter reads its <daw-clip> children when\n // it enters (#848 PR 3), this one included.\n if (!this._entryQueue.includes(trackId)) {\n this._rejectAwaitedClips(\n (id) => id === clipEl.clipId,\n 'addClip: track \"' + trackId + '\" is not in the editor (an Undo took it out)'\n );\n }\n return;\n }\n // A clip the editor took already: read when its track entered (this is\n // its own deferred connect), or a reconnect from a DOM move (custom\n // elements fire disconnectedCallback+connectedCallback on insertBefore).\n if (this._extras.get(trackId)?.peaksSrc.has(clipEl.clipId)) return;\n this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));\n };\n /**\n * A `<daw-clip>` now under `trackId` whose clip another track holds: the\n * clip moves to this track (one undo step) when both have entered the same\n * arrangement; a clip of the other kind stays with `daw-clip-error`.\n * Otherwise the old track lets it go and the element goes on as a new\n * arrival. Returns true when nothing more is to be done.\n */\n private _rehomeClip(trackId: string, clipEl: DawClipElement): boolean {\n const clipId = clipEl.clipId;\n // Declared here already (its own deferred connect, a move inside the\n // track, an Undo that left the element here): not a move.\n if (this._extras.get(trackId)?.peaksSrc.has(clipId)) return true;\n // The arrangement whose history holds the track: the own one for a page\n // track that is waiting or detached while a handed-in one is played.\n const arrangement = this._historyOf(trackId);\n // Back in the track that holds its clip (the page moved it back after an\n // Undo of its move): what the other tracks took comes here.\n if (\n arrangement.getTracks().some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId))\n ) {\n let peaksSrc = clipEl.peaksSrc || '';\n for (const [id, extras] of this._extras) {\n if (id === trackId || !extras.peaksSrc.has(clipId)) continue;\n peaksSrc = extras.peaksSrc.get(clipId) ?? peaksSrc;\n this._forgetClip(id, clipId);\n }\n this._takeClip(trackId, clipId, peaksSrc);\n return true;\n }\n const fromTrackId = trackHoldingClip(arrangement, clipId, trackId);\n if (!fromTrackId) {\n // Taken by another track of this editor and not held now: that one forgets it.\n for (const [id, extras] of this._extras) {\n if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);\n }\n return false;\n }\n const entered = arrangement.getTracks().some((t) => t.id === trackId);\n // Into a track waiting to enter: the clip moves when it enters, as it is,\n // with its arrival (the maintainer's choice c, #848; _enterTrack).\n if (!entered && this._pending.has(trackId)) return true;\n const toExtras = this._extras.get(trackId) ?? this._defaultExtras(trackId);\n if (!entered || !toExtras) {\n // Into a detached track (an Undo took its arrival): refused. The clip\n // stays where it is; the element is taken here, shows detached, and is\n // linked to its clip by id once a Redo brings the track back.\n this._takeClip(trackId, clipId, this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? '');\n console.warn(\n '[dawcore] <daw-clip> cannot move into <daw-track> \"' +\n (this._trackElements.get(trackId)?.name || 'Untitled') +\n '\": the track is not in the arrangement (an Undo took it out). Its clip stays in its track.'\n );\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n clipId,\n error: new Error('track \"' + trackId + '\" is not in the arrangement'),\n },\n })\n );\n this._refreshLinkStates();\n return true;\n }\n const error = moveClipToTrack(arrangement, fromTrackId, trackId, clipId, toExtras.kind);\n if (error) {\n // Refused (a clip of the other kind): nothing changes, no undo step,\n // and the element stays where the page put it (the editor moves no\n // element, #848). It is taken here too, so a later announcement does\n // not try again, and it stays linked to its clip by id.\n this._takeClip(trackId, clipId, this._extras.get(fromTrackId)?.peaksSrc.get(clipId) ?? '');\n console.warn(\n '[dawcore] <daw-clip> cannot move to track \"' +\n (this._trackElements.get(trackId)?.name || 'Untitled') +\n '\" (' +\n String(error) +\n '): its clip stays in its track.'\n );\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error },\n })\n );\n return true;\n }\n const peaksSrc = this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? '';\n // Every other track that took the element forgets it: after an Undo of\n // a move it is still taken where it sat (review of #919, round 2).\n for (const [id, extras] of this._extras) {\n if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);\n }\n if (!this._extras.has(trackId)) this._extras = new Map(this._extras).set(trackId, toExtras);\n this._takeClip(trackId, clipId, peaksSrc);\n return true;\n }\n private _onClipRemovedFromDom(clipEl: DawClipElement) {\n const clipId = clipEl.clipId;\n // The arrangement played, and the own one (a page track's clip while a\n // handed-in arrangement is played).\n for (const arrangement of new Set([this._arrangement, this._ownArrangement])) {\n for (const t of arrangement.getTracks()) {\n if (t.clips.some((c) => c.id === clipId)) {\n this._removeClipFromTrack(t.id, clipId);\n return;\n }\n }\n }\n // A clip the arrangement refused (its kind): it goes from what the editor took.\n for (const [trackId, extras] of this._extras) {\n if (!extras.peaksSrc.has(clipId)) continue;\n this._dropUnheldClip(trackId, clipId);\n return;\n }\n // Removed before its deferred connect, or from a track that has not\n // entered (it reads its clips when it enters) (in the task of its addClip()): the\n // connect will never reach the editor, so the addClip() is rejected (#917).\n this._rejectAwaitedClips((id) => id === clipId, 'the clip was removed before it loaded');\n // No matching engine clip. May be benign (clip was removed before its load\n // completed), but it can also indicate a DOM/engine id mismatch — purge any\n // orphan cache entries and warn so the leak is visible.\n if (\n this._clipBuffers.has(clipId) ||\n this._clipOffsets.has(clipId) ||\n this._peaksData.has(clipId)\n ) {\n console.warn(\n '[dawcore] _onClipRemovedFromDom: orphaned cache entries for clip \"' +\n clipId +\n '\" — purging (DOM/engine id mismatch?)'\n );\n this._purgeClipCaches(clipId);\n }\n }\n /**\n * A `<daw-clip>` appended to a track that has entered: the clip goes in as\n * a loading clip (a loaded one for MIDI), one undo step. Its audio loads\n * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).\n */\n private _loadAndAppendClip(trackId: string, clipDesc: ClipDescriptor & { clipId: string }) {\n const arrangement = this._arrangementOf(trackId);\n const track = arrangement.getTracks().find((t) => t.id === trackId);\n // A track with no extras (a handed-in one, one an Undo brought back)\n // takes the defaults (P14).\n const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);\n if (!extras || !track) return;\n // A <daw-clip>'s clip is taken, also when refused: its own deferred\n // connect must not add it again. One from addClip() has no element.\n if (isDomClip(clipDesc)) this._takeClip(trackId, clipDesc.clipId, clipDesc.peaksSrc);\n const clipIsMidi = isMidiDescriptor(clipDesc);\n const kindError = clipKindError(\n track.name ?? '',\n extras.kind,\n clipIsMidi,\n clipDesc.name || clipDesc.src || clipDesc.clipId\n );\n const clip = clipIsMidi\n ? buildMidiClip(clipDesc, this.effectiveSampleRate)\n : buildLoadingClip(clipDesc);\n if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);\n try {\n if (kindError) throw kindError;\n // The function form: the track's loading clips stay as they are.\n arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: [...current.clips, clip],\n }));\n } catch (err) {\n console.warn('[dawcore] _loadAndAppendClip failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clipDesc.clipId, error: err },\n })\n );\n return;\n }\n if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);\n }\n /**\n * Resolve pre-computed peaks for a clip: fetch the .dat/.json, validate the\n * sample rate matches the AudioContext, return the WaveformData or null.\n * Warns on fetch failure and on sample-rate mismatch — never silent.\n *\n * Used by `_requestPreview` for a clip that is still loading.\n */\n private async _resolvePeaks(peaksSrc: string): Promise<import('waveform-data').default | null> {\n try {\n const wd = await this._fetchPeaks(peaksSrc);\n const contextRate = this.audioContext.sampleRate;\n if (wd.sample_rate === contextRate) return wd;\n console.warn(\n '[dawcore] Pre-computed peaks at ' +\n wd.sample_rate +\n ' Hz do not match AudioContext at ' +\n contextRate +\n ' Hz — ignoring ' +\n peaksSrc +\n ', generating from audio'\n );\n return null;\n } catch (err) {\n if (isAbortError(err)) return null; // a swap: nothing failed\n console.warn(\n '[dawcore] Failed to load peaks from ' +\n peaksSrc +\n ': ' +\n String(err) +\n ' — falling back to AudioBuffer generation'\n );\n return null;\n }\n }\n /** Remove a single clip from all per-clip caches. Used by error rollbacks. */\n private _purgeClipCaches(clipId: string) {\n const nextBuffers = new Map(this._clipBuffers);\n nextBuffers.delete(clipId);\n this._clipBuffers = nextBuffers;\n const nextPeaks = new Map(this._peaksData);\n nextPeaks.delete(clipId);\n this._peaksData = nextPeaks;\n this._clipOffsets.delete(clipId);\n this._spectrogramController?.unregisterClipAudio(clipId);\n }\n /**\n * Replace one loaded clip of a track in the arrangement: an undo step. The\n * function form, so the track's loading clips stay as they are (#848).\n */\n private _replaceClip(trackId: string, clipId: string, clip: AudioClip) {\n this._arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: current.clips.map((c) => (c.id === clipId ? clip : c)),\n }));\n }\n private _applyClipUpdate(trackId: string, clipId: string, clipEl: ClipUpdateValues) {\n const t = this._arrangement.getTracks().find((track) => track.id === trackId);\n if (!t) {\n console.warn('[dawcore] _applyClipUpdate: no track for id \"' + trackId + '\"');\n return;\n }\n const loadedClip = this._loadedClip(trackId, clipId);\n if (!loadedClip) {\n const loading = t.clips.find((c) => c.id === clipId);\n if (loading && isLoadingClip(loading)) {\n this._updateLoadingClip(trackId, loading, clipEl);\n return;\n }\n console.warn(\n '[dawcore] _applyClipUpdate: clip \"' +\n clipId +\n '\" not found in track \"' +\n trackId +\n '\" (DOM/engine clip-id misalignment?)'\n );\n return;\n }\n const oldClip = loadedClip;\n const sr = oldClip.sampleRate ?? this.effectiveSampleRate;\n\n // MIDI clips: rebuild the clip when notes/channel/program change. Detect\n // MIDI by either current or previous state being MIDI. oldClip.midiNotes\n // is an array (possibly empty []) for any clip registered via _buildMidiClip\n // — including placeholders. For audio clips it is undefined.\n // Use loose != null consistently: treats both null and undefined as \"not MIDI\"\n // for both clipEl.midiNotes (DawClipElement defaults to null) and oldClip.midiNotes.\n // A clip with a src is an audio clip even if notes are set on it, as at\n // load (isMidiDescriptor: \"treating as audio, notes will be ignored\").\n const isMidiNow = clipEl.midiNotes != null && !clipEl.src;\n const wasMidi = oldClip.midiNotes != null;\n if (isMidiNow && trackKind(t) !== 'midi') {\n // Notes assigned to a clip of an audio track: the clip would become a\n // MIDI clip on an audio track (#756). Leave the engine clip as it is.\n const kindError = clipKindError(t.name ?? '', 'audio', true, clipEl.name || clipId);\n console.warn('[dawcore] _applyClipUpdate: ' + kindError?.message);\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error: kindError },\n })\n );\n return;\n }\n if (isMidiNow || wasMidi) {\n // The value the arrangement holds already changes nothing (#848).\n if (\n clipEl.midiNotes === oldClip.midiNotes &&\n (clipEl.midiChannel ?? undefined) === oldClip.midiChannel &&\n (clipEl.midiProgram ?? undefined) === oldClip.midiProgram &&\n Math.round(clipEl.start * sr) === oldClip.startSample &&\n Math.round(clipEl.offset * sr) === oldClip.offsetSamples &&\n (clipEl.duration <= 0 || Math.round(clipEl.duration * sr) === oldClip.durationSamples) &&\n clipEl.gain === (oldClip.gain ?? 1) &&\n (clipEl.name || oldClip.name) === oldClip.name\n ) {\n return;\n }\n const notes = validMidiNotes(clipEl.midiNotes ?? []);\n const noteSpanSeconds = notes.length\n ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0)\n : 0;\n const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);\n const requestedDurationSamples =\n clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : sourceDurationSamples;\n\n const updatedClip: AudioClip = {\n ...oldClip,\n audioBuffer: undefined,\n startSample: Math.round(clipEl.start * sr),\n offsetSamples: Math.round(clipEl.offset * sr),\n durationSamples: requestedDurationSamples,\n sourceDurationSamples,\n gain: clipEl.gain,\n name: clipEl.name || oldClip.name,\n midiNotes: notes,\n midiChannel: clipEl.midiChannel ?? undefined,\n midiProgram: clipEl.midiProgram ?? undefined,\n };\n // Drop any audio caches in case this clip was previously loaded as audio.\n this._purgeClipCaches(clipId);\n this._replaceClip(trackId, clipId, updatedClip);\n return;\n }\n\n const newStartSample = Math.round(clipEl.start * sr);\n const newDurationSamples =\n clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : oldClip.durationSamples;\n const newOffsetSamples = Math.round(clipEl.offset * sr);\n const updatedClip = {\n ...oldClip,\n startSample: newStartSample,\n durationSamples: newDurationSamples,\n offsetSamples: newOffsetSamples,\n gain: clipEl.gain,\n name: clipEl.name || oldClip.name,\n };\n // The value the arrangement holds already changes nothing (#848).\n if (\n newStartSample === oldClip.startSample &&\n newDurationSamples === oldClip.durationSamples &&\n newOffsetSamples === oldClip.offsetSamples &&\n updatedClip.gain === (oldClip.gain ?? 1) &&\n updatedClip.name === oldClip.name\n ) {\n return;\n }\n const boundsChanged =\n oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;\n if (boundsChanged) {\n this._clipOffsets.set(clipId, {\n offsetSamples: newOffsetSamples,\n durationSamples: newDurationSamples,\n });\n const peaks = this.reextractClipPeaks(clipId, newOffsetSamples, newDurationSamples);\n if (peaks) {\n this._peaksData = new Map(this._peaksData).set(clipId, peaks);\n }\n }\n\n this._replaceClip(trackId, clipId, updatedClip);\n }\n /**\n * A change to a clip still loading (#848 P10): its times, gain and name in\n * seconds on the `LoadingClip`, one undo step; the audio loads into it.\n */\n private _updateLoadingClip(trackId: string, clip: LoadingClip, values: ClipUpdateValues): void {\n const next: LoadingClip = {\n ...clip,\n start: values.start,\n ...(values.duration > 0 ? { duration: values.duration } : {}),\n offset: values.offset,\n gain: values.gain,\n ...(values.name ? { name: values.name } : {}),\n };\n if (\n (next.start ?? 0) === (clip.start ?? 0) &&\n next.duration === clip.duration &&\n (next.offset ?? 0) === (clip.offset ?? 0) &&\n (next.gain ?? 1) === (clip.gain ?? 1) &&\n next.name === clip.name\n ) {\n return;\n }\n this._arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: current.clips.map((c) => (c.id === clip.id ? next : c)),\n }));\n }\n /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */\n /**\n * An aborted addClip (D3): its clip leaves for good, from the track it\n * entered or from what a waiting track will enter with.\n */\n private _discardAddedClip(trackId: string, clipId: string): void {\n const pending = this._pending.get(trackId);\n if (pending) {\n this._pending = new Map(this._pending).set(\n trackId,\n 'element' in pending\n ? { ...pending, extraClips: pending.extraClips.filter((c) => c.clipId !== clipId) }\n : {\n ...pending,\n descriptor: {\n ...pending.descriptor,\n clips: pending.descriptor.clips.filter((c) => c.clipId !== clipId),\n },\n }\n );\n return;\n }\n const holder = this._arrangementOf(trackId)\n .getTracks()\n .find((t) => t.id === trackId);\n if (holder?.clips.some((c) => c.id === clipId)) {\n this._removeClipFromTrack(trackId, clipId, { undoable: false });\n }\n }\n private _removeClipFromTrack(\n trackId: string,\n clipId: string,\n options: { undoable?: boolean } = {}\n ) {\n const arrangement = this._arrangementOf(trackId);\n const track = arrangement.getTracks().find((t) => t.id === trackId);\n if (!track) {\n console.warn('[dawcore] _removeClipFromTrack: no track for id \"' + trackId + '\"');\n return;\n }\n if (!track.clips.some((c) => c.id === clipId)) {\n console.warn(\n '[dawcore] _removeClipFromTrack: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n this._purgeClipCaches(clipId);\n this._previewWaveforms.delete(clipId);\n if (this._previewPeaks.has(clipId)) {\n const nextPreview = new Map(this._previewPeaks);\n nextPreview.delete(clipId);\n this._previewPeaks = nextPreview;\n }\n this._forgetClip(trackId, clipId);\n const wasLoading = track.clips.some((c) => c.id === clipId && isLoadingClip(c));\n // `undoable: false`: out of every undo and redo state too (an aborted\n // addClip leaves nothing behind, D3).\n if (options.undoable === false) arrangement.removeClip(trackId, clipId, { undoable: false });\n else\n arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: current.clips.filter((c) => c.id !== clipId),\n }));\n // Its load will never be announced (an addClip() waiting for it watches\n // the arrangement and rejects).\n if (wasLoading) this._announcer.forgetClip(clipId);\n }\n /** Record that the editor took a clip of a track (with its `peaks-src`, '' when none). */\n private _takeClip(trackId: string, clipId: string, peaksSrc: string): void {\n const extras = this._extras.get(trackId);\n if (!extras || extras.peaksSrc.get(clipId) === peaksSrc) return;\n const next = new Map(extras.peaksSrc).set(clipId, peaksSrc);\n this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });\n }\n /**\n * A `<daw-clip>` the editor took is removed while the arrangement does not\n * hold its clip (its track or its own arrival undone, or refused): it is\n * gone for good, also from the undo and redo states, so no Redo brings it\n * back (maintainer's choice, #848).\n */\n private _dropUnheldClip(trackId: string, clipId: string): void {\n this._historyOf(trackId).removeClip(trackId, clipId, { undoable: false });\n this._purgeClipCaches(clipId);\n this._previewWaveforms.delete(clipId);\n this._forgetClip(trackId, clipId);\n }\n /** The editor no longer holds anything for a clip of a track. */\n private _forgetClip(trackId: string, clipId: string): void {\n const extras = this._extras.get(trackId);\n if (!extras?.peaksSrc.has(clipId)) return;\n const next = new Map(extras.peaksSrc);\n next.delete(clipId);\n this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });\n }\n private _readTrackDescriptor(trackEl: DawTrackElement): StoredTrackDescriptor {\n const clipEls = trackEl.querySelectorAll('daw-clip') as NodeListOf<DawClipElement>;\n const clips: ClipDescriptor[] = [];\n\n if (clipEls.length === 0 && trackEl.src) {\n // <daw-track src> shorthand — synthetic descriptor with no <daw-clip>\n // backing element. No DOM clipId to align with.\n clips.push({\n kind: 'drop',\n src: trackEl.src,\n peaksSrc: '',\n start: 0,\n duration: 0,\n offset: 0,\n gain: 1,\n name: trackEl.name || '',\n fadeIn: 0,\n fadeOut: 0,\n fadeType: 'linear',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n });\n } else {\n for (const clipEl of clipEls) clips.push(this._readClipDescriptor(clipEl));\n }\n return {\n name: trackEl.name || 'Untitled',\n src: trackEl.src,\n kind: trackEl.kind,\n renderMode: trackDescriptorRenderMode(trackEl.kind, trackEl.renderMode),\n clips,\n };\n }\n private _readClipDescriptor(clipEl: DawClipElement): DomClipDescriptor {\n return {\n kind: 'dom',\n clipId: clipEl.clipId,\n src: clipEl.src,\n peaksSrc: clipEl.peaksSrc,\n start: clipEl.start,\n duration: clipEl.duration,\n offset: clipEl.offset,\n gain: clipEl.gain,\n name: clipEl.name,\n fadeIn: clipEl.fadeIn,\n fadeOut: clipEl.fadeOut,\n fadeType: clipEl.fadeType as FadeType,\n midiNotes: clipEl.midiNotes,\n midiChannel: clipEl.midiChannel,\n midiProgram: clipEl.midiProgram,\n };\n }\n // --- Entering the arrangement (#848) ---\n private _isEntered(trackId: string): boolean {\n return this._arrangement.getTracks().some((t) => t.id === trackId);\n }\n /** Queue a registered track for the next flush. */\n _queueEntry(trackId: string): void {\n if (!this._entryQueue.includes(trackId)) this._entryQueue = [...this._entryQueue, trackId];\n if (this._entryFlushScheduled) return;\n this._entryFlushScheduled = true;\n // A microtask: tracks connected in one task (an innerHTML, a script\n // appending several) enter together, at once. The page's children connect\n // in tasks of their own and enter one by one; the history rule holds for\n // each, because the flush before cleared what it added.\n queueMicrotask(() => {\n this._entryFlushScheduled = false;\n this._flushTrackEntries();\n });\n }\n /**\n * Enter the queued tracks into the arrangement, in DOM order. Without an\n * engine they wait (the sample rate of a MIDI clip comes from the\n * adapter); the engine's build flushes again. The page's tracks entering\n * while the arrangement has no history are not undo steps: the history is\n * cleared after them, so Undo right after load removes nothing (and the\n * next page track finds it empty again).\n */\n _flushTrackEntries(): void {\n if (this._entryQueue.length === 0) return;\n // Without an engine the queue waits, silently (maintainer, #917; play()\n // without an adapter warns and fires daw-error with the no-adapter error).\n if (!this._engine) return;\n // No drag holds a transaction (#848 PR 3): a track enters during a drag\n // as at any other time, an undo step of its own.\n const isPageTrack = (id: string) => this._trackElements.has(id);\n // The children declare the editor's OWN arrangement: while a handed-in\n // one is played they wait (P7); addTrack() and drops go to the one played.\n const queued = this._handedIn\n ? this._entryQueue.filter((id) => !isPageTrack(id))\n : this._entryQueue;\n this._entryQueue = this._handedIn ? this._entryQueue.filter(isPageTrack) : [];\n const domOrder: string[] = [...this.querySelectorAll('daw-track')].map(\n (el) => (el as DawTrackElement).trackId\n );\n const position = (id: string) => {\n const at = domOrder.indexOf(id);\n return at === -1 ? domOrder.length : at;\n };\n const ordered = [...queued].sort((a, b) => position(a) - position(b));\n const arrangement = this._arrangement;\n const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo;\n let pageEntered = false;\n for (const id of ordered.filter(isPageTrack)) {\n if (this._enterTrack(id)) pageEntered = true;\n }\n if (historyWasEmpty && pageEntered) arrangement.clearHistory();\n for (const id of ordered.filter((id) => !isPageTrack(id))) this._enterTrack(id);\n }\n /** Enter one registered track. False when it is gone, already in, or refused. */\n private _enterTrack(trackId: string): boolean {\n const descriptor = this._pendingDescriptor(trackId);\n if (!descriptor || this._isEntered(trackId)) return false;\n const el = this._trackElements.get(trackId);\n const built = buildArrangementTrack(\n trackId,\n descriptor,\n this._mixOf(trackId),\n this.effectiveSampleRate\n );\n // From here the arrangement holds it; the editor keeps only what the\n // arrangement has no field for (#848 PR 3).\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._extras = new Map(this._extras).set(trackId, extrasOf(built.descriptor));\n for (const { clipId, error } of built.refused) {\n console.warn('[dawcore] ' + error.message);\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error },\n })\n );\n }\n const index = el\n ? entryIndex(\n [...this.querySelectorAll('daw-track')] as DawTrackElement[],\n trackId,\n this._arrangement.getTracks().map((t) => t.id)\n )\n : undefined;\n // A child whose clip another track holds was moved here by the page: the\n // clip moves in as it is, in the same undo step as the arrival (the\n // maintainer's choice c, #848). One of the other kind stays where it is.\n const moved = this._takeOverMovedClips(trackId, built.track);\n const entering = moved.track;\n for (const { clipId, error } of moved.refused) {\n console.warn('[dawcore] ' + error.message);\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error },\n })\n );\n }\n // Before the add: the announcement it causes counts the refused clips,\n // and a clip whose source is loaded already is still announced ready.\n this._announcer.expect(trackId, built.refused.length + moved.refused.length);\n for (const clip of entering.clips) {\n if (isLoadingClip(clip)) this._announcer.expectClip(clip.id);\n }\n try {\n if (moved.from.size === 0) {\n this._arrangement.addTrack(entering, index === undefined ? undefined : { index });\n } else {\n this._inOneStep([this._arrangement], () => {\n for (const [fromId, clipIds] of moved.from) {\n this._arrangement.updateTrack(fromId, (t) => ({\n ...t,\n clips: t.clips.filter((c) => !clipIds.has(c.id)),\n }));\n for (const clipId of clipIds) this._forgetClip(fromId, clipId);\n }\n this._arrangement.addTrack(entering, index === undefined ? undefined : { index });\n });\n }\n } catch (err) {\n console.warn('[dawcore] Failed to add track \"' + trackId + '\": ' + String(err));\n // An element stays linked to the refused track (it is not added\n // again); a track with no element is gone.\n if (!el) {\n const nextExtras = new Map(this._extras);\n nextExtras.delete(trackId);\n this._extras = nextExtras;\n }\n this._refreshLinkStates();\n this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));\n this.dispatchEvent(\n new CustomEvent<DawTrackErrorDetail>('daw-track-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, error: err },\n })\n );\n return false;\n }\n this._settleEntry(trackId, ENTERED);\n for (const clipDesc of built.descriptor.clips) {\n if (clipDesc.clipId && moved.movedIds.has(clipDesc.clipId)) continue; // loaded as it is\n if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {\n this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);\n }\n }\n return true;\n }\n /**\n * The `<daw-track src>` shorthand changed its src: the entered track gets a\n * new loading clip for it, one undo step. A track whose clips are\n * `<daw-clip>` children keeps them. A track still queued reads the new\n * descriptor when it enters.\n */\n private _replaceShorthandClips(trackId: string, trackEl: DawTrackElement): void {\n const descriptor = this._readTrackDescriptor(trackEl);\n if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;\n const built = buildArrangementTrack(\n trackId,\n descriptor,\n DEFAULT_TRACK_MIX,\n this.effectiveSampleRate\n );\n const extras = this._extras.get(trackId);\n if (extras) {\n this._extras = new Map(this._extras).set(trackId, {\n ...extras,\n peaksSrc: extrasOf(built.descriptor).peaksSrc,\n });\n }\n this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));\n }\n /** Run the load announcements over the arrangement's current state. */\n private _announceLoading(): void {\n this._announcer.update(\n this._arrangement.getTracks(),\n this._arrangement.sources.getSnapshot().sources\n );\n }\n /**\n * Fetch a loading clip's `.dat` peaks and draw them until its audio\n * arrives (an editor-only cache, not the arrangement: writing the clip\n * after it entered would be an undo step).\n */\n private async _requestPreview(clipId: string, peaksSrc: string): Promise<void> {\n const waveformData = await this._resolvePeaks(peaksSrc);\n if (!waveformData) return;\n const clip = this._arrangement\n .getTracks()\n .flatMap((t) => t.clips)\n .find((c) => c.id === clipId);\n // Loaded first (the worker draws it), or gone.\n if (!clip || !isLoadingClip(clip)) return;\n const rate = waveformData.sample_rate;\n const offset = clip.offset ?? 0;\n const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);\n const peakData = extractPeaks(\n waveformData,\n Math.max(this._renderSpp, waveformData.scale),\n this.mono,\n Math.round(offset * rate),\n Math.round(seconds * rate)\n );\n this._previewPeaks = new Map(this._previewPeaks).set(clipId, peakData);\n this._previewWaveforms.set(clipId, waveformData);\n this._raiseZoomFloor(waveformData.scale);\n this._recomputeDuration();\n }\n /** The peak sync made a clip's peaks: its zoom floor holds, its preview goes. */\n _clipPeaksReady(clipId: string, audioBuffer: AudioBuffer): void {\n this._raiseZoomFloor(this._peakPipeline.getCachedScale(audioBuffer));\n if (!this._previewPeaks.has(clipId)) return;\n const next = new Map(this._previewPeaks);\n next.delete(clipId);\n this._previewPeaks = next;\n }\n /** Who waits for a track to enter (addTrack, a dropped file). */\n private _entryWaiters = new Map<\n string,\n { resolve: (trackId: string) => void; reject: (error: unknown) => void }\n >();\n private _waitForEntry(trackId: string): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n this._entryWaiters.set(trackId, { resolve, reject });\n });\n }\n /** Settle the wait for a track's entry: entered (`ENTERED`), or refused or gone (the reason).*/\n private _settleEntry(trackId: string, outcome: unknown): void {\n const waiter = this._entryWaiters.get(trackId);\n if (!waiter) return;\n this._entryWaiters.delete(trackId);\n // Anything but ENTERED rejects, also a falsy abort reason ('', 0, null,\n // false: a signal's reason is passed on as it is; review of #919).\n if (outcome === ENTERED) waiter.resolve(trackId);\n else waiter.reject(outcome);\n }\n /**\n * A dropped file as a track with no element (a File cannot be an attribute):\n * one loading clip whose source is the file. Resolves with the track id once\n * it has entered, an undo step like any track an editor method adds.\n */\n _addDroppedFile(file: File): Promise<string> {\n const trackId = crypto.randomUUID();\n const name = file.name.replace(/\\.\\w+$/, '');\n const descriptor: StoredTrackDescriptor = {\n name,\n src: '',\n kind: 'audio',\n renderMode: trackDescriptorRenderMode('audio', 'waveform'),\n clips: [\n {\n kind: 'drop',\n file,\n src: '',\n peaksSrc: '',\n start: 0,\n duration: 0,\n offset: 0,\n gain: 1,\n name,\n fadeIn: 0,\n fadeOut: 0,\n fadeType: 'linear',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n },\n ],\n };\n this._pending = new Map(this._pending).set(trackId, { descriptor, mix: DEFAULT_TRACK_MIX });\n const entered = this._waitForEntry(trackId);\n // A swap before it enters ends it, as a disconnect does (review of #919).\n this._endEntryOnSwap(trackId, entered);\n this._queueEntry(trackId);\n return entered;\n }\n /**\n * Take a track out for good: no undo step, and no undo or redo brings it\n * back (a dropped file that could not be loaded was never a declaration).\n */\n _discardTrack(trackId: string, from: Arrangement = this._arrangement): void {\n // From the arrangement it entered: after a swap that is no longer the one\n // played (review of #919). The editor shows nothing of that one, so only\n // its own record of the track goes (no event, no playhead change).\n if (from !== this._arrangement) {\n from.removeTrack(trackId, { undoable: false });\n if (this._extras.has(trackId)) {\n const nextExtras = new Map(this._extras);\n nextExtras.delete(trackId);\n this._extras = nextExtras;\n }\n return;\n }\n const track = from.getTracks().find((t) => t.id === trackId);\n this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);\n from.removeTrack(trackId, { undoable: false });\n this._onTrackRemoved(trackId);\n }\n /** One AbortController per arrangement while it is played (D2, interactions/abort.ts). */\n private _playSignals = new PlaySignals();\n /** The signal of the arrangement played now: aborted when it is swapped out. */\n private get _playSignal(): AbortSignal {\n return this._playSignals.signalOf(this._arrangement);\n }\n /** @internal A caller's signal combined with the arrangement played now (loadMidi, D6). */\n _operationSignal(signal?: AbortSignal): AbortSignal {\n return signal ? AbortSignal.any([signal, this._playSignal]) : this._playSignal;\n }\n /** One AbortController per connection: aborted in disconnectedCallback (D8). */\n private _connection = new AbortController();\n /**\n * Resolves once the track has loaded (`daw-track-ready`), or when the\n * editor is disconnected meanwhile (the track is kept and loads after a\n * reparent); rejects when its audio failed (`daw-track-error`).\n */\n _whenTrackLoaded(trackId: string): Promise<void> {\n const state = this._announcer.stateOf(trackId);\n if (state === 'ready') return Promise.resolve();\n if (state === 'failed') return Promise.reject(this._announcer.errorOf(trackId));\n // Ends as loaded when the arrangement is swapped out or the editor is\n // disconnected meanwhile (the track is kept and loads after a reparent).\n const ended = AbortSignal.any([this._playSignal, this._connection.signal]);\n if (ended.aborted) return Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const done = new AbortController();\n const signal = AbortSignal.any([ended, done.signal]);\n this.addEventListener(\n 'daw-track-ready',\n (e: Event) => {\n if ((e as CustomEvent<DawTrackIdDetail>).detail.trackId !== trackId) return;\n done.abort();\n resolve();\n },\n { signal }\n );\n this.addEventListener(\n 'daw-track-error',\n (e: Event) => {\n const detail = (e as CustomEvent<DawTrackErrorDetail>).detail;\n if (detail.trackId !== trackId) return;\n done.abort();\n reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));\n },\n { signal }\n );\n ended.addEventListener('abort', () => resolve(), { signal: done.signal });\n });\n }\n /**\n * Load again every failed source the track's clips name (#848). A track\n * whose audio failed stays in the editor, like a broken `<img>`;\n * `daw-track-ready` follows when it loads.\n */\n retryTrack(trackId: string): void {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n if (!track) {\n console.warn('[dawcore] retryTrack: no track found for id \"' + trackId + '\"');\n return;\n }\n const sources = this._arrangement.sources.getSnapshot().sources;\n const failed = new Set(\n track.clips\n .filter(isLoadingClip)\n .map((clip) => clip.src)\n .filter((src) => sources.get(src)?.status === 'failed')\n );\n for (const src of failed) this._arrangement.retry(src);\n }\n private _fetchPeaks(src: string): Promise<import('waveform-data').default> {\n const cached = this._peaksCache.get(src);\n if (cached) return cached;\n // The fetch belongs to the arrangement played now: a swap aborts it (D2),\n // and an aborted one is dropped from the cache so a later request fetches again.\n const promise = loadWaveformDataFromUrl(src, this._playSignal).catch((err) => {\n this._peaksCache.delete(src);\n throw err;\n });\n this._peaksCache.set(src, promise);\n return promise;\n }\n /**\n * The timeline's duration, the one writer of `_duration`: the loaded clips,\n * and the clips still loading whose length is known (a duration, or `.dat`\n * peaks), so the timeline is as wide as what is drawn (#848).\n */\n _recomputeDuration() {\n const sr = this.effectiveSampleRate;\n let maxSample = 0;\n for (const track of this._loadedTracks()) {\n for (const clip of track.clips) {\n const endSample = clip.startSample + clip.durationSamples;\n if (endSample > maxSample) maxSample = endSample;\n }\n }\n for (const track of this._arrangement.getTracks()) {\n for (const clip of track.clips) {\n if (!isLoadingClip(clip)) continue;\n const seconds = this._placeholderSeconds(clip);\n if (seconds === null) continue;\n maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));\n }\n }\n this._duration = maxSample / sr;\n }\n /** How long a loading clip is drawn: its duration, else what its `.dat` peaks cover; null when unknown. */\n private _placeholderSeconds(clip: LoadingClip): number | null {\n if (clip.duration != null && clip.duration > 0) return clip.duration;\n const waveformData = this._previewWaveforms.get(clip.id);\n if (!waveformData) return null;\n const seconds = waveformData.duration - (clip.offset ?? 0);\n return seconds > 0 ? seconds : null;\n }\n // --- Engine ---\n /**\n * The engine, built now when the editor is connected with an adapter.\n * Rejects without an adapter, and on a detached editor (an engine built\n * there would hold the adapter's graph with nothing to dispose it).\n */\n _ensureEngine(): Promise<EditorEngine> {\n if (this._engine) return Promise.resolve(this._engine);\n try {\n if (!this.isConnected && this._externalAdapter) {\n throw new Error('[dawcore] <daw-editor> is not connected: no engine is built for it.');\n }\n return Promise.resolve(this._buildEngine());\n } catch (err) {\n return Promise.reject(err);\n }\n }\n /** Build the engine from the adapter setter or a connect: a failure is reported, not thrown. */\n private _buildEngineReporting(): void {\n try {\n this._buildEngine();\n } catch (err) {\n console.warn('[dawcore] Failed to build the engine: ' + String(err));\n // An addTrack() waiting to enter would wait for an engine that does not\n // come (#848): it fails with the build's error, and its track goes.\n const error = err instanceof Error ? err : new Error(String(err));\n for (const trackId of [...this._entryQueue]) {\n const pending = this._pending.get(trackId);\n if (!pending || 'element' in pending || !this._entryWaiters.has(trackId)) continue;\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._entryQueue = this._entryQueue.filter((id) => id !== trackId);\n this._settleEntry(trackId, error);\n }\n this.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'engine', error: err },\n })\n );\n }\n }\n /** Last versions the statechange handler worked from; reset for each engine. */\n private _lastTracksVersion = -1;\n private _lastMixerVersion = -1;\n private _buildEngine(): EditorEngine {\n if (!this._externalAdapter) {\n throw new Error(noAdapterError());\n }\n const adapter = this._externalAdapter;\n\n // Forward initial tempo if adapter supports it — skipped when tick\n // callbacks are present (external tempo map is authoritative, #407)\n if (!this._hasTickCallbacks) {\n if (adapter.setTempo) {\n adapter.setTempo(this._bpm);\n } else if (this._bpm !== 120) {\n console.warn(\n '[dawcore] Adapter does not implement setTempo. ' +\n 'Initial BPM ' +\n this._bpm +\n ' will not be applied — clips may use wrong tempo.'\n );\n }\n }\n\n // Try to set the editor's desired PPQN on the adapter, then sync back.\n // Adapter is the source of truth — it may ignore the request.\n adapter.setPpqn?.(this._ppqn);\n this.ppqn = adapter.ppqn;\n\n const engine = new EditorEngine({\n adapter,\n arrangement: this._arrangement,\n sampleRate: adapter.audioContext.sampleRate,\n samplesPerPixel: this.samplesPerPixel,\n bpm: this._bpm,\n zoomLevels: [256, 512, 1024, 2048, 4096, 8192, this.samplesPerPixel]\n .filter((v, i, a) => a.indexOf(v) === i)\n .sort((a, b) => a - b),\n });\n this._lastTracksVersion = -1;\n this._lastMixerVersion = -1;\n engine.on('statechange', (engineState) => this._onEngineState(engineState));\n engine.on('pause', () => {\n this._currentTime = engine.getCurrentTime();\n });\n engine.on('stop', () => this._onEngineStop(engine));\n this._engine = engine;\n // A new engine (a swap, a fresh adapter) plays the selection the editor shows.\n if (this._selectionStartTime !== 0 || this._selectionEndTime !== 0) {\n engine.setSelection(this._selectionStartTime, this._selectionEndTime);\n }\n // A kept arrangement (a reconnect) already has tracks: draw them now,\n // and give a spectrogram track its audio again (the controller went with\n // the disconnect).\n this._onEngineState(engine.getState());\n for (const track of this._loadedTracks()) {\n for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);\n }\n this._flushTrackEntries();\n return engine;\n }\n /**\n * Clips whose audio has just arrived: a `.dat` preview's data goes to the\n * peak pipeline (no worker run), a spectrogram track gets the audio. The\n * peak sync then makes their peaks.\n */\n private _adoptLoadedClips(tracks: readonly ClipTrack[]): void {\n for (const track of tracks) {\n for (const clip of track.clips) {\n const waveformData = this._previewWaveforms.get(clip.id);\n if (waveformData && clip.audioBuffer) {\n if (waveformData.sample_rate === clip.audioBuffer.sampleRate) {\n this._peakPipeline.cacheWaveformData(clip.audioBuffer, waveformData);\n }\n this._previewWaveforms.delete(clip.id);\n }\n if (!this._clipBuffers.has(clip.id))\n this._maybeRegisterSpectrogramClipAudio(track.id, clip);\n }\n }\n }\n /** The engine's state changed: draw it (the rows are read from the arrangement). */\n private _onEngineState(engineState: EngineState): void {\n this._isPlaying = engineState.isPlaying;\n this._selectedTrackId = engineState.selectedTrackId;\n const structuralChange = engineState.tracksVersion !== this._lastTracksVersion;\n // Per-track mixer edits (volume/mute/solo/pan) bump mixerVersion, NOT\n // tracksVersion (#501). Draw again on either so the controls show the\n // current mix — but only run the\n // expensive structural work below for true structural changes, never on\n // every volume/pan drag frame.\n const mixerChange = engineState.mixerVersion !== this._lastMixerVersion;\n if (structuralChange || mixerChange) {\n this._lastTracksVersion = engineState.tracksVersion;\n this._lastMixerVersion = engineState.mixerVersion;\n this.requestUpdate();\n }\n // Sync clip positions when tracks change structurally (moveClip, trimClip,\n // splitClip, setTracks, addTrack, removeTrack).\n if (structuralChange) {\n this._recomputeDuration();\n // Transport setTracks rebuilds TrackNodes, severing effects hookups.\n this._effectsManager?.rewireTrackChains();\n // Regenerate peaks for new or trimmed clips.\n // MIDI tracks have no AudioBuffer — skip them to avoid noisy\n // \"no AudioBuffer\" warnings on every tracksVersion bump.\n const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== 'midi');\n this._adoptLoadedClips(audioTracks);\n syncPeaksForChangedClips(this, audioTracks);\n this._announceLoading();\n }\n // Tick-based annotations: BPM changes move their time-domain positions —\n // re-derive the seconds caches (write-only-on-change; loop-safe).\n if (engineState.bpm !== this._lastAnnotationBpm) {\n this._lastAnnotationBpm = engineState.bpm;\n this._annotations.deriveSecondsCaches();\n }\n }\n private _onEngineStop(engine: EditorEngine): void {\n // Fires synchronously from EditorEngine.stop() (see engine CLAUDE.md\n // \"Bounded playback\" / #608) — reached via EITHER a consumer-initiated\n // stop (editor.stop(), or a seek-adjacent stop+reschedule guarded by\n // _inSeekTransition — pointer-handler seek, seekTo, splitAtPlayhead,\n // empty-timeline rewind) OR the engine's OWN bounded-playback\n // completion path: an adapter (Tone, native) reports `onPlaybackEnded` for a\n // duration-limited play(start, end) (selection/annotation playback),\n // and the engine calls `this.stop()` internally from a queued\n // microtask with no consumer call in sight. That engine-initiated case\n // has no other `daw-stop` dispatcher — mirror it here so consumers\n // still get a daw-stop paired with their earlier daw-play. Consumer\n // stops dispatch their own daw-stop (editor.stop(), guarded by\n // _inConsumerStop) or intentionally suppress it (seek-adjacent stops,\n // guarded by _inSeekTransition) — this handler must not double-fire\n // for those.\n this._currentTime = engine.getCurrentTime();\n this._stopPlayhead();\n this._activePlayEndTime = null;\n if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {\n this.dispatchEvent(new CustomEvent('daw-stop', { bubbles: true, composed: true }));\n }\n }\n private _disposeEngine() {\n if (this._engine) {\n this._engine.dispose();\n this._engine = null;\n }\n }\n // --- File Drop ---\n private _onDragOver = (e: DragEvent) => {\n if (!this.fileDrop) return;\n e.preventDefault();\n if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';\n this._dragOver = true;\n };\n private _onDragLeave = (e: DragEvent) => {\n if (!this.fileDrop) return;\n // relatedTarget is null when cursor leaves the browser window — that's fine,\n // we still want to clear _dragOver in that case.\n const timeline = this.shadowRoot?.querySelector('.timeline');\n if (timeline && !timeline.contains(e.relatedTarget as Node)) {\n this._dragOver = false;\n }\n };\n private _onDrop = async (e: DragEvent) => {\n if (!this.fileDrop) return;\n e.preventDefault();\n this._dragOver = false;\n const files = e.dataTransfer?.files;\n if (!files || files.length === 0) return;\n try {\n await this.loadFiles(files);\n } catch (err) {\n console.warn('[dawcore] File drop failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'file-drop', error: err },\n })\n );\n }\n };\n async loadFiles(\n files: FileList | File[],\n options: EditorCallOptions = {}\n ): Promise<LoadFilesResult> {\n return loadFilesImpl(this, files, options);\n }\n /**\n * Imperatively load a `.mid` file (URL or File) and add N tracks (no\n * element, #848), one per note-bearing MIDI track. On any per-track\n * failure, every track the call added is removed with no undo step, so the\n * editor is as before the call.\n *\n * `options.signal` cancels the fetch, the parse and the tracks still\n * waiting to enter (combined with the arrangement played: a swap cancels\n * too); the call rejects with its `reason` and removes the tracks it added.\n *\n * Requires the optional `@dawcore/midi` peer dep — throws with an install\n * hint (and `console.warn`s the original error) when the dynamic import\n * fails for any reason.\n */\n async loadMidi(source: string | File, options?: MidiLoadOptions): Promise<MidiLoadResult> {\n return loadMidiImpl(this, source, options);\n }\n // --- Programmatic Track API ---\n /**\n * Build the engine if it hasn't been built yet. Lets consumers obtain a\n * non-null `editor.engine` before any track has been loaded — useful for\n * wiring analyzers, effects, or master taps before content arrives.\n */\n async ready(): Promise<EditorEngine> {\n return this._ensureEngine();\n }\n /**\n * Add a track built from `config` to the arrangement the editor plays when\n * it is called, and resolve with its id once it has entered (#848), before\n * its audio has loaded. A swap of `editor.arrangement` before it enters\n * rejects with an `AbortError` and the track enters nowhere; to add to\n * another arrangement, call that arrangement's own `addTrack`. No element is created: the track is drawn and listed like any\n * other, and `<daw-track>` children stay the page's declaration. To follow\n * loading, add the `daw-track-ready` / `daw-track-error` listener BEFORE\n * calling: for a track with nothing to fetch it fires before this\n * resolves. Without `editor.adapter` it waits for one. Rejects when the\n * arrangement refuses the track, when it is removed before it enters, or\n * when the engine cannot be built.\n *\n * `options.signal` (#848): aborting it before the track has entered takes\n * it out of the queue (it never enters) and rejects with its `reason`;\n * after that it changes nothing (the audio goes on loading). A signal\n * already aborted rejects at once and queues nothing.\n */\n addTrack(config: TrackConfig = {}, options: EditorCallOptions = {}): Promise<string> {\n const signal = options.signal;\n if (signal?.aborted) return Promise.reject(reasonOf(signal));\n const trackId = crypto.randomUUID();\n let kind: TrackKind = config.kind ?? (config.midi ? 'midi' : 'audio');\n if (kind !== 'audio' && kind !== 'midi') {\n console.warn(\n '[dawcore] addTrack: kind \"' +\n String(kind) +\n \"\\\" is not a track kind ('audio' or 'midi'); using \\\"audio\\\"\"\n );\n kind = 'audio';\n }\n let renderMode = normalizeRenderMode(config.renderMode);\n if (renderMode === 'both') {\n console.warn(\n '[dawcore] render-mode=\"both\" is not yet supported; falling back to \\'spectrogram\\''\n );\n renderMode = 'spectrogram';\n }\n const clipConfigs: ClipConfig[] = [...(config.clips ?? [])];\n if (config.midi) {\n clipConfigs.push({\n midiNotes: config.midi.notes,\n midiChannel: config.midi.channel,\n midiProgram: config.midi.program,\n });\n }\n const descriptor: StoredTrackDescriptor = {\n name: config.name || 'Untitled',\n src: '',\n kind,\n renderMode: trackDescriptorRenderMode(kind, renderMode),\n spectrogramConfig: config.spectrogramConfig ?? null,\n clips: clipConfigs.map((c) => clipDescriptorOf(c)),\n };\n const mix: TrackMixerValues = {\n volume: config.volume ?? DEFAULT_TRACK_MIX.volume,\n pan: config.pan ?? DEFAULT_TRACK_MIX.pan,\n muted: config.muted ?? false,\n soloed: config.soloed ?? false,\n panLaw: declaredPanLaw(config.panLaw),\n };\n this._pending = new Map(this._pending).set(trackId, { descriptor, mix });\n const entered = this._waitForEntry(trackId);\n // It goes into the arrangement played now: a swap before it enters ends\n // the call (the maintainer's choice, #848: capture it).\n this._endEntryOnSwap(trackId, entered);\n this._queueEntry(trackId);\n if (!signal) return entered;\n const settled = new AbortController();\n signal.addEventListener('abort', () => this._abortEntry(trackId, reasonOf(signal)), {\n signal: settled.signal,\n });\n return entered.finally(() => settled.abort());\n }\n /**\n * A queued track goes into the arrangement played when it was queued: when\n * that one is swapped out first, the track leaves the queue and its wait\n * rejects with the swap's AbortError (addTrack, a dropped file).\n */\n private _endEntryOnSwap(trackId: string, entered: Promise<string>): void {\n const settled = new AbortController();\n this._playSignal.addEventListener(\n 'abort',\n (e) => this._abortEntry(trackId, reasonOf(e.target as AbortSignal)),\n { signal: settled.signal }\n );\n void entered.then(\n () => settled.abort(),\n () => settled.abort()\n );\n }\n /** A track that has not entered leaves the queue and its wait rejects with `reason` (D4). */\n private _abortEntry(trackId: string, reason: unknown): void {\n if (!this._pending.has(trackId) || this._isEntered(trackId)) return;\n // Out of what is waiting; its id left in the queue enters nothing.\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._settleEntry(trackId, reason);\n this.requestUpdate();\n }\n /**\n * Remove a track by id: its `<daw-track>` element is removed (the\n * MutationObserver does the rest), or, for a track with no element\n * (`addTrack`, a dropped file, an Undo), the track itself. One undo step.\n * Warns when no track has the id.\n */\n removeTrack(trackId: string): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n trackEl.remove();\n // Detached, the MutationObserver is off: remove the track here (#917).\n if (!this.isConnected) this._onTrackRemoved(trackId);\n } else if (\n this._pending.has(trackId) ||\n this._extras.has(trackId) ||\n this._isEntered(trackId)\n ) {\n // File-dropped and undo-restored tracks have no DOM element.\n this._onTrackRemoved(trackId);\n } else {\n console.warn('[dawcore] removeTrack: no track found for id \"' + trackId + '\"');\n }\n }\n /**\n * Move a track to a 0-based position in the arrangement's order (every\n * track counts, those with no element too; `trackEl.index` and\n * `editor.tracks` give the positions). One undo step; no element moves.\n */\n reorderTrack(trackId: string, toIndex: number): void {\n if (!Number.isFinite(toIndex)) {\n console.warn('[dawcore] reorderTrack: invalid toIndex ' + String(toIndex));\n return;\n }\n if (!this._isEntered(trackId)) {\n console.warn('[dawcore] reorderTrack: no track found for id \"' + trackId + '\"');\n return;\n }\n // The arrangement's order; no element moves (#848: the markup is the\n // starting declaration, order included).\n const last = this._arrangement.getTracks().length - 1;\n this._arrangement.reorderTrack(trackId, Math.max(0, Math.min(Math.trunc(toIndex), last)));\n }\n\n private _onTrackReorder = (e: CustomEvent<DawTrackReorderDetail>) => {\n this.reorderTrack(e.detail.trackId, e.detail.toIndex);\n };\n\n private _onTrackReorderGrab = (e: CustomEvent<DawTrackReorderGrabDetail>) => {\n if (!this.trackReordering) return;\n this._trackReorderDrag.onGrab(e.detail.trackId, e.detail.pointerEvent, e.detail.gripElement);\n };\n\n /**\n * Change a track: the mix (one undo step, #843), the name (an undo step),\n * the render mode and spectrogram config (the editor's). The arrangement\n * is changed, never an element's attributes (#848): a `<daw-track>`'s\n * properties show the change. A track that has not entered yet gets it as\n * the value it enters with.\n */\n updateTrack(trackId: string, partial: Partial<TrackConfig>): void {\n if (!this._isEntered(trackId)) {\n this._updatePendingTrack(trackId, partial);\n return;\n }\n const mix: Partial<TrackMixerValues> = {\n volume: partial.volume,\n pan: partial.pan,\n muted: partial.muted,\n soloed: partial.soloed,\n ...(partial.panLaw !== undefined && { panLaw: declaredPanLaw(partial.panLaw) }),\n };\n this._writeMixFields(trackId, mix);\n if (partial.name !== undefined) this._renameTrack(trackId, partial.name);\n const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);\n if (!extras) return;\n let renderMode =\n partial.renderMode === undefined ? undefined : normalizeRenderMode(partial.renderMode);\n if (renderMode === 'both') {\n console.warn(\n '[dawcore] render-mode=\"both\" is not yet supported; falling back to \\'spectrogram\\''\n );\n renderMode = 'spectrogram';\n }\n if (renderMode === undefined && partial.spectrogramConfig === undefined) return;\n const next: TrackExtras = {\n ...extras,\n ...(renderMode !== undefined && {\n renderMode: trackDescriptorRenderMode(extras.kind, renderMode),\n }),\n ...(partial.spectrogramConfig !== undefined && {\n spectrogramConfig: partial.spectrogramConfig,\n }),\n };\n this._extras = new Map(this._extras).set(trackId, next);\n if (next.spectrogramConfig !== extras.spectrogramConfig) {\n this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);\n }\n }\n /** `updateTrack` on a track waiting to enter: the values it will enter with. */\n private _updatePendingTrack(trackId: string, partial: Partial<TrackConfig>): void {\n const pending = this._pending.get(trackId);\n if (!pending) {\n console.warn('[dawcore] updateTrack: no track found for id \"' + trackId + '\"');\n return;\n }\n if ('element' in pending) {\n // Before entry an element's properties are its declaration (P9).\n const el = pending.element;\n if (partial.name !== undefined) el.name = partial.name;\n if (partial.volume !== undefined) el.volume = partial.volume;\n if (partial.pan !== undefined) el.pan = partial.pan;\n if (partial.panLaw !== undefined) el.panLaw = partial.panLaw;\n if (partial.muted !== undefined) el.muted = partial.muted;\n if (partial.soloed !== undefined) el.soloed = partial.soloed;\n if (partial.renderMode !== undefined) el.renderMode = partial.renderMode;\n if (partial.spectrogramConfig !== undefined) el.spectrogramConfig = partial.spectrogramConfig;\n return;\n }\n const { descriptor, mix } = pending;\n this._pending = new Map(this._pending).set(trackId, {\n descriptor: {\n ...descriptor,\n ...(partial.spectrogramConfig !== undefined && {\n spectrogramConfig: partial.spectrogramConfig,\n }),\n ...(partial.name !== undefined && { name: partial.name }),\n ...(partial.renderMode !== undefined && {\n renderMode: trackDescriptorRenderMode(\n descriptor.kind,\n normalizeRenderMode(partial.renderMode)\n ),\n }),\n },\n mix: {\n volume: partial.volume ?? mix.volume,\n pan: partial.pan ?? mix.pan,\n muted: partial.muted ?? mix.muted,\n soloed: partial.soloed ?? mix.soloed,\n panLaw: partial.panLaw !== undefined ? declaredPanLaw(partial.panLaw) : mix.panLaw,\n },\n });\n }\n /**\n * Add a clip to a track (with or without an element) and resolve with its\n * id once its audio has loaded (`daw-clip-ready`, before its peaks are\n * drawn). The clip enters the arrangement as a loading clip, one undo\n * step; no `<daw-clip>` is created (#848). Rejects when it fails to load,\n * is refused (its kind), or leaves the arrangement before it loads (a\n * removal, an Undo). A clip added while the editor is detached loads once\n * a fresh adapter is set.\n *\n * `options.signal` (#848): aborting it before the clip has loaded rejects\n * with its `reason` and removes the clip for good (no undo step); after it\n * has loaded it changes nothing. A signal already aborted rejects at once\n * and adds nothing. A swap of `editor.arrangement` rejects the call with an\n * `AbortError`; its loading clip stays in the arrangement swapped out.\n */\n addClip(trackId: string, config: ClipConfig, options: EditorCallOptions = {}): Promise<string> {\n const callerSignal = options.signal;\n if (callerSignal?.aborted) return Promise.reject(reasonOf(callerSignal));\n if (!config.src) {\n return Promise.reject(\n new Error(\n 'addClip: config.src is required — pass a URL to load. ' +\n 'Empty/recording clips are not yet supported via addClip.'\n )\n );\n }\n const pending = this._pending.get(trackId);\n if (!this._isEntered(trackId) && !pending) {\n return Promise.reject(\n new Error(\n 'addClip: track \"' +\n trackId +\n '\" is not in the editor (an Undo took it out, the arrangement refused it, or no ' +\n 'track has this id)'\n )\n );\n }\n const clipDesc = clipDescriptorOf(config);\n const clipId = clipDesc.clipId;\n // Settled by daw-clip-ready / daw-clip-error for this clip; and, since a\n // clip that leaves the arrangement before its audio loads (a removal, an\n // Undo, its track removed) is never announced, rejected once it has been\n // in the arrangement and is gone (#917). Every way out removes all three\n // listeners.\n return new Promise<string>((resolve, reject) => {\n let seen = false;\n // One controller for this call: its abort removes every listener.\n const call = new AbortController();\n const cleanup = () => {\n call.abort();\n this._awaitedClips.delete(clipId);\n };\n this.addEventListener(\n 'daw-clip-ready',\n (e: Event) => {\n if ((e as CustomEvent<DawClipIdDetail>).detail.clipId !== clipId) return;\n cleanup();\n resolve(clipId);\n },\n { signal: call.signal }\n );\n this.addEventListener(\n 'daw-clip-error',\n (e: Event) => {\n const detail = (e as CustomEvent<DawClipErrorDetail>).detail;\n if (detail.clipId !== clipId) return;\n cleanup();\n reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));\n },\n { signal: call.signal }\n );\n // One arrangement, the one the clip goes into, subscribed to and read.\n const watched =\n pending && 'element' in pending && !this._isEntered(trackId)\n ? this._ownArrangement\n : this._arrangement;\n const stopWatching = watched.subscribe(() => {\n const present = watched.getTracks().some((t) => t.clips.some((c) => c.id === clipId));\n if (present) {\n seen = true;\n } else if (seen) {\n cleanup();\n reject(new Error('clip \"' + clipId + '\" was removed before its audio loaded'));\n }\n });\n call.signal.addEventListener('abort', stopWatching);\n // That arrangement swapped out (D2): the call ends; the clip stays there.\n this._playSignals.signalOf(watched).addEventListener(\n 'abort',\n (e) => {\n cleanup();\n reject(reasonOf(e.target as AbortSignal));\n },\n { signal: call.signal }\n );\n // The caller's abort (D3): the clip goes for good, and the call rejects.\n callerSignal?.addEventListener(\n 'abort',\n () => {\n cleanup();\n this._discardAddedClip(trackId, clipId);\n reject(reasonOf(callerSignal));\n },\n { signal: call.signal }\n );\n this._awaitedClips.set(clipId, {\n trackId,\n reject: (error) => {\n cleanup();\n reject(error);\n },\n });\n if (this._isEntered(trackId)) {\n seen = true;\n this._loadAndAppendClip(trackId, clipDesc);\n } else if (pending) {\n // It enters with its track.\n this._pending = new Map(this._pending).set(\n trackId,\n 'element' in pending\n ? { ...pending, extraClips: [...pending.extraClips, clipDesc] }\n : {\n ...pending,\n descriptor: {\n ...pending.descriptor,\n clips: [...pending.descriptor.clips, clipDesc],\n },\n }\n );\n }\n });\n }\n /**\n * Remove a clip by id: its `<daw-clip>` when there is one (the observer\n * removes the clip, as `select.remove(i)` removes an option), otherwise\n * the clip itself, one undo step. Undo brings the clip back with no\n * element. No-op with a warning when there is no such clip.\n */\n removeClip(trackId: string, clipId: string): void {\n const trackEl = this._trackElements.get(trackId);\n const clipEl = trackEl\n ? ([...trackEl.querySelectorAll('daw-clip')].find(\n (c) => (c as DawClipElement).clipId === clipId\n ) as DawClipElement | undefined)\n : undefined;\n if (clipEl) {\n clipEl.remove();\n // Detached, the MutationObserver is off: remove the clip here.\n if (!this.isConnected && this._isEntered(trackId)) this._removeClipFromTrack(trackId, clipId);\n return;\n }\n if (this._isEntered(trackId)) {\n this._removeClipFromTrack(trackId, clipId);\n return;\n }\n // A clip addClip() gave a track that has not entered yet.\n const pending = this._pending.get(trackId);\n if (pending) {\n const without = (clips: ClipDescriptor[]) => clips.filter((c) => c.clipId !== clipId);\n this._pending = new Map(this._pending).set(\n trackId,\n 'element' in pending\n ? { ...pending, extraClips: without(pending.extraClips) as DropClipDescriptor[] }\n : {\n ...pending,\n descriptor: { ...pending.descriptor, clips: without(pending.descriptor.clips) },\n }\n );\n this._rejectAwaitedClips((id) => id === clipId, 'the clip was removed before it loaded');\n return;\n }\n console.warn(\n '[dawcore] removeClip: no track found for id \"' + trackId + '\" (clipId \"' + clipId + '\")'\n );\n }\n /**\n * Change a clip's position (start/duration/offset), gain or name: one undo\n * step on the arrangement (#848; a clip still loading changes its loading\n * clip). A `<daw-clip>`'s properties show the change, its attributes do\n * not. Fades are a `<daw-clip>` declaration only (engine-side fades are\n * #489): `fadeIn` / `fadeOut` / `fadeType` here change nothing.\n *\n * Re-decoding (changing `src`) is not supported via this method — remove and\n * re-add the clip instead.\n */\n updateClip(trackId: string, clipId: string, partial: Partial<ClipConfig>): void {\n if (!this._isEntered(trackId)) {\n console.warn('[dawcore] updateClip: no track found for id \"' + trackId + '\"');\n return;\n }\n if (!this._clipValues(trackId, clipId)) {\n console.warn(\n '[dawcore] updateClip: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n const request: Partial<ClipLinkValues> = {};\n if (partial.start !== undefined) request.start = partial.start;\n if (partial.duration !== undefined) request.duration = partial.duration;\n if (partial.offset !== undefined) request.offset = partial.offset;\n if (partial.gain !== undefined) request.gain = partial.gain;\n if (partial.name !== undefined) request.name = partial.name;\n if (partial.midiNotes !== undefined) request.midiNotes = partial.midiNotes;\n if (partial.midiChannel !== undefined) request.midiChannel = partial.midiChannel;\n if (partial.midiProgram !== undefined) request.midiProgram = partial.midiProgram;\n this._requestClipChange(trackId, clipId, request);\n }\n // --- Playback ---\n /**\n * Start playback, optionally seeking to `startTime` first. When `endTime`\n * is provided, playback stops at that time (selection/annotation playback).\n */\n async play(startTime?: number, endTime?: number) {\n try {\n const engine = await this._ensureEngine();\n // Always init — resumes AudioContext if suspended (requires user gesture).\n await engine.init();\n // Register the editor's rAF loop BEFORE starting the low-level engine\n // playback: the catch block below relies on it having been started so\n // it can undo it. Bounded play(start, end) completion does NOT depend\n // on this loop racing the transport: the native transport's timer runs\n // in a Worker (not rAF, #636) and reports its endTime self-stop through\n // the adapter's onPlaybackEnded hook → engine 'stop' → the daw-stop\n // dispatch in the engine stop handler. This loop's own time >= endTime\n // check is a belt-and-braces path for adapters without the hook.\n this._activePlayEndTime = endTime ?? null;\n this._startPlayhead();\n engine.play(startTime, endTime);\n this.dispatchEvent(new CustomEvent('daw-play', { bubbles: true, composed: true }));\n } catch (err) {\n // _startPlayhead() above runs BEFORE engine.play() (see the ordering\n // comment above), so a throwing engine.play() (EditorEngine rolls\n // back its own state and rethrows on adapter.play() failure) leaves a\n // dangling rAF loop unless we undo the pre-start here — mirrors stop().\n this._stopPlayhead();\n this._activePlayEndTime = null;\n console.warn('[dawcore] Playback failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'play', error: err },\n })\n );\n }\n }\n pause() {\n if (!this._engine) return;\n this._engine.pause();\n this._stopPlayhead();\n this.dispatchEvent(new CustomEvent('daw-pause', { bubbles: true, composed: true }));\n }\n stop() {\n if (!this._engine) return;\n this._activePlayEndTime = null;\n // The engine 'stop' handler fires SYNCHRONOUSLY during engine.stop() —\n // bracket it so that handler's own daw-stop dispatch is suppressed and\n // this method remains the single dispatcher for a consumer-initiated stop.\n this._inConsumerStop = true;\n try {\n this._engine.stop();\n } finally {\n this._inConsumerStop = false;\n }\n this._stopPlayhead();\n this.dispatchEvent(new CustomEvent('daw-stop', { bubbles: true, composed: true }));\n }\n /** Toggle between play and pause. */\n togglePlayPause() {\n if (this.isRecording) {\n this.togglePauseRecording();\n } else if (this._isPlaying) {\n this.pause();\n } else {\n this.play();\n }\n }\n /** Run `fn` with the stop-settle daw-timeupdate suppressed. Every\n * stop-adjacent code path that immediately re-positions (seek, split,\n * empty-timeline rewind) must use this — engine.stop() rewinds to the\n * play-start position and the settle would leak a backward-jumping\n * daw-timeupdate to consumers (CLAUDE.md seek-while-playing invariant).\n * The `finally` is load-bearing: a wedged true silently drops every\n * subsequent stop-settle dispatch. */\n private _withSeekSuppression(fn: () => void) {\n this._inSeekTransition = true;\n try {\n fn();\n } finally {\n this._inSeekTransition = false;\n }\n }\n\n seekTo(time: number) {\n if (!this._engine) {\n console.warn('[dawcore] seekTo: engine not ready, call ignored');\n return;\n }\n if (!Number.isFinite(time)) {\n // NaN would reach the adapter clock and wedge playback until a valid seek.\n console.warn('[dawcore] seekTo: ignoring non-finite time ' + String(time));\n return;\n }\n const target = Math.max(0, time);\n if (this._isPlaying) {\n // Transport needs stop+play to reschedule audio sources at the new\n // position — but via DIRECT engine calls (synchronous), not the public\n // stop()/play(): those dispatch daw-stop/daw-play (spurious for a\n // seek — consumers keyed on them misfire on every programmatic seek)\n // and the async play() opens a window where a user pause is overridden\n // by the deferred play. The engine is already initialized while\n // playing. Mirrors the pointer-handler seek path.\n try {\n this._withSeekSuppression(() => this._engine!.stop());\n this._engine.play(target);\n } catch (err) {\n // The engine rethrows adapter failures — surface via daw-error like\n // the public play() path does, instead of an unheralded throw.\n console.warn('[dawcore] seekTo: engine reschedule failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'seek', error: err },\n })\n );\n return;\n }\n // Seeking past a bounded (selection/annotation) play reschedules via\n // the engine directly (no endTime) — clear the stale watermark so\n // the rAF loop doesn't stop the resumed playback prematurely at the\n // old bound. Mirrors Transport.seek()'s own _endTime clearing.\n this._activePlayEndTime = null;\n this._currentTime = target;\n this._startPlayhead();\n } else {\n this._engine.seek(target);\n this._currentTime = target;\n this._stopPlayhead();\n }\n this.dispatchEvent(\n new CustomEvent('daw-seek', {\n bubbles: true,\n composed: true,\n detail: { time: target },\n })\n );\n }\n\n /**\n * A clip or track drag is in progress: undo and redo do nothing until it\n * ends (#848). A clip counts once its pointer has moved past the drag\n * threshold; annotation drags do not count (annotations are not in the\n * undo history).\n */\n get _dragInProgress(): boolean {\n return this._clipPointer.isDragging || this._trackReorderDrag.isActive;\n }\n\n /**\n * Cancel every drag in progress, as a `pointercancel` would. Returns whether\n * one was. A clip or annotation press that has not moved is not a drag and\n * is left alone, unless `includePresses` (the editor's disconnect, which\n * ends every pointer interaction).\n */\n _cancelDrags(includePresses = false): boolean {\n let cancelled = false;\n if (includePresses || this._clipPointer.isDragging) {\n cancelled = this._pointer.cancelClipDrag() || cancelled;\n }\n if (this._trackReorderDrag.isActive) {\n this._trackReorderDrag.cancel();\n cancelled = true;\n }\n const annotation = this._annotationDrag;\n if (includePresses ? annotation.isActive : annotation.isDragging) {\n annotation.cancel();\n cancelled = true;\n }\n return cancelled;\n }\n\n /**\n * Escape during a drag cancels it and does nothing else: the default is\n * prevented, so `<daw-keyboard-shortcuts>` (core's `handleKeyboardEvent`)\n * does not also stop playback. No `stopPropagation`: an app's own listener\n * can read `defaultPrevented`.\n */\n private _onDragEscape = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n if (this._cancelDrags()) e.preventDefault();\n };\n\n /** Undo the last edit. Does nothing while a drag is in progress. */\n undo(): void {\n if (this._dragInProgress) return;\n if (!this._engine) {\n console.warn('[dawcore] undo: engine not ready, call ignored');\n return;\n }\n this._engine.undo();\n }\n\n /** Redo the last undone edit. Does nothing while a drag is in progress. */\n redo(): void {\n if (this._dragInProgress) return;\n if (!this._engine) {\n console.warn('[dawcore] redo: engine not ready, call ignored');\n return;\n }\n this._engine.redo();\n }\n\n /** Whether undo is available. */\n get canUndo(): boolean {\n return this._engine?.canUndo ?? false;\n }\n\n /** Whether redo is available. */\n get canRedo(): boolean {\n return this._engine?.canRedo ?? false;\n }\n\n /** Split the clip under the playhead on the selected track. */\n splitAtPlayhead(): boolean {\n return performSplitAtPlayhead({\n effectiveSampleRate: this.effectiveSampleRate,\n currentTime: this.currentTime,\n isPlaying: this._isPlaying,\n engine: this._engine,\n dispatchEvent: (e: Event) => this.dispatchEvent(e),\n stop: () => {\n // Suppressed settle: without it every split during playback leaks a\n // backward-jumping daw-timeupdate (30→0→30) before play(time) resumes.\n this._withSeekSuppression(() => {\n this._engine?.stop();\n this._stopPlayhead();\n });\n },\n // Call engine.play directly (synchronous) — not the async editor play()\n // which yields to microtask queue via await engine.init(). Engine is\n // already initialized at split time; the async gap causes audio desync.\n play: (time: number) => {\n this._engine?.play(time);\n this._startPlayhead();\n },\n });\n }\n\n // --- Recording ---\n recordingStream: MediaStream | null = null;\n get currentTime(): number {\n // During playback, read live from engine (not cached _currentTime)\n if (this._isPlaying && this._engine) {\n return this._engine.getCurrentTime();\n }\n return this._currentTime;\n }\n /** Read-only: whether playback is running (HTMLMediaElement-adjacent). */\n get isPlaying(): boolean {\n return this._isPlaying;\n }\n /** Read-only: total content duration in seconds. */\n get duration(): number {\n return this._duration;\n }\n get isRecording(): boolean {\n return this._recordingController.isRecording;\n }\n get isRecordingPaused(): boolean {\n return this._recordingController.isPaused;\n }\n pauseRecording(): void {\n this._recordingController.pauseRecording();\n }\n resumeRecording(): void {\n this._recordingController.resumeRecording();\n // Programmatic resume bypasses togglePauseRecording — clear the\n // ref so the next pause cycle doesn't restart Transport based on\n // stale state from an earlier toggle.\n this._wasPlayingDuringRecording = false;\n }\n /**\n * Audacity-style pause toggle for active recordings: pauses both the\n * worklet capture and (if running) the playback Transport. On resume,\n * Transport restarts only if it was running before — non-overdub\n * recordings stay silent on resume.\n */\n togglePauseRecording(): void {\n if (!this.isRecording) return;\n if (this.isRecordingPaused) {\n // Snapshot the flag before resumeRecording — that method clears\n // the ref defensively (so external callers don't leak it into the\n // next cycle), so reading after the call is too late.\n const wasPlaying = this._wasPlayingDuringRecording;\n this.resumeRecording();\n if (wasPlaying) {\n // play() is async on the editor; fire and forget — caller doesn't await.\n void this.play(this.currentTime);\n }\n } else {\n this.pauseRecording();\n if (this._isPlaying) {\n this._wasPlayingDuringRecording = true;\n this.pause();\n }\n }\n }\n /** Set in togglePauseRecording when Transport is paused alongside the\n * worklet, so resume can restart it. Cleared on resume and on stop. */\n private _wasPlayingDuringRecording = false;\n stopRecording(): Promise<void> {\n this._wasPlayingDuringRecording = false;\n return this._recordingController.stopRecording();\n }\n _addRecordedClip(\n trackId: string,\n buf: AudioBuffer,\n startSample: number,\n durSamples: number,\n offsetSamples = 0,\n clipName?: string\n ) {\n addRecordedClip(this, trackId, buf, startSample, durSamples, offsetSamples, clipName);\n }\n // --- RecordingHost bridge methods for cross-context worklet support ---\n // These delegate to the adapter's context type (native or standardized-audio-context).\n // The RecordingController calls these when available, falling back to native APIs.\n\n addWorkletModule(url: string): Promise<void> {\n return (\n this._externalAdapter?.addWorkletModule?.(url) ??\n this.audioContext.audioWorklet.addModule(url)\n );\n }\n\n createAudioWorkletNode(name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode {\n return (\n this._externalAdapter?.createAudioWorkletNode?.(name, options) ??\n new AudioWorkletNode(this.audioContext, name, options)\n );\n }\n\n createMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode {\n return (\n this._externalAdapter?.createMediaStreamSource?.(stream) ??\n this.audioContext.createMediaStreamSource(stream)\n );\n }\n\n async startRecording(stream?: MediaStream, options?: RecordingOptions): Promise<void> {\n const s = stream ?? this.recordingStream;\n if (!s) {\n console.warn('[dawcore] startRecording: no stream provided and recordingStream is null');\n return;\n }\n // A take is audio: it cannot land on a MIDI track (#756).\n const targetId = options?.trackId ?? this._selectedTrackId;\n const target = targetId\n ? this._arrangement.getTracks().find((t) => t.id === targetId)\n : undefined;\n if (targetId && target && trackKind(target) === 'midi') {\n const error = new Error(\n 'Cannot record onto MIDI track \"' +\n target.name +\n '\": a recording is audio. Select or create an audio track first.'\n );\n console.warn('[dawcore] startRecording: ' + error.message);\n this.dispatchEvent(\n new CustomEvent<DawRecordingErrorDetail>('daw-recording-error', {\n bubbles: true,\n composed: true,\n detail: { trackId: targetId, error },\n })\n );\n return;\n }\n await this._recordingController.startRecording(s, options);\n }\n\n /** Live-recording preview left/width. Beats mode uses the same tick-space\n * math as finalized clips — the sample÷renderSpp path is ceil-quantized,\n * so the take would visibly jump sideways on finalization (drift grows\n * with distance from t=0; CLAUDE.md live-preview parity invariant). */\n private _previewPosition(\n startSample: number,\n audibleSamples: number\n ): { left: number; width: number } {\n if (this.scaleMode === 'beats') {\n const sr = this.effectiveSampleRate;\n const startSec = startSample / sr;\n const startTick = this._secondsToTicks(startSec);\n const endTick = this._secondsToTicks(startSec + audibleSamples / sr);\n const left = Math.round(startTick / this.ticksPerPixel);\n return { left, width: Math.round(endTick / this.ticksPerPixel) - left };\n }\n const renderSpp = this._renderSpp;\n return {\n left: Math.floor(startSample / renderSpp),\n width: Math.floor(audibleSamples / renderSpp),\n };\n }\n\n private _renderRecordingPreview(trackId: string, chH: number) {\n const rs = this._recordingController.getSession(trackId);\n if (!rs) return '';\n // Skip latency samples in the preview — they'll be sliced on finalization.\n // Position stays at startSample (same as finalized clip).\n const audibleSamples = Math.max(0, rs.totalSamples - rs.latencySamples);\n if (audibleSamples === 0) return '';\n const renderSpp = this._renderSpp;\n const latencyPixels = Math.floor(rs.latencySamples / renderSpp);\n const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);\n // Same container + header chrome as finalized clips so the take reads as\n // a clip WHILE it's being captured, and the waveforms sit at the same\n // vertical offset they'll have after finalization. The container's width\n // stays in sync with the growing take: the RecordingController calls\n // requestUpdate() whenever the preview grows a pixel (overflow:hidden on\n // .clip-container would otherwise clip the live canvas growth).\n const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;\n const height = hdrH + chH * rs.peaks.length;\n return html`<div\n class=\"clip-container recording-preview\"\n style=\"left:${left}px;top:0;width:${w}px;height:${height}px;\"\n >\n ${hdrH > 0\n ? html`<div class=\"clip-header\" data-track-id=${trackId}>\n <span>${rs.clipName ?? 'Recording…'}</span>\n </div>`\n : ''}\n ${rs.peaks.map((chPeaks, ch) => {\n // Slice peaks to skip latency prefix (2 entries per pixel: min/max)\n const slicedPeaks = latencyPixels > 0 ? chPeaks.slice(latencyPixels * 2) : chPeaks;\n return html`\n <daw-waveform\n data-recording-track=${trackId}\n data-recording-channel=${ch}\n style=\"position:absolute;left:0;top:${hdrH + ch * chH}px;\"\n .peaks=${slicedPeaks}\n .length=${w}\n .waveHeight=${chH}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${left}\n ></daw-waveform>\n `;\n })}\n </div>`;\n }\n // --- Playback animation (single RAF loop: playhead + daw-timeupdate) ---\n /** Convert playback seconds to a timeline pixel offset for the active mode. */\n private _timeToPixels = (time: number): number => {\n if (this.scaleMode === 'beats') {\n return this._secondsToTicks(time) / this.ticksPerPixel;\n }\n return (time * this.effectiveSampleRate) / this.samplesPerPixel;\n };\n\n _startPlayhead() {\n if (!this._engine) return;\n const engine = this._engine;\n // engine.getAudibleTime(): while playing, engine time minus hardware DAC\n // latency (outputLatency) and scheduler lookahead (0.1s on Tone-backed\n // adapters, 0 native), held at the play-start position during the\n // pre-roll window. Without the subtraction the playhead leads audio by\n // ~100ms with the Tone adapter.\n // Runs even when the playhead element isn't rendered (empty/indefinite\n // editors) so daw-timeupdate consumers still get frames.\n this._playbackAnimation.start(() => {\n // Bounded playback (selection/annotation via play(start, end)): an\n // adapter with the onPlaybackEnded hook reports its endTime self-stop\n // through the engine's `stop` event; this check is the fallback for\n // adapters without it. Checked before the whole-track duration bound\n // below.\n if (\n this._activePlayEndTime !== null &&\n !this.isRecording &&\n engine.getCurrentTime() >= this._activePlayEndTime\n ) {\n this.stop();\n const t = this._currentTime;\n return Number.isFinite(t) ? Math.max(0, t) : 0;\n }\n // Auto-stop at the end of the timeline (player-style default — parity\n // with the React provider's animation loop). `indefinite-playback`\n // opts out (DAW-style: roll until explicit stop), and an active\n // recording session must run past the end of existing material\n // (punch-in takes land beyond the current duration). Raw engine time\n // is the boundary check, matching React's loop.\n if (\n !this.indefinitePlayback &&\n !this.isRecording &&\n engine.getCurrentTime() >= this._duration\n ) {\n this.stop();\n // stop() rewinds to the play-start position via the engine 'stop'\n // handler; settle this frame on that resting position.\n const t = this._currentTime;\n return Number.isFinite(t) ? Math.max(0, t) : 0;\n }\n return engine.getAudibleTime();\n });\n }\n _stopPlayhead() {\n // Resting playhead displays the raw position — latency compensation is a\n // playback-time concept (Transport scheduling vs audible output). A\n // seeked/stopped/paused cursor shows exactly the commanded position.\n // Storage (`_currentTime`) is already raw, so play() resumes correctly.\n const t = this._currentTime;\n const visualTime = Number.isFinite(t) ? Math.max(0, t) : 0;\n this._playbackAnimation.stop(visualTime, { dispatch: !this._inSeekTransition });\n }\n private _getPlayhead(): DawPlayheadElement | null {\n return this.shadowRoot?.querySelector('daw-playhead') as DawPlayheadElement | null;\n }\n\n /** True when the controls column should be rendered (and its selector is valid). */\n private get _showControls(): boolean {\n return this._getOrderedTracks().length > 0 || this.indefinitePlayback || this.fillViewport;\n }\n\n /** True when the ruler header band should be rendered (and its selector is valid). */\n private get _showRuler(): boolean {\n return (\n (this._getOrderedTracks().length > 0 ||\n this.scaleMode === 'beats' ||\n this.indefinitePlayback ||\n this.fillViewport) &&\n this.timescale\n );\n }\n\n /**\n * `<daw-track>` elements the page moved (one MutationObserver batch): each\n * is placed after the arrangement track of the nearest `<daw-track>` before\n * it, in DOM order, as one undo step (#848 P13). Elements whose track is\n * not in the arrangement are left alone (a queued one enters at its DOM\n * position). The arrangement's own order changes (an Undo) move no element.\n */\n private _placeMovedTracks(movedIds: ReadonlySet<string>): void {\n const els = [...this.querySelectorAll('daw-track')] as DawTrackElement[];\n const moved = els.filter((el) => movedIds.has(el.trackId) && this._isEntered(el.trackId));\n if (moved.length === 0) return;\n const arrangement = this._arrangement;\n arrangement.beginTransaction();\n try {\n for (const el of moved) {\n const others = arrangement\n .getTracks()\n .map((t) => t.id)\n .filter((id) => id !== el.trackId);\n // The index it already has changes nothing.\n arrangement.reorderTrack(el.trackId, entryIndex(els, el.trackId, others));\n }\n } finally {\n arrangement.commitTransaction();\n }\n }\n\n /**\n * The rows, in the arrangement's order (#848): each track's loaded clips\n * (the engine's projection, with the current mix) and the clips still loading.\n */\n private _getOrderedTracks(): Array<[string, ClipTrack, LoadingClip[]]> {\n const rows: Array<[string, ClipTrack, LoadingClip[]]> = [];\n for (const track of this._arrangement.getTracks()) {\n const loaded = loadedTrack(\n track,\n this._mixOf(track.id),\n this._arrangement.recordingTrackIds.has(track.id)\n );\n rows.push([track.id, loaded, track.clips.filter(isLoadingClip)]);\n }\n return rows;\n }\n /**\n * A clip still loading: a placeholder box where its length is known, with\n * its `.dat` peaks when they came, drawn failed when its source failed. Its\n * header carries no clip id, so it cannot be dragged.\n */\n private _renderPlaceholder(\n clip: LoadingClip,\n row: { trackId: string; trackHeight: number; descriptor?: RowInfo }\n ) {\n const seconds = this._placeholderSeconds(clip);\n if (seconds === null) return '';\n const sr = this.effectiveSampleRate;\n const spp = this._renderSpp;\n const startSec = clip.start ?? 0;\n let left: number;\n let width: number;\n if (this.scaleMode === 'beats') {\n left = Math.round(this._secondsToTicks(startSec) / this.ticksPerPixel);\n width = Math.round(this._secondsToTicks(startSec + seconds) / this.ticksPerPixel) - left;\n } else {\n const startSample = Math.round(startSec * sr);\n left = Math.floor(startSample / spp);\n width = clipPixelWidth(startSample, Math.round(seconds * sr), spp);\n }\n const failed =\n this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === 'failed';\n const peakData = this._previewPeaks.get(clip.id);\n const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;\n const chH = this.waveHeight;\n return html`<div\n class=\"clip-container placeholder ${failed ? 'failed' : ''}\"\n style=\"left:${left}px;top:0;width:${width}px;height:${row.trackHeight}px;\"\n data-clip-id=${clip.id}\n >\n ${hdrH > 0\n ? html`<div class=\"clip-header\">\n <span>${clip.name || row.descriptor?.name || ''}</span>\n </div>`\n : ''}\n ${(peakData?.data ?? []).map(\n (chPeaks, chIdx) =>\n html`<daw-waveform\n style=\"position:absolute;left:0;top:${hdrH + chIdx * chH}px;\"\n .peaks=${chPeaks}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${left}\n ></daw-waveform>`\n )}\n </div>`;\n }\n\n // --- Render ---\n render() {\n const sr = this.effectiveSampleRate;\n const spp = this._renderSpp;\n // In beats mode, derive selection pixels from tick space (same as clip positions)\n // to avoid 1-2px quantization error from the sample round-trip.\n let selStartPx: number;\n let selEndPx: number;\n if (this.scaleMode === 'beats') {\n const startTick = this._secondsToTicks(this._selectionStartTime);\n const endTick = this._secondsToTicks(this._selectionEndTime);\n selStartPx = startTick / this.ticksPerPixel;\n selEndPx = endTick / this.ticksPerPixel;\n } else {\n selStartPx = (this._selectionStartTime * sr) / spp;\n selEndPx = (this._selectionEndTime * sr) / spp;\n }\n\n // Precompute track info once for both controls column and timeline\n const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {\n // What the template reads about the track: from the arrangement and the extras.\n const descriptor: RowInfo = {\n name: track.name ?? '',\n kind: trackKind(track),\n renderMode: this._renderModeOf(trackId),\n };\n const firstPeaks = [...track.clips, ...loading]\n .map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id))\n .find((p) => p && p.data.length > 0);\n // Use recording session channel count if no finalized clips yet\n const recSession = this._recordingController.getSession(trackId);\n const numChannels = firstPeaks\n ? firstPeaks.data.length\n : recSession\n ? recSession.channelCount\n : 1;\n return {\n trackId,\n track,\n loading,\n descriptor,\n numChannels,\n trackHeight: this.waveHeight * numChannels + (this.clipHeaders ? this.clipHeaderHeight : 0),\n };\n });\n\n const showControls = this._showControls;\n const showRuler = this._showRuler;\n\n return html`\n ${showRuler\n ? html`<div class=\"header-row\" style=\"height: ${RULER_HEIGHT}px;\">\n ${showControls ? html`<div class=\"ruler-gap\"></div>` : ''}\n <div class=\"ruler-viewport\" @pointerdown=${this._pointer.onPointerDown}>\n <div\n class=\"ruler-content\"\n style=\"width: ${this._totalWidth > 0 ? this._totalWidth + 'px' : '100%'};\"\n >\n <daw-ruler\n .samplesPerPixel=${spp}\n .sampleRate=${this.effectiveSampleRate}\n .duration=${this._duration}\n .scaleMode=${this.scaleMode}\n .ticksPerPixel=${this.ticksPerPixel}\n .meterEntries=${this._meterEntries}\n .ppqn=${this.ppqn}\n .totalWidth=${this._totalWidth}\n .rulerHeight=${RULER_HEIGHT}\n ></daw-ruler>\n </div>\n </div>\n </div>`\n : ''}\n <div class=\"body\">\n ${showControls\n ? html`<div class=\"controls-viewport\">\n <div class=\"controls-column\">\n ${this._annotations.tracks.map(\n (track) =>\n html`<div\n class=\"annotation-lane-spacer\"\n style=\"height: ${ANNOTATION_LANE_HEIGHT}px;\"\n >\n <span class=\"annotation-lane-name\">${track.name}</span>\n </div>`\n )}\n ${repeat(\n orderedTracks,\n // Keyed by track: a swap or an outside reorder must not hand\n // a row (and a slider gesture held in it) to another track.\n (t) => t.trackId,\n (t, i) => {\n const mix = this._mixOf(t.trackId);\n return html`\n <daw-track-controls\n style=\"height: ${t.trackHeight}px;\"\n .trackId=${t.trackId}\n .trackName=${t.descriptor?.name ?? 'Untitled'}\n .volume=${mix.volume}\n .pan=${mix.pan}\n .muted=${mix.muted}\n .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}\n .soloed=${mix.soloed}\n .reorderable=${this.trackReordering}\n .trackIndex=${i}\n .trackCount=${orderedTracks.length}\n ></daw-track-controls>\n `;\n }\n )}\n </div>\n </div>`\n : ''}\n <div class=\"scroll-area\">\n <div\n class=\"timeline ${this._dragOver ? 'drag-over' : ''}\"\n style=\"width: ${this._totalWidth > 0 ? this._totalWidth + 'px' : '100%'};\"\n data-playing=${this._isPlaying}\n @pointerdown=${this._pointer.onPointerDown}\n @dragover=${this._onDragOver}\n @dragleave=${this._onDragLeave}\n @drop=${this._onDrop}\n >\n ${this._annotations.renderLanes(\n spp,\n this.effectiveSampleRate,\n this._annotationDrag.onPointerDown,\n this.scaleMode === 'beats' ? this.ticksPerPixel : null\n )}\n ${this.scaleMode === 'beats'\n ? html`<daw-grid\n style=\"top: ${this._annotations.totalLaneHeight}px;\"\n .ticksPerPixel=${this.ticksPerPixel}\n .meterEntries=${this._meterEntries}\n .ppqn=${this.ppqn}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .length=${this._totalWidth}\n .height=${orderedTracks.length > 0\n ? orderedTracks.reduce((sum, t) => sum + t.trackHeight, 0)\n : this._emptyGridHeight}\n ></daw-grid>`\n : ''}\n ${orderedTracks.length > 0 ||\n this.scaleMode === 'beats' ||\n this.indefinitePlayback ||\n this.fillViewport\n ? html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>\n <daw-playhead></daw-playhead>`\n : ''}\n ${repeat(\n orderedTracks,\n (t) => t.trackId,\n (t) => {\n const channelHeight = this.waveHeight;\n return html`\n <div\n class=\"track-row ${t.trackId === this._selectedTrackId ? 'selected' : ''}\"\n style=\"height: ${t.trackHeight}px;\"\n data-track-id=${t.trackId}\n >\n ${t.track.clips.map((clip) => {\n const peakData =\n this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);\n // In beats mode, derive pixel positions from tick space to\n // match grid lines exactly. The sample→spp path introduces\n // 1-2px quantization error from integer sample rounding.\n let clipLeft: number;\n let width: number;\n if (this.scaleMode === 'beats') {\n // Use startTick directly when available — stable across BPM changes.\n // Fall back to sample→seconds→ticks for clips without startTick.\n const startTick =\n clip.startTick !== undefined\n ? clip.startTick\n : this._secondsToTicks(clip.startSample / sr);\n const durSec = clip.durationSamples / sr;\n const startSec =\n clip.startTick !== undefined\n ? this._ticksToSeconds(clip.startTick)\n : clip.startSample / sr;\n const endTick = this._secondsToTicks(startSec + durSec);\n clipLeft = Math.round(startTick / this.ticksPerPixel);\n width = Math.round(endTick / this.ticksPerPixel) - clipLeft;\n } else {\n clipLeft = Math.floor(clip.startSample / spp);\n width = clipPixelWidth(clip.startSample, clip.durationSamples, spp);\n }\n // Per-segment waveform rendering for variable tempo.\n // Uses base-scale (128) peaks directly — segments handle stretching,\n // so no BPM-dependent intermediate resampling needed.\n let clipSegments: WaveformSegment[] | undefined;\n let segmentChannels: Peaks[] | undefined;\n if (this.scaleMode === 'beats' && this.secondsToTicks) {\n const audioBuffer = this._clipBuffers.get(clip.id);\n const basePeaks = audioBuffer\n ? this._peakPipeline.getBaseScalePeaks(\n audioBuffer,\n this.mono,\n clip.offsetSamples,\n clip.durationSamples\n )\n : null;\n if (basePeaks) {\n const baseScale = basePeaks.scale;\n segmentChannels = basePeaks.peaks.data;\n const MIN_RENDER_STEP = 80;\n const stepTicks = Math.max(\n MIN_RENDER_STEP,\n Math.ceil(this.ticksPerPixel)\n );\n const startSec =\n clip.startTick !== undefined\n ? this._ticksToSeconds(clip.startTick)\n : clip.startSample / sr;\n const clipOffsetSec = clip.offsetSamples / sr;\n const segStartTick =\n clip.startTick !== undefined\n ? clip.startTick\n : this._secondsToTicks(startSec);\n const endTick = this._secondsToTicks(\n startSec + clip.durationSamples / sr\n );\n clipSegments = [];\n for (let tick = segStartTick; tick < endTick; tick += stepTicks) {\n const segEndTick = Math.min(tick + stepTicks, endTick);\n const segStartAudioSec =\n this._ticksToSeconds(tick) - startSec + clipOffsetSec;\n const segEndAudioSec =\n this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;\n // Peak indices at base scale (128) — clamped to valid range.\n const segStartSample = Math.round(segStartAudioSec * sr);\n const segEndSample = Math.round(segEndAudioSec * sr);\n const totalPeaks = clip.durationSamples / baseScale;\n clipSegments.push({\n peakStart: Math.max(\n 0,\n (segStartSample - clip.offsetSamples) / baseScale\n ),\n peakEnd: Math.min(\n totalPeaks,\n (segEndSample - clip.offsetSamples) / baseScale\n ),\n pixelStart: (tick - segStartTick) / this.ticksPerPixel,\n pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel,\n });\n }\n }\n }\n const channels: Peaks[] = segmentChannels ??\n peakData?.data ?? [new Int16Array(0)];\n const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;\n const chH = this.waveHeight;\n return html` <div\n class=\"clip-container\"\n style=\"left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;\"\n data-clip-id=${clip.id}\n >\n ${hdrH > 0\n ? html`<div\n class=\"clip-header\"\n data-clip-id=${clip.id}\n data-track-id=${t.trackId}\n ?data-interactive=${this.interactiveClips}\n >\n <span>${clip.name || t.descriptor?.name || ''}</span>\n </div>`\n : ''}\n ${t.descriptor?.kind === 'midi'\n ? html`<daw-piano-roll\n style=\"position:absolute;left:0;top:${hdrH}px;\"\n .midiNotes=${clip.midiNotes ?? []}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH * channels.length}\n .samplesPerPixel=${this._renderSpp}\n .sampleRate=${this.effectiveSampleRate}\n .clipOffsetSeconds=${(clip.offsetSamples ?? 0) /\n this.effectiveSampleRate}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${clipLeft}\n ?selected=${t.trackId === this._selectedTrackId}\n ></daw-piano-roll>`\n : t.descriptor?.renderMode === 'spectrogram'\n ? channels.map(\n (_chPeaks, chIdx) =>\n html`<daw-spectrogram\n style=\"position:absolute;left:0;top:${hdrH +\n chIdx * chH}px;height:${chH}px;width:${peakData?.length ??\n width}px;\"\n .clipId=${clip.id}\n .trackId=${t.trackId}\n .channelIndex=${chIdx}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH}\n .samplesPerPixel=${this._renderSpp}\n .sampleRate=${this.effectiveSampleRate}\n .clipOffsetSeconds=${(clip.offsetSamples ?? 0) /\n this.effectiveSampleRate}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${clipLeft}\n ></daw-spectrogram>`\n )\n : channels.map(\n (chPeaks, chIdx) =>\n html` <daw-waveform\n style=\"position:absolute;left:0;top:${hdrH + chIdx * chH}px;\"\n .peaks=${chPeaks}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n .gain=${this.gainScaledWaveforms ? (clip.gain ?? 1) : 1}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${clipLeft}\n .segments=${clipSegments}\n ></daw-waveform>`\n )}\n ${this.interactiveClips\n ? html` <div\n class=\"clip-boundary\"\n data-boundary-edge=\"left\"\n data-clip-id=${clip.id}\n data-track-id=${t.trackId}\n ></div>\n <div\n class=\"clip-boundary\"\n data-boundary-edge=\"right\"\n data-clip-id=${clip.id}\n data-track-id=${t.trackId}\n ></div>`\n : ''}\n </div>`;\n })}\n ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}\n ${this._renderRecordingPreview(t.trackId, channelHeight)}\n </div>\n `;\n }\n )}\n </div>\n </div>\n </div>\n <slot></slot>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-editor': DawEditorElement;\n }\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 offset += 4;\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 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\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 console.warn('[dawcore] Failed to create peaks worker (CSP restriction?): ' + String(err));\n return {\n generate() {\n return Promise.reject(\n new Error(\n 'Peaks worker unavailable (CSP may block blob: URLs). Add blob: to worker-src directive.'\n )\n );\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 let idCounter = 0;\n\n worker.onmessage = (e: MessageEvent) => {\n const msg = e.data;\n const entry = pending.get(msg.id);\n if (!entry) {\n console.warn('[dawcore] Received worker message for unknown id: ' + String(msg.id));\n return;\n }\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 const reason = e.error ?? new Error(e.message);\n console.warn('[dawcore] Peaks worker crashed: ' + String(reason));\n terminated = true;\n worker.terminate();\n for (const [, entry] of pending) {\n entry.reject(reason);\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","/**\n * Utilities for converting WaveformData to PeakData format.\n * Adapted from @waveform-playlist/browser waveformDataLoader.ts.\n */\n\nimport WaveformData from 'waveform-data';\nimport type { PeakData, Peaks } from '@waveform-playlist/core';\n\n/**\n * Slice and resample WaveformData with aligned source indices.\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 const targetStart = Math.floor(offsetSamples / samplesPerPixel);\n const targetEnd = Math.ceil((offsetSamples + durationSamples) / samplesPerPixel);\n\n const sourceStart = Math.max(0, Math.floor(targetStart * ratio));\n const sourceEnd = Math.min(waveformData.length, Math.ceil(targetEnd * ratio));\n\n if (sourceStart >= sourceEnd) {\n return null;\n }\n\n processedData = processedData.slice({\n startIndex: sourceStart,\n endIndex: sourceEnd,\n });\n processedData = processedData.resample({ scale: samplesPerPixel });\n } else {\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, handling all channels, mono merging,\n * slicing, and resampling.\n */\nexport function extractPeaks(\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 const numChannels = isMono ? 1 : waveformData.channels;\n const emptyData: Peaks[] = Array.from({ length: numChannels }, () =>\n bits === 8 ? new Int8Array(0) : new Int16Array(0)\n );\n return { length: 0, data: emptyData, bits };\n }\n\n const numChannels = processedData.channels;\n const bits = processedData.bits as 8 | 16;\n\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 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 { length: numPeaks, data: [monoPeaks], bits };\n }\n\n const peakLength = channelPeaks.length > 0 ? channelPeaks[0].length / 2 : 0;\n return { length: peakLength, data: channelPeaks, bits };\n}\n","/**\n * Peak generation pipeline: AudioBuffer → web worker → WaveformData → PeakData.\n *\n * Manages worker lifecycle, WaveformData caching per AudioBuffer (WeakMap),\n * inflight dedup, and peak extraction via resample() for any zoom level\n * coarser than the base scale.\n *\n * The base scale determines the finest zoom level that can be rendered without\n * regenerating. Resampling only works to coarser (larger) scales. Set baseScale\n * to the finest zoom level the user might need.\n */\n\nimport type WaveformData from 'waveform-data';\nimport type { PeakData } from '@waveform-playlist/core';\nimport { createPeaksWorker, type PeaksWorkerApi } from './peaksWorker';\nimport { extractPeaks } from './waveformDataUtils';\n\nexport class PeakPipeline {\n private _worker: PeaksWorkerApi | null = null;\n private _cache = new WeakMap<AudioBuffer, WaveformData>();\n private _inflight = new WeakMap<AudioBuffer, Promise<WaveformData>>();\n private _baseScale: number;\n private _bits: 8 | 16;\n\n constructor(baseScale = 128, bits: 8 | 16 = 16) {\n this._baseScale = baseScale;\n this._bits = bits;\n }\n\n /**\n * Inject externally-loaded WaveformData (e.g., from a .dat file) into the cache.\n * Prevents worker generation for this AudioBuffer on all subsequent calls.\n */\n cacheWaveformData(audioBuffer: AudioBuffer, waveformData: WaveformData): void {\n this._cache.set(audioBuffer, waveformData);\n }\n\n /**\n * Generate PeakData for a clip from its AudioBuffer.\n * Uses cached WaveformData when available; otherwise generates via worker.\n * Worker generates at baseScale (default 128); extractPeaks resamples to the requested zoom.\n */\n async generatePeaks(\n audioBuffer: AudioBuffer,\n samplesPerPixel: number,\n isMono: boolean,\n offsetSamples?: number,\n durationSamples?: number\n ): Promise<PeakData> {\n const waveformData = await this._getWaveformData(audioBuffer);\n const effectiveScale = this._clampScale(waveformData, samplesPerPixel);\n try {\n return extractPeaks(waveformData, effectiveScale, isMono, offsetSamples, durationSamples);\n } catch (err) {\n console.warn('[dawcore] extractPeaks failed: ' + String(err));\n throw err;\n }\n }\n\n /**\n * Re-extract peaks for all clips at a new zoom level using cached WaveformData.\n * Returns a new Map of clipId → PeakData. Clips without cached data are skipped.\n * When the requested scale is finer than cached data, peaks are clamped to the\n * cached scale and a single summary warning is logged.\n */\n reextractPeaks(\n clipBuffers: ReadonlyMap<string, AudioBuffer>,\n samplesPerPixel: number,\n isMono: boolean,\n clipOffsets?: ReadonlyMap<string, { offsetSamples: number; durationSamples: number }>\n ): Map<string, PeakData> {\n const result = new Map<string, PeakData>();\n let clampedCount = 0;\n let clampedScale = 0;\n for (const [clipId, audioBuffer] of clipBuffers) {\n const cached = this._cache.get(audioBuffer);\n if (cached) {\n const effectiveScale = this._clampScale(cached, samplesPerPixel, false);\n if (effectiveScale !== samplesPerPixel) {\n clampedCount++;\n clampedScale = effectiveScale;\n }\n try {\n const offsets = clipOffsets?.get(clipId);\n result.set(\n clipId,\n extractPeaks(\n cached,\n effectiveScale,\n isMono,\n offsets?.offsetSamples,\n offsets?.durationSamples\n )\n );\n } catch (err) {\n console.warn('[dawcore] reextractPeaks failed for clip ' + clipId + ': ' + String(err));\n }\n }\n }\n if (clampedCount > 0) {\n console.warn(\n '[dawcore] Requested zoom ' +\n samplesPerPixel +\n ' spp is finer than pre-computed peaks (' +\n clampedScale +\n ' spp) — ' +\n clampedCount +\n ' clip(s) using available resolution'\n );\n }\n return result;\n }\n\n /**\n * Clamp requested scale to cached WaveformData scale.\n * WaveformData.resample() can only go coarser — if the requested zoom is\n * finer than the cached data, use the cached scale. Set warn=true to log\n * (default); reextractPeaks passes false and logs a single summary instead.\n */\n private _clampScale(waveformData: WaveformData, requestedScale: number, warn = true): number {\n if (requestedScale < waveformData.scale) {\n if (warn) {\n console.warn(\n '[dawcore] Requested zoom ' +\n requestedScale +\n ' spp is finer than pre-computed peaks (' +\n waveformData.scale +\n ' spp) — using available resolution'\n );\n }\n return waveformData.scale;\n }\n return requestedScale;\n }\n\n /**\n * Extract peaks at the base scale from cached WaveformData.\n * Returns null if no cached data exists for this buffer.\n * Used by variable-tempo segments which handle stretching themselves.\n */\n getBaseScalePeaks(\n audioBuffer: AudioBuffer,\n isMono: boolean,\n offsetSamples?: number,\n durationSamples?: number\n ): { peaks: PeakData; scale: number } | null {\n const cached = this._cache.get(audioBuffer);\n if (!cached) return null;\n return {\n peaks: extractPeaks(cached, cached.scale, isMono, offsetSamples, durationSamples),\n scale: cached.scale,\n };\n }\n\n /** Scale of the cached WaveformData for this buffer — 0 when not cached.\n * Worker generation caches at baseScale; injected .dat data at its own\n * scale. This is the finest zoom the buffer's peaks can render at. */\n getCachedScale(audioBuffer: AudioBuffer): number {\n return this._cache.get(audioBuffer)?.scale ?? 0;\n }\n\n /**\n * Return the coarsest (largest) scale among cached WaveformData entries\n * that correspond to the given clip buffers. Returns 0 if none are cached.\n */\n getMaxCachedScale(clipBuffers: ReadonlyMap<string, AudioBuffer>): number {\n let max = 0;\n for (const audioBuffer of clipBuffers.values()) {\n const cached = this._cache.get(audioBuffer);\n if (cached && cached.scale > max) max = cached.scale;\n }\n return max;\n }\n\n terminate() {\n this._worker?.terminate();\n this._worker = null;\n }\n\n private async _getWaveformData(audioBuffer: AudioBuffer): Promise<WaveformData> {\n const cached = this._cache.get(audioBuffer);\n if (cached) return cached;\n\n const inflight = this._inflight.get(audioBuffer);\n if (inflight) return inflight;\n\n // Also replace a crashed worker (onerror marks it terminated) — reusing\n // it would reject every later generatePeaks for the editor's lifetime.\n if (!this._worker || this._worker.isTerminated()) {\n this._worker = createPeaksWorker();\n }\n\n // Generate at baseScale — the finest zoom we can resample from\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 const promise = this._worker\n .generate({\n channels,\n length: audioBuffer.length,\n sampleRate: audioBuffer.sampleRate,\n scale: this._baseScale,\n bits: this._bits,\n splitChannels: true,\n })\n .then((waveformData) => {\n this._cache.set(audioBuffer, waveformData);\n this._inflight.delete(audioBuffer);\n return waveformData;\n })\n .catch((err) => {\n this._inflight.delete(audioBuffer);\n console.warn('[dawcore] Peak generation via worker failed: ' + String(err));\n throw err;\n });\n\n this._inflight.set(audioBuffer, promise);\n return promise;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { computeTemporalTicks, type TickData } from '../utils/smart-scale';\nimport { getCachedMusicalTicks } from '../utils/musical-tick-cache';\nimport type { MusicalTickData, MeterEntry } from '@waveform-playlist/core';\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n@customElement('daw-ruler')\nexport class DawRulerElement extends LitElement {\n @property({ type: Number, attribute: false }) samplesPerPixel = 1024;\n @property({ type: Number, attribute: false }) sampleRate = 48000;\n @property({ type: Number, attribute: false }) duration = 0;\n @property({ type: Number, attribute: false }) rulerHeight = 30;\n @property({ type: String, attribute: false }) scaleMode: 'temporal' | 'beats' = 'temporal';\n @property({ type: Number, attribute: false }) ticksPerPixel = 4;\n @property({ attribute: false }) meterEntries: MeterEntry[] = [\n { tick: 0, numerator: 4, denominator: 4 },\n ];\n @property({ type: Number, attribute: false }) ppqn = 960;\n @property({ type: Number, attribute: false }) totalWidth = 0;\n\n private _tickData: TickData | null = null;\n private _musicalTickData: MusicalTickData | null = null;\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n background: var(--daw-ruler-background, #0f0f1a);\n }\n .container {\n position: relative;\n }\n canvas {\n position: absolute;\n top: 0;\n }\n .label {\n position: absolute;\n font-size: 0.7rem;\n line-height: 1;\n white-space: nowrap;\n color: var(--daw-ruler-color, #c49a6c);\n top: 1px;\n }\n .label.centered {\n transform: translateX(-50%);\n }\n `;\n\n willUpdate() {\n if (this.scaleMode === 'beats' && this.totalWidth > 0) {\n this._musicalTickData = getCachedMusicalTicks({\n meterEntries: this.meterEntries,\n ticksPerPixel: this.ticksPerPixel,\n startPixel: 0,\n endPixel: this.totalWidth,\n ppqn: this.ppqn,\n });\n this._tickData = null;\n } else if (this.duration > 0 || this.totalWidth > 0) {\n // Cover the larger of natural duration and viewport-floored width.\n // When indefinite-playback is set, totalWidth can exceed the natural\n // duration's width — use that to keep ruler ticks across the full\n // visible area instead of only the audible portion.\n const widthDerivedDuration = (this.totalWidth * this.samplesPerPixel) / this.sampleRate;\n const effectiveDuration = Math.max(this.duration, widthDerivedDuration);\n this._musicalTickData = null;\n this._tickData = computeTemporalTicks(\n this.samplesPerPixel,\n this.sampleRate,\n effectiveDuration,\n this.rulerHeight\n );\n } else {\n this._musicalTickData = null;\n this._tickData = null;\n }\n }\n\n render() {\n const widthX = this.scaleMode === 'beats' ? this.totalWidth : (this._tickData?.widthX ?? 0);\n if (widthX <= 0) return html``;\n\n const totalChunks = Math.ceil(widthX / MAX_CANVAS_WIDTH);\n const indices = Array.from({ length: totalChunks }, (_, i) => i);\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n\n const beatsLabels =\n this.scaleMode === 'beats' ? (this._musicalTickData?.ticks.filter((t) => t.label) ?? []) : [];\n const temporalLabels = this.scaleMode !== 'beats' ? (this._tickData?.labels ?? []) : [];\n\n return html`\n <div class=\"container\" style=\"width: ${widthX}px; height: ${this.rulerHeight}px;\">\n ${indices.map((i) => {\n const width = Math.min(MAX_CANVAS_WIDTH, widthX - i * MAX_CANVAS_WIDTH);\n return html`\n <canvas\n data-index=${i}\n width=${width * dpr}\n height=${this.rulerHeight * dpr}\n style=\"left: ${i * MAX_CANVAS_WIDTH}px; width: ${width}px; height: ${this\n .rulerHeight}px;\"\n ></canvas>\n `;\n })}\n ${this.scaleMode === 'beats'\n ? beatsLabels.map(\n (t) =>\n html`<span\n class=\"label ${t.pixel > 0 ? 'centered' : ''}\"\n style=\"left: ${t.pixel > 0 ? t.pixel : t.pixel + 4}px;\"\n >${t.label}</span\n >`\n )\n : temporalLabels.map(\n ({ pix, text }) =>\n html`<span class=\"label\" style=\"left: ${pix + 4}px;\">${text}</span>`\n )}\n </div>\n `;\n }\n\n updated() {\n this._drawTicks();\n }\n\n private _drawTicks() {\n const canvases = this.shadowRoot?.querySelectorAll('canvas');\n if (!canvases) return;\n\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const rulerColor =\n getComputedStyle(this).getPropertyValue('--daw-ruler-color').trim() || '#c49a6c';\n const widthX = this.scaleMode === 'beats' ? this.totalWidth : (this._tickData?.widthX ?? 0);\n\n for (const canvas of canvases) {\n const idx = Number(canvas.dataset.index);\n const ctx = canvas.getContext('2d');\n if (!ctx) continue;\n\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, widthX - idx * MAX_CANVAS_WIDTH);\n const globalOffset = idx * MAX_CANVAS_WIDTH;\n\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.scale(dpr, dpr);\n ctx.strokeStyle = rulerColor;\n ctx.lineWidth = 1;\n\n if (this.scaleMode === 'beats' && this._musicalTickData) {\n // Ticks draw upward from the bottom. Leave top ~40% for labels.\n // major=60%, minor=35%, minorMinor=15%\n const h = this.rulerHeight;\n for (const tick of this._musicalTickData.ticks) {\n const localX = tick.pixel - globalOffset;\n if (localX < 0 || localX >= canvasWidth) continue;\n\n const tickH =\n tick.type === 'major' ? h * 0.6 : tick.type === 'minor' ? h * 0.35 : h * 0.15;\n\n ctx.globalAlpha = tick.type === 'major' ? 1.0 : 0.5;\n ctx.beginPath();\n ctx.moveTo(localX + 0.5, h);\n ctx.lineTo(localX + 0.5, h - tickH);\n ctx.stroke();\n }\n ctx.globalAlpha = 1.0;\n } else if (this._tickData) {\n for (const [pix, height] of this._tickData.canvasInfo) {\n const localX = pix - globalOffset;\n if (localX < 0 || localX >= canvasWidth) continue;\n\n ctx.beginPath();\n ctx.moveTo(localX + 0.5, this.rulerHeight);\n ctx.lineTo(localX + 0.5, this.rulerHeight - height);\n ctx.stroke();\n }\n }\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-ruler': DawRulerElement;\n }\n}\n","/**\n * Format milliseconds into a m:ss display string.\n */\nexport function formatTime(milliseconds: number): string {\n const seconds = Math.floor(milliseconds / 1000);\n const s = seconds % 60;\n const m = (seconds - s) / 60;\n\n return `${m}:${String(s).padStart(2, '0')}`;\n}\n","import { formatTime } from './time-format';\n\nconst timeinfo = new Map([\n [700, { marker: 1000, bigStep: 500, smallStep: 100 }],\n [1500, { marker: 2000, bigStep: 1000, smallStep: 200 }],\n [2500, { marker: 2000, bigStep: 1000, smallStep: 500 }],\n [5000, { marker: 5000, bigStep: 1000, smallStep: 500 }],\n [10000, { marker: 10000, bigStep: 5000, smallStep: 1000 }],\n [12000, { marker: 15000, bigStep: 5000, smallStep: 1000 }],\n [Infinity, { marker: 30000, bigStep: 10000, smallStep: 5000 }],\n]);\n\nexport function getScaleInfo(samplesPerPixel: number) {\n for (const [resolution, config] of timeinfo) {\n if (samplesPerPixel < resolution) {\n return config;\n }\n }\n return { marker: 30000, bigStep: 10000, smallStep: 5000 };\n}\n\nexport interface TickData {\n /** Map of pixel position → tick height */\n canvasInfo: Map<number, number>;\n /** Labeled ticks with pixel positions */\n labels: Array<{ pix: number; text: string }>;\n /** Total width in pixels */\n widthX: number;\n}\n\n/**\n * Compute temporal tick data for a ruler.\n *\n * Pure function — no DOM dependencies.\n */\nexport function computeTemporalTicks(\n samplesPerPixel: number,\n sampleRate: number,\n duration: number,\n rulerHeight: number\n): TickData {\n const widthX = Math.ceil((duration * sampleRate) / samplesPerPixel);\n const config = getScaleInfo(samplesPerPixel);\n const { marker, bigStep, smallStep } = config;\n const canvasInfo = new Map<number, number>();\n const labels: Array<{ pix: number; text: string }> = [];\n\n // Each tick's pixel comes from its own time (an integer counter in\n // milliseconds), in one division (#722): the floor of\n // samples / samplesPerPixel, as the editor draws a clip at that time. With\n // an integer zoom both operands are exact integers, so the floor is exact.\n // `(counter / 1000) * pixPerSec` rounds twice and put some ticks one pixel\n // early, also at the default 1024 samples per pixel.\n for (let counter = 0; ; counter += smallStep) {\n const pix = Math.floor((counter * sampleRate) / (1000 * samplesPerPixel));\n // Written as `!(<)` so a NaN width ends the loop too.\n if (!(pix < widthX)) break;\n\n if (counter % marker === 0) {\n canvasInfo.set(pix, rulerHeight);\n labels.push({ pix, text: formatTime(counter) });\n } else if (counter % bigStep === 0) {\n canvasInfo.set(pix, Math.floor(rulerHeight / 2));\n } else if (counter % smallStep === 0) {\n canvasInfo.set(pix, Math.floor(rulerHeight / 5));\n }\n }\n\n return { widthX, canvasInfo, labels };\n}\n","import { computeMusicalTicks } from '@waveform-playlist/core';\nimport type { MusicalTickParams, MusicalTickData, MeterEntry } from '@waveform-playlist/core';\n\nlet cachedParams: MusicalTickParams | null = null;\nlet cachedResult: MusicalTickData | null = null;\n\nfunction meterEntriesMatch(\n a: { tick: number; numerator: number; denominator: number }[],\n b: { tick: number; numerator: number; denominator: number }[]\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (\n a[i].tick !== b[i].tick ||\n a[i].numerator !== b[i].numerator ||\n a[i].denominator !== b[i].denominator\n )\n return false;\n }\n return true;\n}\n\nfunction paramsMatch(a: MusicalTickParams, b: MusicalTickParams): boolean {\n return (\n a.ticksPerPixel === b.ticksPerPixel &&\n a.startPixel === b.startPixel &&\n a.endPixel === b.endPixel &&\n meterEntriesMatch(a.meterEntries, b.meterEntries) &&\n (a.ppqn ?? 960) === (b.ppqn ?? 960)\n );\n}\n\nexport function getCachedMusicalTicks(params: MusicalTickParams): MusicalTickData {\n if (cachedParams && cachedResult && paramsMatch(cachedParams, params)) {\n return cachedResult;\n }\n cachedResult = computeMusicalTicks(params);\n cachedParams = {\n ...params,\n meterEntries: params.meterEntries.map((e: MeterEntry) => ({ ...e })),\n };\n return cachedResult;\n}\n\nexport function clearMusicalTickCache(): void {\n cachedParams = null;\n cachedResult = null;\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { createMixerGesture } from '@waveform-playlist/core';\nimport type { MixerGesture } from '@waveform-playlist/core';\nimport type {\n DawTrackControlDetail,\n DawTrackReorderDetail,\n DawTrackReorderGrabDetail,\n} from '../events';\n\n@customElement('daw-track-controls')\nexport class DawTrackControlsElement extends LitElement {\n /** Track ID — set by the editor to link controls to a track row. */\n @property({ attribute: false }) trackId: string | null = null;\n @property({ attribute: false }) trackName = '';\n @property({ type: Number, attribute: false }) volume = 1;\n @property({ type: Number, attribute: false }) pan = 0;\n @property({ type: Boolean, attribute: false }) muted = false;\n /** A take is recording onto the track: it plays muted, and the M button is disabled. */\n @property({ type: Boolean, attribute: false }) recording = false;\n @property({ type: Boolean, attribute: false }) soloed = false;\n /** Show the reorder grip + move up/down buttons (set by the editor from\n * its track-reordering attribute). */\n @property({ type: Boolean, attribute: false }) reorderable = false;\n @property({ type: Number, attribute: false }) trackIndex = 0;\n @property({ type: Number, attribute: false }) trackCount = 1;\n\n /**\n * One gesture per slider (#843): the `daw-track-control` events of one\n * drag, or of one key press (a held key included), carry the same\n * `gesture` id, and the editor makes them one undo step. Each gesture is\n * attached to its range input while the element is connected.\n */\n private readonly _volumeGesture: MixerGesture = createMixerGesture();\n private readonly _panGesture: MixerGesture = createMixerGesture();\n private _detachGestures: Array<() => void> = [];\n\n static styles = css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n box-sizing: border-box;\n padding: 6px 8px;\n background: var(--daw-controls-background, #0f0f1a);\n color: var(--daw-controls-text, #c49a6c);\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\n font-family: system-ui, sans-serif;\n font-size: 11px;\n overflow: hidden;\n container-type: size;\n }\n .header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 4px;\n margin-bottom: 3px;\n }\n .name {\n flex: 1;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n font-weight: 600;\n font-size: 11px;\n }\n .remove-btn {\n background: none;\n border: none;\n color: var(--daw-controls-text, #c49a6c);\n cursor: pointer;\n padding: 0 2px;\n font-size: 14px;\n line-height: 1;\n opacity: 0.4;\n }\n .remove-btn:hover {\n opacity: 1;\n color: #d08070;\n }\n .grip {\n background: none;\n border: none;\n color: var(--daw-controls-text, #c49a6c);\n cursor: grab;\n padding: 0 2px;\n font-size: 12px;\n line-height: 1;\n opacity: 0.4;\n touch-action: none;\n }\n .grip:hover {\n opacity: 1;\n }\n .buttons {\n display: flex;\n gap: 3px;\n margin-bottom: 3px;\n }\n .btn {\n background: rgba(255, 255, 255, 0.06);\n border: 1px solid rgba(255, 255, 255, 0.1);\n border-radius: 3px;\n color: var(--daw-controls-text, #c49a6c);\n cursor: pointer;\n font-size: 10px;\n font-weight: 600;\n padding: 2px 8px;\n text-align: center;\n }\n .btn:hover {\n background: rgba(255, 255, 255, 0.12);\n }\n .btn.active {\n background: rgba(99, 199, 95, 0.25);\n border-color: rgba(99, 199, 95, 0.5);\n color: #63c75f;\n }\n .btn.muted-active {\n background: rgba(208, 128, 112, 0.25);\n border-color: rgba(208, 128, 112, 0.5);\n color: #d08070;\n }\n .btn:disabled {\n opacity: 0.3;\n cursor: default;\n }\n .slider-row {\n display: flex;\n align-items: center;\n gap: 4px;\n height: 16px;\n }\n .slider-label {\n width: 50px;\n font-size: 9px;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n opacity: 0.6;\n flex-shrink: 0;\n display: flex;\n justify-content: space-between;\n }\n .slider-label-name {\n opacity: 0.5;\n }\n .slider-label-value {\n font-family: 'Courier New', monospace;\n }\n input[type='range'] {\n flex: 1;\n min-width: 0;\n height: 20px;\n margin: 0;\n -webkit-appearance: none;\n appearance: none;\n background: transparent;\n cursor: pointer;\n }\n input[type='range']::-webkit-slider-runnable-track {\n height: 3px;\n background: rgba(255, 255, 255, 0.12);\n border-radius: 2px;\n }\n input[type='range']::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background: var(--daw-controls-text, #c49a6c);\n margin-top: -4.5px;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);\n }\n input[type='range']::-moz-range-track {\n height: 3px;\n background: rgba(255, 255, 255, 0.12);\n border-radius: 2px;\n border: none;\n }\n input[type='range']::-moz-range-thumb {\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background: var(--daw-controls-text, #c49a6c);\n border: none;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);\n }\n /* Compact modes: drop sliders when the row is too short for the full\n stack. Thresholds are CONTENT-BOX heights — the host is border-box\n with 12px vertical padding + 1px border, so an editor-given height H\n enters compact mode at H <= 89px (Pan hidden) and H <= 73px (Vol also\n hidden). NOTE: container-type: size requires an explicit height on\n the host — the editor always provides one; standalone consumers must\n too (see the firstUpdated guard). */\n @container (max-height: 76px) {\n .pan-row {\n display: none;\n }\n }\n @container (max-height: 60px) {\n .vol-row {\n display: none;\n }\n }\n `;\n\n connectedCallback(): void {\n super.connectedCallback();\n // A reconnect (the element was moved): the inputs are still in the\n // shadow root. On the first connect they do not exist yet; firstUpdated\n // attaches.\n if (this.hasUpdated) this._attachGestures();\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this._detachAllGestures();\n }\n\n private _attachGestures(): void {\n this._detachAllGestures();\n const volumeInput = this.shadowRoot?.querySelector<HTMLInputElement>('.vol-row input');\n const panInput = this.shadowRoot?.querySelector<HTMLInputElement>('.pan-row input');\n const detach: Array<() => void> = [];\n if (volumeInput) detach.push(this._volumeGesture.attach(volumeInput));\n if (panInput) detach.push(this._panGesture.attach(panInput));\n this._detachGestures = detach;\n }\n\n private _detachAllGestures(): void {\n for (const detach of this._detachGestures) detach();\n this._detachGestures = [];\n }\n\n protected firstUpdated(): void {\n this._attachGestures();\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n const rect = this.getBoundingClientRect();\n // width > 0 proves a real layout engine ran (happy-dom reports 0×0,\n // so unit tests stay quiet); height 0 then means size containment\n // collapsed the element because no explicit height was provided.\n if (rect.width > 0 && rect.height === 0) {\n console.warn(\n '[dawcore] <daw-track-controls> has zero height: container-type: size requires an explicit height on the element (the editor sets one automatically; standalone usage must too). The controls are currently invisible.'\n );\n }\n });\n }\n\n private _onVolumeInput = (e: Event) => {\n const value = Number((e.target as HTMLInputElement).value);\n if (Number.isFinite(value)) this._dispatchControl('volume', value, this._volumeGesture.id);\n };\n\n private _onPanInput = (e: Event) => {\n const value = Number((e.target as HTMLInputElement).value);\n if (Number.isFinite(value)) this._dispatchControl('pan', value, this._panGesture.id);\n };\n\n private _onMuteClick = () => {\n if (this.recording) return;\n this._dispatchControl('muted', !this.muted);\n };\n\n private _onSoloClick = () => {\n this._dispatchControl('soloed', !this.soloed);\n };\n\n private _onRemoveClick = () => {\n if (!this.trackId) return;\n this.dispatchEvent(\n new CustomEvent('daw-track-remove', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId },\n })\n );\n };\n\n /** `gesture` for the sliders only: each mute or solo click is a step. */\n private _dispatchControl(prop: string, value: number | boolean, gesture?: string) {\n if (!this.trackId) return;\n const detail: DawTrackControlDetail =\n gesture === undefined\n ? { trackId: this.trackId, prop, value }\n : { trackId: this.trackId, prop, value, gesture };\n this.dispatchEvent(\n new CustomEvent<DawTrackControlDetail>('daw-track-control', {\n bubbles: true,\n composed: true,\n detail,\n })\n );\n }\n\n private _dispatchReorder(toIndex: number) {\n if (!this.trackId) return;\n this.dispatchEvent(\n new CustomEvent<DawTrackReorderDetail>('daw-track-reorder', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId, fromIndex: this.trackIndex, toIndex },\n })\n );\n }\n\n private _onMoveUp = () => this._dispatchReorder(this.trackIndex - 1);\n private _onMoveDown = () => this._dispatchReorder(this.trackIndex + 1);\n\n private _onGripPointerDown = (e: PointerEvent) => {\n if (!this.trackId) return;\n e.preventDefault();\n this.dispatchEvent(\n new CustomEvent<DawTrackReorderGrabDetail>('daw-track-reorder-grab', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: this.trackId,\n pointerEvent: e,\n gripElement: e.currentTarget as HTMLElement,\n },\n })\n );\n };\n\n render() {\n const volPercent = Math.round(this.volume * 100);\n const panPercent = Math.round(Math.abs(this.pan) * 100);\n const panDisplay = this.pan === 0 ? 'C' : (this.pan > 0 ? 'R' : 'L') + panPercent;\n\n return html`\n <div class=\"header\">\n ${this.reorderable\n ? html`<button\n class=\"grip\"\n title=\"Drag to reorder track\"\n aria-label=\"Drag to reorder track\"\n @pointerdown=${this._onGripPointerDown}\n >\n ⠿\n </button>`\n : ''}\n <span class=\"name\" title=${this.trackName}>${this.trackName || 'Untitled'}</span>\n <button class=\"remove-btn\" @click=${this._onRemoveClick} title=\"Remove track\">\n &times;\n </button>\n </div>\n <div class=\"buttons\">\n <button\n class=\"btn ${this.muted ? 'muted-active' : ''}\"\n @click=${this._onMuteClick}\n ?disabled=${this.recording}\n title=\"Mute\"\n >\n M\n </button>\n <button class=\"btn ${this.soloed ? 'active' : ''}\" @click=${this._onSoloClick} title=\"Solo\">\n S\n </button>\n ${this.reorderable\n ? html`<button\n class=\"btn reorder-up\"\n title=\"Move track up\"\n aria-label=\"Move track up\"\n ?disabled=${this.trackIndex <= 0}\n @click=${this._onMoveUp}\n >\n ▲\n </button>\n <button\n class=\"btn reorder-down\"\n title=\"Move track down\"\n aria-label=\"Move track down\"\n ?disabled=${this.trackIndex >= this.trackCount - 1}\n @click=${this._onMoveDown}\n >\n ▼\n </button>`\n : ''}\n </div>\n <div class=\"slider-row vol-row\">\n <span class=\"slider-label\">\n <span class=\"slider-label-name\">Vol</span>\n <span class=\"slider-label-value\">${volPercent}%</span>\n </span>\n <input\n type=\"range\"\n min=\"0\"\n max=\"1\"\n step=\"0.01\"\n .value=${String(this.volume)}\n @input=${this._onVolumeInput}\n />\n </div>\n <div class=\"slider-row pan-row\">\n <span class=\"slider-label\">\n <span class=\"slider-label-name\">Pan</span>\n <span class=\"slider-label-value\">${panDisplay}</span>\n </span>\n <input\n type=\"range\"\n min=\"-1\"\n max=\"1\"\n step=\"0.01\"\n .value=${String(this.pan)}\n @input=${this._onPanInput}\n />\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-track-controls': DawTrackControlsElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { MIN_PIXELS_PER_UNIT } from '@waveform-playlist/core';\nimport type { MusicalTickData, MeterEntry } from '@waveform-playlist/core';\nimport { getCachedMusicalTicks } from '../utils/musical-tick-cache';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n/**\n * `<daw-grid>` renders a musical grid overlay behind waveforms using the\n * Audacity three-tier model:\n *\n * - **Zebra stripes**: Alternating bar backgrounds at 2% white opacity.\n * - **Major lines** (bars): 10% white opacity, full height.\n * - **Minor lines** (beats): 6% white opacity, full height.\n * - **MinorMinor** (subdivisions): Ruler ticks only — no grid lines.\n *\n * Uses chunked 1000px canvases with virtual scrolling (same as daw-waveform).\n *\n * CSS custom properties:\n * --daw-grid-bar-highlight Alternating bar fill (default: rgba(255,255,255,0.02))\n * --daw-grid-major-line Bar line color (default: rgba(255,255,255,0.1))\n * --daw-grid-minor-line Beat line color (default: rgba(255,255,255,0.06))\n */\n@customElement('daw-grid')\nexport class DawGridElement extends LitElement {\n @property({ type: Number, attribute: false }) ticksPerPixel = 24;\n @property({ attribute: false }) meterEntries: MeterEntry[] = [\n { tick: 0, numerator: 4, denominator: 4 },\n ];\n @property({ type: Number, attribute: false }) ppqn = 960;\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) height = 200;\n\n private _tickData: MusicalTickData | null = null;\n\n static styles = css`\n :host {\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n pointer-events: none;\n z-index: 0;\n }\n .container {\n position: relative;\n }\n canvas {\n position: absolute;\n top: 0;\n }\n `;\n\n willUpdate() {\n if (this.length > 0) {\n this._tickData = getCachedMusicalTicks({\n ticksPerPixel: this.ticksPerPixel,\n meterEntries: this.meterEntries,\n ppqn: this.ppqn,\n startPixel: 0,\n endPixel: this.length,\n });\n } else {\n this._tickData = null;\n }\n }\n\n render() {\n if (!this._tickData) return html``;\n\n const totalWidth = this.length;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const indices = getVisibleChunkIndices(\n totalWidth,\n MAX_CANVAS_WIDTH,\n this.visibleStart,\n this.visibleEnd\n );\n\n return html`\n <div class=\"container\" style=\"width: ${totalWidth}px; height: ${this.height}px;\">\n ${indices.map((i) => {\n const width = Math.min(MAX_CANVAS_WIDTH, totalWidth - i * MAX_CANVAS_WIDTH);\n return html`\n <canvas\n data-index=${i}\n width=${width * dpr}\n height=${this.height * dpr}\n style=\"left: ${i * MAX_CANVAS_WIDTH}px; width: ${width}px; height: ${this.height}px;\"\n ></canvas>\n `;\n })}\n </div>\n `;\n }\n\n updated() {\n this._drawGrid();\n }\n\n private _drawGrid() {\n if (!this._tickData) return;\n\n const canvases = this.shadowRoot?.querySelectorAll('canvas');\n if (!canvases) return;\n\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const style = getComputedStyle(this);\n const barHighlight =\n style.getPropertyValue('--daw-grid-bar-highlight').trim() || 'rgba(255,255,255,0.02)';\n const majorLine =\n style.getPropertyValue('--daw-grid-major-line').trim() || 'rgba(255,255,255,0.1)';\n const minorLine =\n style.getPropertyValue('--daw-grid-minor-line').trim() || 'rgba(255,255,255,0.06)';\n\n const { ticks, pixelsPerQuarterNote } = this._tickData;\n\n for (const canvas of canvases) {\n const idx = Number(canvas.dataset.index);\n const ctx = canvas.getContext('2d');\n if (!ctx) continue;\n\n const chunkLeft = idx * MAX_CANVAS_WIDTH;\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, this.length - chunkLeft);\n\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.scale(dpr, dpr);\n\n // Zebra stripes: use barIndex from tick data for exact alignment with grid lines.\n // Draw a stripe from each odd-barIndex major tick to the next major tick.\n // Threshold: show stripes when a 4-beat bar would be >= MIN_PIXELS_PER_UNIT wide.\n if (pixelsPerQuarterNote * 4 >= MIN_PIXELS_PER_UNIT) {\n ctx.fillStyle = barHighlight;\n const majorTicks = ticks.filter((t) => t.type === 'major');\n for (let i = 0; i < majorTicks.length; i++) {\n if (majorTicks[i].barIndex % 2 === 1) {\n const x = majorTicks[i].pixel - chunkLeft;\n // Use actual next major tick pixel for exact bar width (handles variable meter).\n // Last bar: use the last meter entry's numerator for correct width.\n const lastMeter = this.meterEntries[this.meterEntries.length - 1];\n const lastBarWidth =\n pixelsPerQuarterNote * lastMeter.numerator * (4 / lastMeter.denominator);\n const nextX =\n i + 1 < majorTicks.length ? majorTicks[i + 1].pixel - chunkLeft : x + lastBarWidth;\n ctx.fillRect(x, 0, nextX - x, this.height);\n }\n }\n }\n\n // Grid lines: major (bars) and minor (beats) only.\n // Subdivisions (minorMinor) get ruler ticks but no grid lines.\n ctx.lineWidth = 1;\n for (const tick of ticks) {\n if (tick.type === 'minorMinor') continue;\n\n const localX = tick.pixel - chunkLeft;\n if (localX < 0 || localX >= canvasWidth) continue;\n\n ctx.strokeStyle = tick.type === 'major' ? majorLine : minorLine;\n ctx.beginPath();\n ctx.moveTo(localX + 0.5, 0);\n ctx.lineTo(localX + 0.5, this.height);\n ctx.stroke();\n }\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-grid': DawGridElement;\n }\n}\n","import { css } from 'lit';\n\n/**\n * Default CSS custom properties for dawcore elements.\n * Consumers override these on <daw-editor> or any ancestor.\n * Values inherit through Shadow DOM boundaries automatically.\n */\nexport const hostStyles = css`\n :host {\n --daw-wave-color: #c49a6c;\n --daw-progress-color: #63c75f;\n --daw-playhead-color: #d08070;\n --daw-background: #1a1a2e;\n --daw-track-background: #16213e;\n --daw-ruler-color: #c49a6c;\n --daw-ruler-background: #0f0f1a;\n --daw-controls-background: #1a1a2e;\n --daw-controls-text: #e0d4c8;\n --daw-selection-color: rgba(99, 199, 95, 0.3);\n --daw-clip-header-background: rgba(0, 0, 0, 0.4);\n --daw-clip-header-text: #e0d4c8;\n }\n`;\n\n/** Clip container and header styles for the editor timeline. */\nexport const clipStyles = css`\n .clip-container {\n position: absolute;\n overflow: hidden;\n }\n /* A clip whose audio is still loading (#848). */\n .clip-container.placeholder {\n opacity: var(--daw-placeholder-clip-opacity, 0.5);\n background: color-mix(in srgb, var(--daw-wave-color, #c49a6c) 35%, transparent);\n }\n /* A clip whose audio failed to load: it stays, like a broken <img>. */\n .clip-container.placeholder.failed {\n opacity: 1;\n background: color-mix(in srgb, var(--daw-clip-failed-color, #e06c75) 15%, transparent);\n outline: 2px dashed var(--daw-clip-failed-color, #e06c75);\n outline-offset: -2px;\n }\n .clip-header {\n position: relative;\n z-index: 1;\n height: 20px;\n background: var(--daw-clip-header-background, rgba(0, 0, 0, 0.4));\n border-bottom: 1px solid rgba(255, 255, 255, 0.08);\n display: flex;\n align-items: center;\n padding: 0 6px;\n user-select: none;\n -webkit-user-drag: none;\n }\n .clip-header span {\n font-size: 10px;\n font-weight: 500;\n letter-spacing: 0.02em;\n font-family: system-ui, sans-serif;\n color: var(--daw-clip-header-text, #e0d4c8);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n opacity: 0.8;\n }\n .clip-boundary {\n position: absolute;\n top: 0;\n width: 8px;\n height: 100%;\n z-index: 2;\n cursor: col-resize;\n background: transparent;\n border: none;\n touch-action: none;\n user-select: none;\n -webkit-user-drag: none;\n transition: background 0.1s, border-color 0.1s;\n }\n .clip-boundary[data-boundary-edge='left'] {\n left: 0;\n }\n .clip-boundary[data-boundary-edge='right'] {\n right: 0;\n }\n .clip-boundary[data-boundary-edge='left']:hover {\n background: rgba(255, 255, 255, 0.2);\n border-left: 2px solid rgba(255, 255, 255, 0.5);\n }\n .clip-boundary[data-boundary-edge='right']:hover {\n background: rgba(255, 255, 255, 0.2);\n border-right: 2px solid rgba(255, 255, 255, 0.5);\n }\n .clip-boundary[data-boundary-edge='left'].dragging {\n background: rgba(255, 255, 255, 0.4);\n border-left: 2px solid rgba(255, 255, 255, 0.8);\n }\n .clip-boundary[data-boundary-edge='right'].dragging {\n background: rgba(255, 255, 255, 0.4);\n border-right: 2px solid rgba(255, 255, 255, 0.8);\n }\n .clip-header[data-interactive] {\n cursor: grab;\n }\n .clip-header[data-interactive]:active {\n cursor: grabbing;\n }\n`;\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\nexport { getVisibleChunkIndices };\n\nconst OVERSCAN_MULTIPLIER = 1.5;\nconst SCROLL_THRESHOLD = 100;\n\nexport class ViewportController implements ReactiveController {\n private _host: ReactiveControllerHost & HTMLElement;\n private _scrollContainer: HTMLElement | null = null;\n private _lastScrollLeft = 0;\n private _resizeObserver: ResizeObserver | null = null;\n /** The scroll listener on `_scrollContainer`, aborted when it is replaced or the host disconnects. */\n private _scrollListener: AbortController | null = null;\n\n // Permissive defaults: render everything until scroll container is attached\n visibleStart = -Infinity;\n visibleEnd = Infinity;\n containerWidth = 0;\n\n constructor(host: ReactiveControllerHost & HTMLElement) {\n this._host = host;\n host.addController(this);\n }\n\n /** CSS selector for the scroll container inside the host's Shadow DOM. */\n scrollSelector = '';\n\n hostConnected() {\n // Defer to allow Shadow DOM to render before querying\n requestAnimationFrame(() => {\n if (!this._host.isConnected) return;\n const container = this.scrollSelector\n ? (this._host.shadowRoot?.querySelector(this.scrollSelector) as HTMLElement)\n : this._host;\n if (container) {\n this._attachScrollContainer(container);\n } else if (this.scrollSelector) {\n console.warn(\n '[dawcore] ViewportController: scroll container not found for \"' +\n this.scrollSelector +\n '\"'\n );\n }\n });\n }\n\n hostDisconnected() {\n this._scrollListener?.abort();\n this._scrollListener = null;\n this._resizeObserver?.disconnect();\n this._resizeObserver = null;\n this._scrollContainer = null;\n }\n\n private _attachScrollContainer(container: HTMLElement) {\n this._scrollListener?.abort();\n this._resizeObserver?.disconnect();\n this._scrollContainer = container;\n this._scrollListener = new AbortController();\n container.addEventListener('scroll', this._onScroll, {\n passive: true,\n signal: this._scrollListener.signal,\n });\n this._update(container.scrollLeft, container.clientWidth);\n if (typeof ResizeObserver !== 'undefined') {\n this._resizeObserver = new ResizeObserver(() => {\n if (!this._scrollContainer) return;\n const next = this._scrollContainer.clientWidth;\n if (next === this.containerWidth) return;\n this._update(this._scrollContainer.scrollLeft, next);\n this._host.requestUpdate();\n });\n this._resizeObserver.observe(container);\n }\n this._host.requestUpdate();\n }\n\n private _onScroll = () => {\n if (!this._scrollContainer) return;\n const { scrollLeft, clientWidth } = this._scrollContainer;\n if (Math.abs(scrollLeft - this._lastScrollLeft) >= SCROLL_THRESHOLD) {\n this._update(scrollLeft, clientWidth);\n this._host.requestUpdate();\n }\n };\n\n private _update(scrollLeft: number, containerWidth: number) {\n this._lastScrollLeft = scrollLeft;\n this.containerWidth = containerWidth;\n const buffer = containerWidth * OVERSCAN_MULTIPLIER;\n this.visibleStart = scrollLeft - buffer;\n this.visibleEnd = scrollLeft + containerWidth + buffer;\n }\n}\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\nexport interface AudioResumeHost extends ReactiveControllerHost, HTMLElement {\n /** Returns the AudioContext to resume on user gesture */\n readonly audioContext: AudioContext;\n}\n\nexport class AudioResumeController implements ReactiveController {\n private _host: AudioResumeHost;\n private _target: EventTarget | null = null;\n /** The gesture listeners on `_target`: one controller per attach. */\n private _listeners: AbortController | null = null;\n private _attached = false;\n private _generation = 0;\n\n /** CSS selector, or 'document'. When undefined, controller is inert. */\n target?: string;\n\n constructor(host: AudioResumeHost) {\n this._host = host;\n host.addController(this);\n }\n\n hostConnected() {\n // Defer to next frame so Lit's willUpdate() can set `target` from\n // the host's attribute before we read it. Same pattern as ViewportController.\n const gen = ++this._generation;\n requestAnimationFrame(() => {\n if (gen !== this._generation) return; // stale callback from previous connect\n if (!this._host.isConnected || this._attached || this.target === undefined) return;\n\n let resolvedTarget: EventTarget | null;\n try {\n resolvedTarget = this._resolveTarget();\n } catch (err) {\n console.warn(\n '[dawcore] AudioResumeController: failed to resolve target \"' +\n this.target +\n '\": ' +\n String(err)\n );\n return;\n }\n if (!resolvedTarget) return;\n\n this._target = resolvedTarget;\n this._attached = true;\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n resolvedTarget.addEventListener('pointerdown', this._onGesture, {\n once: true,\n capture: true,\n signal,\n });\n resolvedTarget.addEventListener('keydown', this._onGesture, {\n once: true,\n capture: true,\n signal,\n });\n });\n }\n\n hostDisconnected() {\n this._removeListeners();\n this._attached = false;\n }\n\n private _onGesture = () => {\n let ctx: AudioContext;\n try {\n ctx = this._host.audioContext;\n } catch (err) {\n if (err instanceof Error && err.message.includes('No PlayoutAdapter set')) {\n // No adapter set yet — nothing to resume. Will be resumed on first play().\n this._removeListeners();\n return;\n }\n console.warn(\n '[dawcore] AudioResumeController: unexpected error accessing audioContext: ' + String(err)\n );\n this._removeListeners();\n return;\n }\n if (ctx.state === 'closed') {\n console.warn('[dawcore] AudioResumeController: AudioContext is closed, cannot resume.');\n } else if (ctx.state === 'suspended') {\n ctx.resume().catch((err) => {\n console.warn(\n '[dawcore] AudioResumeController: eager resume failed, will retry on play: ' + String(err)\n );\n });\n }\n // The fired listener was removed by { once: true }; this removes the other.\n this._removeListeners();\n };\n\n private _resolveTarget(): EventTarget | null {\n const t = this.target;\n if (t === undefined) return null;\n if (t === '') return this._host;\n if (t === 'document') return document;\n\n const el = document.querySelector(t);\n if (!el) {\n console.warn(\n '[dawcore] AudioResumeController: target \"' +\n t +\n '\" not found in DOM at attach time, falling back to host element. ' +\n 'Ensure the target exists before <daw-editor> connects.'\n );\n return this._host;\n }\n return el;\n }\n\n private _removeListeners() {\n if (!this._target) return;\n this._listeners?.abort();\n this._listeners = null;\n this._target = null;\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), and dawcore's peer ranges are\n * `>=` floors, which also admit a later breaking release. So each name carries\n * a caret on the version this build was made with, which lies inside dawcore's\n * peer range; where the floor does not admit that version yet, the peer range\n * itself (see `hintRange` in the script below). playout, which is no peer, gets\n * a caret too.\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 dawcore Vite examples alias this\n * source) prints the bare name; the website uses the built `dist`.\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 { ReactiveController, ReactiveControllerHost } from 'lit';\nimport type { Bits } from '@waveform-playlist/core';\nimport type { DawWaveformElement } from '../elements/daw-waveform';\nimport { installCommand } from '../utils/install-command';\nimport {\n appendPeaks,\n concatenateAudioData,\n createAudioBuffer,\n resolveRecordingOffsetSamples,\n} from '@waveform-playlist/core';\nimport type {\n DawRecordingStartDetail,\n DawRecordingCompleteDetail,\n DawRecordingErrorDetail,\n DawRecordingPauseDetail,\n DawRecordingResumeDetail,\n} from '../events';\n\nexport interface RecordingOptions {\n trackId?: string;\n bits?: 8 | 16;\n /** Fallback channel count when stream doesn't report one via getSettings(). Must be 1 or 2. */\n channelCount?: 1 | 2;\n startSample?: number;\n /** Start playback during recording so user hears existing tracks. */\n overdub?: boolean;\n /**\n * Latency offset to skip at the start of the recording, in **seconds**.\n * Absolute replacement for the auto-computed `outputLatency`-based value —\n * use this to apply an externally-measured round-trip latency. `0` disables\n * compensation; when omitted, the auto-computed value is used.\n * Negative or non-finite values are treated as 0.\n */\n latencyOffset?: number;\n /**\n * Display name for the take: shown in the live-preview clip header while\n * recording (falls back to \"Recording…\") and used as the finalized clip's\n * name (falls back to \"Recording\").\n */\n clipName?: string;\n}\n\nexport interface RecordingSession {\n readonly trackId: string;\n readonly stream: MediaStream;\n readonly source: { disconnect(): void; connect(dest: unknown): void };\n readonly workletNode: { port: MessagePort; disconnect(): void };\n readonly chunks: Float32Array[][];\n totalSamples: number;\n readonly peaks: (Int8Array | Int16Array)[];\n readonly startSample: number;\n readonly channelCount: number;\n /** Sample rate of the AudioContext the worklet captured at. The finalized\n * AudioBuffer must be labeled with THIS rate — the host's sticky\n * effectiveSampleRate can lag after a context swap, mislabeling the take\n * (~8.9% off-speed for 44.1k vs 48k). */\n readonly captureSampleRate: number;\n readonly bits: Bits;\n isFirstMessage: boolean;\n /** Latency samples to skip in live preview (outputLatency only). */\n readonly latencySamples: number;\n /** Display name for the take (preview header + finalized clip name). */\n readonly clipName?: string;\n readonly wasOverdub: boolean;\n /** Set during stopRecording, cleared by the done message from the worklet. */\n stopAckResolve: (() => void) | null;\n /** In-flight stop completion — re-entrant stopRecording calls await this\n * instead of running a second handshake. */\n stopPromise: Promise<void> | null;\n /** True from the start of stopRecording until the session is deleted.\n * Guards pauseRecording / resumeRecording so a mid-drain pause toggle\n * can't dispatch events for a session that's already terminating. */\n stopping: boolean;\n}\n\n/** Readonly view of a recording session for external consumers. */\nexport type ReadonlyRecordingSession = Readonly<\n Omit<RecordingSession, 'chunks' | 'peaks' | 'latencySamples'>\n> & {\n readonly latencySamples: number;\n readonly chunks: ReadonlyArray<ReadonlyArray<Float32Array>>;\n readonly peaks: ReadonlyArray<Int8Array | Int16Array>;\n};\n\n/** Narrow interface for the host editor. */\nexport interface RecordingHost extends ReactiveControllerHost {\n readonly audioContext: AudioContext;\n readonly samplesPerPixel: number;\n /** Render-space samples-per-pixel. In beats mode this is derived from\n * ticksPerPixel/bpm and differs from samplesPerPixel — live-preview peaks\n * must be generated at THIS scale or the drawn waveform disagrees with the\n * preview container's width/position. */\n readonly renderSamplesPerPixel: number;\n readonly effectiveSampleRate: number;\n readonly _selectedTrackId: string | null;\n /** Live playhead position in seconds. Must read from the engine during\n * playback — a cached field only written on pause/stop/seek lags the real\n * position and misplaces punch-in (record-during-playback) clips. */\n readonly currentTime: number;\n readonly shadowRoot: ShadowRoot | null;\n _addRecordedClip?(\n trackId: string,\n buf: AudioBuffer,\n startSample: number,\n durSamples: number,\n offsetSamples?: number,\n clipName?: string\n ): void;\n /** Structural view of the editor's engine for the take's mute (#843):\n * punch-in replaces the overlapped content, so the recorded-over track's\n * existing material must not play under the take. The track a take is\n * recording onto plays muted; that mute is outside the undo history and\n * leaves the stored mute alone. Optional — hosts without an engine skip\n * it. */\n _engine?: {\n setTrackRecording(trackId: string, recording: boolean): void;\n } | null;\n play?(startTime?: number): Promise<void>;\n stop?(): void;\n dispatchEvent(event: Event): boolean;\n /**\n * Register a worklet module URL on the adapter's AudioContext.\n * Abstracts native vs standardized-audio-context differences.\n * When absent, falls back to native audioContext.audioWorklet.addModule().\n */\n addWorkletModule?(url: string): Promise<void>;\n /**\n * Create an AudioWorkletNode on the adapter's context.\n * When absent, falls back to new AudioWorkletNode(audioContext, ...).\n */\n createAudioWorkletNode?(name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode;\n /**\n * Create a MediaStreamSource on the adapter's context.\n * When absent, falls back to audioContext.createMediaStreamSource().\n */\n createMediaStreamSource?(stream: MediaStream): MediaStreamAudioSourceNode;\n}\n\n/** Bookkeeping for a startRecording still in its async setup window\n * (session not yet in _sessions). */\ninterface StartingEntry {\n /** Set by stopRecording — the in-flight start consults this after its\n * awaits and aborts instead of losing the stop. */\n stopRequested: boolean;\n /** Resolves when the in-flight start settles (session live OR aborted) —\n * a session-less stopRecording returns this so `await stop(); start()`\n * sequences correctly instead of hitting the still-held _starting guard. */\n done: Promise<void>;\n}\n\nexport class RecordingController implements ReactiveController {\n private _host: RecordingHost & HTMLElement;\n private _sessions = new Map<string, RecordingSession>();\n /** Each session's mic-unplug listener, aborted when the session ends. */\n private _trackEndedListeners = new WeakMap<RecordingSession, AbortController>();\n /** Track IDs with a startRecording in flight (session not yet in _sessions).\n * The session is only set after several awaits — without this, two rapid\n * start calls both pass the _sessions guard and build two capture\n * pipelines feeding one session (garbled audio + a leaked worklet). */\n private _starting = new Map<string, StartingEntry>();\n /** True between hostDisconnected and hostConnected. An in-flight\n * startRecording consults this after its awaits so a teardown mid-setup\n * doesn't leak a live capture session on a detached editor. */\n private _hostDisconnected = false;\n private _workletLoadedCtx: AudioContext | null = null;\n /** Tracks worklet pause state explicitly so external consumers (editor,\n * pause button, spacebar) can share one source of truth. */\n private _isPaused = false;\n\n constructor(host: RecordingHost & HTMLElement) {\n this._host = host;\n host.addController(this);\n }\n\n hostConnected() {\n this._hostDisconnected = false;\n }\n\n hostDisconnected() {\n this._hostDisconnected = true;\n for (const trackId of [...this._sessions.keys()]) {\n // notifyError: captured audio is silently discarded here — without an\n // event, record buttons living in a still-connected <daw-transport>\n // stay wedged in their recording state forever.\n this._cleanupSession(trackId, true);\n }\n this._workletLoadedCtx = null;\n }\n\n get isRecording(): boolean {\n // The start window counts: <daw-stop-button> gates stopRecording() on\n // this getter, so excluding _starting would make the stop-during-start\n // cancel path unreachable from the stop button.\n return this._sessions.size > 0 || this._starting.size > 0;\n }\n\n get isPaused(): boolean {\n return this._isPaused && this._sessions.size > 0;\n }\n\n getSession(trackId: string): ReadonlyRecordingSession | undefined {\n return this._sessions.get(trackId);\n }\n\n async startRecording(stream: MediaStream, options: RecordingOptions = {}): Promise<void> {\n const trackId = options.trackId ?? this._host._selectedTrackId;\n if (!trackId) {\n console.warn('[dawcore] RecordingController: No track selected for recording');\n return;\n }\n if (this._sessions.has(trackId) || this._starting.has(trackId)) {\n console.warn('[dawcore] RecordingController: Already recording on track \"' + trackId + '\"');\n return;\n }\n let resolveStartSettled!: () => void;\n const startEntry: StartingEntry = {\n stopRequested: false,\n done: new Promise<void>((resolve) => {\n resolveStartSettled = resolve;\n }),\n };\n this._starting.set(trackId, startEntry);\n\n const bits: Bits = options.bits ?? 16;\n\n try {\n const rawCtx = this._host.audioContext;\n\n // A suspended context delivers no samples while the UI shows recording\n // (worklet process() never runs). Resume before wiring the capture\n // graph — parity with the React hook, which resumes at record start.\n if (rawCtx.state === 'suspended') {\n await rawCtx.resume();\n }\n\n // Load worklet module — guard tied to context identity so a\n // swapped AudioContext gets the module re-registered.\n if (!this._workletLoadedCtx || this._workletLoadedCtx !== rawCtx) {\n let addRecordingWorkletModule: (addModule: (url: string) => Promise<void>) => Promise<void>;\n try {\n ({ addRecordingWorkletModule } = await import('@waveform-playlist/worklets'));\n } catch (importErr) {\n throw new Error(\n 'Recording requires @waveform-playlist/worklets. ' +\n 'Install it: ' +\n installCommand('@waveform-playlist/worklets') +\n ' (cause: ' +\n String(importErr) +\n ')'\n );\n }\n const addModule = this._host.addWorkletModule\n ? (url: string) => this._host.addWorkletModule!(url)\n : (url: string) => rawCtx.audioWorklet.addModule(url);\n await addRecordingWorkletModule(addModule);\n this._workletLoadedCtx = rawCtx;\n }\n\n // A stop request or host disconnect that arrived during the awaits\n // above (context resume, worklet module load — 50-300ms on first use)\n // must cancel the start. Without this re-check the stop is silently\n // lost (recording runs on) or a live capture session leaks on a\n // torn-down editor. Nothing is wired yet at this point, so bailing\n // needs no cleanup — but it must be OBSERVABLE: no daw-recording-start\n // ever fires, so without an error event an awaiting consumer cannot\n // distinguish \"recording\" from \"cancelled\".\n // NOTE: this re-check must stay AFTER every await that precedes\n // _sessions.set() — inserting a new await below it reopens the race.\n if (startEntry.stopRequested || this._hostDisconnected) {\n this._dispatchRecordingError(\n trackId,\n new Error(\n this._hostDisconnected\n ? 'Recording start cancelled: editor was disconnected during setup'\n : 'Recording start cancelled: stop requested before setup completed'\n )\n );\n return;\n }\n\n // Detect channel count from stream (not source.channelCount — defaults to 2 per spec).\n // Fall back to user-provided channelCount option, then 1.\n const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;\n if (detectedChannelCount === undefined && options.channelCount !== undefined) {\n console.warn(\n '[dawcore] Could not detect stream channel count, using fallback: ' + options.channelCount\n );\n }\n const channelCount = detectedChannelCount ?? options.channelCount ?? 1;\n\n const startSample =\n options.startSample ?? Math.floor(this._host.currentTime * this._host.effectiveSampleRate);\n\n // Compute latency offset once at start (doesn't change during session).\n // An explicit latencyOffset option (seconds) replaces the outputLatency\n // estimate; native transport has no scheduler look-ahead (lookAhead: 0).\n const latencySamples = resolveRecordingOffsetSamples({\n overrideSeconds: options.latencyOffset,\n outputLatency: rawCtx.outputLatency ?? 0,\n lookAhead: 0,\n sampleRate: rawCtx.sampleRate,\n });\n\n // Use host methods when available (supports standardized-audio-context),\n // fall back to native AudioContext methods.\n const source = this._host.createMediaStreamSource\n ? this._host.createMediaStreamSource(stream)\n : rawCtx.createMediaStreamSource(stream);\n const workletNode = this._host.createAudioWorkletNode\n ? this._host.createAudioWorkletNode('recording-processor', {\n channelCount,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n })\n : new AudioWorkletNode(rawCtx, 'recording-processor', {\n channelCount,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n });\n\n // Listen on MediaStreamTrack (not MediaStream — MediaStream has no 'ended' event)\n const audioTrack = stream.getAudioTracks()[0] ?? null;\n const onTrackEnded = audioTrack\n ? () => {\n if (this._sessions.has(trackId)) {\n this.stopRecording(trackId);\n }\n }\n : null;\n\n const session: RecordingSession = {\n trackId,\n stream,\n source,\n workletNode,\n chunks: Array.from({ length: channelCount }, () => []),\n totalSamples: 0,\n peaks: Array.from({ length: channelCount }, () =>\n bits === 8 ? new Int8Array(0) : new Int16Array(0)\n ),\n startSample,\n channelCount,\n captureSampleRate: rawCtx.sampleRate,\n bits,\n isFirstMessage: true,\n latencySamples,\n clipName: options.clipName,\n wasOverdub: options.overdub ?? false,\n stopAckResolve: null,\n stopPromise: null,\n stopping: false,\n };\n this._sessions.set(trackId, session);\n\n // dawcore CLAUDE.md: wire onmessage BEFORE source.connect() and postMessage start\n workletNode.port.onmessage = (e: MessageEvent) => {\n this._onWorkletMessage(trackId, e.data);\n };\n source.connect(workletNode);\n workletNode.port.postMessage({ command: 'start', channelCount });\n\n // Attach mic-unplug listener (stored in session for cleanup)\n if (audioTrack && onTrackEnded) {\n const listener = new AbortController();\n this._trackEndedListeners.set(session, listener);\n audioTrack.addEventListener('ended', onTrackEnded, { signal: listener.signal });\n }\n\n // Mute the track the take is recording onto — punch-in replaces\n // whatever the take overlaps (#579), so the doomed material must not\n // play under the overdub. The take's mute is the engine's (#843): the\n // track plays muted and the engine's tracks carry `muted: true`, which\n // the track controls and an export read; the stored mute is untouched\n // and the take's mute is no undo step, so a mute changed during the\n // take stays after it. Cleared by _clearTakeMute on every\n // session-teardown path. Must engage BEFORE the overdub host.play()\n // below so the track never blips.\n this._host._engine?.setTrackRecording(trackId, true);\n\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingStartDetail>('daw-recording-start', {\n bubbles: true,\n composed: true,\n detail: { trackId, stream },\n })\n );\n\n this._host.requestUpdate();\n\n // Overdub: start playback so user hears existing tracks and playhead advances\n if (options.overdub && typeof this._host.play === 'function') {\n await this._host.play(this._host.currentTime);\n }\n } catch (err) {\n // Clean up partially-created session to prevent stuck isRecording state\n this._cleanupSession(trackId);\n console.warn('[dawcore] RecordingController: Failed to start recording: ' + String(err));\n this._dispatchRecordingError(trackId, err);\n } finally {\n this._starting.delete(trackId);\n resolveStartSettled();\n }\n }\n\n pauseRecording(trackId?: string): void {\n const id = trackId ?? [...this._sessions.keys()][0];\n if (!id) return;\n const session = this._sessions.get(id);\n // Skip if the session is already on its way out — would otherwise\n // dispatch a pause event for a session about to be deleted.\n if (!session || session.stopping) return;\n session.workletNode.port.postMessage({ command: 'pause' });\n this._isPaused = true;\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingPauseDetail>('daw-recording-pause', {\n bubbles: true,\n composed: true,\n detail: { trackId: id },\n })\n );\n }\n\n resumeRecording(trackId?: string): void {\n const id = trackId ?? [...this._sessions.keys()][0];\n if (!id) return;\n const session = this._sessions.get(id);\n if (!session || session.stopping) return;\n session.workletNode.port.postMessage({ command: 'resume' });\n this._isPaused = false;\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingResumeDetail>('daw-recording-resume', {\n bubbles: true,\n composed: true,\n detail: { trackId: id },\n })\n );\n }\n\n async stopRecording(trackId?: string): Promise<void> {\n // Fall back to an in-flight start's trackId too — the stop button fires\n // with no id, and during the async start window there's no session yet.\n // (Single-session assumption: with a live session AND an in-flight start\n // on different tracks, a no-arg stop targets the session.)\n const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];\n if (!id) return;\n\n const session = this._sessions.get(id);\n if (!session) {\n // startRecording is still in its async setup — flag it to abort after\n // its awaits instead of losing the stop, and resolve only once the\n // start has actually settled so `await stop(); start()` doesn't hit\n // the still-held _starting guard.\n const starting = this._starting.get(id);\n if (starting) {\n starting.stopRequested = true;\n return starting.done;\n }\n return;\n }\n\n // Re-entrant stop (stop-button double-click, unmount cleanup) during the\n // ack/drain window must not build a second AudioBuffer or dispatch a\n // second complete event — both callers observe the same in-flight stop.\n if (session.stopping) {\n return session.stopPromise ?? undefined;\n }\n // Block any further pause/resume/stop calls on this session — they could\n // race with the drain loop and dispatch events for a session that's\n // about to be deleted.\n session.stopping = true;\n const stopPromise = this._finishStopRecording(id, session);\n session.stopPromise = stopPromise;\n return stopPromise;\n }\n\n private async _finishStopRecording(id: string, session: RecordingSession): Promise<void> {\n try {\n await this._finalizeRecording(id, session);\n } catch (err) {\n // A throw anywhere in the stop pipeline (host.stop(), chunk\n // concatenation RangeError on a long take, AudioBuffer creation, clip\n // insertion) must not strand the session with stopping=true — that\n // wedges isRecording, keeps the mic graph connected, and leaves the\n // track playing muted. Resolve (not reject) and surface\n // the failure via daw-recording-error, matching the no-audio/too-short\n // error-path convention — fire-and-forget callers (stop button,\n // mic-unplug handler) only observe the event.\n const sessionWasActive = this._sessions.has(id);\n console.warn('[dawcore] RecordingController: Failed to finalize recording: ' + String(err));\n this._cleanupSession(id);\n this._host.requestUpdate();\n // If the session was already finalized, daw-recording-complete has\n // fired and the take was delivered — the throw came from clip\n // insertion. A daw-recording-error for the same take would contradict\n // the complete event, so only the warn above reports it.\n if (sessionWasActive) {\n this._dispatchRecordingError(id, err);\n }\n }\n }\n\n private async _finalizeRecording(id: string, session: RecordingSession): Promise<void> {\n // Capture whether we were paused — pause already flushed the partial\n // buffer, so there's no full-buffer backlog to wait for on stop.\n const wasPaused = this._isPaused;\n this._isPaused = false;\n\n // Stop playback only if this was an overdub session\n if (session.wasOverdub && typeof this._host.stop === 'function') {\n this._host.stop();\n }\n\n // Send stop. If the recording was already paused, pause's flushBuffers()\n // already drained the partial buffer — no need to await the terminal\n // message (and the worklet's audio thread may have throttled back while\n // paused, making the round-trip slow / unreliable).\n if (wasPaused) {\n session.workletNode.port.postMessage({ command: 'stop' });\n // No ack await here — the paused audio thread may be throttled, making\n // the done round-trip slow/unreliable. But posting `stop` does NOT mean\n // earlier messages were delivered: the pause-time flush (and any\n // backlog) can still be in transit, so the queue must still be drained\n // or those chunks are silently dropped from the finalized clip.\n await this._drainWorkletQueue(session);\n } else {\n // Active recording: await the worklet's terminal flush so the partial\n // buffer at stop time isn't silently dropped.\n const stopAck = new Promise<void>((resolve) => {\n session.stopAckResolve = resolve;\n });\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n // Safety timeout (1s). Prevents infinite hang on a real failure\n // (worklet crashed, context closed). The drain loop below catches any\n // straggler flush messages that were queued before the timeout fired,\n // so this is purely a circuit breaker — not a data-correctness budget.\n const timeout = new Promise<void>((resolve) => {\n timeoutId = setTimeout(resolve, 1000);\n });\n session.workletNode.port.postMessage({ command: 'stop' });\n await Promise.race([stopAck, timeout]);\n clearTimeout(timeoutId);\n session.stopAckResolve = null;\n\n await this._drainWorkletQueue(session);\n }\n session.source.disconnect();\n session.workletNode.disconnect();\n\n // Remove mic-unplug listener\n this._removeTrackEndedListener(session);\n\n // Build AudioBuffer from accumulated chunks\n if (session.totalSamples === 0) {\n this._abandonFinalize(id, session, 'No audio data captured');\n return;\n }\n const stopCtx = this._host.audioContext;\n const channelData = session.chunks.map((chunkArr) => concatenateAudioData(chunkArr));\n const audioBuffer = createAudioBuffer(\n stopCtx,\n channelData,\n session.captureSampleRate,\n session.channelCount\n );\n\n // Latency compensation: use the offset computed at start time\n const latencyOffsetSamples = session.latencySamples;\n const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);\n\n if (effectiveDuration === 0) {\n this._abandonFinalize(\n id,\n session,\n 'Recording too short for latency compensation',\n 'Recording too short to save'\n );\n return;\n }\n\n // Dispatch cancelable event\n const event = new CustomEvent<DawRecordingCompleteDetail>('daw-recording-complete', {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n trackId: id,\n audioBuffer,\n startSample: session.startSample,\n durationSamples: effectiveDuration,\n offsetSamples: latencyOffsetSamples,\n },\n });\n const notPrevented = this._host.dispatchEvent(event);\n\n // Clean up session\n this._clearTakeMute(session);\n this._sessions.delete(id);\n this._host.requestUpdate();\n\n if (notPrevented) {\n this._createClipFromRecording(\n id,\n audioBuffer,\n session.startSample,\n effectiveDuration,\n latencyOffsetSamples,\n session.clipName\n );\n }\n }\n\n /** Drain the event-loop queue of pending worklet flush messages. During\n * recording the worklet posts a flush every ~16ms; if main was slower,\n * messages back up. Yield repeatedly until session.totalSamples stabilizes\n * (no new messages processed) for several consecutive ticks — at that\n * point the queue is empty and chunks are complete. */\n private async _drainWorkletQueue(session: RecordingSession): Promise<void> {\n let lastSamples = -1;\n let stable = 0;\n for (let i = 0; i < 50; i++) {\n if (session.totalSamples === lastSamples) {\n if (++stable >= 3) break;\n } else {\n stable = 0;\n lastSamples = session.totalSamples;\n }\n await new Promise<void>((r) => setTimeout(r, 5));\n }\n }\n\n // Session fields are mutated in place on the hot path (~60fps worklet messages).\n // This is intentional — creating new session objects + Map entries per message\n // would cause significant GC pressure. Mutations are confined to the controller's\n // private map and do not affect Lit's reactive rendering.\n private _onWorkletMessage(trackId: string, data: unknown) {\n const session = this._sessions.get(trackId);\n if (!session) return;\n\n const { channels, done } = data as { channels: Float32Array[]; done?: boolean };\n\n // Resolve the stop barrier in a finally block so a throw in peak generation\n // (e.g. samplesPerPixel=0 transient, host shadowRoot churn) doesn't strand\n // the await in stopRecording for the full 1000ms safety timeout.\n try {\n const hasSamples = !!(\n channels &&\n channels.length > 0 &&\n channels[0] &&\n channels[0].length > 0\n );\n if (!hasSamples) return;\n this._processWorkletSamples(trackId, session, channels);\n } finally {\n if (done && session.stopAckResolve) {\n const resolve = session.stopAckResolve;\n session.stopAckResolve = null;\n resolve();\n }\n }\n }\n\n private _processWorkletSamples(\n trackId: string,\n session: RecordingSession,\n channels: Float32Array[]\n ) {\n // Capture pre-increment value for appendPeaks\n const samplesProcessedBefore = session.totalSamples;\n\n // Accumulate chunks per channel — always do this, even during stop,\n // so the AudioBuffer captures every sample.\n for (let ch = 0; ch < session.channelCount; ch++) {\n if (channels[ch]) {\n session.chunks[ch].push(channels[ch]);\n }\n }\n session.totalSamples += channels[0].length;\n\n // If stop is already in flight, skip peak generation and live-preview\n // waveform updates. The recording is ending; the AudioBuffer's final\n // peaks will be regenerated by the consumer. Skipping this drains the\n // backlog of queued flush messages faster, getting us to the terminal\n // `done` message sooner.\n if (session.stopAckResolve !== null) return;\n\n // Generate peaks per channel and update live preview waveforms\n for (let ch = 0; ch < session.channelCount; ch++) {\n if (!channels[ch]) continue;\n const oldPeakCount = Math.floor(session.peaks[ch].length / 2);\n (session.peaks as (Int8Array | Int16Array)[])[ch] = appendPeaks(\n session.peaks[ch],\n channels[ch],\n // Render-space scale — in beats mode this differs from\n // samplesPerPixel, and the preview container is laid out in\n // render space (see RecordingHost.renderSamplesPerPixel).\n this._host.renderSamplesPerPixel,\n samplesProcessedBefore,\n session.bits\n );\n const newPeakCount = Math.floor(session.peaks[ch].length / 2);\n\n // Update live preview waveform — host is already & HTMLElement so shadowRoot is typed\n const waveformSelector = `daw-waveform[data-recording-track=\"${trackId}\"][data-recording-channel=\"${ch}\"]`;\n const waveformEl = this._host.shadowRoot?.querySelector(\n waveformSelector\n ) as DawWaveformElement | null;\n if (waveformEl) {\n if (session.isFirstMessage) {\n waveformEl.peaks = session.peaks[ch];\n } else {\n waveformEl.setPeaksQuiet(session.peaks[ch]);\n waveformEl.updatePeaks(Math.max(0, oldPeakCount - 1), newPeakCount);\n }\n }\n }\n\n session.isFirstMessage = false;\n\n // Throttle requestUpdate — only when container width needs to grow\n const newPixelWidth = Math.floor(session.totalSamples / this._host.renderSamplesPerPixel);\n const oldPixelWidth = Math.floor(\n (session.totalSamples - channels[0].length) / this._host.renderSamplesPerPixel\n );\n if (newPixelWidth > oldPixelWidth) {\n this._host.requestUpdate();\n }\n }\n\n private _createClipFromRecording(\n trackId: string,\n audioBuffer: AudioBuffer,\n startSample: number,\n durationSamples: number,\n offsetSamples = 0,\n clipName?: string\n ) {\n if (typeof this._host._addRecordedClip === 'function') {\n this._host._addRecordedClip(\n trackId,\n audioBuffer,\n startSample,\n durationSamples,\n offsetSamples,\n clipName\n );\n } else {\n console.warn(\n '[dawcore] RecordingController: host does not implement _addRecordedClip — clip not created for track \"' +\n trackId +\n '\"'\n );\n }\n }\n\n private _removeTrackEndedListener(session: RecordingSession) {\n this._trackEndedListeners.get(session)?.abort();\n this._trackEndedListeners.delete(session);\n }\n\n private _dispatchRecordingError(trackId: string, error: unknown) {\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingErrorDetail>('daw-recording-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, error },\n })\n );\n }\n\n /** Shared teardown for finalize paths that end without a take (no data\n * captured / too short after latency compensation): clear the take's mute, drop\n * the session, and notify via daw-recording-error so record buttons reset\n * their state. */\n private _abandonFinalize(\n id: string,\n session: RecordingSession,\n warnMessage: string,\n errorMessage: string = warnMessage\n ) {\n console.warn('[dawcore] RecordingController: ' + warnMessage);\n this._clearTakeMute(session);\n this._sessions.delete(id);\n this._host.requestUpdate();\n this._dispatchRecordingError(id, new Error(errorMessage));\n }\n\n /** Clear the take's mute on the session's track, by its id. Each teardown\n * path calls this once, right before it drops the session from the map, so\n * a later path never reaches the same session; clearing an id that is not\n * set is a no-op in the engine. Another session's mute on another track is\n * left alone. */\n private _clearTakeMute(session: RecordingSession) {\n this._host._engine?.setTrackRecording(session.trackId, false);\n }\n\n /** @param notifyError dispatch daw-recording-error after cleanup — used by\n * disposal paths that would otherwise discard the session silently. The\n * startRecording catch path passes false (it dispatches its own error). */\n private _cleanupSession(trackId: string, notifyError = false) {\n const session = this._sessions.get(trackId);\n if (!session) return;\n try {\n this._clearTakeMute(session);\n this._removeTrackEndedListener(session);\n session.workletNode.port.postMessage({ command: 'stop' });\n session.source.disconnect();\n session.workletNode.disconnect();\n } catch (err) {\n console.warn(\n '[dawcore] RecordingController: disconnect error during cleanup for track \"' +\n trackId +\n '\": ' +\n String(err)\n );\n }\n this._sessions.delete(trackId);\n if (this._sessions.size === 0) {\n // A leftover pause flag would misreport isPaused for the next session\n // and send its stop down the no-ack fast path.\n this._isPaused = false;\n }\n if (notifyError) {\n this._dispatchRecordingError(\n trackId,\n new Error('Recording cancelled: editor was disconnected mid-recording')\n );\n }\n }\n}\n","import { html } from 'lit';\nimport type { ReactiveController, ReactiveControllerHost, TemplateResult } from 'lit';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport type { DawAnnotationTrackElement } from '../elements/daw-annotation-track';\nimport type { DawTimeUpdateDetail } from '../events';\nimport { computePlayingAnnotationId } from '../utils/annotation-playing';\n\n/**\n * Fixed lane height. A TS constant (not a CSS var) because the frozen-panes\n * controls-column spacer and the beats-grid top offset need it in layout math.\n */\nexport const ANNOTATION_LANE_HEIGHT = 32;\n\nexport interface AnnotationControllerHost extends ReactiveControllerHost, HTMLElement {\n effectiveSampleRate: number;\n seekTo(time: number): void;\n /** Tick→seconds conversion (fixed BPM or variable-tempo callbacks) —\n * the editor owns tempo; the controller derives annotation seconds caches. */\n _ticksToSeconds(ticks: number): number;\n}\n\n/**\n * Registers <daw-annotation-track> light-DOM children and renders their\n * timeline lanes inside the editor's shadow DOM. Rendering only — drag\n * interactions live in interactions/annotation-drag.ts.\n */\nexport class AnnotationController implements ReactiveController {\n private _host: AnnotationControllerHost;\n private _tracks: DawAnnotationTrackElement[] = [];\n private _removalObserver: MutationObserver | null = null;\n /** Playback-following highlight per track, separate from each track's\n * `activeAnnotationId` (selection) so playback never disturbs selection.\n * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.\n * Replaced immutably (a fresh Map) on every change. */\n private _playingIds: Map<DawAnnotationTrackElement, string | null> = new Map();\n\n constructor(host: AnnotationControllerHost) {\n this._host = host;\n host.addController(this);\n }\n\n get tracks(): readonly DawAnnotationTrackElement[] {\n return this._tracks;\n }\n\n /** Current playback-following highlight id for a track, or `null` when the\n * playhead isn't inside any of the track's annotations. */\n getPlayingAnnotationId(track: DawAnnotationTrackElement): string | null {\n return this._playingIds.get(track) ?? null;\n }\n\n get totalLaneHeight(): number {\n return this._tracks.length * ANNOTATION_LANE_HEIGHT;\n }\n\n /** Max annotation end (seconds) across registered tracks — 0 when none.\n * Lets the editor extend the timeline so annotations past the audio stay\n * reachable/scrollable. */\n get maxAnnotationEndSeconds(): number {\n return this._tracks.reduce(\n (max, track) => track.annotations.reduce((m, a) => Math.max(m, a.end), max),\n 0\n );\n }\n\n /** The host listeners of this connection, aborted in hostDisconnected. */\n private _listeners: AbortController | null = null;\n\n hostConnected(): void {\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n this._host.addEventListener('daw-annotation-update', this._onDataChange, { signal });\n this._host.addEventListener('daw-annotation-select', this._onDataChange, { signal });\n this._host.addEventListener('daw-annotation-connected', this._onDataChange, { signal });\n // The host IS the editor and daw-timeupdate/daw-stop are dispatched on\n // it directly (see playback-animation-controller.ts) — no document-level\n // listening or target filtering needed, unlike <daw-annotation-list>.\n this._host.addEventListener('daw-timeupdate', this._onTimeUpdate as EventListener, { signal });\n this._host.addEventListener('daw-stop', this._onStop, { signal });\n // Removals can't bubble — observe childList like the editor's track observer.\n this._removalObserver = new MutationObserver((mutations) => {\n let changed = false;\n for (const m of mutations) {\n for (const node of Array.from(m.removedNodes)) {\n if (!(node instanceof HTMLElement)) continue;\n if (node.tagName === 'DAW-ANNOTATION-TRACK') {\n this._tracks = this._tracks.filter((t) => t !== node);\n changed = true;\n } else if (node.tagName === 'DAW-ANNOTATION') {\n changed = true;\n }\n // A wrapper element containing a track (rather than the track\n // itself) is removed — recurse into the subtree like the editor's\n // track observer, or the nested track is never unregistered.\n const nestedTracks = node.querySelectorAll?.('daw-annotation-track');\n if (nestedTracks) {\n for (const nested of nestedTracks) {\n this._tracks = this._tracks.filter((t) => t !== nested);\n changed = true;\n }\n }\n const nestedAnnotations = node.querySelectorAll?.('daw-annotation');\n if (nestedAnnotations && nestedAnnotations.length > 0) {\n changed = true;\n }\n }\n }\n if (changed) this._host.requestUpdate();\n });\n this._removalObserver.observe(this._host, { childList: true, subtree: true });\n }\n\n hostDisconnected(): void {\n this._listeners?.abort();\n this._listeners = null;\n this._removalObserver?.disconnect();\n this._removalObserver = null;\n this._tracks = [];\n this._playingIds = new Map();\n }\n\n private _onDataChange = (): void => {\n this.deriveSecondsCaches();\n this._host.requestUpdate();\n };\n\n /**\n * Update only on annotation-boundary crossings, not per animation frame.\n */\n private _onTimeUpdate = (e: CustomEvent<DawTimeUpdateDetail>): void => {\n const time = e.detail.time;\n let changed = false;\n const next = new Map(this._playingIds);\n for (const track of this._tracks) {\n const playingId = computePlayingAnnotationId(track.annotations, time);\n if (playingId !== (this._playingIds.get(track) ?? null)) {\n next.set(track, playingId);\n changed = true;\n }\n }\n if (!changed) return;\n this._playingIds = next;\n this._host.requestUpdate();\n };\n\n private _onStop = (): void => {\n if (this._playingIds.size === 0) return;\n this._playingIds = new Map();\n this._host.requestUpdate();\n };\n\n handleTrackConnected(el: DawAnnotationTrackElement): void {\n if (this._tracks.includes(el)) return;\n this._tracks = [...this._tracks, el];\n this._host.requestUpdate();\n this.deriveSecondsCaches();\n }\n\n /**\n * Keep the seconds attributes (derived cache) of tick-based annotations in\n * sync with the host's tempo. Write-only-on-change: a write fires\n * daw-annotation-update → _onDataChange → this sweep again → values equal →\n * no write → the loop settles (idempotent).\n */\n deriveSecondsCaches(): void {\n for (const track of this._tracks) {\n for (const el of track.annotationElements) {\n if (!el.isTickBased) continue;\n const startSeconds = this._host._ticksToSeconds(el.startTick as number);\n const endSeconds = this._host._ticksToSeconds(el.endTick as number);\n if (el.start !== startSeconds) el.start = startSeconds;\n if (el.end !== endSeconds) el.end = endSeconds;\n }\n }\n }\n\n /** Pixel geometry for one annotation box. Tick-based annotations in beats\n * mode use CLIP-IDENTICAL tick math (round(tick / ticksPerPixel)) so they\n * align pixel-exactly with <daw-grid>; everything else uses the floor-based\n * seconds math (temporal mode reads the always-fresh seconds cache). */\n boxGeometry(\n a: AnnotationData,\n spp: number,\n sampleRate: number,\n ticksPerPixel: number | null = null\n ): { left: number; width: number } {\n if (\n ticksPerPixel !== null &&\n ticksPerPixel > 0 &&\n a.startTick !== undefined &&\n a.endTick !== undefined\n ) {\n const left = Math.round(a.startTick / ticksPerPixel);\n const width = Math.round(a.endTick / ticksPerPixel) - left;\n return { left, width };\n }\n const left = Math.floor((a.start * sampleRate) / spp);\n const width = Math.floor((a.end * sampleRate) / spp) - left;\n return { left, width };\n }\n\n /**\n * Lane templates for the editor's .timeline. onPointerDown is supplied by\n * the editor and dispatches into the drag interaction (Task 9).\n */\n renderLanes(\n spp: number,\n sampleRate: number,\n onPointerDown: (e: PointerEvent, track: DawAnnotationTrackElement) => void = () => {},\n ticksPerPixel: number | null = null\n ): TemplateResult[] {\n return this._tracks.map((track) => {\n const activeId = track.activeAnnotationId;\n const playingId = this._playingIds.get(track) ?? null;\n const elements = track.annotationElements;\n return html`\n <div\n class=\"annotation-lane\"\n style=\"height: ${ANNOTATION_LANE_HEIGHT}px;\"\n @pointerdown=${(e: PointerEvent) => onPointerDown(e, track)}\n >\n ${elements.map((el, i) => {\n const a = el.toAnnotationData();\n const geo = this.boxGeometry(a, spp, sampleRate, ticksPerPixel);\n const label =\n track.boxLabel === 'none'\n ? ''\n : track.boxLabel === 'id'\n ? el.id || String(i + 1)\n : a.lines.join(' ');\n return html`\n <div\n class=\"annotation-box ${a.id === activeId ? 'active' : ''} ${a.id === playingId\n ? 'playing'\n : ''}\"\n data-annotation-id=${a.id}\n style=\"left: ${geo.left}px; width: ${geo.width}px;\"\n >\n ${track.editable\n ? html`<div class=\"annotation-boundary\" data-edge=\"start\"></div>`\n : ''}\n <span class=\"annotation-box-text\">${label}</span>\n ${track.editable\n ? html`<div class=\"annotation-boundary\" data-edge=\"end\"></div>`\n : ''}\n </div>\n `;\n })}\n </div>\n `;\n });\n }\n}\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport {\n SpectrogramOrchestrator,\n type ClipRegistration,\n type CanvasRegistration,\n type ViewportState,\n} from '@dawcore/spectrogram';\nimport type { SpectrogramConfig, ColorMapValue } from '@waveform-playlist/core';\nimport {\n SPECTROGRAM_DEFAULTS as LIBRARY_DEFAULTS,\n DEFAULT_SPECTROGRAM_COLOR_MAP as LIBRARY_DEFAULT_COLOR_MAP,\n} from '@waveform-playlist/core';\n\nexport interface SpectrogramControllerHost extends ReactiveControllerHost {\n dispatchEvent(event: Event): boolean;\n}\n\n/**\n * Lit reactive controller that owns a `SpectrogramOrchestrator` for the\n * `<daw-editor>` host. Creates the orchestrator lazily on first canvas\n * registration so editors without spectrogram tracks pay nothing.\n *\n * Holds editor-level defaults and per-track overrides separately; merges\n * them down to a single (config, colorMap) pair for the orchestrator on\n * each change.\n *\n * v1 limitation: orchestrator accepts ONE config / colorMap at a time, so\n * the \"first registered track wins\" rule applies when multiple tracks are\n * in spectrogram mode with different overrides. Multi-track per-clip\n * configs are deferred to a follow-up.\n */\nexport class SpectrogramController implements ReactiveController {\n private host: SpectrogramControllerHost;\n private workerFactory: () => Worker;\n private orchestrator: SpectrogramOrchestrator | null = null;\n\n private editorConfig: SpectrogramConfig | null = null;\n private editorColorMap: ColorMapValue | null = null;\n private trackConfigs = new Map<string, SpectrogramConfig | null>();\n private trackColorMaps = new Map<string, ColorMapValue | null>();\n\n constructor(host: SpectrogramControllerHost, workerFactory: () => Worker) {\n this.host = host;\n this.workerFactory = workerFactory;\n this.host.addController(this);\n }\n\n hostConnected(): void {\n // Lazy — orchestrator created on first registerCanvas.\n }\n\n hostDisconnected(): void {\n this.dispose();\n }\n\n setEditorConfig(config: SpectrogramConfig | null): void {\n this.editorConfig = config;\n this.reapply();\n }\n\n setEditorColorMap(colorMap: ColorMapValue | null): void {\n this.editorColorMap = colorMap;\n this.reapply();\n }\n\n setTrackConfig(trackId: string, config: SpectrogramConfig | null): void {\n if (config === null) {\n this.trackConfigs.delete(trackId);\n } else {\n this.trackConfigs.set(trackId, config);\n }\n this.reapply();\n }\n\n setTrackColorMap(trackId: string, colorMap: ColorMapValue | null): void {\n if (colorMap === null) {\n this.trackColorMaps.delete(trackId);\n } else {\n this.trackColorMaps.set(trackId, colorMap);\n }\n this.reapply();\n }\n\n registerClipAudio(reg: ClipRegistration): void {\n this.ensureOrchestrator().registerClip(reg);\n }\n\n unregisterClipAudio(clipId: string): void {\n this.orchestrator?.unregisterClip(clipId);\n }\n\n registerCanvas(reg: CanvasRegistration): void {\n this.ensureOrchestrator().registerCanvas(reg);\n }\n\n unregisterCanvas(canvasId: string): void {\n this.orchestrator?.unregisterCanvas(canvasId);\n }\n\n setViewport(state: ViewportState): void {\n this.orchestrator?.setViewport(state);\n }\n\n dispose(): void {\n if (this.orchestrator) {\n this.orchestrator.dispose();\n this.orchestrator = null;\n }\n }\n\n private ensureOrchestrator(): SpectrogramOrchestrator {\n if (!this.orchestrator) {\n this.orchestrator = new SpectrogramOrchestrator({\n workerFactory: this.workerFactory,\n workerPoolSize: 2,\n config: this.mergedConfig(),\n colorMap: this.mergedColorMap(),\n });\n this.orchestrator.addEventListener('viewport-ready', (e: Event) => {\n const detail = (e as CustomEvent<{ trackId: string; generation: number }>).detail;\n this.host.dispatchEvent(\n new CustomEvent('daw-spectrogram-ready', {\n detail: { trackId: detail.trackId, generation: detail.generation },\n bubbles: true,\n composed: true,\n })\n );\n });\n this.orchestrator.addEventListener('viewport-error', (e: Event) => {\n const detail = (e as CustomEvent<{ trackId: string; generation: number; error: Error }>)\n .detail;\n this.host.dispatchEvent(\n new CustomEvent('daw-spectrogram-error', {\n detail: {\n trackId: detail.trackId,\n generation: detail.generation,\n error: detail.error,\n },\n bubbles: true,\n composed: true,\n })\n );\n });\n this.reapply();\n }\n return this.orchestrator;\n }\n\n private reapply(): void {\n if (!this.orchestrator) return;\n this.orchestrator.setConfig(this.mergedConfig());\n this.orchestrator.setColorMap(this.mergedColorMap());\n }\n\n private mergedConfig(): SpectrogramConfig {\n // First track override wins (v1 limitation noted above).\n let track: SpectrogramConfig | null = null;\n for (const c of this.trackConfigs.values()) {\n track = c;\n break;\n }\n return { ...LIBRARY_DEFAULTS, ...(this.editorConfig ?? {}), ...(track ?? {}) };\n }\n\n private mergedColorMap(): ColorMapValue {\n for (const c of this.trackColorMaps.values()) {\n return c ?? LIBRARY_DEFAULT_COLOR_MAP;\n }\n return this.editorColorMap ?? LIBRARY_DEFAULT_COLOR_MAP;\n }\n}\n","import { pixelsToSeconds, snapTickToGrid } from '@waveform-playlist/core';\nimport type { SnapTo, MeterEntry } from '@waveform-playlist/core';\nimport { DRAG_THRESHOLD } from './constants';\n\n/** Narrow engine contract for pointer interactions. */\nexport interface PointerEngineContract {\n setSelection(start: number, end: number): void;\n stop(): void;\n play(time: number): void;\n seek(time: number): void;\n selectTrack(trackId: string | null): void;\n}\n\n/** Manages pointer interactions on the timeline: click-to-seek and drag-to-select. */\nexport interface PointerHandlerHost {\n readonly samplesPerPixel: number;\n readonly _engine: PointerEngineContract | null;\n readonly _isPlaying: boolean;\n readonly effectiveSampleRate: number;\n _currentTime: number;\n _selectionStartTime: number;\n _selectionEndTime: number;\n _dragOver: boolean;\n /** Suppresses the transient settle daw-timeupdate during stop+play seeks. */\n _inSeekTransition: boolean;\n _setSelectedTrackId(trackId: string | null): void;\n _startPlayhead(): void;\n _stopPlayhead(): void;\n dispatchEvent(event: Event): boolean;\n shadowRoot: ShadowRoot | null;\n requestUpdate(): void;\n readonly _clipHandler: {\n tryHandle(target: Element, e: PointerEvent): boolean;\n onPointerMove(e: PointerEvent): void;\n onPointerUp(e: PointerEvent): void;\n onPointerCancel(e: PointerEvent): void;\n isActive: boolean;\n } | null;\n readonly scaleMode: 'temporal' | 'beats';\n readonly ticksPerPixel: number;\n readonly bpm: number;\n readonly ppqn: number;\n readonly _meterEntries: MeterEntry[];\n readonly snapTo: SnapTo;\n readonly _secondsToTicks: (seconds: number) => number;\n readonly _ticksToSeconds: (ticks: number) => number;\n}\n\nexport class PointerHandler {\n private _host: PointerHandlerHost;\n private _isDragging = false;\n private _dragStartPx = 0;\n private _dragStartTime = 0;\n private _timeline: HTMLElement | null = null;\n // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag\n private _timelineRect: DOMRect | null = null;\n /** Pointer that started the current interaction — a pointercancel from any\n * OTHER pointer (palm rejection on touch) must not kill the active drag. */\n private _activePointerId: number | null = null;\n // Selection values at pointerdown — restored on cancel so an interrupted\n // drag doesn't destroy a previously committed selection (which the engine\n // still holds; zeroing only the host would desync the two).\n private _preDragSelectionStart = 0;\n private _preDragSelectionEnd = 0;\n\n constructor(host: PointerHandlerHost) {\n this._host = host;\n }\n\n private _pxFromPointer(e: PointerEvent): number {\n if (!this._timelineRect) {\n console.warn('[dawcore] _pxFromPointer called without timeline reference');\n return 0;\n }\n // .timeline is wider than :host (which has overflow-x: auto).\n // getBoundingClientRect().left already reflects scroll position\n // (goes negative when scrolled), so no scrollLeft adjustment needed.\n return e.clientX - this._timelineRect.left;\n }\n\n private _pxToTime(px: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n let tick = px * h.ticksPerPixel;\n tick = snapTickToGrid(tick, h.snapTo, h._meterEntries, h.ppqn);\n return h._ticksToSeconds(tick);\n }\n return pixelsToSeconds(px, h.samplesPerPixel, h.effectiveSampleRate);\n }\n\n private _timeToPx(time: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n const tick = h._secondsToTicks(time);\n return tick / h.ticksPerPixel;\n }\n return (time * h.effectiveSampleRate) / h.samplesPerPixel;\n }\n\n /** The timeline's listeners of the seek / selection press in progress. */\n private _seekGesture: AbortController | null = null;\n\n /** Cancels the armed clip drag; set while one is armed (#848). */\n private _cancelArmedClipDrag: (() => void) | null = null;\n\n /**\n * Cancel an armed clip move or trim as a `pointercancel` would: the clip\n * handler reverts it and the timeline's listeners and pointer capture are\n * released. Returns whether a clip drag was armed.\n */\n cancelClipDrag(): boolean {\n const cancel = this._cancelArmedClipDrag;\n if (!cancel) return false;\n cancel();\n return true;\n }\n\n onPointerDown = (e: PointerEvent) => {\n // Check if click landed on an interactive clip element\n const clipHandler = this._host._clipHandler;\n if (clipHandler) {\n const target = e.composedPath()[0] as Element;\n if (target && clipHandler.tryHandle(target, e)) {\n // Prevent browser native drag (globe icon) and text selection\n e.preventDefault();\n // Clip handler took over — wire move/up to it\n this._timeline = this._host.shadowRoot?.querySelector('.timeline') as HTMLElement | null;\n if (this._timeline) {\n try {\n this._timeline.setPointerCapture(e.pointerId);\n } catch (err) {\n console.warn('[dawcore] setPointerCapture failed: ' + String(err));\n }\n const onMove = (me: Event) => clipHandler.onPointerMove(me as PointerEvent);\n // This clip drag's listeners: aborted on every way it ends.\n const gesture = new AbortController();\n const detach = (pointerId: number) => {\n this._cancelArmedClipDrag = null;\n gesture.abort();\n try {\n this._timeline?.releasePointerCapture(pointerId);\n } catch (err) {\n console.warn(\n '[dawcore] releasePointerCapture failed (may already be released): ' + String(err)\n );\n }\n this._timeline = null;\n };\n const onUp = (ue: Event) => {\n clipHandler.onPointerUp(ue as PointerEvent);\n detach((ue as PointerEvent).pointerId);\n };\n // pointercancel fires INSTEAD of pointerup on touch interruption /\n // pen leaving range / OS gestures — the clip drag must be reverted\n // or it stays armed and its transaction stays open. Only the\n // initiating pointer's cancel counts (palm rejection cancels the\n // palm's pointer, not the drag).\n const downPointerId = e.pointerId;\n const onCancel = (ce: Event) => {\n if ((ce as PointerEvent).pointerId !== downPointerId) return;\n clipHandler.onPointerCancel(ce as PointerEvent);\n detach((ce as PointerEvent).pointerId);\n };\n // Escape and the editor's disconnect cancel the drag the same way (#848).\n this._cancelArmedClipDrag = () => {\n clipHandler.onPointerCancel(\n new PointerEvent('pointercancel', { pointerId: downPointerId })\n );\n detach(downPointerId);\n };\n const { signal } = gesture;\n this._timeline.addEventListener('pointermove', onMove, { signal });\n this._timeline.addEventListener('pointerup', onUp, { signal });\n this._timeline.addEventListener('pointercancel', onCancel, { signal });\n }\n return;\n }\n }\n\n this._timeline = this._host.shadowRoot?.querySelector('.timeline') as HTMLElement | null;\n if (!this._timeline) {\n console.warn(\n '[dawcore] PointerHandler: .timeline not found in shadow root — seek/selection ignored'\n );\n return;\n }\n\n this._timelineRect = this._timeline.getBoundingClientRect();\n this._dragStartPx = this._pxFromPointer(e);\n this._isDragging = false;\n this._activePointerId = e.pointerId;\n this._preDragSelectionStart = this._host._selectionStartTime;\n this._preDragSelectionEnd = this._host._selectionEndTime;\n\n try {\n this._timeline.setPointerCapture(e.pointerId);\n } catch (err) {\n console.warn('[dawcore] setPointerCapture failed: ' + String(err));\n }\n // A press while one is in progress (a second touch) keeps one set of\n // listeners, as adding the same listeners again did.\n this._seekGesture?.abort();\n this._seekGesture = new AbortController();\n const { signal } = this._seekGesture;\n this._timeline.addEventListener('pointermove', this._onPointerMove, { signal });\n this._timeline.addEventListener('pointerup', this._onPointerUp, { signal });\n this._timeline.addEventListener('pointercancel', this._onPointerCancel, { signal });\n };\n\n private _onPointerMove = (e: PointerEvent) => {\n if (!this._timeline) return;\n\n const currentPx = this._pxFromPointer(e);\n\n if (!this._isDragging && Math.abs(currentPx - this._dragStartPx) > DRAG_THRESHOLD) {\n this._isDragging = true;\n // Cache snapped start time once — don't recompute every frame\n this._dragStartTime = this._pxToTime(this._dragStartPx);\n }\n\n if (this._isDragging) {\n const h = this._host;\n const startTime = this._dragStartTime;\n const endTime = this._pxToTime(currentPx);\n // Mutate host fields directly (not @state) and update <daw-selection>\n // imperatively to avoid triggering Lit re-renders at 60fps during drag\n h._selectionStartTime = Math.min(startTime, endTime);\n h._selectionEndTime = Math.max(startTime, endTime);\n const sel = h.shadowRoot?.querySelector('daw-selection') as\n | { startPx: number; endPx: number }\n | undefined;\n if (sel) {\n sel.startPx = this._timeToPx(h._selectionStartTime);\n sel.endPx = this._timeToPx(h._selectionEndTime);\n }\n }\n };\n\n /** Detach the drag listeners and release capture — shared by the up and\n * cancel terminals so a new listener added to onPointerDown can't be\n * missed on one of them. */\n private _detachTimeline(e: PointerEvent) {\n if (!this._timeline) return;\n try {\n this._timeline.releasePointerCapture(e.pointerId);\n } catch (err) {\n console.warn(\n '[dawcore] releasePointerCapture failed (may already be released): ' + String(err)\n );\n }\n this._seekGesture?.abort();\n this._seekGesture = null;\n }\n\n private _resetInteractionState() {\n this._isDragging = false;\n this._timeline = null;\n this._timelineRect = null;\n this._activePointerId = null;\n }\n\n private _onPointerUp = (e: PointerEvent) => {\n if (!this._timeline) return;\n\n this._detachTimeline(e);\n\n try {\n if (this._isDragging) {\n this._finalizeSelection();\n } else {\n this._handleSeekClick(e);\n }\n } catch (err) {\n console.warn('[dawcore] Pointer interaction failed: ' + String(err));\n } finally {\n this._resetInteractionState();\n }\n };\n\n /** pointercancel fires INSTEAD of pointerup on touch interruption / pen\n * leaving range / OS gestures — discard the interaction (no seek, no\n * selection finalize) and detach the drag listeners, or the still-attached\n * move handler keeps mutating the selection on hover with a stale rect. */\n private _onPointerCancel = (e: PointerEvent) => {\n if (!this._timeline) return;\n // Only the initiating pointer's cancel ends the interaction — a palm\n // touch that the OS rejects fires pointercancel for the PALM's pointer.\n if (e.pointerId !== this._activePointerId) return;\n\n this._detachTimeline(e);\n\n if (this._isDragging) {\n // Cancel = as if the drag never happened: restore the pre-drag\n // selection (the engine still holds it — zeroing only the host would\n // desync the two and destroy a committed selection).\n const h = this._host;\n h._selectionStartTime = this._preDragSelectionStart;\n h._selectionEndTime = this._preDragSelectionEnd;\n const sel = h.shadowRoot?.querySelector('daw-selection') as\n | { startPx: number; endPx: number }\n | undefined;\n if (sel) {\n sel.startPx = this._timeToPx(this._preDragSelectionStart);\n sel.endPx = this._timeToPx(this._preDragSelectionEnd);\n }\n h.requestUpdate();\n }\n\n this._resetInteractionState();\n };\n\n private _finalizeSelection() {\n const h = this._host;\n if (h._engine) {\n h._engine.setSelection(h._selectionStartTime, h._selectionEndTime);\n }\n h.dispatchEvent(\n new CustomEvent('daw-selection', {\n bubbles: true,\n composed: true,\n detail: { start: h._selectionStartTime, end: h._selectionEndTime },\n })\n );\n h.requestUpdate();\n }\n\n private _handleSeekClick(e: PointerEvent) {\n const h = this._host;\n const px = this._pxFromPointer(e);\n const time = this._pxToTime(px);\n\n // Clear selection\n h._selectionStartTime = 0;\n h._selectionEndTime = 0;\n\n // Detect which track was clicked by Y position\n if (this._timeline) {\n const trackRows = this._timeline.querySelectorAll('.track-row');\n for (const row of trackRows) {\n const rowRect = row.getBoundingClientRect();\n if (e.clientY >= rowRect.top && e.clientY < rowRect.bottom) {\n const trackId = (row as HTMLElement).dataset.trackId;\n if (trackId) {\n this._selectTrack(trackId);\n }\n break;\n }\n }\n }\n\n // Capture playing state before engine calls (stop emits statechange\n // which synchronously flips _isPlaying — use wasPlaying for all guards)\n const wasPlaying = h._isPlaying;\n\n if (h._engine) {\n h._engine.setSelection(0, 0);\n if (wasPlaying) {\n // Tone.js needs stop + play to reschedule audio sources.\n // Suppress the transient settle dispatch — engine.stop() rewinds to\n // the play-start position and the editor's engine-'stop' handler would\n // leak a backward-jumping daw-timeupdate before frames resume at the\n // seek target.\n h._inSeekTransition = true;\n try {\n h._engine.stop();\n } finally {\n h._inSeekTransition = false;\n }\n h._engine.play(time);\n h._startPlayhead();\n } else {\n h._engine.seek(time);\n }\n }\n\n h._currentTime = time;\n if (!wasPlaying) {\n h._stopPlayhead();\n }\n\n h.dispatchEvent(\n new CustomEvent('daw-seek', {\n bubbles: true,\n composed: true,\n detail: { time },\n })\n );\n h.requestUpdate();\n }\n\n private _selectTrack(trackId: string) {\n const h = this._host;\n if (h._engine) {\n try {\n h._engine.selectTrack(trackId);\n // Engine sets _selectedTrackId via statechange — don't set locally\n } catch (err) {\n console.warn(\n '[dawcore] selectTrack via engine failed, falling back to local: ' + String(err)\n );\n // Fall through to local selection below\n h._setSelectedTrackId(trackId);\n }\n } else {\n // No engine — set locally (will be lost when engine builds, acceptable for Phase 2)\n h._setSelectedTrackId(trackId);\n }\n h.dispatchEvent(\n new CustomEvent('daw-track-select', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n }\n}\n","/** Minimum pixel movement before a drag is activated (click vs drag). */\nexport const DRAG_THRESHOLD = 3;\n\n// Boundary width (8px) is defined in CSS (styles/theme.ts .clip-boundary).\n// Not exported as a JS constant since CSS template literals can't import it.\n","import { snapTickToGrid } from '@waveform-playlist/core';\nimport type { AudioClip, SnapTo, MeterEntry } from '@waveform-playlist/core';\nimport { constrainClipDrag } from '@waveform-playlist/engine';\nimport type { DraggedClip } from './drag-watch';\nimport { DRAG_THRESHOLD } from './constants';\n\n/** Snapshot of a clip's bounds for trim constraint computation. */\nexport interface ClipBounds {\n readonly offsetSamples: number;\n readonly durationSamples: number;\n readonly startSample: number;\n readonly sourceDurationSamples: number;\n}\n\n/** Narrow engine contract for clip move/trim interactions. */\nexport interface ClipEngineContract {\n /** Move a clip; returns the delta actually applied. One undo step. */\n moveClip(trackId: string, clipId: string, deltaSamples: number): number;\n trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): void;\n /** The loaded clips of each track (a move collides with them, as `moveClip` does). */\n getState(): { tracks: readonly { id: string; clips: readonly AudioClip[] }[] };\n /** Get a clip's full bounds for trim constraint computation. */\n getClipBounds(trackId: string, clipId: string): ClipBounds | null;\n /** Constrain a trim delta using the engine's collision/bounds logic. */\n constrainTrimDelta(\n trackId: string,\n clipId: string,\n boundary: 'left' | 'right',\n deltaSamples: number\n ): number;\n}\n\n/** Peak data returned by reextractClipPeaks for imperative waveform updates. */\nexport interface ClipPeakSlice {\n data: ArrayLike<number>[];\n length: number;\n}\n\n/** Host interface required by ClipPointerHandler. */\nexport interface ClipPointerHost {\n readonly samplesPerPixel: number;\n /** In beats mode, the tick-derived SPP used for rendering. */\n readonly renderSamplesPerPixel: number;\n readonly effectiveSampleRate: number;\n readonly interactiveClips: boolean;\n readonly engine: ClipEngineContract | null;\n readonly shadowRoot: ShadowRoot | null;\n readonly scaleMode: 'temporal' | 'beats';\n readonly ticksPerPixel: number;\n readonly bpm: number;\n readonly ppqn: number;\n readonly _meterEntries: MeterEntry[];\n readonly snapTo: SnapTo;\n readonly _secondsToTicks: (seconds: number) => number;\n readonly _ticksToSeconds: (ticks: number) => number;\n dispatchEvent(event: Event): boolean;\n /** Re-extract peaks for a clip at new offset/duration from cached WaveformData. */\n reextractClipPeaks(\n clipId: string,\n offsetSamples: number,\n durationSamples: number\n ): ClipPeakSlice | null;\n /**\n * Returns true if the clip is a MIDI clip (has midiNotes).\n * Trim handles are inert for MIDI clips — note slicing is not yet implemented.\n */\n isMidiClip(trackId: string, clipId: string): boolean;\n}\n\ntype DragMode = 'move' | 'trim-left' | 'trim-right';\n\n/**\n * Handles pointer interactions for clip move and trim drag operations.\n * Converts pixel deltas to sample deltas and delegates to the engine.\n *\n * Both show the drag in the view and change the arrangement once, on release\n * (#848): nothing is written while the pointer moves, so an arrangement change\n * during a drag always came from outside.\n *\n * Move: the clip container's `left` follows the pointer, constrained by the\n * track's other loaded clips as `moveClip` will be; one `moveClip` on release.\n * Trim: updates clip container CSS and peaks imperatively during drag, then\n * applies the cumulative delta to the engine once on release.\n */\nexport class ClipPointerHandler {\n private _host: ClipPointerHost;\n private _mode: DragMode | null = null;\n private _clipId = '';\n private _trackId = '';\n private _startPx = 0;\n private _isDragging = false;\n private _cumulativeDeltaSamples = 0;\n // Trim visual feedback: snapshot of original clip state\n private _clipContainer: HTMLElement | null = null;\n private _boundaryEl: HTMLElement | null = null;\n private _originalLeft = 0;\n private _originalWidth = 0;\n private _originalOffsetSamples = 0;\n private _originalDurationSamples = 0;\n private _originalStartSample = 0;\n // Move: the dragged clip and the track's loaded clips, sorted, at drag start\n private _moveClip: AudioClip | null = null;\n private _moveSorted: AudioClip[] = [];\n\n constructor(host: ClipPointerHost) {\n this._host = host;\n }\n\n /**\n * Convert a pixel delta to samples, snapping in tick space when in beats mode.\n *\n * The anchor is the absolute sample position being moved (e.g., clip start\n * for move/left-trim, clip end for right-trim). Snapping the absolute\n * position — not just the delta — ensures clips land exactly on grid lines\n * even if they started off-grid.\n */\n private _snapDeltaToSamples(totalDeltaPx: number, anchorSample: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n const anchorSeconds = anchorSample / h.effectiveSampleRate;\n const anchorTick = h._secondsToTicks(anchorSeconds);\n const deltaTicks = totalDeltaPx * h.ticksPerPixel;\n const targetTick = anchorTick + deltaTicks;\n const snappedTick =\n h.snapTo !== 'off'\n ? snapTickToGrid(targetTick, h.snapTo, h._meterEntries, h.ppqn)\n : targetTick;\n const snappedSeconds = h._ticksToSeconds(snappedTick);\n const snappedSample = Math.round(snappedSeconds * h.effectiveSampleRate);\n return snappedSample - anchorSample;\n }\n return Math.round(totalDeltaPx * h.renderSamplesPerPixel);\n }\n\n /** A sample delta from `anchorSample` in pixels: in tick space in beats mode,\n * so the drawn position does not drift from the sample round-trip. */\n private _samplesToPx(anchorSample: number, deltaSamples: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n const anchorSec = anchorSample / h.effectiveSampleRate;\n const anchorTick = h._secondsToTicks(anchorSec);\n const newTick = h._secondsToTicks(anchorSec + deltaSamples / h.effectiveSampleRate);\n return Math.round((newTick - anchorTick) / h.ticksPerPixel);\n }\n return Math.round(deltaSamples / h.renderSamplesPerPixel);\n }\n\n /** Returns true if a drag interaction is currently in progress. */\n get isActive(): boolean {\n return this._mode !== null;\n }\n\n /** True once the pointer of the current press has moved past the drag\n * threshold: a press that has not moved is not a drag (#848). */\n get isDragging(): boolean {\n return this._isDragging;\n }\n\n /**\n * The clip being dragged (past the threshold) with its bounds at the drag's\n * start, or null; null too while the release makes its one arrangement\n * call, so that call is not taken for an outside change (#848).\n */\n get draggedClip(): DraggedClip | null {\n if (!this._isDragging || this._committing) return null;\n return {\n trackId: this._trackId,\n clipId: this._clipId,\n startSample: this._originalStartSample,\n durationSamples: this._originalDurationSamples,\n offsetSamples: this._originalOffsetSamples,\n };\n }\n private _committing = false;\n\n /**\n * Attempts to handle a pointerdown event on the given target element.\n * Returns true if the target is a recognized clip interaction element.\n */\n tryHandle(target: Element, e: PointerEvent): boolean {\n if (!this._host.interactiveClips) return false;\n\n // Walk up from click target to find clip interaction elements.\n // composedPath()[0] may be a child (e.g. <span> inside .clip-header).\n const boundary = (target as HTMLElement).closest?.('.clip-boundary') as HTMLElement | null;\n const header = (target as HTMLElement).closest?.('.clip-header') as HTMLElement | null;\n\n // Check boundary first (higher z-index, overlaps header at corners)\n if (boundary && boundary.dataset.boundaryEdge !== undefined) {\n const clipId = boundary.dataset.clipId;\n const trackId = boundary.dataset.trackId;\n const edge = boundary.dataset.boundaryEdge as 'left' | 'right';\n if (!clipId || !trackId || (edge !== 'left' && edge !== 'right')) return false;\n\n // Trim is not supported for MIDI clips — note slicing is a follow-up PR.\n // Consume the event: no trim drag starts, but prevent the click from\n // falling through to the timeline seek handler.\n if (this._host.isMidiClip(trackId, clipId)) return true;\n\n this._beginDrag(edge === 'left' ? 'trim-left' : 'trim-right', clipId, trackId, e);\n this._boundaryEl = boundary;\n return true;\n }\n\n // Check for clip header (move target)\n if (header && header.dataset.interactive !== undefined) {\n const clipId = header.dataset.clipId;\n const trackId = header.dataset.trackId;\n if (!clipId || !trackId) return false;\n\n this._beginDrag('move', clipId, trackId, e);\n return true;\n }\n\n return false;\n }\n\n private _beginDrag(mode: DragMode, clipId: string, trackId: string, e: PointerEvent): void {\n this._mode = mode;\n this._clipId = clipId;\n this._trackId = trackId;\n this._startPx = e.clientX;\n this._isDragging = false;\n\n this._cumulativeDeltaSamples = 0;\n }\n\n /**\n * The press has become a drag (the pointer passed the threshold): take the\n * clip's bounds now, not at the press, so a drag after an undo made during\n * the press starts from the clip as the undo left it (#848, review of\n * #915). Returns false when the clip is gone (the undo removed it): the\n * press is dropped.\n */\n private _startDrag(): boolean {\n const engine = this._host.engine;\n const trackId = this._trackId;\n const clipId = this._clipId;\n // Snapshot clip start position for snap calculations\n if (engine) {\n const bounds = engine.getClipBounds(trackId, clipId);\n if (!bounds) return false;\n this._originalStartSample = bounds.startSample;\n this._originalOffsetSamples = bounds.offsetSamples;\n this._originalDurationSamples = bounds.durationSamples;\n if (this._mode === 'move') {\n const track = engine.getState().tracks.find((t) => t.id === trackId);\n const clip = track?.clips.find((c) => c.id === clipId) ?? null;\n if (!track || !clip) return false;\n this._moveClip = clip;\n this._moveSorted = [...track.clips].sort((a, b) => a.startSample - b.startSample);\n }\n } else {\n console.warn('[dawcore] drag start: engine unavailable, the drag will not be applied');\n }\n\n // Snapshot the clip container's current position/width for the preview\n {\n const container = this._host.shadowRoot?.querySelector(\n `.clip-container[data-clip-id=\"${clipId}\"]`\n ) as HTMLElement | null;\n if (container) {\n this._clipContainer = container;\n this._originalLeft = parseFloat(container.style.left) || 0;\n this._originalWidth = parseFloat(container.style.width) || 0;\n } else {\n console.warn('[dawcore] clip container not found for drag visual feedback: ' + clipId);\n }\n }\n return true;\n }\n\n /** Processes pointermove events during an active drag. */\n onPointerMove(e: PointerEvent): void {\n if (this._mode === null) return;\n\n const totalDeltaPx = e.clientX - this._startPx;\n\n // Activate drag after threshold is exceeded\n if (!this._isDragging && Math.abs(totalDeltaPx) > DRAG_THRESHOLD) {\n if (!this._startDrag()) {\n this._reset();\n return;\n }\n this._isDragging = true;\n // Apply .dragging class to boundary element for active drag styling\n if (this._boundaryEl) {\n this._boundaryEl.classList.add('dragging');\n }\n }\n\n if (!this._isDragging) return;\n\n const engine = this._host.engine;\n if (!engine) return;\n\n if (this._mode === 'move') {\n // Move: snap the clip start, constrain against the track's clips as\n // moveClip will on release, and draw the clip there. Nothing is written.\n const totalSnappedDelta = this._snapDeltaToSamples(totalDeltaPx, this._originalStartSample);\n const clip = this._moveClip;\n const index = clip ? this._moveSorted.indexOf(clip) : -1;\n const delta =\n clip && index !== -1\n ? constrainClipDrag(clip, totalSnappedDelta, this._moveSorted, index)\n : totalSnappedDelta;\n this._cumulativeDeltaSamples = delta;\n if (this._clipContainer) {\n const deltaPx = this._samplesToPx(this._originalStartSample, delta);\n this._clipContainer.style.left = this._originalLeft + deltaPx + 'px';\n }\n } else {\n // Trim: constrain delta using engine's full collision/bounds logic,\n // then track for visual feedback. Engine called once at pointerup.\n const boundary = this._mode === 'trim-left' ? 'left' : 'right';\n // Anchor = the boundary edge being dragged\n // Left trim: snap the left edge (startSample)\n // Right trim: snap the right edge (startSample + durationSamples)\n const anchor =\n boundary === 'left'\n ? this._originalStartSample\n : this._originalStartSample + this._originalDurationSamples;\n const rawDeltaSamples = this._snapDeltaToSamples(totalDeltaPx, anchor);\n const deltaSamples = engine.constrainTrimDelta(\n this._trackId,\n this._clipId,\n boundary,\n rawDeltaSamples\n );\n const deltaPx = this._samplesToPx(anchor, deltaSamples);\n\n this._cumulativeDeltaSamples = deltaSamples;\n\n // Visual feedback: update clip container CSS and re-extract peaks\n if (this._clipContainer) {\n if (this._mode === 'trim-left') {\n // Left trim: container shifts and resizes\n const newLeft = this._originalLeft + deltaPx;\n const newWidth = this._originalWidth - deltaPx;\n if (newWidth > 0) {\n this._clipContainer.style.left = newLeft + 'px';\n this._clipContainer.style.width = newWidth + 'px';\n // Re-extract peaks at new offset/duration from cached WaveformData.\n // New peaks cover the full new bounds, so waveforms stay at left:0\n // (no shift needed — the container position handles global alignment).\n const newOffset = this._originalOffsetSamples + deltaSamples;\n const newDuration = this._originalDurationSamples - deltaSamples;\n if (this._updateWaveformPeaks(newOffset, newDuration)) {\n // Peaks updated — reset waveform positions to fill container\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (const wf of waveforms) {\n (wf as HTMLElement).style.left = '0px';\n }\n } else {\n // No cached peaks — fall back to shifting waveforms for visual stability\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (const wf of waveforms) {\n (wf as HTMLElement).style.left = -deltaPx + 'px';\n }\n }\n }\n } else {\n // Right trim: extend/shrink right edge — left stays fixed\n const newWidth = this._originalWidth + deltaPx;\n if (newWidth > 0) {\n this._clipContainer.style.width = newWidth + 'px';\n // Re-extract peaks at new duration from cached WaveformData\n const newDuration = this._originalDurationSamples + deltaSamples;\n this._updateWaveformPeaks(this._originalOffsetSamples, newDuration);\n }\n }\n }\n }\n }\n\n /** Processes pointerup events to finalize and dispatch result events. */\n onPointerUp(_e: PointerEvent): void {\n if (this._mode === null) return;\n\n try {\n if (!this._isDragging || this._cumulativeDeltaSamples === 0) {\n // Restore original CSS if the drag didn't produce a delta\n this._restoreVisual();\n return;\n }\n\n const engine = this._host.engine;\n this._committing = true;\n\n if (this._mode === 'move') {\n // Back to where the clip was drawn; the re-render after the move puts it there.\n this._restoreVisual();\n if (engine) {\n // The one arrangement call of the drag: an undo step.\n const applied = engine.moveClip(\n this._trackId,\n this._clipId,\n this._cumulativeDeltaSamples\n );\n if (applied !== 0) {\n this._host.dispatchEvent(\n new CustomEvent('daw-clip-move', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: this._trackId,\n clipId: this._clipId,\n deltaSamples: applied,\n },\n })\n );\n }\n } else {\n console.warn(\n '[dawcore] engine unavailable at move drop — move not applied for clip ' + this._clipId\n );\n }\n } else {\n // Restore visual before engine applies — Lit will re-render with correct values\n this._restoreVisual();\n\n // Trim: apply cumulative delta to engine in one shot (adapter updated internally)\n const boundary = this._mode === 'trim-left' ? 'left' : 'right';\n if (engine) {\n engine.trimClip(this._trackId, this._clipId, boundary, this._cumulativeDeltaSamples);\n this._host.dispatchEvent(\n new CustomEvent('daw-clip-trim', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: this._trackId,\n clipId: this._clipId,\n boundary,\n deltaSamples: this._cumulativeDeltaSamples,\n },\n })\n );\n } else {\n console.warn(\n '[dawcore] engine unavailable at trim drop — trim not applied for clip ' + this._clipId\n );\n }\n }\n } finally {\n this._committing = false;\n this._reset();\n }\n }\n\n /** Processes pointercancel — reverts the in-progress drag.\n *\n * pointercancel fires INSTEAD of pointerup on touch interruption, pen\n * leaving hover range, or OS gestures. Without this handler the drag stays\n * armed (hover keeps moving the clip). The drag wrote nothing to the\n * arrangement, so reverting is putting the view back. */\n onPointerCancel(_e: PointerEvent): void {\n if (this._mode === null) return;\n try {\n this._restoreVisual();\n } finally {\n this._reset();\n }\n }\n\n /** Re-extract peaks from cache and set on waveform elements during trim drag.\n * Returns true if peaks were successfully updated. */\n private _updateWaveformPeaks(offsetSamples: number, durationSamples: number): boolean {\n if (!this._clipContainer || durationSamples <= 0) return false;\n const peakSlice = this._host.reextractClipPeaks(this._clipId, offsetSamples, durationSamples);\n if (!peakSlice) return false;\n\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (let i = 0; i < waveforms.length; i++) {\n const wf = waveforms[i] as HTMLElement & { peaks: unknown; length: number };\n const channelPeaks = peakSlice.data[i];\n if (channelPeaks) {\n wf.peaks = channelPeaks;\n wf.length = peakSlice.length;\n }\n }\n return true;\n }\n\n /** Restore clip container CSS AND waveform peaks to original values after\n * a drag's visual preview. Peaks matter: a trim wrote re-extracted peak\n * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and\n * a cancelled/zero-delta drag makes no engine mutation — so no statechange\n * re-render will ever repair them. */\n private _restoreVisual(): void {\n if (this._clipContainer) {\n this._clipContainer.style.left = this._originalLeft + 'px';\n this._clipContainer.style.width = this._originalWidth + 'px';\n // Restore waveform positions (shifted during left trim preview)\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (const wf of waveforms) {\n (wf as HTMLElement).style.left = '0px';\n }\n // Re-extract at the original bounds (no-op when the peak cache is\n // unavailable — in that case the drag never overwrote peaks either).\n this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);\n }\n }\n\n private _reset(): void {\n // Remove .dragging class from boundary element\n if (this._boundaryEl) {\n this._boundaryEl.classList.remove('dragging');\n this._boundaryEl = null;\n }\n this._mode = null;\n this._clipId = '';\n this._trackId = '';\n this._startPx = 0;\n this._isDragging = false;\n\n this._cumulativeDeltaSamples = 0;\n this._clipContainer = null;\n this._originalLeft = 0;\n this._originalWidth = 0;\n this._originalOffsetSamples = 0;\n this._originalDurationSamples = 0;\n this._originalStartSample = 0;\n this._moveClip = null;\n this._moveSorted = [];\n }\n}\n","import { updateAnnotationBoundaries, snapTickToGrid } from '@waveform-playlist/core';\nimport {\n ANNOTATION_LINK_THRESHOLD_TICKS,\n annotationMinDurationTicks,\n} from '@waveform-playlist/core';\nimport type { AnnotationData, SnapTo, MeterEntry } from '@waveform-playlist/core';\nimport {\n applyBoundaryResults,\n applyTickBoundaryResults,\n tickSpaceData,\n type DawAnnotationTrackElement,\n} from '../elements/daw-annotation-track';\nimport { DRAG_THRESHOLD } from './constants';\n\nexport interface AnnotationDragHost {\n effectiveSampleRate: number;\n _renderSpp: number;\n _annotationClampDuration: number;\n seekTo(time: number): void;\n scaleMode: string;\n ticksPerPixel: number;\n snapTo: SnapTo;\n _meterEntries: MeterEntry[];\n ppqn: number;\n _secondsToTicks(seconds: number): number;\n _ticksToSeconds(ticks: number): number;\n}\n\ninterface DragState {\n track: DawAnnotationTrackElement;\n captureEl: HTMLElement;\n /** The listeners on `captureEl`: aborted when this drag ends. */\n listeners: AbortController;\n pointerId: number;\n startClientX: number;\n moved: boolean;\n /** Boundary drag only (null = box click candidate). */\n edge: 'start' | 'end' | null;\n annotationId: string;\n /** 'ticks' when the dragged annotation is tick-based; 'seconds' otherwise. */\n mode: 'seconds' | 'ticks';\n /** Snapshot at drag start — pointercancel restores it. In 'ticks' mode this\n * is tick-space data (see tickSpaceData); in 'seconds' mode it's the\n * ordinary AnnotationData snapshot. */\n snapshot: AnnotationData[];\n /** Edge time at drag start (boundary drags). Ticks in 'ticks' mode,\n * seconds in 'seconds' mode. */\n edgeTime: number;\n}\n\n/**\n * Pointer interaction for annotation lanes: boundary drag (write-through via\n * core boundary math), box click-to-select+seek, cancel-restores-snapshot.\n * Wired by <daw-editor> as the renderLanes pointerdown callback.\n */\nexport class AnnotationDragHandler {\n private _host: AnnotationDragHost;\n private _drag: DragState | null = null;\n\n constructor(host: AnnotationDragHost) {\n this._host = host;\n }\n\n onPointerDown = (e: PointerEvent, track: DawAnnotationTrackElement): void => {\n const target = e.target as HTMLElement;\n const boundary = target.closest('.annotation-boundary') as HTMLElement | null;\n const box = target.closest('.annotation-box') as HTMLElement | null;\n if (!box) return; // empty lane space — fall through to timeline seek\n\n const annotationId = box.getAttribute('data-annotation-id') ?? '';\n const isBoundary = boundary !== null && track.editable;\n if (boundary !== null && !track.editable) {\n // Boundary handles are only rendered when editable, but guard anyway.\n return;\n }\n\n e.stopPropagation();\n e.preventDefault();\n\n const elements = track.annotationElements;\n const el = elements.find((x) => x.annotationId === annotationId);\n if (!el) return;\n const mode: 'seconds' | 'ticks' = el.isTickBased ? 'ticks' : 'seconds';\n const snapshot =\n mode === 'ticks' ? elements.map((x) => tickSpaceData(x, this._host)) : track.annotations;\n const index = snapshot.findIndex((a) => a.id === annotationId);\n if (index === -1) return;\n\n const edge = isBoundary ? (boundary.getAttribute('data-edge') as 'start' | 'end') : null;\n const captureEl = isBoundary ? boundary : box;\n\n // A press while another drag is in progress (a second touch) replaces\n // it: its listeners go, as they did when the same element was pressed.\n this._drag?.listeners.abort();\n const listeners = new AbortController();\n this._drag = {\n track,\n captureEl,\n listeners,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n moved: false,\n edge,\n annotationId,\n mode,\n snapshot,\n // edgeTime holds ticks in 'ticks' mode, seconds in 'seconds' mode.\n edgeTime: edge === 'start' ? snapshot[index].start : snapshot[index].end,\n };\n\n try {\n captureEl.setPointerCapture(e.pointerId);\n } catch {\n // Fabricated pointerIds (tests) or detached elements — capture is best-effort.\n }\n const { signal } = listeners;\n captureEl.addEventListener('pointermove', this._onPointerMove as EventListener, { signal });\n captureEl.addEventListener('pointerup', this._onPointerUp as EventListener, { signal });\n captureEl.addEventListener('pointercancel', this._onPointerCancel as EventListener, { signal });\n };\n\n /** Non-private (underscore convention) so tests can drive moves directly. */\n _onPointerMove = (e: PointerEvent): void => {\n const drag = this._drag;\n if (!drag || e.pointerId !== drag.pointerId) return;\n const deltaPx = e.clientX - drag.startClientX;\n if (Math.abs(deltaPx) >= DRAG_THRESHOLD) drag.moved = true;\n if (drag.edge === null || !drag.moved) return;\n\n const elements = drag.track.annotationElements;\n const index = drag.snapshot.findIndex((a) => a.id === drag.annotationId);\n if (index === -1) return;\n\n if (drag.mode === 'ticks') {\n // px → tick delta: beats mode is tick-linear; temporal mode converts\n // through seconds at the edge's local tempo.\n const deltaTicks =\n this._host.scaleMode === 'beats'\n ? deltaPx * this._host.ticksPerPixel\n : this._host._secondsToTicks(\n this._host._ticksToSeconds(drag.edgeTime) +\n (deltaPx * this._host._renderSpp) / this._host.effectiveSampleRate\n ) - drag.edgeTime;\n let newTick = drag.edgeTime + deltaTicks;\n if (this._host.scaleMode === 'beats' && this._host.snapTo !== 'off') {\n newTick = snapTickToGrid(\n newTick,\n this._host.snapTo,\n this._host._meterEntries,\n this._host.ppqn\n );\n }\n const clamp = this._host._annotationClampDuration;\n const updated = updateAnnotationBoundaries(\n {\n annotationIndex: index,\n newTime: newTick,\n isDraggingStart: drag.edge === 'start',\n annotations: drag.snapshot,\n duration: clamp === Infinity ? Infinity : this._host._secondsToTicks(clamp),\n linkEndpoints: drag.track.linkEndpoints,\n },\n {\n linkThreshold: ANNOTATION_LINK_THRESHOLD_TICKS,\n minDuration: annotationMinDurationTicks(this._host.ppqn),\n }\n );\n applyTickBoundaryResults(elements, updated, (t) => this._host._ticksToSeconds(t));\n return;\n }\n\n const deltaSeconds = (deltaPx * this._host._renderSpp) / this._host.effectiveSampleRate;\n // Compute from the drag-start snapshot each move — cumulative deltas\n // against live state would compound the link/collision adjustments.\n const updated = updateAnnotationBoundaries({\n annotationIndex: index,\n newTime: drag.edgeTime + deltaSeconds,\n isDraggingStart: drag.edge === 'start',\n annotations: drag.snapshot,\n duration: this._host._annotationClampDuration,\n linkEndpoints: drag.track.linkEndpoints,\n });\n applyBoundaryResults(elements, updated);\n };\n\n _onPointerUp = (e: PointerEvent): void => {\n const drag = this._drag;\n if (!drag || e.pointerId !== drag.pointerId) return;\n if (!drag.moved && drag.edge === null) {\n // Click: select + seek to the annotation start.\n const data = drag.track.annotations.find((a) => a.id === drag.annotationId);\n if (data) {\n drag.track.activeAnnotationId = drag.annotationId;\n this._host.seekTo(data.start);\n }\n }\n this._teardown();\n };\n\n _onPointerCancel = (e: PointerEvent): void => {\n const drag = this._drag;\n if (!drag || e.pointerId !== drag.pointerId) return;\n this._restoreAndTeardown(drag);\n };\n\n /** True from pointerdown on an annotation until the drag ends or is cancelled. */\n get isActive(): boolean {\n return this._drag !== null;\n }\n\n /** True once the pointer has moved at least `DRAG_THRESHOLD` px (an edge\n * drag, or a box press that moved): a press that has not moved (a click on\n * the box) is not a drag (#848). */\n get isDragging(): boolean {\n return this._drag?.moved ?? false;\n }\n\n /** Cancel the drag in progress (Escape, editor disconnect): the boundaries\n * go back to where they were when it began (#848). */\n cancel(): void {\n if (this._drag) this._restoreAndTeardown(this._drag);\n }\n\n /** Restore the drag-start snapshot — a cancelled drag must not commit. */\n private _restoreAndTeardown(drag: DragState): void {\n const elements = drag.track.annotationElements;\n if (drag.mode === 'ticks') {\n applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));\n } else {\n applyBoundaryResults(elements, drag.snapshot);\n }\n this._teardown();\n }\n\n private _teardown(): void {\n const drag = this._drag;\n if (!drag) return;\n try {\n drag.captureEl.releasePointerCapture(drag.pointerId);\n } catch {\n // Already released or never captured.\n }\n drag.listeners.abort();\n this._drag = null;\n }\n}\n","/**\n * Vertical track-reorder drag for the controls column. Follows the\n * pointer-handler host pattern: pointerdown on the grip (surfaced from\n * <daw-track-controls>' shadow DOM via daw-track-reorder-grab) +\n * setPointerCapture, Y-midpoint hit testing against control rows, translate\n * preview, commit on pointerup, revert on pointercancel. Covers mouse,\n * touch, and pen uniformly.\n */\n\nimport type { DraggedTrack } from './drag-watch';\n\nexport interface TrackReorderHost {\n readonly isConnected: boolean;\n shadowRoot: ShadowRoot | null;\n reorderTrack(trackId: string, toIndex: number): void;\n}\n\ninterface RowInfo {\n el: HTMLElement;\n top: number;\n height: number;\n trackId: string;\n}\n\nexport class TrackReorderHandler {\n private _host: TrackReorderHost;\n private _trackId: string | null = null;\n private _pointerId = -1;\n private _startY = 0;\n private _rows: RowInfo[] = [];\n private _lanes: (RowInfo | null)[] = []; // aligned with _rows indices; null = lane not found\n private _fromIndex = 0;\n private _targetIndex = 0;\n private _gripEl: HTMLElement | null = null;\n /** The grip's listeners of the drag in progress: one controller per drag. */\n private _gesture: AbortController | null = null;\n\n constructor(host: TrackReorderHost) {\n this._host = host;\n }\n\n private static _reducedMotion(): boolean {\n return (\n typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n }\n\n onGrab = (trackId: string, e: PointerEvent, gripEl: HTMLElement): void => {\n if (this._trackId !== null) return; // one drag at a time\n const column = this._host.shadowRoot?.querySelector('.controls-column');\n if (!column) return;\n const rows = [...column.querySelectorAll('daw-track-controls')] as HTMLElement[];\n this._rows = rows.map((el) => {\n const rect = el.getBoundingClientRect();\n return {\n el,\n top: rect.top,\n height: rect.height,\n trackId: (el as HTMLElement & { trackId: string | null }).trackId ?? '',\n };\n });\n this._fromIndex = this._rows.findIndex((r) => r.trackId === trackId);\n if (this._fromIndex === -1) {\n this._rows = [];\n return;\n }\n this._trackId = trackId;\n this._targetIndex = this._fromIndex;\n this._pointerId = e.pointerId;\n this._startY = e.clientY;\n this._gripEl = gripEl;\n\n // Waveform-lane parity (drag-preview spec): snapshot the shadow timeline's\n // .track-row lanes by trackId. Transform-only mirroring: the lanes' DOM\n // order does not change during the drag; the release is one reorderTrack.\n const timeline = this._host.shadowRoot?.querySelector('.timeline');\n const laneEls = timeline ? ([...timeline.querySelectorAll('.track-row')] as HTMLElement[]) : [];\n this._lanes = this._rows.map((r) => {\n const el = laneEls.find((l) => l.getAttribute('data-track-id') === r.trackId) ?? null;\n if (!el) return null;\n const rect = el.getBoundingClientRect();\n return { el, top: rect.top, height: rect.height, trackId: r.trackId };\n });\n\n const draggedLane = this._lanes[this._fromIndex];\n if (draggedLane) {\n draggedLane.el.setAttribute('data-track-drag-source', '');\n draggedLane.el.style.zIndex = '10';\n draggedLane.el.style.position = 'relative';\n }\n if (!TrackReorderHandler._reducedMotion()) {\n // Displaced rows and ALL lanes animate; the dragged CONTROLS row does not\n // (it pixel-follows the pointer, a transition would make it lag).\n for (let i = 0; i < this._rows.length; i++) {\n if (i !== this._fromIndex) this._rows[i].el.style.transition = 'transform 150ms ease';\n const lane = this._lanes[i];\n if (lane) lane.el.style.transition = 'transform 150ms ease';\n }\n }\n\n try {\n gripEl.setPointerCapture(e.pointerId);\n } catch {\n // Fabricated pointerIds (tests) can't be captured — listeners still work.\n }\n this._gesture = new AbortController();\n const { signal } = this._gesture;\n gripEl.addEventListener('pointermove', this._onPointerMove, { signal });\n gripEl.addEventListener('pointerup', this._onPointerUp, { signal });\n gripEl.addEventListener('pointercancel', this._onPointerCancel, { signal });\n };\n\n /** The dragged track and the order of the rows at the grab (#848), or null. */\n get draggedTrack(): DraggedTrack | null {\n if (this._trackId === null) return null;\n return { trackId: this._trackId, order: this._rows.map((r) => r.trackId) };\n }\n\n /** True from the grab until the drag ends or is cancelled. */\n get isActive(): boolean {\n return this._trackId !== null;\n }\n\n /** Abort any in-progress drag and reset state. Called by the editor on\n * disconnect — without this, a drag interrupted by editor removal (with no\n * pointercancel delivered) would leave the handler wedged and silently\n * block every future grab. */\n cancel(): void {\n this._cleanup();\n }\n\n private _onPointerMove = (e: PointerEvent): void => {\n if (e.pointerId !== this._pointerId || this._trackId === null) return;\n const dragged = this._rows[this._fromIndex];\n const dy = e.clientY - this._startY;\n dragged.el.style.transform = 'translateY(' + dy + 'px)';\n dragged.el.style.zIndex = '10';\n dragged.el.style.position = 'relative';\n\n // Target slot: crossing another row's midpoint claims its slot.\n let target = this._fromIndex;\n for (let i = 0; i < this._rows.length; i++) {\n if (i === this._fromIndex) continue;\n const mid = this._rows[i].top + this._rows[i].height / 2;\n if (i < this._fromIndex && e.clientY < mid) {\n target = i;\n break;\n }\n if (i > this._fromIndex && e.clientY > mid) {\n target = i;\n }\n }\n this._targetIndex = target;\n\n // Shift displaced rows out of the way.\n for (let i = 0; i < this._rows.length; i++) {\n if (i === this._fromIndex) continue;\n const row = this._rows[i];\n let shift = 0;\n if (i > this._fromIndex && i <= target) shift = -dragged.height;\n else if (i < this._fromIndex && i >= target) shift = dragged.height;\n row.el.style.transform = shift === 0 ? '' : 'translateY(' + shift + 'px)';\n }\n\n // Mirror the preview onto the waveform lanes.\n const draggedLaneInfo = this._lanes[this._fromIndex];\n for (let i = 0; i < this._lanes.length; i++) {\n const lane = this._lanes[i];\n if (!lane || !draggedLaneInfo) continue;\n if (i === this._fromIndex) {\n // Slot-snap the dragged lane to the target slot (not pixel-follow).\n let offset = 0;\n const targetLane = this._lanes[target];\n if (targetLane && target > this._fromIndex) {\n offset =\n targetLane.top + targetLane.height - (draggedLaneInfo.top + draggedLaneInfo.height);\n } else if (targetLane && target < this._fromIndex) {\n offset = targetLane.top - draggedLaneInfo.top;\n }\n lane.el.style.transform = offset === 0 ? '' : 'translateY(' + offset + 'px)';\n continue;\n }\n let laneShift = 0;\n if (i > this._fromIndex && i <= target) laneShift = -draggedLaneInfo.height;\n else if (i < this._fromIndex && i >= target) laneShift = draggedLaneInfo.height;\n lane.el.style.transform = laneShift === 0 ? '' : 'translateY(' + laneShift + 'px)';\n }\n };\n\n private _onPointerUp = (e: PointerEvent): void => {\n if (e.pointerId !== this._pointerId || this._trackId === null) return;\n const trackId = this._trackId;\n const target = this._targetIndex;\n const from = this._fromIndex;\n this._cleanup();\n if (target !== from) {\n this._host.reorderTrack(trackId, target);\n }\n };\n\n private _onPointerCancel = (e: PointerEvent): void => {\n if (e.pointerId !== this._pointerId) return;\n this._cleanup();\n };\n\n private _cleanup(): void {\n for (const row of this._rows) {\n row.el.style.transform = '';\n row.el.style.zIndex = '';\n row.el.style.position = '';\n row.el.style.transition = '';\n }\n for (const lane of this._lanes) {\n if (!lane) continue;\n lane.el.style.transform = '';\n lane.el.style.transition = '';\n lane.el.style.zIndex = '';\n lane.el.style.position = '';\n lane.el.removeAttribute('data-track-drag-source');\n }\n this._lanes = [];\n const grip = this._gripEl;\n if (grip) {\n this._gesture?.abort();\n this._gesture = null;\n try {\n grip.releasePointerCapture(this._pointerId);\n } catch {\n // already released / fabricated pointerId\n }\n }\n this._gripEl = null;\n this._trackId = null;\n this._pointerId = -1;\n this._rows = [];\n }\n}\n","/**\n * Time display formats for <daw-time-display> / <daw-time-format> and the\n * editor's `time-format` attribute. The three formats come from the\n * web-components-migration spec (\"Element Registry\": hh:mm:ss.sss | hh:mm:ss\n * | seconds). parseDisplayTime exists for the selection inputs (#463).\n */\nexport type TimeDisplayFormat = 'hh:mm:ss.sss' | 'hh:mm:ss' | 'seconds';\n\nexport const TIME_DISPLAY_FORMATS: readonly TimeDisplayFormat[] = [\n 'hh:mm:ss.sss',\n 'hh:mm:ss',\n 'seconds',\n];\n\nexport function isTimeDisplayFormat(value: unknown): value is TimeDisplayFormat {\n return TIME_DISPLAY_FORMATS.includes(value as TimeDisplayFormat);\n}\n\nfunction clockFormat(totalSeconds: number, decimals: number): string {\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor(totalSeconds / 60) % 60;\n const secsRem = totalSeconds % 60;\n // Truncate (not round) to prevent overflow across the minute boundary\n // (59.9999s -> 59.999, not 60.000). The epsilon compensates for binary\n // float representation (1.001 * 1000 === 1000.9999...; plain floor would\n // render it 1ms low); the Math.min clamp keeps the boundary guard airtight\n // for values the epsilon would otherwise push over (59.9999999...).\n let secs: string;\n if (decimals === 0) {\n secs = String(Math.min(Math.floor(secsRem + 1e-6), 59)).padStart(2, '0');\n } else {\n const factor = 10 ** decimals;\n const truncated = Math.min(Math.floor(secsRem * factor + 1e-6), 60 * factor - 1);\n secs = (truncated / factor).toFixed(decimals).padStart(decimals + 3, '0');\n }\n return String(hours).padStart(2, '0') + ':' + String(minutes).padStart(2, '0') + ':' + secs;\n}\n\n/** Format seconds for display. Non-finite or negative input renders as 0. */\nexport function formatDisplayTime(seconds: number, format: TimeDisplayFormat): string {\n const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;\n switch (format) {\n case 'seconds':\n // 'seconds' rounds via toFixed; clock formats truncate. Rounding is safe here since no minute-boundary overflow can occur in plain seconds.\n return safe.toFixed(3);\n case 'hh:mm:ss':\n return clockFormat(safe, 0);\n case 'hh:mm:ss.sss':\n default:\n return clockFormat(safe, 3);\n }\n}\n\n/**\n * A non-negative decimal number with nothing around it: `5`, `1.5`, `1.`, `.5`.\n * Each string has one way to match (the point is not optional inside the\n * digits), so a long digit string that fails is refused in linear time.\n */\nconst DECIMAL = /^(\\d+(\\.\\d*)?|\\.\\d+)$/;\n/** A whole number of hours or minutes. */\nconst WHOLE = /^\\d+$/;\nconst SECONDS_PER_UNIT = [3600, 60, 1];\n\n/**\n * Read `s`, `m:s` or `h:m:s`. Only the last part (the seconds) may have\n * decimals; the first part may be any size, and each later part must be\n * under 60. The same rule as `parseTime` in `@waveform-playlist/ui-components`\n * (`src/utils/timeFormat.ts`): keep the two in step.\n */\nfunction parseClock(text: string): number | null {\n const parts = text.split(':');\n if (parts.length > 3) return null;\n const units = SECONDS_PER_UNIT.slice(3 - parts.length);\n let total = 0;\n for (let i = 0; i < parts.length; i++) {\n const isLast = i === parts.length - 1;\n if (!(isLast ? DECIMAL : WHOLE).test(parts[i])) return null;\n const value = Number(parts[i]);\n if (i > 0 && value >= 60) return null;\n total += value * units[i];\n }\n return Number.isFinite(total) ? total : null;\n}\n\n/**\n * Parse text typed for a time back to seconds, or `null` when it is not a\n * time: empty text, a negative number, letters, a number followed by\n * anything else, a number too large to be finite, or a value that is not a\n * string. Spaces around the text are ignored. `seconds` reads a plain\n * number; the clock formats also read `1.5` (seconds) and `1:30` (minutes and\n * seconds) besides `01:02:03.500`. Segment ranges are checked: `00:75:00` is\n * not a time.\n */\nexport function parseDisplayTime(value: string, format: TimeDisplayFormat): number | null {\n // Plain-JS callers can pass anything.\n if (typeof value !== 'string') return null;\n const text = value.trim();\n if (format !== 'seconds') return parseClock(text);\n if (!DECIMAL.test(text)) return null;\n const seconds = Number(text);\n return Number.isFinite(seconds) ? seconds : null;\n}\n","/**\n * Cancellation (#848, the maintainer's design D1-D8): every abort is an\n * `AbortError` DOMException whose message names the cause, as `fetch()`\n * rejects (modern-web-guidance `js`: callers check `err.name`). A caller's\n * own signal rejects with that signal's `reason`.\n */\n\n/** An `AbortError` with a message that names why. */\nexport function abortError(message: string): DOMException {\n return new DOMException(message, 'AbortError');\n}\n\n/** True for an abort (`AbortError`), the kind a caller asked for or a swap caused. */\nexport function isAbortError(error: unknown): boolean {\n return (error as { name?: unknown } | null)?.name === 'AbortError';\n}\n\n/**\n * The reason of an aborted signal, as it is: a call rejects with it, as\n * `fetch()` does (`abort()` without one gives an `AbortError` DOMException).\n */\nexport function reasonOf(signal: AbortSignal): unknown {\n return signal.reason;\n}\n\n/**\n * One AbortController per arrangement while the editor plays it, aborted\n * when it is swapped out (D2). Keyed by the arrangement, so a swap ends only\n * the waits of the one leaving: a clip added to the editor's own arrangement\n * while a handed-in one plays is not rejected when the own one comes back.\n */\nexport class PlaySignals {\n private _controllers = new WeakMap<object, AbortController>();\n\n /** The signal of an arrangement: aborted when it is next swapped out. */\n signalOf(arrangement: object): AbortSignal {\n let controller = this._controllers.get(arrangement);\n if (!controller) {\n controller = new AbortController();\n this._controllers.set(arrangement, controller);\n }\n return controller.signal;\n }\n\n /** The arrangement leaves play: its waits end with `reason`; a later play gets a new signal. */\n swappedOut(arrangement: object, reason: DOMException): void {\n const controller = this._controllers.get(arrangement);\n this._controllers.delete(arrangement);\n controller?.abort(reason);\n }\n}\n\n/** `promise`, or a rejection with the signal's reason as soon as it aborts. */\nexport function untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(reasonOf(signal));\n return new Promise<T>((resolve, reject) => {\n const done = new AbortController();\n signal.addEventListener('abort', () => reject(reasonOf(signal)), { signal: done.signal });\n promise.then(\n (value) => {\n done.abort();\n resolve(value);\n },\n (error: unknown) => {\n done.abort();\n reject(error);\n }\n );\n });\n}\n","/**\n * File loading (#848): each dropped file enters the editor's arrangement as a\n * track with one loading clip whose source is the `File` itself (a File\n * cannot be an attribute, so a dropped track has no `<daw-track>` element).\n * The arrangement reads and decodes it. A file that cannot be loaded is\n * removed again without an undo step: it was never a declaration.\n */\n\nimport type { DawFilesLoadErrorDetail, LoadFilesResult } from '../events';\nimport { reasonOf, untilAborted } from './abort';\nimport type { EditorCallOptions } from '../types';\nimport type { Arrangement } from '@waveform-playlist/engine';\n\nexport interface FileLoaderHost {\n readonly isConnected: boolean;\n /** Add the file as a track; resolves with its id once it has entered. */\n _addDroppedFile(file: File): Promise<string>;\n /** Resolves when the track has loaded or the editor was disconnected; rejects when its audio failed. */\n _whenTrackLoaded(trackId: string): Promise<void>;\n /** Take a track out for good: no undo step, and no undo brings it back. */\n _discardTrack(trackId: string, from?: Arrangement): void;\n /** The arrangement played (the tracks enter it). */\n readonly arrangement: Arrangement;\n /** The signal of the arrangement played: aborted when it is swapped out. */\n _operationSignal(signal?: AbortSignal): AbortSignal;\n dispatchEvent(event: Event): boolean;\n}\n\n/**\n * `options.signal` (#848, D5): an abort rejects with its reason; the files\n * not started are skipped, and every track this call added is removed for\n * good (no undo step). A signal already aborted rejects at once.\n */\nexport async function loadFiles(\n host: FileLoaderHost,\n files: FileList | File[],\n options: EditorCallOptions = {}\n): Promise<LoadFilesResult> {\n const signal = options.signal;\n if (signal?.aborted) throw reasonOf(signal);\n if (!files) {\n console.warn('[dawcore] loadFiles called with null/undefined');\n return { loaded: [], failed: [] };\n }\n\n const fileArray = Array.from(files);\n // The arrangement the files enter, and its signal: a swap ends the call as\n // a disconnect does (the file loading is kept; the rest fail).\n const target = host.arrangement;\n const played = host._operationSignal();\n const loaded: string[] = [];\n const failed: Array<{ file: File; error: unknown }> = [];\n\n const dispatchLoadError = (file: File, error: unknown) => {\n failed.push({ file, error });\n if (host.isConnected) {\n host.dispatchEvent(\n new CustomEvent<DawFilesLoadErrorDetail>('daw-files-load-error', {\n bubbles: true,\n composed: true,\n detail: { file, error },\n })\n );\n }\n };\n\n for (const file of fileArray) {\n // A disconnect ends the call: the file loading then is kept (it loads\n // after a reparent); the ones not started are not added (#917).\n if (!host.isConnected) {\n dispatchLoadError(file, new Error('<daw-editor> was disconnected'));\n continue;\n }\n if (played.aborted) {\n dispatchLoadError(file, reasonOf(played));\n continue;\n }\n // file.type can be '' for valid audio (.opus on some browsers) — only\n // reject explicitly non-audio MIME types.\n if (file.type && !file.type.startsWith('audio/')) {\n const error = new Error('Non-audio MIME type: ' + file.type);\n console.warn('[dawcore] Skipping non-audio file: ' + file.name + ' (' + file.type + ')');\n dispatchLoadError(file, error);\n continue;\n }\n let trackId: string | null = null;\n try {\n // Sequential on purpose: preserves drop order as track order.\n const adding = host._addDroppedFile(file);\n trackId = await untilAborted(adding, signal).catch((err: unknown) => {\n // Aborted while it entered: it is taken out once it has.\n if (signal?.aborted)\n void adding.then(\n (id) => host._discardTrack(id, target),\n () => {}\n );\n throw err;\n });\n await untilAborted(host._whenTrackLoaded(trackId), signal);\n loaded.push(trackId);\n } catch (err) {\n if (signal?.aborted) {\n // The caller's abort: everything this call added goes, and it rejects.\n for (const id of [...loaded, ...(trackId !== null ? [trackId] : [])])\n host._discardTrack(id, target);\n throw reasonOf(signal);\n }\n console.warn('[dawcore] Failed to load file: ' + file.name + ' — ' + String(err));\n if (trackId !== null) host._discardTrack(trackId, target);\n dispatchLoadError(file, err);\n }\n }\n\n return { loaded, failed };\n}\n","/**\n * MIDI loading logic extracted from daw-editor. Operates on the editor via a\n * narrow host interface (`addTrack`, `_discardTrack`, `_operationSignal`) —\n * `<daw-editor>` satisfies it.\n *\n * Numbered steps below match the Data Flow diagram in\n * `docs/specs/2026-05-23-dawcore-load-midi-design.md`.\n */\n\nimport type { MidiLoadOptions, MidiLoadResult } from '@dawcore/midi';\nimport type { EditorCallOptions, TrackConfig } from '../types';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { installCommand } from '../utils/install-command';\nimport { reasonOf } from './abort';\n\nexport type { MidiLoadOptions, MidiLoadResult };\n\n/**\n * Minimal host surface needed by `loadMidiImpl`. `<daw-editor>` satisfies this\n * structurally. A track `addTrack` added is taken out for good on a failure\n * or an abort; a track whose entry was refused never entered, so there is\n * nothing to remove (#848: `addTrack` makes no element).\n */\nexport interface MidiLoaderHost {\n /** Resolves with the track id once the track has entered (#848). */\n addTrack(config: TrackConfig, options?: EditorCallOptions): Promise<string>;\n /** Take a track out for good: no undo step, and no undo brings it back. */\n _discardTrack(trackId: string, from?: Arrangement): void;\n /** The arrangement played (the tracks enter it). */\n readonly arrangement: Arrangement;\n /** The caller's signal combined with the arrangement played (D6). */\n _operationSignal(signal?: AbortSignal): AbortSignal;\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst installHint = (): string =>\n '@dawcore/midi is required for loadMidi(). Install with: ' + installCommand('@dawcore/midi');\n\n/**\n * Loads a `.mid` file (URL or `File`) and adds N tracks, one per note-bearing\n * MIDI track. On any per-track failure or an abort, every track added during\n * this call is removed for good (no undo step), so the editor is as before\n * the call.\n *\n * `options.signal` reaches the fetch and the parse and, combined with the\n * arrangement played (a swap aborts it too), the `addTrack` waits (#848, D6).\n */\nexport async function loadMidiImpl(\n host: MidiLoaderHost,\n source: string | File,\n options: MidiLoadOptions = {}\n): Promise<MidiLoadResult> {\n // Reject NaN / Infinity / negative startTime up front. Without this, every\n // clip silently inherits the bogus value and the timeline corrupts.\n const startTime = options.startTime ?? 0;\n if (!Number.isFinite(startTime) || startTime < 0) {\n throw new RangeError(\n 'loadMidi: startTime must be a non-negative finite number (got ' +\n String(options.startTime) +\n ')'\n );\n }\n\n // (1) Dynamic-import the optional peer dep. Log the original error so\n // debugging isn't blocked when the failure is something other than\n // \"not installed\" (broken exports map, 404 chunk, CSP, etc.). Targeting\n // ES2020 means we can't use Error.cause yet; console.warn carries the\n // diagnostic detail.\n const signal = host._operationSignal(options.signal);\n // The arrangement the tracks enter: a cleanup after a swap removes them there.\n const target = host.arrangement;\n if (signal.aborted) throw reasonOf(signal);\n let midiModule: typeof import('@dawcore/midi');\n try {\n midiModule = await import('@dawcore/midi');\n } catch (originalErr) {\n console.warn('[dawcore] @dawcore/midi dynamic import failed: ' + String(originalErr));\n throw new Error(installHint());\n }\n const { parseMidiUrl, parseMidiFile } = midiModule;\n\n // (2) Branch on source type. Wrap the File path so a failed disk read\n // surfaces with file context instead of a bare DOMException.\n let parsed;\n if (typeof source === 'string') {\n parsed = await parseMidiUrl(source, undefined, signal);\n } else {\n let buffer: ArrayBuffer;\n try {\n buffer = await source.arrayBuffer();\n } catch (err) {\n throw new Error(\n 'loadMidi: failed to read File \"' +\n source.name +\n '\" (' +\n source.size +\n ' bytes): ' +\n String(err)\n );\n }\n parsed = parseMidiFile(buffer);\n }\n if (signal.aborted) throw reasonOf(signal);\n\n // (4) Concurrent addTrack with allSettled so we can wait for every settlement\n // before deciding. Promise.all would early-reject while other addTrack calls\n // keep running, leaving orphan tracks after cleanup.\n const settlements = await Promise.allSettled(\n parsed.tracks.map((t) =>\n host.addTrack(\n {\n name: t.name,\n kind: 'midi',\n clips: [\n {\n midiNotes: t.notes,\n midiChannel: t.channel,\n midiProgram: t.programNumber,\n start: startTime,\n },\n ],\n },\n { signal }\n )\n )\n );\n\n // (5) Partition fulfilled vs rejected. Capture EVERY rejection (not just\n // the first) for diagnosability of multi-track failures.\n const succeeded: string[] = [];\n const rejections: unknown[] = [];\n for (const s of settlements) {\n if (s.status === 'fulfilled') {\n succeeded.push(s.value);\n } else {\n rejections.push(s.reason);\n }\n }\n\n // (6) On any rejection: remove every track added during this call, then\n // throw a summary Error and console.warn each additional rejection so\n // multi-track failure modes stay diagnosable.\n if (rejections.length > 0) {\n for (const trackId of succeeded) {\n try {\n host._discardTrack(trackId, target);\n } catch (cleanupErr) {\n console.warn('[dawcore] loadMidi cleanup failed for a track: ' + String(cleanupErr));\n }\n }\n // Aborted: the abort is the outcome, not the per-track rejections it caused.\n if (signal.aborted) throw reasonOf(signal);\n\n // Log every rejection beyond the first so multi-track failure modes are\n // diagnosable (the thrown Error only carries the first). AggregateError\n // would be ideal here but requires ES2021+; defer until the project\n // bumps its lib target.\n for (let i = 1; i < rejections.length; i++) {\n console.warn(\n '[dawcore] loadMidi: additional track failure (' +\n i +\n '): ' +\n stringifyReason(rejections[i])\n );\n }\n const first = rejections[0];\n if (rejections.length > 1) {\n const message =\n 'loadMidi: ' +\n rejections.length +\n ' of ' +\n settlements.length +\n ' tracks failed; first: ' +\n (first instanceof Error ? first.message : stringifyReason(first));\n throw new Error(message);\n }\n throw first instanceof Error ? first : new Error(stringifyReason(first));\n }\n\n // (7) Build the result.\n return {\n trackIds: succeeded,\n bpm: parsed.bpm,\n timeSignature: parsed.timeSignature,\n duration: parsed.duration,\n name: parsed.name,\n };\n}\n\n/**\n * Render a non-Error rejection reason as a useful string. Plain `String(x)`\n * gives `\"[object Object]\"` for object rejections, losing all structured info.\n */\nfunction stringifyReason(reason: unknown): string {\n if (reason === null) return 'null';\n if (reason === undefined) return 'undefined';\n if (typeof reason === 'object') {\n try {\n return JSON.stringify(reason);\n } catch {\n return Object.prototype.toString.call(reason);\n }\n }\n return String(reason);\n}\n","/**\n * Recording clip creation extracted from daw-editor to keep the editor under 800 lines.\n * Operates on the editor instance via a narrow interface.\n */\n\nimport type { AudioClip, LoadingClip, PeakData } from '@waveform-playlist/core';\nimport { carveClipRange, createClip, isLoadingClip } from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport type { PeakPipeline } from '../workers/peakPipeline';\nimport type { DawErrorDetail, DawRecordingClipAddDetail } from '../events';\n\nexport interface RecordingClipHost {\n readonly samplesPerPixel: number;\n /** Render-space samples-per-pixel — tick-derived in beats mode. Finalized\n * peaks MUST be generated at this scale (containers are laid out in render\n * space); the temporal samplesPerPixel draws the wrong width. */\n readonly renderSamplesPerPixel: number;\n readonly mono: boolean;\n readonly isConnected: boolean;\n readonly effectiveSampleRate: number;\n /** The take goes into the editor's arrangement (#848); the engine follows it. */\n _arrangement: Arrangement;\n _peaksData: Map<string, PeakData>;\n _clipBuffers: Map<string, AudioBuffer>;\n _clipOffsets: Map<string, { offsetSamples: number; durationSamples: number }>;\n /** Raise the editor zoom floor (recording worker-caches peaks at the\n * pipeline base scale like any other load — the floor must cover them). */\n _raiseZoomFloor(scale: number): void;\n _peakPipeline: PeakPipeline;\n dispatchEvent(event: Event): boolean;\n}\n\nexport function addRecordedClip(\n host: RecordingClipHost,\n trackId: string,\n buf: AudioBuffer,\n startSample: number,\n durSamples: number,\n offsetSamples = 0,\n clipName?: string\n) {\n // Slice off latency samples so peaks and playback only cover the audible portion\n let trimmedBuf = buf;\n if (offsetSamples > 0 && offsetSamples < buf.length) {\n const trimmed = new AudioBuffer({\n numberOfChannels: buf.numberOfChannels,\n length: durSamples,\n sampleRate: buf.sampleRate,\n });\n for (let ch = 0; ch < buf.numberOfChannels; ch++) {\n const source = buf.getChannelData(ch);\n trimmed.copyToChannel(source.subarray(offsetSamples, offsetSamples + durSamples), ch);\n }\n trimmedBuf = trimmed;\n }\n\n const clip = createClip({\n audioBuffer: trimmedBuf,\n startSample,\n durationSamples: durSamples,\n offsetSamples: 0, // offset already applied by slicing\n gain: 1,\n name: clipName ?? 'Recording',\n });\n host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);\n // Record the offsets like every other clip-insertion path — without this\n // entry the statechange peak-sync treats the clip as uncached and re-runs\n // the worker after EVERY recording.\n host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });\n host._peakPipeline\n .generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono)\n .then((pd) => {\n if (!host._arrangement.getTracks().some((t) => t.id === trackId)) {\n // Track was removed during peak generation — clean up the orphaned\n // buffer and never insert the peaks entry (this clip never reaches\n // the engine, so nothing else would ever delete it).\n const next = new Map(host._clipBuffers);\n next.delete(clip.id);\n host._clipBuffers = next;\n host._clipOffsets.delete(clip.id);\n return;\n }\n host._peaksData = new Map(host._peaksData).set(clip.id, pd);\n // The same floor policy as every loaded clip (_clipPeaksReady): the worker cached this\n // buffer's WaveformData at the base scale — zooming finer than it\n // would render the recorded waveform squeezed in its container.\n host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));\n // One undo step, in the function form so the track's loading clips\n // stay. Punch-in replace (#579): the recorded clip owns [startSample,\n // startSample + durSamples) — carve overlapped LOADED content out\n // before inserting (parity with the React provider); a clip still\n // loading has no samples to carve and is kept as it is.\n host._arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: [\n ...current.clips.flatMap((c): (AudioClip | LoadingClip)[] =>\n isLoadingClip(c) ? [c] : carveClipRange([c], startSample, startSample + durSamples)\n ),\n clip,\n ],\n }));\n // daw-recording-complete fires BEFORE the clip exists (it is\n // cancelable), so it cannot carry the id. This follow-up fires once\n // the clip is in the engine and addressable (#659).\n if (host.isConnected) {\n host.dispatchEvent(\n new CustomEvent<DawRecordingClipAddDetail>('daw-recording-clip-add', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clip.id },\n })\n );\n }\n })\n .catch((err) => {\n console.warn('[dawcore] Failed to generate peaks for recorded clip: ' + String(err));\n const next = new Map(host._clipBuffers);\n next.delete(clip.id);\n host._clipBuffers = next;\n host._clipOffsets.delete(clip.id);\n if (host.isConnected) {\n host.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'recording-peaks', error: err },\n })\n );\n }\n });\n}\n","import type { AudioClip, ClipTrack } from '@waveform-playlist/core';\nimport type { DawClipSplitDetail } from '../events';\n\n// ---------------------------------------------------------------------------\n// Contracts\n// ---------------------------------------------------------------------------\n\n/** Narrow engine contract for split operations. */\nexport interface SplitEngineContract {\n getState(): { selectedTrackId: string | null; tracks: readonly ClipTrack[] };\n splitClip(trackId: string, clipId: string, atSample: number): void;\n}\n\n/** Host interface for splitAtPlayhead. */\nexport interface SplitHost {\n readonly effectiveSampleRate: number;\n readonly currentTime: number;\n readonly isPlaying: boolean;\n readonly engine: SplitEngineContract | null;\n dispatchEvent(event: Event): boolean;\n stop(): void;\n play(time: number): void;\n}\n\n// ---------------------------------------------------------------------------\n// splitAtPlayhead\n// ---------------------------------------------------------------------------\n\n/**\n * Split the clip under the playhead on the selected track.\n * Stops playback before split and resumes after to avoid duplicate audio\n * from Transport rescheduling during playback.\n *\n * Returns true if the split occurred and dispatched a daw-clip-split event.\n * Returns false for any guard failure or engine no-op.\n */\nexport function splitAtPlayhead(host: SplitHost): boolean {\n const wasPlaying = host.isPlaying;\n const time = host.currentTime;\n\n // Check guards before stopping playback — don't interrupt audio for a no-op\n if (!canSplitAtTime(host, time)) return false;\n\n if (wasPlaying) {\n host.stop();\n }\n\n let result: boolean;\n try {\n result = performSplit(host, time);\n } catch (err) {\n console.warn('[dawcore] splitAtPlayhead failed: ' + String(err));\n result = false;\n }\n\n // Always resume if was playing — even on failed split, don't leave audio stopped\n if (wasPlaying) {\n host.play(time);\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\n/** Pre-flight check — can a split happen at this time without touching playback? */\nfunction canSplitAtTime(host: SplitHost, time: number): boolean {\n const { engine } = host;\n if (!engine) return false;\n\n const state = engine.getState();\n if (!state.selectedTrackId) return false;\n\n const track = state.tracks.find((t) => t.id === state.selectedTrackId);\n if (!track) return false;\n\n const atSample = Math.round(time * host.effectiveSampleRate);\n const clip = findClipAtSample(track.clips, atSample);\n // A MIDI clip splits like an audio clip: both halves keep its notes, each a\n // window on them (#838).\n return clip !== undefined;\n}\n\n/** Core split logic — finds clip at position, calls engine, diffs state for the right half's new id. */\nfunction performSplit(host: SplitHost, time: number): boolean {\n const { engine } = host;\n if (!engine) return false;\n\n const stateBefore = engine.getState();\n const { selectedTrackId, tracks } = stateBefore;\n\n if (!selectedTrackId) return false;\n\n const track = tracks.find((t) => t.id === selectedTrackId);\n if (!track) return false;\n\n const atSample = Math.round(time * host.effectiveSampleRate);\n\n const clip = findClipAtSample(track.clips, atSample);\n if (!clip) return false;\n\n const originalClipId = clip.id;\n const clipIdsBefore = new Set(track.clips.map((c) => c.id));\n\n engine.splitClip(selectedTrackId, originalClipId, atSample);\n\n const stateAfter = engine.getState();\n const trackAfter = stateAfter.tracks.find((t) => t.id === selectedTrackId);\n if (!trackAfter) {\n console.warn(\n '[dawcore] splitAtPlayhead: track \"' + selectedTrackId + '\" disappeared after split'\n );\n return false;\n }\n\n // The left half keeps the original's id (#848); the right half is the one new id.\n const leftClip = trackAfter.clips.find((c) => c.id === originalClipId);\n const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));\n if (!leftClip || newClips.length !== 1) {\n if (newClips.length > 0) {\n console.warn(\n '[dawcore] splitAtPlayhead: expected the original clip and 1 new clip after split but got ' +\n newClips.length +\n ' new'\n );\n }\n return false;\n }\n const leftClipId = leftClip.id;\n const rightClipId = newClips[0].id;\n\n host.dispatchEvent(\n new CustomEvent<DawClipSplitDetail>('daw-clip-split', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: selectedTrackId,\n originalClipId,\n leftClipId,\n rightClipId,\n },\n })\n );\n\n return true;\n}\n\n/**\n * Finds a clip that strictly contains the given sample position.\n * The position must be > clip.startSample and < clip.startSample + clip.durationSamples.\n */\nfunction findClipAtSample(clips: AudioClip[], atSample: number): AudioClip | undefined {\n return clips.find(\n (c) => atSample > c.startSample && atSample < c.startSample + c.durationSamples\n );\n}\n","import type { AudioClip, ClipTrack, PeakData } from '@waveform-playlist/core';\nimport type { PeakPipeline } from '../workers/peakPipeline';\n\n/** Host interface for clip peak synchronization. */\nexport interface ClipPeakSyncHost {\n /** The effective samplesPerPixel for rendering (tick-derived in beats mode). */\n readonly renderSamplesPerPixel: number;\n readonly mono: boolean;\n _clipBuffers: Map<string, AudioBuffer>;\n _clipOffsets: Map<string, { offsetSamples: number; durationSamples: number }>;\n _peaksData: Map<string, PeakData>;\n _peakPipeline: PeakPipeline;\n /** Told when a clip's peaks are made (the zoom floor, a preview to drop). */\n _clipPeaksReady?(clipId: string, audioBuffer: AudioBuffer): void;\n}\n\n/**\n * Regenerate peaks for clips that are new or whose offset/duration changed.\n * Handles split (the left half keeps its id with a shorter duration, the\n * right half is a new id; #848) and trim (same ID, changed bounds).\n *\n * Called from the statechange handler when tracksVersion changes.\n */\nexport function syncPeaksForChangedClips(\n host: ClipPeakSyncHost,\n tracks: readonly ClipTrack[]\n): void {\n // Collect all current clip IDs for orphan detection\n const currentClipIds = new Set<string>();\n\n for (const track of tracks) {\n for (const clip of track.clips) {\n currentClipIds.add(clip.id);\n\n // Check if peaks need regeneration: new clip or changed offset/duration\n const cached = host._clipOffsets.get(clip.id);\n const needsPeaks =\n !host._peaksData.has(clip.id) ||\n !cached ||\n cached.offsetSamples !== clip.offsetSamples ||\n cached.durationSamples !== clip.durationSamples;\n\n if (!needsPeaks) continue;\n\n const audioBuffer =\n clip.audioBuffer ??\n host._clipBuffers.get(clip.id) ??\n findAudioBufferForClip(host, clip, track);\n if (!audioBuffer) {\n console.warn(\n '[dawcore] syncPeaksForChangedClips: no AudioBuffer for clip ' +\n clip.id +\n ' — waveform will be blank'\n );\n continue;\n }\n\n // Update cached state\n host._clipBuffers = new Map(host._clipBuffers).set(clip.id, audioBuffer);\n host._clipOffsets = new Map(host._clipOffsets).set(clip.id, {\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n });\n\n // Generate peaks asynchronously\n host._peakPipeline\n .generatePeaks(\n audioBuffer,\n host.renderSamplesPerPixel,\n host.mono,\n clip.offsetSamples,\n clip.durationSamples\n )\n .then((peakData) => {\n host._peaksData = new Map(host._peaksData).set(clip.id, peakData);\n host._clipPeaksReady?.(clip.id, audioBuffer);\n })\n .catch((err) => {\n console.warn(\n '[dawcore] Failed to generate peaks for clip ' + clip.id + ': ' + String(err)\n );\n });\n }\n }\n\n // Clean up orphaned entries for clip IDs no longer in any track\n // (e.g., a clip removed, or a whole track undone away)\n cleanupOrphanedClipData(host, currentClipIds);\n}\n\n/**\n * Remove entries from per-clip Maps for clip IDs that no longer exist in any track.\n * Prevents memory leaks from orphaned AudioBuffer references after split operations.\n */\nfunction cleanupOrphanedClipData(host: ClipPeakSyncHost, currentClipIds: Set<string>): void {\n let buffersChanged = false;\n let peaksChanged = false;\n\n for (const id of host._clipBuffers.keys()) {\n if (!currentClipIds.has(id)) {\n host._clipBuffers.delete(id);\n buffersChanged = true;\n }\n }\n let offsetsChanged = false;\n for (const id of host._clipOffsets.keys()) {\n if (!currentClipIds.has(id)) {\n host._clipOffsets.delete(id);\n offsetsChanged = true;\n }\n }\n for (const id of host._peaksData.keys()) {\n if (!currentClipIds.has(id)) {\n host._peaksData.delete(id);\n peaksChanged = true;\n }\n }\n\n // Reassign Maps that changed — _peaksData is @state() (triggers Lit re-render),\n // _clipBuffers uses reference identity for change detection in syncPeaksForChangedClips\n if (buffersChanged) {\n host._clipBuffers = new Map(host._clipBuffers);\n }\n if (offsetsChanged) {\n host._clipOffsets = new Map(host._clipOffsets);\n }\n if (peaksChanged) {\n host._peaksData = new Map(host._peaksData);\n }\n}\n\n/** Find an AudioBuffer for a clip by checking siblings on the same track. */\nfunction findAudioBufferForClip(\n host: ClipPeakSyncHost,\n clip: AudioClip,\n track: ClipTrack\n): AudioBuffer | null {\n for (const sibling of track.clips) {\n if (sibling.id === clip.id) continue;\n const buf = host._clipBuffers.get(sibling.id);\n if (buf) return buf;\n }\n return null;\n}\n","/**\n * How a track the page (or an editor method) declared becomes a track of the\n * editor's arrangement (#848): each audio clip a `LoadingClip` that the\n * arrangement loads, each MIDI clip a loaded clip built at the editor's\n * sample rate, a clip of the wrong kind refused. Pure functions; the editor\n * calls the arrangement.\n */\nimport { createClip, createTrack, isDecidedPanLaw } from '@waveform-playlist/core';\nimport type {\n ArrangementTrack,\n AudioClip,\n ClipSource,\n LoadingClip,\n MidiNoteData,\n TrackKind,\n} from '@waveform-playlist/core';\nimport type { TrackMixerValues } from '@waveform-playlist/engine';\nimport type { ClipDescriptor, StoredTrackDescriptor } from '../types';\nimport { isDomClip } from '../types';\n\n/**\n * Keep only notes with finite, in-range fields; warn for each one dropped.\n * Prevents NaN reaching the timeline.\n */\nexport function validMidiNotes(notes: MidiNoteData[]): MidiNoteData[] {\n return notes.filter((n) => {\n const ok =\n Number.isFinite(n.time) &&\n n.time >= 0 &&\n Number.isFinite(n.duration) &&\n n.duration > 0 &&\n Number.isInteger(n.midi) &&\n n.midi >= 0 &&\n n.midi <= 127 &&\n Number.isFinite(n.velocity) &&\n n.velocity >= 0 &&\n n.velocity <= 1;\n if (!ok) {\n console.warn('[dawcore] dropping malformed MIDI note: ' + JSON.stringify(n));\n }\n return ok;\n });\n}\n\n/** What a clip descriptor loads: its `File` (a dropped file) or its `src` URL; '' for none. */\nexport function clipSourceOf(clipDesc: ClipDescriptor): ClipSource | '' {\n return (!isDomClip(clipDesc) && clipDesc.file) || clipDesc.src;\n}\n\n/**\n * A clip descriptor is MIDI when it has nothing to load. Includes placeholder\n * MIDI clips (no notes, no duration yet: a 1 s span; notes arrive through a\n * clip update). Warns when a clip has both a source and notes: it is audio,\n * and the notes are ignored.\n */\nexport function isMidiDescriptor(clipDesc: ClipDescriptor): boolean {\n if (clipSourceOf(clipDesc)) {\n if (clipDesc.midiNotes != null) {\n console.warn(\n '[dawcore] clip \"' +\n (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : '?')) +\n '\" has both src and midiNotes — treating as audio (notes will be ignored)'\n );\n }\n return false;\n }\n return true;\n}\n\n/**\n * The error for a clip whose kind is not its track's (#756), or null. A clip\n * with nothing to load is a MIDI clip (see isMidiDescriptor).\n */\nexport function clipKindError(\n trackName: string,\n kind: TrackKind,\n clipIsMidi: boolean,\n clipLabel: string\n): Error | null {\n if (clipIsMidi === (kind === 'midi')) return null;\n return new Error(\n clipIsMidi\n ? 'clip \"' +\n clipLabel +\n '\" is a MIDI clip (no src) on audio track \"' +\n trackName +\n '\". A track holds one kind of clip: set kind=\"midi\" on the <daw-track>' +\n \" (or kind: 'midi' in addTrack) for a track of MIDI clips.\"\n : 'clip \"' +\n clipLabel +\n '\" is an audio clip on MIDI track \"' +\n trackName +\n '\". A track holds one kind of clip: put the clip on an audio track.'\n );\n}\n\n/**\n * A MIDI clip from its descriptor, at `sampleRate`. Always a clip: no notes\n * or no declared duration give a 1 s placeholder span, so later notes find it.\n */\nexport function buildMidiClip(clipDesc: ClipDescriptor, sampleRate: number): AudioClip {\n const notes = validMidiNotes(clipDesc.midiNotes ?? []);\n const noteSpanSeconds = notes.length\n ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0)\n : 0;\n const sourceDurationSamples = Math.ceil(\n Math.max(noteSpanSeconds, clipDesc.duration, 1) * sampleRate\n );\n const requestedDurationSamples =\n clipDesc.duration > 0 ? Math.round(clipDesc.duration * sampleRate) : sourceDurationSamples;\n const clip = createClip({\n startSample: Math.round(clipDesc.start * sampleRate),\n durationSamples: requestedDurationSamples,\n offsetSamples: Math.round(clipDesc.offset * sampleRate),\n sampleRate,\n sourceDurationSamples,\n gain: clipDesc.gain,\n name: clipDesc.name,\n midiNotes: notes,\n midiChannel: clipDesc.midiChannel ?? undefined,\n midiProgram: clipDesc.midiProgram ?? undefined,\n });\n if (clipDesc.clipId) clip.id = clipDesc.clipId;\n return clip;\n}\n\n/**\n * The loading clip of an audio clip descriptor (its `clipId` must be set):\n * the source, the times in seconds and the gain. A duration of 0 means the\n * whole source from the offset. Fades are not carried: the load path never\n * applied `<daw-clip>` fades (engine-side fades are #489).\n */\nexport function buildLoadingClip(clipDesc: ClipDescriptor & { clipId: string }): LoadingClip {\n return {\n id: clipDesc.clipId,\n src: clipSourceOf(clipDesc) as ClipSource,\n start: clipDesc.start,\n offset: clipDesc.offset,\n gain: clipDesc.gain,\n ...(clipDesc.duration > 0 && { duration: clipDesc.duration }),\n ...(clipDesc.name && { name: clipDesc.name }),\n };\n}\n\n/** A clip descriptor with an id: a drop descriptor without one gets a new id. */\nexport function withClipId(clipDesc: ClipDescriptor): ClipDescriptor & { clipId: string } {\n if (clipDesc.clipId) return clipDesc as ClipDescriptor & { clipId: string };\n return { ...clipDesc, clipId: crypto.randomUUID() };\n}\n\n/** A clip of the descriptor that was refused for its kind. */\nexport interface RefusedClip {\n clipId: string;\n error: Error;\n}\n\nexport interface BuiltTrack {\n track: ArrangementTrack;\n /** The descriptor with an id on every clip (the same object when none was missing). */\n descriptor: StoredTrackDescriptor;\n refused: RefusedClip[];\n}\n\n/**\n * The arrangement track for a declared track: `trackId`, its name, kind and\n * the mix it enters with; a loading clip per audio clip and a loaded clip per\n * MIDI clip. A clip of the wrong kind is left out and listed in `refused`\n * (the arrangement throws for a track that holds both kinds).\n */\nexport function buildArrangementTrack(\n trackId: string,\n descriptor: StoredTrackDescriptor,\n mix: TrackMixerValues,\n sampleRate: number\n): BuiltTrack {\n const clips: (AudioClip | LoadingClip)[] = [];\n const refused: RefusedClip[] = [];\n let changed = false;\n const descClips = descriptor.clips.map((clipDesc) => {\n const identified = withClipId(clipDesc);\n if (identified !== clipDesc) changed = true;\n const isMidi = isMidiDescriptor(identified);\n const source = clipSourceOf(identified);\n const sourceName =\n typeof source === 'string' ? source : source instanceof File ? source.name : '';\n const label = identified.name || sourceName || identified.clipId;\n const kindError = clipKindError(descriptor.name, descriptor.kind, isMidi, label);\n if (kindError) refused.push({ clipId: identified.clipId, error: kindError });\n else clips.push(isMidi ? buildMidiClip(identified, sampleRate) : buildLoadingClip(identified));\n return identified;\n });\n const { panLaw, ...fields } = mix;\n const base = {\n ...createTrack({ name: descriptor.name, kind: descriptor.kind, clips: [], ...fields }),\n // The law the track enters with (#684); 'auto' is the arrangement's default.\n ...(isDecidedPanLaw(panLaw) && { panLaw }),\n };\n const track: ArrangementTrack = { ...base, id: trackId, clips };\n return { track, descriptor: changed ? { ...descriptor, clips: descClips } : descriptor, refused };\n}\n\n/**\n * Where a `<daw-track>` enters among the arrangement's tracks: after the\n * arrangement track of the nearest `<daw-track>` before it (in document\n * order) that has entered; first when there is none.\n */\nexport function entryIndex(\n trackEls: readonly { trackId: string }[],\n trackId: string,\n arrangementIds: readonly string[]\n): number {\n const at = trackEls.findIndex((el) => el.trackId === trackId);\n for (let i = at - 1; i >= 0; i--) {\n const position = arrangementIds.indexOf(trackEls[i].trackId);\n if (position !== -1) return position + 1;\n }\n return 0;\n}\n","/**\n * The editor's load events, read from its arrangement (#848): the tracks\n * (which clips are still loading) and `sources` (which sources failed). Each\n * event is sent once per transition. The announcer remembers what it last\n * announced, so that a statechange and a sources change telling of the same\n * transition do not both dispatch, and so that a track that comes back by an\n * undo or a redo is not announced again.\n *\n * - `daw-clip-error` when a clip's source goes into failed (again after a\n * retry that fails, since the error is a new object).\n * - `daw-clip-ready` when a clip that was loading has loaded.\n * - `daw-track-ready` when no clip of the track is pending and one loaded,\n * or the track asked for no audio; again each time it has loaded again\n * after it was pending or failed (a clip added later, a retry).\n * - `daw-track-error` when every clip of the track failed, also when they\n * were refused for their kind (the track stays, like a broken `<img>`).\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, ClipSource } from '@waveform-playlist/core';\nimport type { ArrangementSourceState } from '@waveform-playlist/engine';\nimport type {\n DawClipErrorDetail,\n DawClipIdDetail,\n DawTrackErrorDetail,\n DawTrackIdDetail,\n} from '../events';\n\ntype TrackLoadState = 'pending' | 'ready' | 'failed';\n\ninterface TrackRecord {\n state: TrackLoadState | null;\n /** Clips refused for their kind when the track entered (never in the arrangement). */\n refused: number;\n /** What `daw-track-error` carried, while the track is failed. */\n error?: Error;\n}\n\nexport class LoadAnnouncer {\n private _tracks = new Map<string, TrackRecord>();\n /** The failure each clip was last announced with. */\n private _clipErrors = new Map<string, Error>();\n /** Clips seen while loading, and not yet announced as loaded. */\n private _loadingClips = new Set<string>();\n\n constructor(private readonly _dispatch: (event: Event) => void) {}\n\n /** A track is about to enter, with `refused` clips left out for their kind. */\n expect(trackId: string, refused: number): void {\n this._tracks.set(trackId, { state: null, refused });\n }\n\n /**\n * A clip is about to enter while loading: it is announced ready when it\n * loads, also when its source was loaded already and it is never seen\n * loading.\n */\n expectClip(clipId: string): void {\n this._loadingClips.add(clipId);\n }\n\n /** A loading clip was removed: its load will not be announced. */\n forgetClip(clipId: string): void {\n this._loadingClips.delete(clipId);\n this._clipErrors.delete(clipId);\n }\n\n /** The error a failed track was announced with. */\n errorOf(trackId: string): Error {\n return this._tracks.get(trackId)?.error ?? new Error('track \"' + trackId + '\" failed to load');\n }\n\n /** A track was removed by the page or an editor method: nothing more is said of it. */\n forget(trackId: string, clipIds: Iterable<string>): void {\n this._tracks.delete(trackId);\n for (const id of clipIds) {\n this._clipErrors.delete(id);\n this._loadingClips.delete(id);\n }\n }\n\n /** The state a track was last announced in (`null` before its first announcement). */\n stateOf(trackId: string): TrackLoadState | null {\n return this._tracks.get(trackId)?.state ?? null;\n }\n\n update(\n tracks: readonly ArrangementTrack[],\n sources: ReadonlyMap<ClipSource, ArrangementSourceState>\n ): void {\n for (const track of tracks) this._updateTrack(track, sources);\n }\n\n private _updateTrack(\n track: ArrangementTrack,\n sources: ReadonlyMap<ClipSource, ArrangementSourceState>\n ): void {\n const record = this._tracks.get(track.id) ?? { state: null, refused: 0 };\n this._tracks.set(track.id, record);\n let pending = 0;\n let failed = 0;\n let loaded = 0;\n let firstError: Error | null = null;\n for (const clip of track.clips) {\n if (!isLoadingClip(clip)) {\n loaded++;\n if (this._loadingClips.delete(clip.id)) {\n this._clipErrors.delete(clip.id);\n this._send<DawClipIdDetail>('daw-clip-ready', { trackId: track.id, clipId: clip.id });\n }\n continue;\n }\n this._loadingClips.add(clip.id);\n const source = sources.get(clip.src);\n if (source?.status !== 'failed') {\n pending++;\n this._clipErrors.delete(clip.id);\n continue;\n }\n failed++;\n const error = source.error ?? new Error('the audio of clip \"' + clip.id + '\" failed to load');\n firstError ??= error;\n if (this._clipErrors.get(clip.id) !== error) {\n this._clipErrors.set(clip.id, error);\n this._send<DawClipErrorDetail>('daw-clip-error', {\n trackId: track.id,\n clipId: clip.id,\n error,\n });\n }\n }\n const next: TrackLoadState =\n pending > 0 ? 'pending' : loaded > 0 || failed + record.refused === 0 ? 'ready' : 'failed';\n if (next === record.state) return;\n record.state = next;\n record.error = undefined;\n if (next === 'ready') {\n this._send<DawTrackIdDetail>('daw-track-ready', { trackId: track.id });\n } else if (next === 'failed') {\n const requested = failed + record.refused;\n const error =\n requested === 1 && firstError\n ? firstError\n : new Error(\n 'all ' + requested + ' clip(s) failed to load — see prior daw-clip-error events'\n );\n record.error = error;\n this._send<DawTrackErrorDetail>('daw-track-error', { trackId: track.id, error });\n }\n }\n\n private _send<T>(type: string, detail: T): void {\n this._dispatch(new CustomEvent<T>(type, { bubbles: true, composed: true, detail }));\n }\n}\n","/**\n * What `<daw-editor>` draws and reports, read from its arrangement (#848):\n * the editor keeps no projection of the tracks. Pure functions; the one\n * cache (`loadedTrack`'s) is keyed by the arrangement's track objects and\n * never written back.\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, AudioClip, ClipTrack, LoadingClip } from '@waveform-playlist/core';\nimport type { Arrangement, TrackMixerValues } from '@waveform-playlist/engine';\n\ninterface Cached {\n mix: TrackMixerValues;\n recording: boolean;\n view: ClipTrack;\n}\n\nconst views = new WeakMap<ArrangementTrack, Cached>();\n\nfunction sameMix(a: TrackMixerValues, b: TrackMixerValues): boolean {\n return (\n a.volume === b.volume &&\n a.pan === b.pan &&\n a.muted === b.muted &&\n a.soloed === b.soloed &&\n a.panLaw === b.panLaw\n );\n}\n\n/**\n * A track as it is played: its loaded clips with the current mix (muted\n * while a take records onto it). The same object for the same track object\n * and the same mix, so a row whose track did not change is not drawn again.\n */\nexport function loadedTrack(\n track: ArrangementTrack,\n mix: TrackMixerValues,\n recording: boolean\n): ClipTrack {\n const cached = views.get(track);\n if (cached && cached.recording === recording && sameMix(cached.mix, mix)) return cached.view;\n const view: ClipTrack = {\n ...track,\n clips: track.clips.filter((c): c is AudioClip => !isLoadingClip(c)),\n volume: mix.volume,\n pan: mix.pan,\n muted: mix.muted || recording,\n soloed: mix.soloed,\n // What both exports pan the track with (core's trackPanLaw, #684).\n panLaw: mix.panLaw,\n };\n views.set(track, { mix: { ...mix }, recording, view });\n return view;\n}\n\n/**\n * A track's mix from its one owner, the arrangement: the stored values,\n * muted while a take records onto it (as the engine plays it). Null for an\n * id the arrangement does not hold.\n */\nexport function mixOf(arrangement: Arrangement, trackId: string): TrackMixerValues | null {\n const mix = arrangement.getMixer().get(trackId);\n if (!mix) return null;\n return arrangement.recordingTrackIds.has(trackId) ? { ...mix, muted: true } : mix;\n}\n\n/** A clip's place in seconds, for a loaded clip and for one still loading (0 where unknown). */\nexport function clipSeconds(\n clip: AudioClip | LoadingClip,\n fallbackSampleRate: number\n): { start: number; duration: number; offset: number } {\n if (isLoadingClip(clip)) {\n return { start: clip.start ?? 0, duration: clip.duration ?? 0, offset: clip.offset ?? 0 };\n }\n const sr = clip.sampleRate ?? fallbackSampleRate;\n return {\n start: clip.startSample / sr,\n duration: clip.durationSamples / sr,\n offset: clip.offsetSamples / sr,\n };\n}\n","/**\n * Setting `editor.arrangement` (#848 PR 3, P5): the editor plays the\n * arrangement it is given alone, like `video.srcObject`, and goes back to its\n * own on `null`. One assignment for the app; this module is the sequence.\n */\nimport { isArrangement, type Arrangement } from '@waveform-playlist/engine';\n\n/** What the swap needs from `<daw-editor>`. */\nexport interface ArrangementSwapHost {\n readonly _ownArrangement: Arrangement;\n readonly _handedIn: Arrangement | null;\n readonly isRecording: boolean;\n readonly isPlaying: boolean;\n /** The arrangement played now (handed-in ?? own). */\n readonly _arrangement: Arrangement;\n _cancelDrags(): boolean;\n stop(): void;\n /** Let the engine go without disposing the adapter (`dispose({ keepAdapter: true })`). */\n _releaseEngine(): void;\n /** Dispose the effects chain of a track id. */\n _disposeTrackChain(trackId: string): void;\n /** Point the editor at `next` (null: its own) and follow it (subscriptions, a fresh announcer). */\n _playArrangement(next: Arrangement | null): void;\n /** Build an engine on the arrangement played now, when connected with an adapter. */\n _buildEngineIfReady(): void;\n}\n\n/**\n * The value to play: `null` for the editor's own arrangement (given `null`,\n * `undefined` or the own arrangement itself). Throws a `TypeError` for a\n * value that is not an arrangement.\n */\nexport function normalizeHandedIn(value: unknown, own: Arrangement): Arrangement | null {\n if (value === null || value === undefined || value === own) return null;\n if (!isArrangement(value)) {\n throw new TypeError(\n '[dawcore] editor.arrangement must be an arrangement made by createArrangement() ' +\n \"(@waveform-playlist/engine), or null for the editor's own.\"\n );\n }\n return value as Arrangement;\n}\n\n/**\n * Play `next` (null: the editor's own arrangement). Refused during a take: the\n * take's track would be in neither. Drags are cancelled, playback stops, the\n * engine is let go without its adapter and a new one is built on `next` with\n * the same adapter; effects chains of tracks `next` does not hold are\n * disposed. The editor never disposes or clears an arrangement it was handed.\n */\nexport function swapArrangement(host: ArrangementSwapHost, next: Arrangement | null): void {\n if (next === host._handedIn) return;\n if (host.isRecording) {\n console.warn(\n '[dawcore] editor.arrangement was not changed: a take is recording. ' +\n 'Set it after stopRecording() resolves.'\n );\n return;\n }\n host._cancelDrags();\n if (host.isPlaying) host.stop();\n const before = host._arrangement.getTracks().map((t) => t.id);\n host._releaseEngine();\n host._playArrangement(next);\n const kept = new Set(host._arrangement.getTracks().map((t) => t.id));\n for (const id of before) if (!kept.has(id)) host._disposeTrackChain(id);\n host._buildEngineIfReady();\n}\n","/**\n * Whether a change to the arrangement made during a drag changed what is\n * dragged (#848 PR 3, P2). A drag writes nothing until its release (P1), so\n * any change while it is in progress came from elsewhere (an app's or an\n * agent's undo, reorder or removal). The drag is cancelled, like a\n * `pointercancel`, only when the change touched it: the dragged clip is gone\n * or no longer where the drag started from, or the dragged track is gone or\n * the order of the tracks changed. A mix change, another clip loading or an\n * edit elsewhere let the drag go on; its release applies to the arrangement\n * as it is then.\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\n\n/** A clip drag past its threshold, with the clip's bounds when it started. */\nexport interface DraggedClip {\n trackId: string;\n clipId: string;\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n}\n\n/** A track drag, with the order of the tracks at the grab. */\nexport interface DraggedTrack {\n trackId: string;\n order: readonly string[];\n}\n\n/** True when the arrangement no longer holds the dragged clip where the drag started from. */\nexport function clipDragChanged(arrangement: Arrangement, drag: DraggedClip): boolean {\n const clip = arrangement\n .getTracks()\n .find((t) => t.id === drag.trackId)\n ?.clips.find((c) => c.id === drag.clipId);\n if (!clip || isLoadingClip(clip)) return true;\n return (\n clip.startSample !== drag.startSample ||\n clip.durationSamples !== drag.durationSamples ||\n clip.offsetSamples !== drag.offsetSamples\n );\n}\n\n/** True when the dragged track is gone or the order of the tracks is not the one at the grab. */\nexport function trackDragChanged(arrangement: Arrangement, drag: DraggedTrack): boolean {\n const ids = arrangement.getTracks().map((t) => t.id);\n if (!ids.includes(drag.trackId) || ids.length !== drag.order.length) return true;\n return ids.some((id, i) => id !== drag.order[i]);\n}\n","/**\n * A `<daw-clip>` the page moves into another `<daw-track>` of the same\n * editor (#848, the maintainer's choice a). Like a `<track>` moved to another\n * `<video>`, its clip leaves the old track and enters the new one, as it is\n * (its times, its audio), in one undo step. On `dev` the new track took the\n * clip and the old one kept it.\n */\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport type { TrackKind } from '@waveform-playlist/core';\nimport { clipKindError } from './track-entry';\n\n/** The track of an arrangement that holds a clip, other than `exceptTrackId`. */\nexport function trackHoldingClip(\n arrangement: Arrangement,\n clipId: string,\n exceptTrackId: string\n): string | null {\n const track = arrangement\n .getTracks()\n .find((t) => t.id !== exceptTrackId && t.clips.some((c) => c.id === clipId));\n return track?.id ?? null;\n}\n\n/**\n * Move a clip from one track to another: one undo step (a transaction).\n * Returns the error that refused it (a clip of the other kind) and changes\n * nothing then.\n */\nexport function moveClipToTrack(\n arrangement: Arrangement,\n fromTrackId: string,\n toTrackId: string,\n clipId: string,\n toKind: TrackKind\n): Error | null {\n const tracks = arrangement.getTracks();\n const clip = tracks.find((t) => t.id === fromTrackId)?.clips.find((c) => c.id === clipId);\n const to = tracks.find((t) => t.id === toTrackId);\n if (!clip || !to) return new Error('clip \"' + clipId + '\" or track \"' + toTrackId + '\" is gone');\n const isMidi = 'midiNotes' in clip && clip.midiNotes != null;\n const kindError = clipKindError(to.name ?? '', toKind, isMidi, clip.name || clipId);\n if (kindError) return kindError;\n arrangement.beginTransaction();\n try {\n arrangement.updateTrack(fromTrackId, (t) => ({\n ...t,\n clips: t.clips.filter((c) => c.id !== clipId),\n }));\n arrangement.updateTrack(toTrackId, (t) => ({ ...t, clips: [...t.clips, clip] }));\n } catch (err) {\n arrangement.abortTransaction();\n return err instanceof Error ? err : new Error(String(err));\n }\n arrangement.commitTransaction();\n return null;\n}\n","import type { EffectChainItem, EffectState, SerializedEffectEntry } from './types';\n\ninterface ChainEntry extends EffectChainItem {\n id: string;\n bypassed: boolean;\n}\n\nlet idCounter = 0;\n\n/**\n * An ordered insert-effects chain. Owns `input`/`output` gain nodes; entries\n * are wired in series between them (empty chain = straight passthrough).\n *\n * Topology changes (add/remove/move/disconnect-bypass) rebuild the internal\n * wiring; parameter changes never do. Only the controller's own outgoing\n * edges are severed during a rebuild — the consumer's edges into `input` and\n * out of `output` are untouched.\n */\nexport class EffectsChainController {\n private _input: GainNode;\n private _output: GainNode;\n private _entries: ChainEntry[] = [];\n private _disposed = false;\n\n constructor(audioContext: BaseAudioContext) {\n this._input = audioContext.createGain();\n this._output = audioContext.createGain();\n this._input.connect(this._output);\n }\n\n /** Connect the upstream source (track mute node, master gain) into this. */\n get input(): AudioNode {\n return this._input;\n }\n\n /** Route this onward (to the master bus / destination). */\n get output(): AudioNode {\n return this._output;\n }\n\n get entries(): EffectState[] {\n return this._entries.map((entry) => ({\n id: entry.id,\n kind: entry.kind,\n type: entry.type,\n params: { ...entry.params },\n bypassed: entry.bypassed,\n ...(entry.url !== undefined ? { url: entry.url } : {}),\n ...(entry.source !== undefined ? { source: { ...entry.source } } : {}),\n ...(entry.label !== undefined ? { label: entry.label } : {}),\n ...(entry.error !== undefined ? { error: entry.error } : {}),\n }));\n }\n\n /** Snapshot the chain in its persisted form. WAM entries are asked for\n * their live state; placeholders re-emit the state they were saved with. */\n serialize(): Promise<SerializedEffectEntry[]> {\n return Promise.all(\n this._entries.map(async (entry): Promise<SerializedEffectEntry> => {\n if (entry.kind === 'wam') {\n // Faust entries persist their DSP source (recompiled on restore);\n // url-loaded entries persist their URL.\n const sourceFields =\n entry.source?.faust !== undefined\n ? {\n faustDsp: entry.source.faust,\n ...(entry.label !== undefined ? { faustName: entry.label } : {}),\n }\n : { url: entry.url ?? '' };\n if (entry.placeholder) {\n return {\n kind: 'wam',\n ...sourceFields,\n bypassed: entry.placeholder.bypassed,\n ...(entry.placeholder.state !== undefined ? { state: entry.placeholder.state } : {}),\n // Lets offline export skip this entry (live playback silently\n // skips it too); restore ignores the flag and retries.\n placeholder: true,\n };\n }\n let state: unknown;\n try {\n state = await entry.instance.getState?.();\n } catch (err) {\n // One misbehaving plugin must not poison the whole snapshot —\n // emit the entry without state and let the consumer persist the rest.\n console.warn(\n '[waveform-playlist] serialize: plugin \"' +\n (entry.url ?? entry.label ?? entry.type) +\n '\" getState failed: ' +\n String(err)\n );\n }\n return {\n kind: 'wam',\n ...sourceFields,\n bypassed: entry.bypassed,\n ...(state !== undefined ? { state } : {}),\n };\n }\n if (entry.placeholder) {\n // Native placeholder (e.g. unregistered custom type on restore):\n // re-emit the SAVED params/bypassed so the snapshot round-trips.\n return {\n kind: 'native',\n type: entry.type,\n params: { ...entry.params },\n bypassed: entry.placeholder.bypassed,\n placeholder: true,\n };\n }\n return {\n kind: 'native',\n type: entry.type,\n params: { ...entry.params },\n bypassed: entry.bypassed,\n };\n })\n );\n }\n\n get disposed(): boolean {\n return this._disposed;\n }\n\n /** Internal (manager-facing): the live entry — including its instance —\n * for GUI wiring. Returns undefined (no warning) when the id is unknown. */\n getEntry(effectId: string): (EffectChainItem & { id: string; bypassed: boolean }) | undefined {\n return this._entries.find((e) => e.id === effectId);\n }\n\n add(item: EffectChainItem, index?: number): string {\n if (this._disposed) {\n throw new Error(\n '[waveform-playlist] EffectsChainController.add: chain is disposed — entries cannot be added'\n );\n }\n const id = 'effect-' + ++idCounter;\n const entry: ChainEntry = { ...item, params: { ...item.params }, id, bypassed: false };\n const at =\n index === undefined\n ? this._entries.length\n : Math.max(0, Math.min(index, this._entries.length));\n this._entries = [...this._entries.slice(0, at), entry, ...this._entries.slice(at)];\n this._rebuild();\n return id;\n }\n\n remove(effectId: string): void {\n const entry = this._find('remove', effectId);\n if (!entry) return;\n this._entries = this._entries.filter((e) => e.id !== effectId);\n entry.instance.output.disconnect();\n entry.instance.dispose?.();\n this._rebuild();\n }\n\n /** Returns the index the entry actually landed at (the requested index is\n * clamped to the chain bounds), or -1 for an unknown effectId — event\n * dispatchers must report the actual index, not the raw request. */\n move(effectId: string, newIndex: number): number {\n const entry = this._find('move', effectId);\n if (!entry) return -1;\n const without = this._entries.filter((e) => e.id !== effectId);\n const at = Math.max(0, Math.min(newIndex, without.length));\n this._entries = [...without.slice(0, at), entry, ...without.slice(at)];\n this._rebuild();\n return at;\n }\n\n setParams(effectId: string, params: Record<string, number>): void {\n const entry = this._find('setParams', effectId);\n if (!entry) return;\n entry.params = { ...entry.params, ...params };\n if (entry.bypassed && entry.wetParam && entry.wetParam in params) {\n // Store the new wet level but keep the audible wet at 0 while bypassed.\n const { [entry.wetParam]: _stored, ...rest } = params;\n if (Object.keys(rest).length > 0) {\n entry.instance.applyParams(rest);\n }\n return;\n }\n entry.instance.applyParams(params);\n }\n\n setBypassed(effectId: string, bypassed: boolean): void {\n const entry = this._find('setBypassed', effectId);\n if (!entry || entry.bypassed === bypassed) return;\n entry.bypassed = bypassed;\n\n if (entry.wetParam) {\n // Wet-style bypass: zero the wet level, restore the stored value later.\n const wet = bypassed ? 0 : (entry.params[entry.wetParam] ?? 0);\n entry.instance.applyParams({ [entry.wetParam]: wet });\n return;\n }\n // No wet param: take the entry out of the series, keep the instance alive.\n this._rebuild();\n }\n\n dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._severOwnEdges();\n for (const entry of this._entries) {\n entry.instance.dispose?.();\n }\n this._entries = [];\n try {\n this._output.disconnect();\n } catch {\n // Output may already be detached by the consumer.\n }\n }\n\n private _find(op: string, effectId: string): ChainEntry | undefined {\n const entry = this._entries.find((e) => e.id === effectId);\n if (!entry) {\n console.warn(\n '[waveform-playlist] EffectsChainController.' + op + ': unknown effectId \"' + effectId + '\"'\n );\n }\n return entry;\n }\n\n /** Sever only this chain's outgoing edges — never the consumer's. */\n private _severOwnEdges(): void {\n this._input.disconnect();\n for (const entry of this._entries) {\n entry.instance.output.disconnect();\n }\n }\n\n private _rebuild(): void {\n this._severOwnEdges();\n let previous: AudioNode = this._input;\n for (const entry of this._entries) {\n if (entry.bypassed && !entry.wetParam) {\n continue;\n }\n previous.connect(entry.instance.input);\n previous = entry.instance.output;\n }\n previous.connect(this._output);\n }\n}\n","import { installCommand } from '../utils/install-command';\n\nconst PREFIX = '[waveform-playlist] ';\n\n/**\n * Dynamic-import an optional peer dep with an actionable error. The thrown\n * message carries BOTH the install hint and the underlying import error —\n * \"not installed\" is only one of the ways a dynamic import fails (dead dev\n * server, broken exports map, CSP, network), and hiding the cause behind a\n * generic hint sends people down the wrong path.\n */\nasync function loadOptionalModule<T>(\n importer: () => Promise<T>,\n packageName: string,\n feature: string\n): Promise<T> {\n try {\n return await importer();\n } catch (originalErr) {\n console.warn(PREFIX + packageName + ' dynamic import failed: ' + String(originalErr));\n throw new Error(\n PREFIX +\n packageName +\n ' is required for ' +\n feature +\n '. Install with: ' +\n installCommand(packageName) +\n ' (import failed: ' +\n String(originalErr) +\n ')'\n );\n }\n}\n\nexport function loadWamModule(feature: string): Promise<typeof import('@dawcore/wam')> {\n return loadOptionalModule(() => import('@dawcore/wam'), '@dawcore/wam', feature);\n}\n\nexport function loadFaustModule(feature: string): Promise<typeof import('@dawcore/faust')> {\n return loadOptionalModule(() => import('@dawcore/faust'), '@dawcore/faust', feature);\n}\n","import { EffectsChainController } from './effects-chain-controller';\nimport { loadWamModule, loadFaustModule } from './optional-modules';\nimport {\n createEffectInstance,\n ensureEffectPrepared,\n getEffectDefinitions,\n needsPrepare,\n prepareEffect,\n} from '@waveform-playlist/core';\nimport './effect-registry'; // registers the native-* built-ins\nimport type { EffectChainItem, EffectState, SerializedEffectEntry } from './types';\n\nconst PREFIX = '[waveform-playlist] ';\n\n/** The transport surface the effects system needs — satisfied by @dawcore/transport's Transport. */\nexport interface EffectsTransportLike {\n /** PRE-FADER track insert (#660): clips → input … output → volume → pan →\n * mute. The transport wires both edges, including the chain's return. */\n connectTrackEffects(trackId: string, input: AudioNode, output: AudioNode): void;\n disconnectTrackEffects(trackId: string): void;\n connectMasterOutput(node: AudioNode): void;\n disconnectMasterOutput(): void;\n readonly masterOutputNode: AudioNode;\n}\n\ninterface AdapterLike {\n audioContext?: AudioContext;\n transport?: EffectsTransportLike;\n}\n\n/** A created (and cached) GUI element plus its idempotent destroyer. */\ninterface GuiRecord {\n element: HTMLElement;\n destroy: () => void;\n /** True for manager-built generic parameter panels — they bake values at\n * build time, so reopen rebuilds them instead of reusing the cache\n * (plugin-provided GUIs manage their own state and stay cached). */\n isFallback: boolean;\n}\n\nfunction makeGuiRecord(\n element: HTMLElement,\n destroyImpl: () => void,\n isFallback = false\n): GuiRecord {\n let destroyed = false;\n return {\n element,\n isFallback,\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n destroyImpl();\n },\n };\n}\n\n/**\n * Owns all effect chains for one editor: the master chain plus one chain per\n * track. Track chains are PRE-FADER inserts (clips → chain → volume → pan →\n * mute); the master chain sits after the master gain. Wires chains into the\n * adapter's transport hooks and dispatches the\n * daw-effect-* events from the owning element (track element for track\n * chains, the editor for the master chain) so they bubble track → editor.\n */\nexport class EffectsManager {\n private _getAdapter: () => AdapterLike | null;\n private _masterTarget: EventTarget;\n private _masterChain: EffectsChainController | null = null;\n private _trackChains = new Map<string, EffectsChainController>();\n /** Per-chain restore ownership — a newer setEffectsState supersedes a stale in-flight one. */\n private _restoreTokens = new WeakMap<EffectsChainController, symbol>();\n /** Cached GUI elements by effectId — close hides, only removal destroys. */\n private _guis = new Map<string, GuiRecord>();\n /** In-flight GUI creation by effectId — concurrent opens share one build. */\n private _guiPending = new Map<string, Promise<GuiRecord>>();\n /** Live WAM plugin nodes across all chains, fed to the wam-transport bridge. */\n private _wamNodes = new Set<import('@dawcore/wam').WamTransportNode>();\n private _transportBridge: { notifyNodeAdded(node: unknown): void; dispose(): void } | null = null;\n /** One-time warn when the adapter transport can't host the wam-transport bridge. */\n private _transportBridgeWarned = false;\n\n constructor(getAdapter: () => AdapterLike | null, masterEventTarget: EventTarget) {\n this._getAdapter = getAdapter;\n this._masterTarget = masterEventTarget;\n }\n\n // --- Master chain ---\n\n addMasterEffect(type: string, params?: Record<string, number>): string {\n const chain = this._ensureMasterChain();\n return this._addToChain(chain, this._masterTarget, type, params);\n }\n\n masterEffects(): EffectState[] {\n return this._masterChain?.entries ?? [];\n }\n\n masterOp(\n op: 'remove' | 'setParams' | 'setBypassed' | 'move',\n effectId: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arg?: any\n ): void {\n this._runOp(this._masterChain, this._masterTarget, op, effectId, arg);\n }\n\n addMasterWamPlugin(url: string, initialState?: unknown): Promise<string> {\n const chain = this._ensureMasterChain();\n return this._addWamToChain(chain, this._masterTarget, url, initialState);\n }\n\n addMasterFaustEffect(dspCode: string, options?: { name?: string }): Promise<string> {\n const chain = this._ensureMasterChain();\n return this._addFaustToChain(chain, this._masterTarget, dspCode, { name: options?.name });\n }\n\n getMasterEffectsState(): Promise<SerializedEffectEntry[]> {\n return this._masterChain?.serialize() ?? Promise.resolve([]);\n }\n\n async setMasterEffectsState(entries: SerializedEffectEntry[]): Promise<void> {\n validateSerializedEntries(entries);\n await this._restoreChain(this._ensureMasterChain(), this._masterTarget, entries);\n }\n\n /** Run a registered effect's async `prepare` hook on the adapter's\n * context, so the synchronous addEffect() can create it. */\n async prepareEffect(type: string): Promise<void> {\n await prepareEffect(type, this._requireWiring().audioContext);\n }\n\n // --- Track chains ---\n\n addTrackEffect(\n trackId: string,\n target: EventTarget,\n type: string,\n params?: Record<string, number>\n ): string {\n const chain = this._ensureTrackChain(trackId);\n return this._addToChain(chain, target, type, params);\n }\n\n addTrackWamPlugin(\n trackId: string,\n target: EventTarget,\n url: string,\n initialState?: unknown\n ): Promise<string> {\n const chain = this._ensureTrackChain(trackId);\n return this._addWamToChain(chain, target, url, initialState);\n }\n\n addTrackFaustEffect(\n trackId: string,\n target: EventTarget,\n dspCode: string,\n options?: { name?: string }\n ): Promise<string> {\n const chain = this._ensureTrackChain(trackId);\n return this._addFaustToChain(chain, target, dspCode, { name: options?.name });\n }\n\n trackEffects(trackId: string): EffectState[] {\n return this._trackChains.get(trackId)?.entries ?? [];\n }\n\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]> {\n return this._trackChains.get(trackId)?.serialize() ?? Promise.resolve([]);\n }\n\n async setTrackEffectsState(\n trackId: string,\n target: EventTarget,\n entries: SerializedEffectEntry[]\n ): Promise<void> {\n validateSerializedEntries(entries);\n await this._restoreChain(this._ensureTrackChain(trackId), target, entries);\n }\n\n trackOp(\n trackId: string,\n target: EventTarget,\n op: 'remove' | 'setParams' | 'setBypassed' | 'move',\n effectId: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arg?: any\n ): void {\n this._runOp(this._trackChains.get(trackId) ?? null, target, op, effectId, arg);\n }\n\n // --- Effect GUIs ---\n\n /** Open (lazily creating) the GUI for a master-chain effect. */\n openMasterEffectGui(effectId: string, container: HTMLElement): Promise<HTMLElement> {\n return this._openGui(this._masterChain, this._masterTarget, effectId, container);\n }\n\n /** Open (lazily creating) the GUI for a track-chain effect. */\n openTrackEffectGui(\n trackId: string,\n target: EventTarget,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement> {\n return this._openGui(this._trackChains.get(trackId) ?? null, target, effectId, container);\n }\n\n /** Hide an open GUI. The element stays cached so reopen is instant —\n * audio processing is never interrupted. */\n closeEffectGui(effectId: string): void {\n const record = this._guis.get(effectId);\n if (!record) {\n console.warn(PREFIX + 'closeEffectGui: no open GUI for effectId \"' + effectId + '\"');\n return;\n }\n record.element.remove();\n }\n\n // --- Lifecycle ---\n\n /** Transport setTracks rebuilds TrackNodes, severing chain hookups — re-wire. */\n rewireTrackChains(): void {\n const transport = this._getAdapter()?.transport;\n if (!transport) return;\n for (const [trackId, chain] of this._trackChains) {\n // The transport owns the chain's return edge (output → fader) and\n // released the old one when it disposed/replaced the track node.\n transport.connectTrackEffects(trackId, chain.input, chain.output);\n }\n }\n\n disposeTrackChain(trackId: string): void {\n const chain = this._trackChains.get(trackId);\n if (!chain) return;\n this._trackChains.delete(trackId);\n for (const entry of chain.entries) {\n this._destroyGui(entry.id);\n }\n try {\n this._getAdapter()?.transport?.disconnectTrackEffects(trackId);\n } catch (err) {\n console.warn(PREFIX + 'EffectsManager: error disconnecting track output: ' + String(err));\n }\n chain.dispose();\n }\n\n disposeAll(): void {\n this._transportBridge?.dispose();\n this._transportBridge = null;\n this._wamNodes.clear();\n for (const trackId of [...this._trackChains.keys()]) {\n this.disposeTrackChain(trackId);\n }\n if (this._masterChain) {\n for (const entry of this._masterChain.entries) {\n this._destroyGui(entry.id);\n }\n try {\n this._getAdapter()?.transport?.disconnectMasterOutput();\n } catch (err) {\n console.warn(PREFIX + 'EffectsManager: error disconnecting master output: ' + String(err));\n }\n this._masterChain.dispose();\n this._masterChain = null;\n }\n }\n\n // --- Private ---\n\n private _requireWiring(): { audioContext: AudioContext; transport: EffectsTransportLike } {\n const adapter = this._getAdapter();\n if (!adapter) {\n throw new Error(\n PREFIX + 'effects require an adapter — set editor.adapter before adding effects.'\n );\n }\n const { audioContext, transport } = adapter;\n if (!audioContext || !transport || typeof transport.connectTrackEffects !== 'function') {\n const outdated =\n typeof (transport as { connectTrackOutput?: unknown } | undefined)?.connectTrackOutput ===\n 'function';\n throw new Error(\n PREFIX +\n (outdated\n ? 'the current adapter exposes the old post-fader effects hook (transport.connectTrackOutput). ' +\n 'Track effects are pre-fader inserts now — upgrade @dawcore/transport (>= 0.0.16) or ' +\n '@waveform-playlist/playout (>= 13) for transport.connectTrackEffects.'\n : 'the current adapter does not expose effects hooks (transport.connectTrackEffects / connectMasterOutput).')\n );\n }\n return { audioContext, transport };\n }\n\n /** Dynamic-import the optional @dawcore/wam peer with an actionable error. */\n private _loadWamModule(feature: string): Promise<typeof import('@dawcore/wam')> {\n return loadWamModule(feature);\n }\n\n /** Dynamic-import the optional @dawcore/faust peer with an actionable error. */\n private _loadFaustModule(feature: string): Promise<typeof import('@dawcore/faust')> {\n return loadFaustModule(feature);\n }\n\n private async _openGui(\n chain: EffectsChainController | null,\n target: EventTarget,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement> {\n if (!container || typeof container.appendChild !== 'function') {\n throw new Error(PREFIX + 'openEffectGui: container must be a DOM element');\n }\n const entry = chain?.getEntry(effectId);\n if (!chain || !entry) {\n throw new Error(PREFIX + 'openEffectGui: unknown effectId \"' + effectId + '\"');\n }\n if (entry.error !== undefined) {\n throw new Error(\n PREFIX +\n 'openEffectGui: effect \"' +\n effectId +\n '\" is a failed-plugin placeholder (' +\n entry.error +\n ') — no GUI is available. Remove it or retry the restore.'\n );\n }\n\n const cached = this._guis.get(effectId);\n if (cached && !cached.isFallback) {\n container.appendChild(cached.element);\n return cached.element;\n }\n // A cached FALLBACK panel is rebuilt instead of reused: generic panels\n // bake their slider values at build time, so an API-side setEffectParams\n // while the panel was closed would show stale values (and the first drag\n // would snap the audio back to the stale position). The old panel is kept\n // until the rebuild succeeds — a transient failure (dynamic-import blip)\n // must not destroy a working panel.\n\n let pending = this._guiPending.get(effectId);\n if (!pending) {\n pending = this._createGuiRecord(chain, target, entry, effectId).finally(() => {\n this._guiPending.delete(effectId);\n });\n this._guiPending.set(effectId, pending);\n }\n let record: GuiRecord;\n try {\n record = await pending;\n } catch (err) {\n if (cached) {\n console.warn(\n PREFIX +\n 'openEffectGui: rebuilding the parameter panel for \"' +\n effectId +\n '\" failed — serving the cached panel (values may be stale): ' +\n String(err)\n );\n container.appendChild(cached.element);\n return cached.element;\n }\n throw err;\n }\n if (cached && cached !== record) {\n cached.element.remove();\n }\n\n // The effect (or its whole chain) may have been removed while the GUI\n // was building — a late mount would leak a GUI for a destroyed plugin.\n if (chain.disposed || !chain.getEntry(effectId)) {\n this._guis.delete(effectId);\n record.element.remove();\n try {\n record.destroy();\n } catch (err) {\n console.warn(\n PREFIX +\n 'openEffectGui: destroying a late GUI for \"' +\n effectId +\n '\" failed: ' +\n String(err)\n );\n }\n throw new Error(\n PREFIX +\n 'openEffectGui: effect \"' +\n effectId +\n '\" was removed while its GUI was loading; the GUI was discarded.'\n );\n }\n\n this._guis.set(effectId, record);\n container.appendChild(record.element);\n return record.element;\n }\n\n /** Build a GUI record: the plugin's own GUI when available, otherwise the\n * generic parameter panel from @dawcore/wam. */\n private async _createGuiRecord(\n chain: EffectsChainController,\n target: EventTarget,\n entry: EffectChainItem & { id: string },\n effectId: string\n ): Promise<GuiRecord> {\n const { instance } = entry;\n if (typeof instance.createGui === 'function') {\n try {\n const element: unknown = await instance.createGui();\n // The WAM SDK's base createGui() exists on every plugin and resolves\n // undefined when the plugin ships no GUI module — \"no GUI\", not a\n // failure. Anything that is not an element takes the fallback below.\n if (element instanceof HTMLElement) {\n return makeGuiRecord(element, () => instance.destroyGui?.(element));\n }\n } catch (err) {\n console.warn(\n PREFIX +\n 'openEffectGui: plugin createGui failed for \"' +\n effectId +\n '\" — falling back to the generic parameter panel: ' +\n String(err)\n );\n }\n }\n const element = await this._createFallbackPanel(chain, target, entry, effectId);\n // The generic panel is plain DOM owned by this manager — removal from the\n // document (done by _destroyGui) is its entire teardown.\n return makeGuiRecord(element, () => {}, true);\n }\n\n /** The generic parameter panel — one code path for \"no custom GUI\":\n * native entries render from the registry's params metadata, WAM entries\n * from getParameterInfo(). Edits route through the regular setParams op so\n * they hit the audio (applyParams → setParameterValues for WAM) AND\n * dispatch daw-effect-change like any other parameter edit. */\n private async _createFallbackPanel(\n chain: EffectsChainController,\n target: EventTarget,\n entry: EffectChainItem & { id: string },\n effectId: string\n ): Promise<HTMLElement> {\n const wamModule = await this._loadWamModule('openEffectGui() parameter panels');\n const onChange = (paramId: string, value: number) => {\n this._runOp(chain, target, 'setParams', effectId, { [paramId]: value });\n };\n\n if (entry.kind === 'native') {\n const definition = getEffectDefinitions().get(entry.type);\n if (!definition) {\n throw new Error(\n PREFIX + 'openEffectGui: no registry definition for effect type \"' + entry.type + '\"'\n );\n }\n const params = Object.entries(definition.params).map(([id, def]) => ({\n id,\n min: def.min,\n max: def.max,\n ...(def.step !== undefined ? { step: def.step } : {}),\n ...(def.unit !== undefined ? { unit: def.unit } : {}),\n value: entry.params[id] ?? definition.defaults[id],\n }));\n return wamModule.createParameterPanel(params, onChange);\n }\n\n if (typeof entry.instance.getParameterInfo !== 'function') {\n throw new Error(\n PREFIX +\n 'openEffectGui: effect \"' +\n effectId +\n '\" has no GUI and exposes no parameter info — nothing to render.'\n );\n }\n return wamModule.createWamParameterPanel(\n { getParameterInfo: () => entry.instance.getParameterInfo!() },\n { onParamChange: onChange }\n );\n }\n\n /** Detach + destroy a cached GUI. Called only from removal paths — close\n * never destroys. Safe when no GUI was ever opened. */\n private _destroyGui(effectId: string): void {\n const record = this._guis.get(effectId);\n if (!record) return;\n this._guis.delete(effectId);\n record.element.remove();\n try {\n record.destroy();\n } catch (err) {\n console.warn(PREFIX + 'destroyGui failed for effect \"' + effectId + '\": ' + String(err));\n }\n }\n\n private _ensureMasterChain(): EffectsChainController {\n if (this._masterChain) return this._masterChain;\n const { audioContext, transport } = this._requireWiring();\n const chain = new EffectsChainController(audioContext);\n transport.connectMasterOutput(chain.input);\n chain.output.connect(audioContext.destination);\n this._masterChain = chain;\n return chain;\n }\n\n private _ensureTrackChain(trackId: string): EffectsChainController {\n const existing = this._trackChains.get(trackId);\n if (existing) return existing;\n const { audioContext, transport } = this._requireWiring();\n const chain = new EffectsChainController(audioContext);\n // Pre-fader insert: the track's volume, pan and mute come AFTER the\n // chain, so the fader never drives a compressor (#660).\n transport.connectTrackEffects(trackId, chain.input, chain.output);\n this._trackChains.set(trackId, chain);\n return chain;\n }\n\n private _addToChain(\n chain: EffectsChainController,\n target: EventTarget,\n type: string,\n params?: Record<string, number>\n ): string {\n const audioContext = this._requireWiring().audioContext;\n const created = createEffectInstance(type, audioContext, params);\n const effectId = chain.add({\n kind: 'native',\n type,\n instance: created.instance,\n params: created.params,\n wetParam: created.wetParam,\n });\n const index = chain.entries.findIndex((e) => e.id === effectId);\n this._dispatch(target, 'daw-effect-add', {\n effectId,\n kind: 'native',\n type,\n params: { ...created.params },\n index,\n });\n return effectId;\n }\n\n /**\n * Load a WAM plugin (via the optional @dawcore/wam peer dep) and add it to\n * a chain as a kind:'wam' entry. WAM entries participate in every chain\n * operation with no special-casing: remove destroys the plugin (via the\n * entry's dispose), bypass uses disconnection semantics (no wet param),\n * and setParams maps onto the plugin's setParameterValues.\n */\n private async _addWamToChain(\n chain: EffectsChainController,\n target: EventTarget,\n url: string,\n initialState?: unknown\n ): Promise<string> {\n const { audioContext } = this._requireWiring();\n const wamModule = await this._loadWamModule('addWamPlugin()');\n const { hostGroupId } = await wamModule.ensureWamHost(audioContext);\n const plugin = await wamModule.createWamInstance(url, audioContext, hostGroupId, {\n initialState,\n });\n return this._insertWamPlugin(chain, target, wamModule, plugin, { url });\n }\n\n /**\n * Compile Faust DSP source in the browser (via the optional @dawcore/faust\n * peer) and add the resulting WAM to a chain. Compilation happens BEFORE\n * any chain work, so a Faust error (with its line/column diagnostics intact)\n * leaves the chain untouched. The entry lands as kind:'wam' with a\n * `source: { faust }` marker so persistence recompiles instead of fetching.\n */\n private async _addFaustToChain(\n chain: EffectsChainController,\n target: EventTarget,\n dspCode: string,\n opts: { name?: string; initialState?: unknown }\n ): Promise<string> {\n if (typeof dspCode !== 'string' || dspCode.trim().length === 0) {\n throw new Error(PREFIX + 'addFaustEffect: dspCode must be a non-empty string');\n }\n this._requireWiring();\n const faustModule = await this._loadFaustModule('addFaustEffect()');\n // Faust compile errors propagate unchanged — the diagnostics are\n // user-facing (the user wrote the DSP).\n const compiled = await faustModule.compileFaustToWam(dspCode, { name: opts.name });\n\n const { audioContext } = this._requireWiring();\n const wamModule = await this._loadWamModule('addFaustEffect()');\n const { hostGroupId } = await wamModule.ensureWamHost(audioContext);\n const plugin = await wamModule.createWamInstanceFromFactory(\n compiled.factory as import('@dawcore/wam').WamFactory,\n audioContext,\n hostGroupId,\n { initialState: opts.initialState, label: compiled.name }\n );\n return this._insertWamPlugin(chain, target, wamModule, plugin, {\n source: { faust: compiled.dspCode },\n });\n }\n\n /**\n * Wire a live WAM plugin instance into a chain as a kind:'wam' entry —\n * shared by the url path (addWamPlugin) and the Faust path (addFaustEffect).\n * WAM entries participate in every chain operation with no special-casing:\n * remove destroys the plugin (via the entry's dispose), bypass uses\n * disconnection semantics (no wet param), and setParams maps onto the\n * plugin's setParameterValues.\n */\n private _insertWamPlugin(\n chain: EffectsChainController,\n target: EventTarget,\n wamModule: typeof import('@dawcore/wam'),\n plugin: import('@dawcore/wam').WamPluginInstance,\n meta: { url?: string; source?: { faust: string } }\n ): string {\n const node = plugin.audioNode;\n const label = plugin.descriptor.name;\n\n // The chain may have been torn down while the plugin was loading/compiling\n // (track removed, editor disconnected, adapter swapped). A late add would\n // wire the plugin into a severed graph and leak its worklet.\n if (chain.disposed) {\n plugin.destroy();\n throw new Error(\n PREFIX +\n 'addWamPlugin: the effects chain was disposed while \"' +\n (meta.url ?? label) +\n '\" was loading; the plugin was discarded.'\n );\n }\n\n let effectId: string;\n try {\n effectId = chain.add({\n kind: 'wam',\n type: 'wam',\n ...(meta.url !== undefined ? { url: meta.url } : {}),\n ...(meta.source !== undefined ? { source: meta.source } : {}),\n label,\n instance: {\n input: node,\n output: node,\n applyParams: (params) => {\n node.setParameterValues?.(toWamParameterMap(params))?.catch((err: unknown) => {\n console.warn(PREFIX + 'WAM setParameterValues failed: ' + String(err));\n });\n },\n dispose: () => {\n this._wamNodes.delete(node);\n plugin.destroy();\n },\n getState: () => plugin.getState(),\n getParameterInfo: () => plugin.getParameterInfo(),\n ...(plugin.createGui ? { createGui: () => plugin.createGui!() } : {}),\n ...(plugin.destroyGui\n ? { destroyGui: (gui: HTMLElement) => plugin.destroyGui!(gui) }\n : {}),\n },\n params: {},\n });\n } catch (err) {\n // Insertion failed — the chain never took ownership, so the live\n // worklet must be torn down here or it leaks.\n try {\n plugin.destroy();\n } catch (destroyErr) {\n console.warn(\n PREFIX + 'addWamPlugin: cleanup after failed insertion also failed: ' + String(destroyErr)\n );\n }\n throw err;\n }\n this._wamNodes.add(node);\n this._ensureTransportBridge(wamModule)?.notifyNodeAdded(node);\n const index = chain.entries.findIndex((e) => e.id === effectId);\n this._dispatch(target, 'daw-effect-add', {\n effectId,\n kind: 'wam',\n type: 'wam',\n ...(meta.url !== undefined ? { url: meta.url } : {}),\n ...(meta.source !== undefined ? { source: meta.source } : {}),\n params: {},\n index,\n });\n return effectId;\n }\n\n /**\n * Lazily create the wam-transport bridge so tempo-synced plugins lock to\n * the timeline. Skipped (not an error, one-time warn) when the adapter's\n * transport lacks the query/event surface — the bridge is an enhancement,\n * not a requirement for audio processing.\n */\n private _ensureTransportBridge(\n wamModule: typeof import('@dawcore/wam')\n ): { notifyNodeAdded(node: unknown): void; dispose(): void } | null {\n if (this._transportBridge) return this._transportBridge;\n if (typeof wamModule.createWamTransportBridge !== 'function') return null;\n const transport = this._getAdapter()?.transport as\n | (EffectsTransportLike & import('@dawcore/wam').TransportQueryLike)\n | undefined;\n if (\n !transport ||\n typeof transport.on !== 'function' ||\n typeof transport.getTempo !== 'function' ||\n typeof transport.tickToBar !== 'function' ||\n typeof transport.timeToTick !== 'function'\n ) {\n if (!this._transportBridgeWarned) {\n this._transportBridgeWarned = true;\n console.warn(\n '[waveform-playlist] wam-transport bridge skipped: the adapter transport does not ' +\n 'implement the query surface (on/getTempo/tickToBar/timeToTick), so WAM plugins ' +\n \"won't receive transport/tempo events. Use NativePlayoutAdapter for transport \" +\n 'sync — see issue #537.'\n );\n }\n return null;\n }\n this._transportBridge = wamModule.createWamTransportBridge(transport, () => [\n ...this._wamNodes,\n ]);\n return this._transportBridge;\n }\n\n /**\n * Replace a chain's contents with a persisted snapshot. Entries restore\n * sequentially so chain order survives async WAM loads. A WAM url that\n * fails to load becomes a bypassed passthrough placeholder at its saved\n * position — the restore continues, a daw-effect-error fires, and the\n * saved state is retained so a later snapshot/retry round-trips it.\n */\n private async _restoreChain(\n chain: EffectsChainController,\n target: EventTarget,\n entries: SerializedEffectEntry[]\n ): Promise<void> {\n // Last writer wins: a newer restore takes ownership of the chain and the\n // stale one aborts at its next checkpoint instead of interleaving entries.\n const token = Symbol('restore');\n this._restoreTokens.set(chain, token);\n const superseded = () => this._restoreTokens.get(chain) !== token;\n\n for (const existing of chain.entries) {\n this._runOp(chain, target, 'remove', existing.id);\n }\n for (const entry of entries) {\n if (superseded()) return;\n if (entry.kind === 'native') {\n try {\n // Restore is already async, so it can run the definition's\n // per-context setup itself (#657). A failure lands in the\n // placeholder path below like any other native restore failure.\n // Only await when there IS something to prepare: a chain of plain\n // natives must still restore synchronously within this call, as it\n // always has (callers read `effects` / add effects right after).\n const liveContext = this._requireWiring().audioContext;\n if (needsPrepare(entry.type, liveContext)) {\n await ensureEffectPrepared(entry.type, liveContext);\n if (superseded() || chain.disposed) return;\n }\n const id = this._addToChain(chain, target, entry.type, entry.params);\n if (entry.bypassed) {\n this._runOp(chain, target, 'setBypassed', id, true);\n }\n } catch (err) {\n // Same policy as failed WAM loads below: the old chain is already\n // destroyed at this point, so a throw here would strand a\n // half-built chain and lose every remaining entry. Placeholder +\n // error event + continue. (Reachable via an unregistered custom\n // type — the consumer saved state with registerEffect()'d types\n // that aren't re-registered on this page.)\n if (superseded() || chain.disposed) return;\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n PREFIX +\n 'setEffectsState: native effect \"' +\n entry.type +\n '\" failed to restore: ' +\n message\n );\n const effectId = this._addNativePlaceholder(chain, entry, message);\n this._dispatch(target, 'daw-effect-error', {\n effectId,\n type: entry.type,\n message,\n });\n }\n continue;\n }\n try {\n // Faust entries recompile from their persisted DSP source; url\n // entries load from their URL.\n const id =\n entry.faustDsp !== undefined\n ? await this._addFaustToChain(chain, target, entry.faustDsp, {\n name: entry.faustName,\n initialState: entry.state,\n })\n : await this._addWamToChain(chain, target, entry.url ?? '', entry.state);\n if (superseded()) {\n // A newer restore cleared the chain while this plugin loaded —\n // remove (and thereby destroy) the late arrival.\n this._runOp(chain, target, 'remove', id);\n return;\n }\n if (entry.bypassed) {\n this._runOp(chain, target, 'setBypassed', id, true);\n }\n } catch (err) {\n // chain.disposed guard: the chain can be torn down mid-restore (track\n // removed while a plugin loaded) — the placeholder add would itself\n // throw on the disposed chain, escaping setEffectsState with an error\n // about internal chain lifecycle instead of the plugin failure.\n if (superseded() || chain.disposed) return;\n const message = err instanceof Error ? err.message : String(err);\n const sourceLabel = entry.url ?? entry.faustName ?? 'Faust effect';\n console.warn(\n PREFIX + 'setEffectsState: plugin \"' + sourceLabel + '\" failed to restore: ' + message\n );\n const effectId = this._addWamPlaceholder(chain, entry, message);\n this._dispatch(target, 'daw-effect-error', {\n effectId,\n ...(entry.url !== undefined ? { url: entry.url } : {}),\n ...(entry.faustDsp !== undefined ? { source: { faust: entry.faustDsp } } : {}),\n message,\n });\n }\n }\n }\n\n /** A silent passthrough occupying a failed NATIVE entry's chain position.\n * Carries the saved params/bypassed so the snapshot round-trips (serialize\n * re-emits them with `placeholder: true`). */\n private _addNativePlaceholder(\n chain: EffectsChainController,\n entry: { type: string; params: Record<string, number>; bypassed: boolean },\n message: string\n ): string {\n const { audioContext } = this._requireWiring();\n const node = audioContext.createGain();\n const effectId = chain.add({\n kind: 'native',\n type: entry.type,\n label: entry.type,\n error: message,\n placeholder: { bypassed: entry.bypassed },\n instance: { input: node, output: node, applyParams: () => {} },\n params: { ...entry.params },\n });\n // Placeholders pass audio through, bypassed-style (no wet param).\n chain.setBypassed(effectId, true);\n return effectId;\n }\n\n /** A silent passthrough occupying the failed plugin's chain position. */\n private _addWamPlaceholder(\n chain: EffectsChainController,\n entry: {\n url?: string;\n faustDsp?: string;\n faustName?: string;\n bypassed: boolean;\n state?: unknown;\n },\n message: string\n ): string {\n const { audioContext } = this._requireWiring();\n const node = audioContext.createGain();\n const effectId = chain.add({\n kind: 'wam',\n type: 'wam',\n ...(entry.url !== undefined ? { url: entry.url } : {}),\n ...(entry.faustDsp !== undefined ? { source: { faust: entry.faustDsp } } : {}),\n label: entry.url ?? entry.faustName ?? 'Faust effect',\n error: message,\n placeholder: { state: entry.state, bypassed: entry.bypassed },\n instance: { input: node, output: node, applyParams: () => {} },\n params: {},\n });\n // Placeholders pass audio through, bypassed-style (no wet param).\n chain.setBypassed(effectId, true);\n return effectId;\n }\n\n private _runOp(\n chain: EffectsChainController | null,\n target: EventTarget,\n op: 'remove' | 'setParams' | 'setBypassed' | 'move',\n effectId: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arg?: any\n ): void {\n const entries = chain?.entries ?? [];\n const fromIndex = entries.findIndex((e) => e.id === effectId);\n if (!chain || fromIndex === -1) {\n console.warn(PREFIX + 'effects.' + op + ': unknown effectId \"' + effectId + '\"');\n return;\n }\n if (entries[fromIndex].error !== undefined && (op === 'setParams' || op === 'setBypassed')) {\n // Error placeholders are inert passthroughs — silently \"succeeding\"\n // would mislead the consumer into thinking the edit took effect.\n console.warn(\n PREFIX +\n 'effects.' +\n op +\n ': effect \"' +\n effectId +\n '\" is a failed-plugin placeholder (' +\n entries[fromIndex].error +\n ') — edit ignored. Remove it or retry the restore.'\n );\n return;\n }\n switch (op) {\n case 'remove':\n this._destroyGui(effectId);\n chain.remove(effectId);\n this._dispatch(target, 'daw-effect-remove', { effectId });\n break;\n case 'setParams':\n chain.setParams(effectId, arg);\n this._dispatch(target, 'daw-effect-change', { effectId, params: { ...arg } });\n break;\n case 'setBypassed':\n chain.setBypassed(effectId, arg);\n this._dispatch(target, 'daw-effect-bypass', { effectId, bypassed: arg });\n break;\n case 'move': {\n // Report the index the chain ACTUALLY used — it clamps out-of-range\n // requests, and a consumer mirroring order from the event detail\n // would mis-sort (or crash indexing) on the raw request.\n const toIndex = chain.move(effectId, arg);\n this._dispatch(target, 'daw-effect-reorder', { effectId, fromIndex, toIndex });\n break;\n }\n }\n }\n\n private _dispatch(target: EventTarget, name: string, detail: Record<string, unknown>): void {\n target.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail }));\n }\n}\n\n/** Fail fast on malformed persisted data — external input, never trusted. */\nfunction validateSerializedEntries(entries: unknown): asserts entries is SerializedEffectEntry[] {\n if (!Array.isArray(entries)) {\n throw new Error(PREFIX + 'setEffectsState: expected an array of serialized effect entries');\n }\n entries.forEach((entry, i) => {\n const at = ' (entry ' + i + ')';\n if (entry === null || typeof entry !== 'object') {\n throw new Error(PREFIX + 'setEffectsState: entry must be an object' + at);\n }\n const e = entry as Record<string, unknown>;\n if (e.kind === 'native') {\n if (typeof e.type !== 'string' || e.type.length === 0) {\n throw new Error(PREFIX + 'setEffectsState: native entry requires a type string' + at);\n }\n if (e.params === null || typeof e.params !== 'object') {\n throw new Error(PREFIX + 'setEffectsState: native entry requires a params object' + at);\n }\n } else if (e.kind === 'wam') {\n const hasUrl = typeof e.url === 'string' && e.url.length > 0;\n const hasFaustDsp = typeof e.faustDsp === 'string' && e.faustDsp.trim().length > 0;\n if (!hasUrl && !hasFaustDsp) {\n throw new Error(\n PREFIX +\n 'setEffectsState: wam entry requires a url string or a faustDsp source string' +\n at\n );\n }\n if (e.faustName !== undefined && typeof e.faustName !== 'string') {\n throw new Error(PREFIX + 'setEffectsState: faustName must be a string when provided' + at);\n }\n } else {\n throw new Error(PREFIX + 'setEffectsState: unknown entry kind \"' + String(e.kind) + '\"' + at);\n }\n if (typeof e.bypassed !== 'boolean') {\n throw new Error(PREFIX + 'setEffectsState: entry requires a boolean bypassed flag' + at);\n }\n if (e.placeholder !== undefined && e.placeholder !== true) {\n // A malformed truthy value (e.g. \"false\", 1, {}) would restore as a\n // working live effect but be silently SKIPPED by exportAudio — an\n // export missing an effect the user hears, with zero warning.\n throw new Error(PREFIX + 'setEffectsState: placeholder must be true when present' + at);\n }\n });\n}\n\n/** WAM setParameterValues takes a map of {id, value, normalized} records. */\nfunction toWamParameterMap(\n params: Record<string, number>\n): Record<string, { id: string; value: number; normalized: boolean }> {\n const map: Record<string, { id: string; value: number; normalized: boolean }> = {};\n for (const [id, value] of Object.entries(params)) {\n map[id] = { id, value, normalized: false };\n }\n return map;\n}\n","/**\n * dawcore's built-in `native-*` effects. The registry itself lives in\n * `@waveform-playlist/core` (shared with the React effects hooks); importing\n * this module registers the built-ins there.\n */\nimport {\n getEffectDefinitions,\n registerEffect,\n unregisterEffect,\n type EffectParamDef,\n type NativeEffectDefinition,\n} from '@waveform-playlist/core';\n\nconst MAX_DELAY_SECONDS = 10;\n\n/** Test-only: restore the registry to just the built-ins. */\nexport function _resetEffectRegistryForTests(): void {\n for (const type of getEffectDefinitions().keys()) {\n unregisterEffect(type);\n }\n registerBuiltIns();\n}\n\nfunction singleNode(\n node: AudioNode,\n applyParams: (params: Record<string, number>) => void\n): { input: AudioNode; output: AudioNode; applyParams: (params: Record<string, number>) => void } {\n return { input: node, output: node, applyParams };\n}\n\ntype BiquadParam = 'frequency' | 'q' | 'gain';\n\nconst BIQUAD_PARAM_DEFS: Record<BiquadParam, EffectParamDef> = {\n frequency: { min: 20, max: 20000, step: 1, unit: 'Hz' },\n q: { min: 0.1, max: 20, step: 0.1 },\n gain: { min: -24, max: 24, step: 0.5, unit: 'dB' },\n};\n\n/**\n * Web Audio gives `Q` two meanings. For bandpass, notch and peaking it is\n * the usual linear quality factor. For LOWPASS and HIGHPASS it is the\n * resonance peak in DECIBELS at the cutoff (Q_linear = 10^(Q/20)): 0 dB is a\n * slight bump, about -3 dB is a flat Butterworth response, and a linear-style\n * 0.707 would actually be +0.7 dB of resonance.\n */\nconst RESONANCE_DB_PARAM_DEF: EffectParamDef = { min: -12, max: 24, step: 0.1, unit: 'dB' };\n/** Flat (Butterworth) response: 20·log10(1/√2). */\nconst BUTTERWORTH_RESONANCE_DB = -3;\n\ninterface BiquadFilterSpec {\n label: string;\n biquadType: BiquadFilterType;\n /** Only the params this biquad shape actually uses (the Web Audio spec\n * ignores Q on shelves and gain on everything but peaking/shelves) — a\n * generic parameter panel must not render dead sliders. */\n defaults: Partial<Record<BiquadParam, number>>;\n /** Per-type overrides of the shared param metadata. */\n paramDefs?: Partial<Record<BiquadParam, EffectParamDef>>;\n}\n\n/**\n * One registry type per biquad shape (#661). Effect params are numeric\n * (`Record<string, number>`), so the shape cannot be a param — sibling types\n * fit the model with no API change. `native-filter` keeps its original\n * (lowpass) meaning so persisted chains restore unchanged.\n */\nconst BIQUAD_FILTERS: Record<string, BiquadFilterSpec> = {\n // Unchanged since before #661 — including its q range, which predates the\n // dB reading above (q here is also resonance in dB; persisted chains rely\n // on these exact defaults and bounds).\n 'native-filter': {\n label: 'Lowpass Filter',\n biquadType: 'lowpass',\n defaults: { frequency: 1000, q: 1 },\n },\n 'native-highpass': {\n label: 'Highpass Filter',\n biquadType: 'highpass',\n defaults: { frequency: 80, q: BUTTERWORTH_RESONANCE_DB },\n paramDefs: { q: RESONANCE_DB_PARAM_DEF },\n },\n 'native-bandpass': {\n label: 'Bandpass Filter',\n biquadType: 'bandpass',\n defaults: { frequency: 1000, q: 1 },\n },\n 'native-notch': {\n label: 'Notch Filter',\n biquadType: 'notch',\n defaults: { frequency: 1000, q: 1 },\n },\n 'native-peaking': {\n label: 'Peaking EQ',\n biquadType: 'peaking',\n defaults: { frequency: 1000, q: 1, gain: 0 },\n },\n 'native-lowshelf': {\n label: 'Low Shelf',\n biquadType: 'lowshelf',\n defaults: { frequency: 200, gain: 0 },\n },\n 'native-highshelf': {\n label: 'High Shelf',\n biquadType: 'highshelf',\n defaults: { frequency: 4000, gain: 0 },\n },\n};\n\nfunction biquadDefinition(spec: BiquadFilterSpec): NativeEffectDefinition {\n const names = Object.keys(spec.defaults) as BiquadParam[];\n return {\n label: spec.label,\n category: 'filter',\n defaults: { ...spec.defaults } as Record<string, number>,\n params: Object.fromEntries(\n names.map((name) => [name, spec.paramDefs?.[name] ?? BIQUAD_PARAM_DEFS[name]])\n ),\n create: (ctx) => {\n const node = ctx.createBiquadFilter();\n node.type = spec.biquadType;\n return singleNode(node, (p) => {\n if (names.includes('frequency') && p.frequency !== undefined) {\n node.frequency.value = p.frequency;\n }\n if (names.includes('q') && p.q !== undefined) node.Q.value = p.q;\n if (names.includes('gain') && p.gain !== undefined) node.gain.value = p.gain;\n });\n },\n };\n}\n\n/**\n * Built-ins yield to whatever is already registered under their name: an app\n * may have registered its own `native-gain` through core before this module\n * loaded, and loading the module twice (HMR) must not warn about overwrites.\n */\nfunction registerBuiltIn(type: string, definition: NativeEffectDefinition): void {\n if (!getEffectDefinitions().has(type)) {\n // Marked as this library's catalogue, so other hosts of the shared\n // registry (the React effects hooks) do not list them as app effects.\n registerEffect(type, { ...definition, builtIn: true });\n }\n}\n\nfunction registerBuiltIns(): void {\n registerBuiltIn('native-gain', {\n label: 'Gain',\n category: 'dynamics',\n defaults: { gain: 1 },\n params: { gain: { min: 0, max: 2, step: 0.01 } },\n create: (ctx) => {\n const node = ctx.createGain();\n return singleNode(node, (p) => {\n if (p.gain !== undefined) node.gain.value = p.gain;\n });\n },\n });\n\n for (const [type, definition] of Object.entries(BIQUAD_FILTERS)) {\n registerBuiltIn(type, biquadDefinition(definition));\n }\n\n registerBuiltIn('native-compressor', {\n label: 'Compressor',\n category: 'dynamics',\n defaults: { threshold: -24, knee: 30, ratio: 12, attack: 0.003, release: 0.25 },\n params: {\n threshold: { min: -60, max: 0, step: 1, unit: 'dB' },\n knee: { min: 0, max: 40, step: 1, unit: 'dB' },\n ratio: { min: 1, max: 20, step: 0.5 },\n attack: { min: 0, max: 1, step: 0.001, unit: 's' },\n release: { min: 0, max: 1, step: 0.01, unit: 's' },\n },\n create: (ctx) => {\n const node = ctx.createDynamicsCompressor();\n return singleNode(node, (p) => {\n if (p.threshold !== undefined) node.threshold.value = p.threshold;\n if (p.knee !== undefined) node.knee.value = p.knee;\n if (p.ratio !== undefined) node.ratio.value = p.ratio;\n if (p.attack !== undefined) node.attack.value = p.attack;\n if (p.release !== undefined) node.release.value = p.release;\n });\n },\n });\n\n registerBuiltIn('native-stereo-panner', {\n label: 'Stereo Panner',\n category: 'spatial',\n defaults: { pan: 0 },\n params: { pan: { min: -1, max: 1, step: 0.01 } },\n create: (ctx) => {\n const node = ctx.createStereoPanner();\n return singleNode(node, (p) => {\n if (p.pan !== undefined) node.pan.value = p.pan;\n });\n },\n });\n\n registerBuiltIn('native-delay', {\n label: 'Delay',\n category: 'delay',\n defaults: { delayTime: 0.25, feedback: 0.4, wet: 0.35 },\n params: {\n delayTime: { min: 0, max: MAX_DELAY_SECONDS, step: 0.01, unit: 's' },\n feedback: { min: 0, max: 0.95, step: 0.01 },\n wet: { min: 0, max: 1, step: 0.01 },\n },\n wetParam: 'wet',\n create: (ctx) => {\n const input = ctx.createGain();\n const output = ctx.createGain();\n const delay = ctx.createDelay(MAX_DELAY_SECONDS);\n const feedback = ctx.createGain();\n const wet = ctx.createGain();\n const dry = ctx.createGain();\n\n input.connect(dry);\n dry.connect(output);\n input.connect(delay);\n delay.connect(feedback);\n feedback.connect(delay);\n delay.connect(wet);\n wet.connect(output);\n\n return {\n input,\n output,\n applyParams: (p) => {\n if (p.delayTime !== undefined) delay.delayTime.value = p.delayTime;\n if (p.feedback !== undefined) feedback.gain.value = p.feedback;\n if (p.wet !== undefined) {\n wet.gain.value = p.wet;\n dry.gain.value = 1 - p.wet;\n }\n },\n };\n },\n });\n}\n\nregisterBuiltIns();\n","import { createPanStage, trackPanLaw } from '@waveform-playlist/core';\nimport type { PanLaw } from '@waveform-playlist/core';\nimport {\n createEffectInstance,\n ensureEffectPrepared,\n getEffectDefinitions,\n} from '@waveform-playlist/core';\nimport '../effects/effect-registry'; // registers the native-* built-ins\nimport { loadWamModule, loadFaustModule } from '../effects/optional-modules';\nimport type { SerializedEffectEntry } from '../effects/types';\n\nconst PREFIX = '[waveform-playlist] ';\n\nexport interface ExportOptions {\n /** Default: the host's sample rate. */\n sampleRate?: number;\n /** Window start in seconds. Default: 0. */\n startTime?: number;\n /** Window length in seconds. Default: host duration minus startTime. */\n duration?: number;\n /** Default: 2 (stereo). */\n channels?: 1 | 2;\n}\n\ninterface ExportClip {\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n sampleRate: number;\n gain?: number;\n audioBuffer?: AudioBuffer;\n}\n\ninterface ExportTrack {\n id: string;\n volume: number;\n pan: number;\n /** The track's pan law (the arrangement's mixer value). `'auto'` or none: from its clips. */\n panLaw?: PanLaw;\n muted: boolean;\n soloed: boolean;\n clips: ExportClip[];\n}\n\n/** What the editor provides to the export pipeline. */\nexport interface ExportAudioHost {\n effectiveSampleRate: number;\n /** Natural session duration in seconds. */\n duration: number;\n tracks: ExportTrack[];\n /** Master output gain (engine setMasterVolume). Default 1. Without it the\n * export renders louder/quieter than what the user mixed against. */\n masterVolume?: number;\n getMasterEffectsState(): Promise<SerializedEffectEntry[]>;\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]>;\n}\n\ninterface OfflineChain {\n input: AudioNode;\n output: AudioNode;\n dispose: () => void;\n}\n\n/**\n * Render the session offline through all effect chains (per-track + master).\n *\n * No Transport involved: clips are known upfront, so sources are scheduled\n * statically on an OfflineAudioContext. Effect chains rebuild from their\n * persisted form (#424) — natives via the registry (definitions take\n * BaseAudioContext for exactly this; a definition's async `prepare` hook is\n * awaited on the offline context first), WAM plugins re-instantiated on the\n * offline context with their saved state (worklets are context-bound, the\n * wam-studio cloneInto pattern). All offline plugin instances are destroyed\n * after rendering, success or failure.\n *\n * Parity note: clip fades are not rendered — the native ClipPlayer does not\n * apply them during playback either.\n */\nexport async function exportAudioImpl(\n host: ExportAudioHost,\n options: ExportOptions = {}\n): Promise<AudioBuffer> {\n const sampleRate = options.sampleRate ?? host.effectiveSampleRate;\n const startTime = options.startTime ?? 0;\n const duration = options.duration ?? Math.max(0, host.duration - startTime);\n const channels = options.channels ?? 2;\n if (!Number.isFinite(sampleRate) || sampleRate <= 0) {\n throw new Error(PREFIX + 'exportAudio: invalid sampleRate ' + String(sampleRate));\n }\n if (!Number.isFinite(duration) || duration <= 0) {\n throw new Error(PREFIX + 'exportAudio: nothing to render (duration ' + String(duration) + ')');\n }\n\n const ctx = new OfflineAudioContext({\n numberOfChannels: channels,\n length: Math.round(duration * sampleRate),\n sampleRate,\n });\n\n const cleanups: Array<() => void> = [];\n try {\n const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());\n cleanups.push(masterChain.dispose);\n // Master volume stage BEFORE the master chain — parity with live\n // playback, where MasterNode's gain feeds connectMasterOutput → chain.\n // Order matters for nonlinear master effects (compressor, distortion):\n // volume→chain and chain→volume compress differently.\n const masterVolume = ctx.createGain();\n masterVolume.gain.value = host.masterVolume ?? 1;\n masterVolume.connect(masterChain.input);\n masterChain.output.connect(ctx.destination);\n\n const anySoloed = host.tracks.some((t) => t.soloed);\n for (const track of host.tracks) {\n if (track.muted || (anySoloed && !track.soloed)) {\n continue;\n }\n const chain = await buildOfflineChain(ctx, await host.getTrackEffectsState(track.id));\n cleanups.push(chain.dispose);\n\n // Live track order (TrackNode, #660): clips → effects → volume → pan.\n // The chain is a PRE-FADER insert — it sees the clips' own level and\n // channel layout, so the fader and pan never change how hard a\n // compressor works. Order matters for every nonlinear effect.\n const volume = ctx.createGain();\n volume.gain.value = track.volume;\n // Same pan stage as live (#669): the law is the track's own (#684),\n // not whatever layout the effects chain outputs.\n const panStage = createPanStage(ctx, track.pan, trackPanLaw(track));\n cleanups.push(panStage.dispose);\n chain.output.connect(volume);\n volume.connect(panStage.input);\n panStage.output.connect(masterVolume);\n\n for (const clip of track.clips) {\n scheduleClip(ctx, clip, startTime, duration, chain.input);\n }\n }\n\n return await ctx.startRendering();\n } finally {\n for (const dispose of cleanups) {\n try {\n dispose();\n } catch (err) {\n console.warn(PREFIX + 'exportAudio: cleanup error: ' + String(err));\n }\n }\n }\n}\n\n/** Schedule one clip's source into the render window, clamping at both edges. */\nfunction scheduleClip(\n ctx: OfflineAudioContext,\n clip: ExportClip,\n windowStart: number,\n windowDuration: number,\n destination: AudioNode\n): void {\n if (!clip.audioBuffer || clip.durationSamples <= 0) {\n return;\n }\n const clipRate = clip.sampleRate;\n const clipStart = clip.startSample / clipRate;\n const clipDuration = clip.durationSamples / clipRate;\n let offset = clip.offsetSamples / clipRate;\n\n let when = clipStart - windowStart;\n let remaining = clipDuration;\n if (when < 0) {\n // Window begins mid-clip: start immediately, further into the file.\n offset += -when;\n remaining += when;\n when = 0;\n }\n remaining = Math.min(remaining, windowDuration - when);\n if (remaining <= 0) {\n return;\n }\n\n const source = ctx.createBufferSource();\n source.buffer = clip.audioBuffer;\n let out: AudioNode = source;\n if (clip.gain !== undefined && clip.gain !== 1) {\n const gainNode = ctx.createGain();\n gainNode.gain.value = clip.gain;\n out.connect(gainNode);\n out = gainNode;\n }\n out.connect(destination);\n source.start(when, offset, remaining);\n}\n\n/**\n * Rebuild a persisted effects chain on the offline context.\n * Bypass parity with live playback: wet-style entries are created with their\n * wet zeroed; disconnect-style entries (including bypassed WAM plugins and\n * placeholders) are skipped from the series entirely.\n */\nasync function buildOfflineChain(\n ctx: OfflineAudioContext,\n entries: SerializedEffectEntry[]\n): Promise<OfflineChain> {\n const input = ctx.createGain();\n const output = ctx.createGain();\n const cleanups: Array<() => void> = [];\n const dispose = (): void => {\n for (const cleanup of cleanups) {\n try {\n cleanup();\n } catch (err) {\n console.warn(PREFIX + 'exportAudio: chain cleanup error: ' + String(err));\n }\n }\n };\n let previous: AudioNode = input;\n\n try {\n await wireEntries();\n } catch (err) {\n // A failure partway through must not leak the plugin worklets already\n // created for this chain — the caller never gets a dispose handle for a\n // chain that threw.\n dispose();\n throw err;\n }\n\n previous.connect(output);\n return { input, output, dispose };\n\n async function wireEntries(): Promise<void> {\n for (const entry of entries) {\n // Failed-plugin placeholders (any kind) are silent passthroughs live —\n // skip them here too, regardless of their SAVED bypassed flag.\n // Instantiating would either fail the export (dead URL / unregistered\n // type) or render an effect absent from live playback. Warn: the only\n // other evidence the effect is missing is a daw-effect-error that\n // fired back at restore time.\n if (entry.placeholder) {\n console.warn(\n PREFIX +\n 'exportAudio: skipping failed-plugin placeholder \"' +\n (entry.kind === 'native' ? entry.type : (entry.url ?? 'Faust effect')) +\n '\"'\n );\n continue;\n }\n if (entry.kind === 'native') {\n // Disconnect-style bypass (no wet param): the effect is out of the\n // series, exactly as live — so do not prepare or create it. A\n // bypassed worklet effect whose module fails to load must not fail\n // an export it takes no part in. (Unknown types fall through to\n // createEffectInstance, which reports them.)\n const definition = getEffectDefinitions().get(entry.type);\n if (entry.bypassed && definition && !definition.wetParam) {\n continue;\n }\n // Async per-context setup (#657) — e.g. an AudioWorklet module must be\n // added to THIS offline context, which only the export ever holds.\n // Shared across chains: one run per type per export.\n await ensureEffectPrepared(entry.type, ctx);\n const created = createEffectInstance(entry.type, ctx, entry.params);\n if (entry.bypassed && created.wetParam) {\n created.instance.applyParams({ [created.wetParam]: 0 });\n }\n if (created.instance.dispose) {\n cleanups.push(created.instance.dispose);\n }\n previous.connect(created.instance.input);\n previous = created.instance.output;\n continue;\n }\n\n // kind 'wam'\n if (entry.bypassed) {\n continue; // disconnection bypass\n }\n const wamModule = await loadWamModule('exportAudio() with WAM effects');\n const { hostGroupId } = await wamModule.ensureWamHost(ctx);\n let plugin: import('@dawcore/wam').WamPluginInstance;\n if (entry.faustDsp !== undefined) {\n // Faust entries have no URL — recompile the persisted DSP source on\n // demand (worklets are context-bound, so the realtime instance can't\n // be reused; the compiled factory path mirrors setEffectsState).\n const faustModule = await loadFaustModule('exportAudio() with Faust effects');\n const compiled = await faustModule.compileFaustToWam(entry.faustDsp, {\n name: entry.faustName,\n });\n plugin = await wamModule.createWamInstanceFromFactory(\n compiled.factory as import('@dawcore/wam').WamFactory,\n ctx,\n hostGroupId,\n { initialState: entry.state, label: compiled.name }\n );\n } else {\n plugin = await wamModule.createWamInstance(entry.url ?? '', ctx, hostGroupId, {\n initialState: entry.state,\n });\n }\n cleanups.push(() => plugin.destroy());\n previous.connect(plugin.audioNode);\n previous = plugin.audioNode;\n }\n }\n}\n","/**\n * Load pre-computed waveform data from a .dat or .json file (BBC audiowaveform format).\n */\n\nimport WaveformData from 'waveform-data';\n\n/**\n * Fetch and parse a waveform data file (.dat binary or .json). An aborted\n * `signal` rejects with its reason (an `AbortError`), as `fetch()` does.\n */\nexport async function loadWaveformDataFromUrl(\n src: string,\n signal?: AbortSignal\n): Promise<WaveformData> {\n const response = await fetch(src, signal ? { signal } : undefined);\n\n if (!response.ok) {\n throw new Error('[dawcore] Failed to fetch peaks 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","import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\n// Line scrolling uses 16px per line (standard line height).\nconst LINE_HEIGHT_PX = 16;\n\n/**\n * Frozen-panes scroll sync. The editor's `.scroll-area` owns both scroll\n * axes; this controller keeps the ruler band (x) and controls column (y)\n * visually locked to it by applying translate3d transforms on EVERY scroll\n * event. (ViewportController's 100px threshold exists for chunk\n * virtualization and is too coarse for visual sync.)\n *\n * Also forwards wheel events from ALL elements matched by `wheelForwardSelector`\n * to the scroll container for both axes:\n * - Horizontal scrub (deltaX) — ruler band stays in sync when the user\n * scrolls the timeline left/right while hovering the ruler.\n * - Vertical scroll (deltaY) — controls column lets the user scroll track\n * rows while hovering the track controls.\n *\n * preventDefault fires only when at least one axis actually moved, so page\n * scrolling is unaffected for unconstrained editors and boundary scrolling\n * chains properly.\n */\nexport class ScrollSyncController implements ReactiveController {\n private _host: ReactiveControllerHost & HTMLElement;\n private _scrollContainer: HTMLElement | null = null;\n /** The scroll listener on `_scrollContainer`, aborted when it is replaced or detached. */\n private _scrollListener: AbortController | null = null;\n /** Each wheel target and the controller of its listener. */\n private _wheelTargets = new Map<HTMLElement, AbortController>();\n private _warnedX = false;\n private _warnedY = false;\n\n /** Selector (in host shadow DOM) for the scroll container. */\n scrollSelector = '';\n /** Selector for the element receiving translate3d(-scrollLeft, 0, 0). */\n xTargetSelector = '';\n /** Selector for the element receiving translate3d(0, -scrollTop, 0). */\n yTargetSelector = '';\n /**\n * Selector (or comma-separated selectors) for elements whose wheel events\n * forward to the scroll container. All matching elements receive listeners.\n */\n wheelForwardSelector = '';\n\n constructor(host: ReactiveControllerHost & HTMLElement) {\n this._host = host;\n host.addController(this);\n }\n\n hostConnected() {\n // Defer so the Shadow DOM renders before querying (same pattern as\n // ViewportController).\n requestAnimationFrame(() => {\n if (!this._host.isConnected) return;\n this._attach();\n if (!this._scrollContainer && this.scrollSelector) {\n console.warn(\n '[dawcore] ScrollSyncController: scroll container not found for \"' +\n this.scrollSelector +\n '\"'\n );\n }\n });\n }\n\n hostDisconnected() {\n this._detachAll();\n }\n\n /** Remove the scroll and every wheel listener. */\n private _detachAll() {\n this._scrollListener?.abort();\n this._scrollListener = null;\n this._scrollContainer = null;\n for (const listener of this._wheelTargets.values()) listener.abort();\n this._wheelTargets.clear();\n }\n\n /**\n * Re-attach and re-apply transforms from the current scroll position.\n * Called from the host's updated() so elements created by a re-render\n * (e.g. the ruler appearing when the first track loads) pick up the\n * current offset and listeners.\n */\n sync() {\n this._attach();\n }\n\n private _query(selector: string): HTMLElement | null {\n return selector ? (this._host.shadowRoot?.querySelector(selector) as HTMLElement | null) : null;\n }\n\n private _queryAll(selector: string): HTMLElement[] {\n if (!selector) return [];\n return Array.from(this._host.shadowRoot?.querySelectorAll(selector) ?? []) as HTMLElement[];\n }\n\n private _attach() {\n const container = this._query(this.scrollSelector);\n if (!container) {\n if (this._scrollContainer && !this._scrollContainer.isConnected) {\n console.warn(\n '[dawcore] ScrollSyncController: scroll container \"' +\n this.scrollSelector +\n '\" was removed from the DOM — detaching listeners until it reappears.'\n );\n this._detachAll();\n }\n return;\n }\n if (container !== this._scrollContainer) {\n this._scrollListener?.abort();\n this._scrollContainer = container;\n this._scrollListener = new AbortController();\n container.addEventListener('scroll', this._onScroll, {\n passive: true,\n signal: this._scrollListener.signal,\n });\n }\n\n // Diff the current set of matched wheel targets.\n const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));\n for (const [old, listener] of [...this._wheelTargets]) {\n if (!nextTargets.has(old)) {\n listener.abort();\n this._wheelTargets.delete(old);\n }\n }\n for (const next of nextTargets) {\n if (!this._wheelTargets.has(next)) {\n const listener = new AbortController();\n next.addEventListener('wheel', this._onWheel, { passive: false, signal: listener.signal });\n this._wheelTargets.set(next, listener);\n }\n }\n\n this._apply();\n }\n\n private _onScroll = () => {\n this._apply();\n };\n\n private _onWheel = (e: WheelEvent) => {\n const sc = this._scrollContainer;\n if (!sc) return;\n\n const scale =\n e.deltaMode === WheelEvent.DOM_DELTA_LINE\n ? LINE_HEIGHT_PX\n : e.deltaMode === WheelEvent.DOM_DELTA_PAGE\n ? sc.clientHeight // used for Y; X uses clientWidth below\n : 1;\n\n const scaleX = e.deltaMode === WheelEvent.DOM_DELTA_PAGE ? sc.clientWidth : scale;\n\n const beforeLeft = sc.scrollLeft;\n const beforeTop = sc.scrollTop;\n\n sc.scrollLeft += e.deltaX * scaleX;\n sc.scrollTop += e.deltaY * scale;\n\n if (sc.scrollLeft !== beforeLeft || sc.scrollTop !== beforeTop) {\n e.preventDefault();\n }\n };\n\n private _apply() {\n const sc = this._scrollContainer;\n if (!sc) return;\n // Re-query targets each time: Lit conditional templates create/replace\n // these elements between renders (e.g. the header row appears with the\n // first loaded track).\n const xTarget = this._query(this.xTargetSelector);\n if (xTarget) {\n xTarget.style.transform = `translate3d(${-sc.scrollLeft}px, 0, 0)`;\n this._warnedX = false;\n } else if (this.xTargetSelector && sc.scrollLeft !== 0 && !this._warnedX) {\n this._warnedX = true;\n console.warn(\n '[dawcore] ScrollSyncController: x target \"' +\n this.xTargetSelector +\n '\" not found while scrolled — the synced pane will appear frozen. Check the selector, or clear it if the target is intentionally not rendered.'\n );\n }\n const yTarget = this._query(this.yTargetSelector);\n if (yTarget) {\n yTarget.style.transform = `translate3d(0, ${-sc.scrollTop}px, 0)`;\n this._warnedY = false;\n } else if (this.yTargetSelector && sc.scrollTop !== 0 && !this._warnedY) {\n this._warnedY = true;\n console.warn(\n '[dawcore] ScrollSyncController: y target \"' +\n this.yTargetSelector +\n '\" not found while scrolled — the synced pane will appear frozen. Check the selector, or clear it if the target is intentionally not rendered.'\n );\n }\n }\n}\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\nexport class AnimationController implements ReactiveController {\n private _rafId: number | null = null;\n private _callback: (() => void) | null = null;\n\n constructor(host: ReactiveControllerHost) {\n host.addController(this);\n }\n\n start(callback: () => void) {\n this.stop();\n this._callback = callback;\n const loop = () => {\n this._callback?.();\n // The callback may have called stop() (e.g. the editor's end-of-\n // timeline auto-stop fires from inside a frame). Rescheduling then\n // would leave a zombie loop burning frames with a null callback.\n if (this._callback !== null) {\n this._rafId = requestAnimationFrame(loop);\n }\n };\n this._rafId = requestAnimationFrame(loop);\n }\n\n stop() {\n if (this._rafId !== null) {\n cancelAnimationFrame(this._rafId);\n this._rafId = null;\n }\n this._callback = null;\n }\n\n hostConnected() {}\n\n hostDisconnected() {\n this.stop();\n }\n}\n","import type { ReactiveControllerHost } from 'lit';\nimport { AnimationController } from './animation-controller';\nimport type { DawTimeUpdateDetail } from '../events';\n\nexport interface PlayheadLike {\n setPosition(px: number): void;\n}\n\nexport interface PlaybackAnimationOptions {\n /** Convert playback seconds to a timeline pixel offset. */\n timeToPixels: (time: number) => number;\n /** Resolve the playhead element (re-queried per call — templates may recreate it). */\n getPlayhead: () => PlayheadLike | null;\n}\n\n/**\n * The single editor-owned playback animation loop (mirror of the React\n * `usePlaybackAnimation` pattern). Each frame reads the latency-compensated\n * playback time ONCE, positions the playhead, and dispatches `daw-timeupdate`\n * from the host element. External consumers hook into the same loop by\n * listening for `daw-timeupdate` — never add a second RAF loop for\n * playback-time concerns.\n *\n * `timeToPixels` and `getPlayhead` are injected once at construction — they\n * are stable per host, and threading them through every `start`/`stop` call\n * invited desync between the two call sites.\n *\n * HTMLMediaElement-adjacent: `stop()` dispatches one final event so idle\n * displays settle on the exact commanded position (media elements fire\n * `timeupdate` on pause and seek too). Pass `{ dispatch: false }` for\n * transitional stops (stop+play seeks) whose settle position must not leak\n * to consumers.\n */\nexport class PlaybackAnimationController {\n private _animation: AnimationController;\n private _host: ReactiveControllerHost & HTMLElement;\n private _options: PlaybackAnimationOptions;\n private _running = false;\n private _lastDispatchedTime: number | null = null;\n\n constructor(host: ReactiveControllerHost & HTMLElement, options: PlaybackAnimationOptions) {\n this._host = host;\n this._options = options;\n this._animation = new AnimationController(host);\n }\n\n start(getTime: () => number): void {\n this._running = true;\n this._animation.start(() => {\n const time = getTime();\n // getTime() (the editor's frame callback) can call this.stop() mid-\n // frame on auto-stop paths (end-of-timeline, bounded play(start, end)\n // annotation playback) — stop() already dispatched its own settle\n // daw-timeupdate synchronously before returning here. Skip this\n // frame's position/dispatch entirely so that settle event isn't\n // immediately followed by a stale trailing one (which would, e.g.,\n // re-set an annotation's \"playing\" highlight that daw-stop just\n // cleared). Manual stop/seek settle events are unaffected — they\n // dispatch from stop() itself, never from this wrapper.\n if (!this._running) return;\n this._options.getPlayhead()?.setPosition(this._options.timeToPixels(time));\n this._dispatchTimeUpdate(time);\n });\n }\n\n stop(finalTime: number, opts?: { dispatch?: boolean }): void {\n // The editor's stop path reaches here twice (the engine 'stop' handler\n // registered in _buildEngine AND editor.stop() both call _stopPlayhead).\n // Dedupe: dispatch only when the loop was actually running or the settled\n // time changed (seek-while-stopped must still fire its event).\n const wasRunning = this._running;\n this._running = false;\n this._animation.stop();\n this._options.getPlayhead()?.setPosition(this._options.timeToPixels(finalTime));\n // dispatch === false: transitional stop (seek-while-playing) — stop the\n // loop and position the playhead, but don't leak the settle time to\n // consumers; _lastDispatchedTime stays untouched so the dedupe logic\n // still reflects the last event consumers actually saw.\n if (opts?.dispatch === false) return;\n if (wasRunning || finalTime !== this._lastDispatchedTime) {\n this._dispatchTimeUpdate(finalTime);\n }\n }\n\n private _dispatchTimeUpdate(time: number): void {\n this._lastDispatchedTime = time;\n this._host.dispatchEvent(\n new CustomEvent<DawTimeUpdateDetail>('daw-timeupdate', {\n bubbles: true,\n composed: true,\n detail: { time },\n })\n );\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\n\n@customElement('daw-selection')\nexport class DawSelectionElement extends LitElement {\n @property({ type: Number, attribute: false }) startPx = 0;\n @property({ type: Number, attribute: false }) endPx = 0;\n\n static styles = css`\n :host {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n pointer-events: none;\n z-index: 5;\n }\n div {\n position: absolute;\n top: 0;\n bottom: 0;\n background: var(--daw-selection-color, rgba(99, 199, 95, 0.3));\n }\n `;\n\n render() {\n const left = Math.min(this.startPx, this.endPx);\n const width = Math.abs(this.endPx - this.startPx);\n if (width === 0) return html``;\n return html`<div style=\"left: ${left}px; width: ${width}px;\"></div>`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-selection': DawSelectionElement;\n }\n}\n","import { html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\nimport { warnNoTargetOnce } from '../utils/transport-capability';\n\n@customElement('daw-record-button')\nexport class DawRecordButtonElement extends DawTransportButton {\n protected static override requiredTargetMethods: readonly string[] = [\n 'startRecording',\n 'stopRecording',\n ];\n\n @state() private _isRecording = false;\n private _targetRef: HTMLElement | null = null;\n /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */\n private _targetListeners: AbortController | null = null;\n private _onStart = () => {\n this._isRecording = true;\n };\n private _onComplete = () => {\n this._isRecording = false;\n };\n private _onError = () => {\n this._isRecording = false;\n };\n\n static override styles = [\n DawTransportButton.styles,\n css`\n button[data-recording] {\n color: #d08070;\n border-color: #d08070;\n background: rgba(208, 128, 112, 0.15);\n }\n `,\n ];\n\n connectedCallback() {\n super.connectedCallback();\n // Defer so <daw-transport for=\"...\"> and the target editor are resolved\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this._ensureTargetListeners();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._cleanupListeners();\n }\n\n protected override updated() {\n // Re-resolve on every render (pointerenter triggers one via the base\n // class) — a target that upgrades/appears after the one-shot\n // connectedCallback rAF would otherwise never get the recording-state\n // listeners: the button starts recordings it can't reflect (#573).\n this._ensureTargetListeners();\n }\n\n private _ensureTargetListeners() {\n const target = this.target;\n if (target === this._targetRef) return;\n this._cleanupListeners();\n if (!target) return;\n this._targetRef = target;\n this._targetListeners = new AbortController();\n const { signal } = this._targetListeners;\n target.addEventListener('daw-recording-start', this._onStart, { signal });\n target.addEventListener('daw-recording-complete', this._onComplete, { signal });\n target.addEventListener('daw-recording-error', this._onError, { signal });\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetListeners?.abort();\n this._targetListeners = null;\n this._targetRef = null;\n }\n }\n\n render() {\n return html`\n <button\n part=\"button\"\n ?disabled=${!this.targetSupported}\n ?data-recording=${this._isRecording}\n @click=${this._onClick}\n >\n <slot>Record</slot>\n </button>\n `;\n }\n\n private _onClick() {\n // Start-only — stop is handled by the stop button\n if (this._isRecording) return;\n const target = this.target;\n // Stale-render race guard: the target can vanish between render and click.\n if (!target) {\n warnNoTargetOnce(this);\n return;\n }\n // Guarantee state listeners exist for any recording this button starts\n // (covers programmatic clicks that never trigger a re-render).\n this._ensureTargetListeners();\n target.startRecording(target.recordingStream);\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-record-button': DawRecordButtonElement;\n }\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { handleKeyboardEvent } from '@waveform-playlist/core';\nimport type { KeyBinding, KeyboardShortcut } from '@waveform-playlist/core';\nimport type { DawEditorElement } from './daw-editor';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PlaybackShortcutMap {\n playPause?: KeyBinding;\n stop?: KeyBinding;\n rewindToStart?: KeyBinding;\n}\n\nexport interface SplittingShortcutMap {\n splitAtPlayhead?: KeyBinding;\n}\n\nexport interface UndoShortcutMap {\n undo?: KeyBinding;\n redo?: KeyBinding;\n}\n\n// ---------------------------------------------------------------------------\n// Element\n// ---------------------------------------------------------------------------\n\n/**\n * Render-less element that enables keyboard shortcuts for a parent <daw-editor>.\n * Place inside the editor element. Boolean attributes enable preset categories;\n * JS properties allow remapping and custom shortcuts.\n *\n * ```html\n * <daw-editor>\n * <daw-keyboard-shortcuts playback splitting undo></daw-keyboard-shortcuts>\n * </daw-editor>\n * ```\n */\n@customElement('daw-keyboard-shortcuts')\nexport class DawKeyboardShortcutsElement extends LitElement {\n // --- Preset attributes ---\n @property({ type: Boolean }) playback = false;\n @property({ type: Boolean }) splitting = false;\n @property({ type: Boolean }) undo = false;\n\n // --- JS properties for remapping ---\n // Accessors, not plain fields: assigning a remap after any keydown has\n // warmed _cachedShortcuts must invalidate it, or the documented remapping\n // API is silently ignored until an unrelated boolean attribute toggles.\n // (connectedCallback runs the standard upgrade-property dance so values\n // assigned BEFORE the element was defined don't shadow these accessors.)\n private _playbackShortcuts: PlaybackShortcutMap | null = null;\n get playbackShortcuts(): PlaybackShortcutMap | null {\n return this._playbackShortcuts;\n }\n set playbackShortcuts(value: PlaybackShortcutMap | null) {\n this._playbackShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n private _splittingShortcuts: SplittingShortcutMap | null = null;\n get splittingShortcuts(): SplittingShortcutMap | null {\n return this._splittingShortcuts;\n }\n set splittingShortcuts(value: SplittingShortcutMap | null) {\n this._splittingShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n private _undoShortcuts: UndoShortcutMap | null = null;\n get undoShortcuts(): UndoShortcutMap | null {\n return this._undoShortcuts;\n }\n set undoShortcuts(value: UndoShortcutMap | null) {\n this._undoShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n /** Additional custom shortcuts. */\n private _customShortcuts: KeyboardShortcut[] = [];\n get customShortcuts(): KeyboardShortcut[] {\n return this._customShortcuts;\n }\n set customShortcuts(value: KeyboardShortcut[]) {\n this._customShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n private _editor: DawEditorElement | null = null;\n private _cachedShortcuts: KeyboardShortcut[] | null = null;\n\n /** All active shortcuts (read-only, cached). */\n get shortcuts(): KeyboardShortcut[] {\n if (!this._cachedShortcuts) {\n this._cachedShortcuts = this._buildShortcuts();\n }\n return this._cachedShortcuts;\n }\n\n /** Invalidate cached shortcuts when Lit properties change. */\n override updated(): void {\n this._cachedShortcuts = null;\n }\n\n // --- Lifecycle ---\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n override connectedCallback(): void {\n super.connectedCallback();\n // Upgrade-property dance: a remap assigned BEFORE this element was\n // defined created an own property that shadows the accessors above —\n // delete it and re-assign through the setter so cache invalidation works.\n for (const prop of [\n 'playbackShortcuts',\n 'splittingShortcuts',\n 'undoShortcuts',\n 'customShortcuts',\n ] as const) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete (this as Record<string, unknown>)[prop];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any)[prop] = value;\n }\n }\n this._editor = this.closest('daw-editor') as DawEditorElement | null;\n if (!this._editor) {\n console.warn(\n '[dawcore] <daw-keyboard-shortcuts> must be placed inside a <daw-editor>. ' +\n 'Preset shortcuts (playback, splitting, undo) will be inactive; only customShortcuts will fire.'\n );\n }\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('keydown', this._onKeyDown, { signal });\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n this._editor = null;\n }\n\n // No shadow DOM — render-less element\n override createRenderRoot(): this {\n return this;\n }\n\n // --- Shortcut building ---\n\n private _buildShortcuts(): KeyboardShortcut[] {\n const editor = this._editor;\n if (!editor) return this.customShortcuts;\n\n const result: KeyboardShortcut[] = [];\n\n if (this.playback) {\n const map = this.playbackShortcuts;\n // Explicit ctrlKey/metaKey: false prevents Cmd+Space (Spotlight on Mac)\n // and Ctrl+0 etc. from triggering playback shortcuts.\n result.push(\n this._makeShortcut(\n map?.playPause ?? { key: ' ', ctrlKey: false, metaKey: false },\n () => editor.togglePlayPause(),\n 'Play/Pause'\n ),\n this._makeShortcut(\n map?.stop ?? { key: 'Escape', ctrlKey: false, metaKey: false },\n () => editor.stop(),\n 'Stop'\n ),\n this._makeShortcut(\n map?.rewindToStart ?? { key: '0', ctrlKey: false, metaKey: false },\n () => editor.seekTo(0),\n 'Rewind to start'\n )\n );\n }\n\n if (this.splitting) {\n const map = this.splittingShortcuts;\n const binding = map?.splitAtPlayhead ?? {\n key: 's',\n ctrlKey: false,\n metaKey: false,\n altKey: false,\n };\n result.push(this._makeShortcut(binding, () => editor.splitAtPlayhead(), 'Split at playhead'));\n }\n\n if (this.undo) {\n const map = this.undoShortcuts;\n const undoBinding = map?.undo ?? { key: 'z' };\n const redoBinding = map?.redo ?? { key: 'z', shiftKey: true };\n\n // Undo: Ctrl+Z (Win/Linux) and Cmd+Z (Mac)\n // Use === undefined to distinguish \"not specified\" (auto-expand) from\n // \"explicitly false\" (user wants no modifier — respect their intent).\n if (undoBinding.ctrlKey === undefined && undoBinding.metaKey === undefined) {\n // Only set shiftKey: false when user didn't provide a value\n const undoShift = undoBinding.shiftKey === undefined ? { shiftKey: false } : {};\n result.push(\n this._makeShortcut(\n { ...undoBinding, ctrlKey: true, ...undoShift },\n () => editor.undo(),\n 'Undo'\n ),\n this._makeShortcut(\n { ...undoBinding, metaKey: true, ...undoShift },\n () => editor.undo(),\n 'Undo'\n )\n );\n } else {\n result.push(this._makeShortcut(undoBinding, () => editor.undo(), 'Undo'));\n }\n\n // Redo: Ctrl+Shift+Z (Win/Linux) and Cmd+Shift+Z (Mac)\n if (redoBinding.ctrlKey === undefined && redoBinding.metaKey === undefined) {\n const redoShift = redoBinding.shiftKey === undefined ? { shiftKey: true } : {};\n result.push(\n this._makeShortcut(\n { ...redoBinding, ctrlKey: true, ...redoShift },\n () => editor.redo(),\n 'Redo'\n ),\n this._makeShortcut(\n { ...redoBinding, metaKey: true, ...redoShift },\n () => editor.redo(),\n 'Redo'\n )\n );\n } else {\n result.push(this._makeShortcut(redoBinding, () => editor.redo(), 'Redo'));\n }\n }\n\n result.push(...this.customShortcuts);\n return result;\n }\n\n private _makeShortcut(\n binding: KeyBinding,\n action: () => void,\n description: string\n ): KeyboardShortcut {\n return {\n key: binding.key,\n ...(binding.ctrlKey !== undefined && { ctrlKey: binding.ctrlKey }),\n ...(binding.shiftKey !== undefined && { shiftKey: binding.shiftKey }),\n ...(binding.metaKey !== undefined && { metaKey: binding.metaKey }),\n ...(binding.altKey !== undefined && { altKey: binding.altKey }),\n action,\n description,\n };\n }\n\n // --- Event handler ---\n\n private _onKeyDown = (e: KeyboardEvent) => {\n const shortcuts = this.shortcuts;\n if (shortcuts.length === 0) return;\n try {\n handleKeyboardEvent(e, shortcuts, true);\n } catch (err) {\n console.warn('[dawcore] Keyboard shortcut failed (key=' + e.key + '): ' + String(err));\n const target = this._editor ?? this;\n target.dispatchEvent(\n new CustomEvent('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'keyboard-shortcut', key: e.key, error: err },\n })\n );\n }\n };\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-keyboard-shortcuts': DawKeyboardShortcutsElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\n// The orchestrator's clip-relative sample math assumes chunk k starts at\n// clip pixel k * MAX_CANVAS_WIDTH — the constant must be the shared one,\n// not a local copy that can drift (#554 layout contract).\nimport { MAX_CANVAS_WIDTH, buildSpectrogramCanvasId } from '@waveform-playlist/core';\n\ninterface SpectrogramHost extends HTMLElement {\n _spectrogramRegisterCanvas?: (reg: {\n canvasId: string;\n canvas: OffscreenCanvas;\n clipId: string;\n trackId: string;\n channelIndex: number;\n chunkIndex: number;\n globalPixelOffset: number;\n widthPx: number;\n heightPx: number;\n }) => void;\n _spectrogramUnregisterCanvas?: (canvasId: string) => void;\n}\n\n@customElement('daw-spectrogram')\nexport class DawSpectrogramElement extends LitElement {\n @property({ attribute: false }) clipId = '';\n @property({ attribute: false }) trackId = '';\n @property({ type: Number, attribute: false }) channelIndex = 0;\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) waveHeight = 128;\n\n @property({ type: Number, attribute: false, noAccessor: true })\n get samplesPerPixel(): number {\n return this._samplesPerPixel;\n }\n set samplesPerPixel(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-spectrogram samplesPerPixel ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._samplesPerPixel;\n this._samplesPerPixel = value;\n this.requestUpdate('samplesPerPixel', old);\n }\n private _samplesPerPixel = 1024;\n\n @property({ type: Number, attribute: false, noAccessor: true })\n get sampleRate(): number {\n return this._sampleRate;\n }\n set sampleRate(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-spectrogram sampleRate ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._sampleRate;\n this._sampleRate = value;\n this.requestUpdate('sampleRate', old);\n }\n private _sampleRate = 44100;\n\n @property({ type: Number, attribute: false }) clipOffsetSeconds = 0;\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n @property({ type: Number, attribute: false }) originX = 0;\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n background: var(--daw-spectrogram-background, #000);\n }\n canvas {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n pointer-events: none;\n }\n `;\n\n private _canvases: HTMLCanvasElement[] = [];\n private _registeredCanvasIds: string[] = [];\n private _warnedNoHost = false;\n\n /**\n * Walk up to the editor host. `closest('daw-editor')` does NOT cross\n * shadow boundaries — and this element lives inside the editor's shadow\n * DOM — so use getRootNode().host to step out.\n */\n private _findHostEditor(): SpectrogramHost | null {\n const root = this.getRootNode();\n const host = root instanceof ShadowRoot ? root.host : null;\n if (!host) return null;\n if (host.tagName === 'DAW-EDITOR') return host as SpectrogramHost;\n return host.closest('daw-editor') as SpectrogramHost | null;\n }\n\n willUpdate(changed: PropertyValues): void {\n const layoutChanged =\n changed.has('length') ||\n changed.has('waveHeight') ||\n changed.has('samplesPerPixel') ||\n changed.has('clipId') ||\n changed.has('channelIndex');\n if (layoutChanged) {\n this._rebuildChunks();\n }\n }\n\n private _rebuildChunks(): void {\n this._unregisterAllCanvases();\n this._canvases = [];\n\n if (this.length <= 0) return;\n\n const chunkCount = Math.ceil(this.length / MAX_CANVAS_WIDTH);\n for (let i = 0; i < chunkCount; i++) {\n const widthPx = Math.min(MAX_CANVAS_WIDTH, this.length - i * MAX_CANVAS_WIDTH);\n const canvas = document.createElement('canvas');\n canvas.style.left = i * MAX_CANVAS_WIDTH + 'px';\n canvas.style.width = widthPx + 'px';\n const dpr = window.devicePixelRatio || 1;\n canvas.width = widthPx * dpr;\n canvas.height = this.waveHeight * dpr;\n this._canvases.push(canvas);\n }\n }\n\n protected updated(_changed: PropertyValues): void {\n if (this._registeredCanvasIds.length === 0 && this._canvases.length > 0) {\n requestAnimationFrame(() => this._registerCanvases());\n }\n }\n\n private _registerCanvases(): void {\n const editor = this._findHostEditor();\n if (!editor || typeof editor._spectrogramRegisterCanvas !== 'function') {\n if (!this._warnedNoHost) {\n this._warnedNoHost = true;\n console.warn(\n '[dawcore] <daw-spectrogram> (clip ' +\n this.clipId +\n ') could not find host <daw-editor>. Canvases will not render. ' +\n 'Ensure the element is mounted inside a <daw-editor>.'\n );\n }\n return;\n }\n\n for (let i = 0; i < this._canvases.length; i++) {\n const canvas = this._canvases[i];\n const canvasId = buildSpectrogramCanvasId({\n clipId: this.clipId,\n channelIndex: this.channelIndex,\n chunkIndex: i,\n });\n let offscreen: OffscreenCanvas;\n try {\n offscreen = canvas.transferControlToOffscreen();\n } catch (err) {\n console.warn(\n '[dawcore] daw-spectrogram transferControlToOffscreen failed for ' +\n canvasId +\n ': ' +\n (err instanceof Error ? err.message : String(err))\n );\n continue;\n }\n editor._spectrogramRegisterCanvas({\n canvasId,\n canvas: offscreen,\n clipId: this.clipId,\n trackId: this.trackId,\n channelIndex: this.channelIndex,\n chunkIndex: i,\n globalPixelOffset: this.originX + i * MAX_CANVAS_WIDTH,\n widthPx: parseFloat(canvas.style.width),\n heightPx: this.waveHeight,\n });\n this._registeredCanvasIds.push(canvasId);\n }\n }\n\n private _unregisterAllCanvases(): void {\n const editor = this._findHostEditor();\n if (editor && typeof editor._spectrogramUnregisterCanvas === 'function') {\n for (const id of this._registeredCanvasIds) {\n editor._spectrogramUnregisterCanvas(id);\n }\n }\n this._registeredCanvasIds = [];\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this._unregisterAllCanvases();\n }\n\n render() {\n return html`${this._canvases.map((c) => c)}`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-spectrogram': DawSpectrogramElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { resolveTransportTarget, warnNoTargetOnce } from '../utils/transport-capability';\nimport {\n formatDisplayTime,\n isTimeDisplayFormat,\n type TimeDisplayFormat,\n} from '../utils/time-display-format';\nimport type { DawEvent } from '../events';\n\n/**\n * Formatted playback time readout for <daw-transport>.\n *\n * Subscribes to bubbled `daw-timeupdate` / `daw-time-format-change` events at\n * the document level and filters by its transport target — works with any\n * target that dispatches them (<daw-editor> today, <daw-player> later) and\n * tolerates targets that upgrade after this element connects.\n *\n * Accessibility (spec): role=\"status\", aria-live=\"off\" — not announced every\n * frame; screen reader users query on demand.\n */\n@customElement('daw-time-display')\nexport class DawTimeDisplayElement extends LitElement {\n /** Null until the first successful target sync or daw-timeupdate. */\n @state() private _time: number | null = null;\n @state() private _format: TimeDisplayFormat = 'hh:mm:ss.sss';\n\n static styles = css`\n span {\n display: inline-block;\n font-family: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;\n font-variant-numeric: tabular-nums;\n color: var(--daw-controls-text, #e0d4c8);\n background: var(--daw-controls-background, #1a1a2e);\n border: 1px solid currentColor;\n padding: 4px 8px;\n }\n `;\n\n private get target(): HTMLElement | null {\n return resolveTransportTarget(this);\n }\n\n private _onTimeUpdate = (e: Event) => {\n if (e.target !== this.target) return;\n if (this._time === null) {\n // Late-target recovery: pick up the format we missed at connect time.\n const timeFormat = (e.target as HTMLElement & { timeFormat?: unknown }).timeFormat;\n if (isTimeDisplayFormat(timeFormat)) this._format = timeFormat;\n }\n this._time = (e as DawEvent<'daw-timeupdate'>).detail.time;\n };\n\n private _onFormatChange = (e: Event) => {\n if (e.target !== this.target) return;\n const detail = (e as DawEvent<'daw-time-format-change'>).detail;\n if (isTimeDisplayFormat(detail.format)) {\n this._format = detail.format;\n }\n };\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('daw-timeupdate', this._onTimeUpdate, { signal });\n document.addEventListener('daw-time-format-change', this._onFormatChange, { signal });\n // Defer the initial read until <daw-transport for> and the target have\n // upgraded (same pattern as the transport buttons).\n requestAnimationFrame(() => this._syncFromTarget());\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n }\n\n private _syncFromTarget() {\n if (!this.isConnected) return;\n const target = this.target;\n if (!target || typeof (target as { currentTime?: unknown }).currentTime !== 'number') {\n warnNoTargetOnce(\n this,\n ' The display recovers automatically once the target dispatches daw-timeupdate.'\n );\n return;\n }\n this._time = (target as unknown as { currentTime: number }).currentTime;\n const fmt = (target as { timeFormat?: unknown }).timeFormat;\n if (isTimeDisplayFormat(fmt)) {\n this._format = fmt;\n }\n }\n\n render() {\n const text = this._time === null ? '--:--:--' : formatDisplayTime(this._time, this._format);\n return html`<span role=\"status\" aria-label=\"Playback time\" aria-live=\"off\">${text}</span>`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-time-display': DawTimeDisplayElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport {\n resolveTransportTarget,\n targetSupports,\n targetUndetermined,\n warnNoTargetOnce,\n warnUnsupportedOnce,\n} from '../utils/transport-capability';\nimport {\n TIME_DISPLAY_FORMATS,\n isTimeDisplayFormat,\n type TimeDisplayFormat,\n} from '../utils/time-display-format';\nimport type { DawEvent } from '../events';\n\n/**\n * Time format select for <daw-transport>. Sets the format ON the target\n * (`target.setTimeFormat(...)`) — the target owns the state (native-form\n * style), and every display/input syncs via the bubbled\n * `daw-time-format-change` event. Renders disabled when the target doesn't\n * implement setTimeFormat (duck-typed capability detection, #474).\n */\n@customElement('daw-time-format')\nexport class DawTimeFormatElement extends LitElement {\n @state() private _format: TimeDisplayFormat = 'hh:mm:ss.sss';\n\n static styles = css`\n select {\n cursor: pointer;\n background: var(--daw-controls-background, #1a1a2e);\n color: var(--daw-controls-text, #e0d4c8);\n border: 1px solid currentColor;\n padding: 4px 8px;\n font: inherit;\n }\n select:disabled {\n opacity: 0.4;\n cursor: default;\n }\n `;\n\n private get target(): HTMLElement | null {\n return resolveTransportTarget(this);\n }\n\n /**\n * False when the target doesn't implement setTimeFormat. An undetermined\n * target (missing, or a not-yet-upgraded custom element) gets the benefit\n * of the doubt and stays enabled — interaction-time resolution warns if\n * it's still unusable.\n */\n private get _targetSupported(): boolean {\n const target = this.target;\n if (targetUndetermined(target)) return true;\n return targetSupports(target, ['setTimeFormat']);\n }\n\n private _onFormatChange = (e: Event) => {\n if (e.target !== this.target) return;\n const detail = (e as DawEvent<'daw-time-format-change'>).detail;\n if (isTimeDisplayFormat(detail.format)) {\n this._format = detail.format;\n }\n };\n\n private _onPointerEnter = () => {\n // A target that became resolvable since the last render should\n // re-evaluate before the click lands.\n this.requestUpdate();\n };\n\n private _onPointerDown = () => {\n const target = this.target;\n if (!target) {\n warnNoTargetOnce(this);\n return;\n }\n if (!this._targetSupported) {\n warnUnsupportedOnce(this, ['setTimeFormat']);\n }\n };\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('daw-time-format-change', this._onFormatChange, { signal });\n this.addEventListener('pointerdown', this._onPointerDown, { signal });\n this.addEventListener('pointerenter', this._onPointerEnter, { signal });\n // Defer until the transport target has upgraded, then sync + re-render.\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n const target = this.target as (HTMLElement & { timeFormat?: unknown }) | null;\n if (target && isTimeDisplayFormat(target.timeFormat)) {\n this._format = target.timeFormat;\n }\n this.requestUpdate();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n }\n\n protected updated() {\n // <option selected> attribute toggles stop working once the user has\n // picked an option (HTML selectedness dirtiness) — sync the IDL value\n // imperatively so programmatic format changes always reflect.\n const select = this.shadowRoot?.querySelector('select');\n if (select && select.value !== this._format) {\n select.value = this._format;\n }\n }\n\n private _onSelectChange(e: Event) {\n const value = (e.target as HTMLSelectElement).value as TimeDisplayFormat;\n const target = this.target as (HTMLElement & { setTimeFormat?: (f: string) => void }) | null;\n if (!target) {\n // Stale-render race guard: the target can vanish between render and change.\n warnNoTargetOnce(this);\n return;\n }\n target.setTimeFormat?.(value);\n }\n\n render() {\n return html`\n <select\n aria-label=\"Time format\"\n ?disabled=${!this._targetSupported}\n @change=${this._onSelectChange}\n >\n ${TIME_DISPLAY_FORMATS.map(\n (f) => html`<option value=${f} ?selected=${f === this._format}>${f}</option>`\n )}\n </select>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-time-format': DawTimeFormatElement;\n }\n}\n","import { LitElement, html, css, type PropertyValues } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { MediaElementPlayout } from '@waveform-playlist/media-element-playout';\nimport { AnimationController } from '../controllers/animation-controller';\nimport type { DawPlayheadElement } from './daw-playhead';\nimport { loadWaveformDataFromUrl } from '../interactions/peaks-loader';\nimport { extractPeaks } from '../workers/waveformDataUtils';\nimport type { Peaks } from '@waveform-playlist/core';\n\n// Side-effect imports register the child custom elements used in the template.\nimport './daw-waveform';\nimport './daw-playhead';\nimport './daw-ruler';\n\nconst MIN_RATE = 0.25;\nconst MAX_RATE = 4.0;\n\n/**\n * `<daw-player>` — lightweight single-track HTMLMediaElement player.\n * Wraps a MediaElementPlayout engine for playback and composes\n * <daw-ruler>/<daw-waveform>/<daw-playhead> for visuals. No EditorEngine,\n * no adapter, no AudioContext. See docs/specs/2026-06-29-daw-player-core-design.md.\n */\n@customElement('daw-player')\nexport class DawPlayerElement extends LitElement {\n @property({ type: String }) src = '';\n @property({ type: String, attribute: 'peaks-src' }) peaksSrc = '';\n @property({ type: Number, attribute: 'wave-height' }) waveHeight = 128;\n @property({ type: Boolean }) timescale = false;\n @property({ type: Boolean }) mono = false;\n @property({ type: Number, attribute: 'bar-width' }) barWidth = 1;\n @property({ type: Number, attribute: 'bar-gap' }) barGap = 0;\n @property({ type: Boolean, attribute: 'rounded-bars' }) roundedBars = false;\n\n @property({ type: Number, attribute: 'playback-rate', noAccessor: true })\n get playbackRate(): number {\n return this._playbackRate;\n }\n set playbackRate(value: number) {\n const valid = Number.isFinite(value);\n if (!valid || value < MIN_RATE || value > MAX_RATE) {\n console.warn(\n '[dawcore] <daw-player> playback-rate ' +\n value +\n ' out of range ' +\n MIN_RATE +\n '–' +\n MAX_RATE +\n ' — clamping'\n );\n }\n const clamped = Math.max(MIN_RATE, Math.min(MAX_RATE, valid ? value : 1));\n const old = this._playbackRate;\n this._playbackRate = clamped;\n this.requestUpdate('playbackRate', old);\n }\n private _playbackRate = 1;\n\n private _engine: MediaElementPlayout = new MediaElementPlayout();\n /** Set by disconnectedCallback — a reconnect (DOM reparent, framework\n * re-render) must rebuild the engine + track or the player is dead. */\n private _engineDisposed = false;\n private _trackId: string | null = null;\n private _anim = new AnimationController(this);\n private _metadataLoaded = false;\n private _readyDispatched = false;\n /** True once peaks resolution is complete: succeeded, failed, or no peaks-src set. */\n private _peaksSettled = false;\n private _waveformData: import('waveform-data').default | null = null;\n @state() private _channelPeaks: Peaks[] = [];\n private _sampleRate = 48000;\n private _resizeObserver: ResizeObserver | null = null;\n\n static styles = css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: block;\n position: relative;\n background: var(--daw-background, #1a1a2e);\n }\n .waveform-area {\n position: relative;\n width: 100%;\n overflow: hidden;\n }\n `;\n\n connectedCallback(): void {\n super.connectedCallback();\n let rebuilt = false;\n if (this._engineDisposed) {\n // A removed player must not keep audio alive, so disconnect disposes\n // the engine — but reparenting (appendChild of a connected element)\n // disconnects and reconnects synchronously, and updated() only reloads\n // on a src CHANGE. Rebuild here or the player never plays again.\n const volume = this._engine.masterVolume;\n this._engine = new MediaElementPlayout();\n this._engine.setMasterVolume(volume);\n this._engineDisposed = false;\n this._trackId = null;\n rebuilt = true;\n }\n this._engine.on('loadedmetadata', this._onLoadedMetadata);\n this._engine.on('play', this._onPlay);\n this._engine.on('pause', this._onPause);\n this._engine.on('ended', this._onEnded);\n this._engine.on('error', this._onError);\n this._resizeObserver = new ResizeObserver(() => this._renderWaveform());\n // Observe after first render so .waveform-area exists.\n requestAnimationFrame(() => {\n const area = this.shadowRoot?.querySelector('.waveform-area');\n if (area) this._resizeObserver?.observe(area);\n });\n // Peaks that had not arrived when it was disconnected (the fetch was\n // aborted, #848): fetch them again.\n if (rebuilt && this.peaksSrc && !this._peaksSettled) void this._loadPeaks();\n if (rebuilt && this.src) {\n this._loadSource();\n // The fresh engine is at 0 but the playhead kept its imperatively-set\n // px from before the reparent — snap it back so they agree. NOTE:\n // _loadSource re-arms daw-ready, so consumers see a second daw-ready\n // after a reparent (it IS a new load cycle; position/metadata reset).\n this._playhead?.setPosition(0);\n }\n }\n\n render() {\n const width = this._timelineWidth;\n const channels = this._channelPeaks.length;\n const channelHeight = channels > 0 ? this.waveHeight / channels : this.waveHeight;\n return html`\n ${this.timescale\n ? html`<daw-ruler\n .samplesPerPixel=${this._channelSpp(width)}\n .sampleRate=${this._sampleRate}\n .duration=${this._engine.duration}\n .totalWidth=${width}\n ></daw-ruler>`\n : null}\n <div\n class=\"waveform-area\"\n style=\"height:${this.waveHeight}px\"\n @pointerdown=${this._onPointerDown}\n >\n ${repeat(\n this._channelPeaks,\n (_p, i) => i,\n (peaks) =>\n html`<daw-waveform\n .peaks=${peaks}\n .length=${width}\n .waveHeight=${channelHeight}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n ></daw-waveform>`\n )}\n <daw-playhead></daw-playhead>\n </div>\n `;\n }\n\n protected updated(changed: PropertyValues): void {\n if (changed.has('src')) this._loadSource();\n if (changed.has('playbackRate')) this._engine.setPlaybackRate(this._playbackRate);\n if (changed.has('peaksSrc')) this._loadPeaks();\n // Only `mono` changes the derived peaks; `wave-height` only affects display\n // height, which render() reads directly (recomputing peaks for it is wasteful\n // and, on first update, sets @state mid-cycle → a Lit change-in-update warning).\n if (changed.has('mono')) this._renderWaveform();\n }\n\n /** The peaks fetch in flight: a newer peaks-src or a disconnect aborts it (#848, D7). */\n private _peaksFetch: AbortController | null = null;\n\n private async _loadPeaks(): Promise<void> {\n this._peaksFetch?.abort();\n this._peaksFetch = null;\n this._waveformData = null;\n this._readyDispatched = false; // re-arm ready for the new source\n this._peaksSettled = false; // new load in progress; wait for outcome before firing daw-ready\n if (!this.peaksSrc) {\n // No peaks-src — peaks are settled immediately (scrubber-only is a valid ready state).\n this._peaksSettled = true;\n this._renderWaveform();\n this._maybeDispatchReady();\n return;\n }\n const requested = this.peaksSrc;\n const fetching = new AbortController();\n this._peaksFetch = fetching;\n try {\n const wd = await loadWaveformDataFromUrl(requested, fetching.signal);\n if (this._peaksFetch === fetching) this._peaksFetch = null;\n if (this.peaksSrc !== requested) return; // stale — a newer peaks-src won (don't settle)\n this._waveformData = wd;\n this._sampleRate = wd.sample_rate;\n this._peaksSettled = true;\n this._renderWaveform();\n this._maybeDispatchReady();\n } catch (err) {\n // Aborted (a newer peaks-src, a disconnect): that one settles nothing.\n if (fetching.signal.aborted) return;\n // Same stale guard as the success path: a superseded load's late\n // rejection must not settle readiness (daw-ready would fire while the\n // NEWER peaks-src is still in flight) or clobber its waveform.\n if (this.peaksSrc !== requested) return;\n console.warn('[dawcore] <daw-player> failed to load peaks-src: ' + String(err));\n // A failed waveform must not permanently block daw-ready — the player IS ready to play.\n this._peaksSettled = true;\n this._renderWaveform(); // scrubber-only fallback\n this._maybeDispatchReady();\n }\n }\n\n /** Recompute fit-to-width peaks from the loaded WaveformData. No-op without data. */\n private _renderWaveform(): void {\n const wd = this._waveformData;\n const width = this._timelineWidth;\n if (!wd || width <= 0) {\n // Avoid churning @state with a fresh empty array when already empty —\n // a redundant reassignment during updated() schedules a wasted re-render.\n if (this._channelPeaks.length > 0) this._channelPeaks = [];\n return;\n }\n // Resample so the peak count ≈ the host width (fit-to-width).\n const totalSamples = wd.length * wd.scale;\n const samplesPerPixel = Math.max(wd.scale, Math.ceil(totalSamples / width));\n const peakData = extractPeaks(wd, samplesPerPixel, this.mono);\n this._channelPeaks = peakData.data;\n }\n\n /**\n * Samples-per-pixel used by the ruler so its time labels span the full width.\n * This is intentionally a separate time-based SPP (duration × sampleRate / width)\n * for the ruler labels — equivalent to the waveform SPP when the WaveformData spans\n * the full audio duration; may differ for pre-trimmed peaks.\n */\n private _channelSpp(width: number): number {\n const d = this._engine.duration;\n if (d <= 0 || width <= 0) return 1;\n return Math.max(1, Math.ceil((d * this._sampleRate) / width));\n }\n\n private _loadSource(): void {\n if (!this.src) return;\n // Re-arm the daw-ready gate so a new audio source fires a fresh event.\n // _peaksSettled is intentionally NOT touched here — for a src-only swap the\n // existing peaks remain valid; _loadPeaks resets it when peaks-src changes.\n this._metadataLoaded = false;\n this._readyDispatched = false;\n const track = this._engine.setSource({ source: this.src });\n this._trackId = track.id;\n this._engine.setPlaybackRate(this._playbackRate);\n }\n\n // --- Transport methods ---\n play(): void {\n // resume() keeps the current position (pause→play, paused seek→play);\n // play() with no offset would reset to 0. After stop() the element's\n // currentTime is already 0, so play-after-stop still starts at the top.\n this._engine.resume();\n }\n pause(): void {\n this._engine.pause();\n }\n stop(): void {\n this._engine.stop();\n this._anim.stop();\n this._updatePlayhead();\n this._dispatch('daw-stop');\n }\n seekTo(time: number): void {\n this._engine.seekTo(time);\n if (!this._engine.isPlaying) {\n // The rAF loop only runs while playing — without this, the playhead\n // and daw-timeupdate consumers (<daw-time-display>) stay stale until\n // the next play.\n this._updatePlayhead();\n this._dispatch('daw-timeupdate', { time: this._engine.getCurrentTime() });\n }\n }\n setPlaybackRate(rate: number): void {\n this.playbackRate = rate; // setter clamps + requestUpdate triggers engine forward\n }\n setVolume(volume: number): void {\n this._engine.setMasterVolume(volume);\n }\n\n // --- Properties ---\n get isPlaying(): boolean {\n return this._engine.isPlaying;\n }\n get duration(): number {\n return this._engine.duration;\n }\n get currentTime(): number {\n return this._engine.getCurrentTime();\n }\n set currentTime(time: number) {\n // Route through seekTo so paused assignments update the playhead and\n // dispatch daw-timeupdate — the property API must not be staler than\n // the method API.\n this.seekTo(time);\n }\n get volume(): number {\n return this._engine.masterVolume;\n }\n set volume(value: number) {\n this._engine.setMasterVolume(value);\n }\n get audioElement(): HTMLAudioElement | null {\n return this._trackId ? (this._engine.getTrack(this._trackId)?.element ?? null) : null;\n }\n\n private _onPointerDown = (e: PointerEvent): void => {\n const area = e.currentTarget as HTMLElement;\n const width = area.clientWidth;\n const d = this._engine.duration;\n // _engine.duration coerces NaN→0 upstream (MediaElementTrack.duration is\n // `audioElement.duration || _peaks?.duration || 0`), so `d <= 0` also\n // covers the pre-metadata/NaN case — no separate NaN check needed.\n if (width <= 0 || d <= 0) return;\n const ratio = Math.max(0, Math.min(1, e.offsetX / width));\n this.seekTo(ratio * d); // seekTo updates the playhead when paused; rAF covers playing\n };\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this._anim.stop();\n this._resizeObserver?.disconnect();\n this._resizeObserver = null;\n this._engine.off('loadedmetadata', this._onLoadedMetadata);\n this._engine.off('play', this._onPlay);\n this._engine.off('pause', this._onPause);\n this._engine.off('ended', this._onEnded);\n this._engine.off('error', this._onError);\n this._engine.dispose();\n this._engineDisposed = true;\n // The peaks fetch in flight is aborted; a reconnect fetches again.\n this._peaksFetch?.abort();\n this._peaksFetch = null;\n }\n\n // --- Private event handlers (arrow fields for stable identity) ---\n\n private _dispatch<T>(name: string, detail?: T): void {\n this.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail }));\n }\n\n private _onLoadedMetadata = (): void => {\n this._metadataLoaded = true;\n // duration (and the ruler SPP derived from it) is a render input read\n // straight off the engine — without this, a render that happened before\n // metadata (peaks usually resolve first) leaves the ruler frozen at 0:00.\n this.requestUpdate();\n this._maybeDispatchReady();\n };\n\n private _onPlay = (): void => {\n this._dispatch('daw-play');\n this._anim.start(this._frame);\n };\n\n private _onPause = (): void => {\n this._anim.stop();\n this._updatePlayhead();\n this._dispatch('daw-pause');\n };\n\n private _onEnded = (): void => {\n this._anim.stop();\n this._updatePlayhead(); // snap playhead to end rather than leaving it ≤1 frame short\n this._dispatch('daw-ended');\n };\n\n private _onError = (err: MediaError | null): void => {\n console.warn('[dawcore] <daw-player> failed to load src: ' + (err?.message ?? 'unknown'));\n this._dispatch('daw-error', { operation: 'load', error: err });\n };\n\n /** rAF tick while playing: positions the playhead and emits daw-timeupdate. */\n private _frame = (): void => {\n this._updatePlayhead();\n this._dispatch('daw-timeupdate', { time: this._engine.getCurrentTime() });\n };\n\n private _maybeDispatchReady(): void {\n if (this._readyDispatched) return;\n if (this._metadataLoaded && this._peaksSettled) {\n this._readyDispatched = true;\n this._dispatch('daw-ready');\n }\n }\n\n private get _playhead(): DawPlayheadElement | null {\n return this.shadowRoot?.querySelector('daw-playhead') ?? null;\n }\n\n private _updatePlayhead(): void {\n const d = this._engine.duration;\n if (d <= 0) return;\n const px = (this._engine.getCurrentTime() / d) * this._timelineWidth;\n this._playhead?.setPosition(px);\n }\n\n private get _timelineWidth(): number {\n return this.shadowRoot?.querySelector<HTMLElement>('.waveform-area')?.clientWidth ?? 0;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-player': DawPlayerElement;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qCAAC,kBAAiB,gCAA+B,iBAAgB,gCAA+B,sBAAqB,sCAAqC,gBAAe,8BAA6B,2BAA0B,2CA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AA7CN,mBAAN;AAAA,MADN,mCAAc,YAAY;AAAA,GACd;","names":["import_lit","import_decorators","updated","import_lit","import_decorators","import_core","import_lit","import_decorators","state","import_lit","import_decorators","import_core","state","import_lit","import_decorators","import_lit","import_decorators","MAX_CANVAS_WIDTH","LAYOUT_PROPS","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_core","idCounter","WaveformData","bits","numChannels","import_lit","import_decorators","import_core","MAX_CANVAS_WIDTH","import_engine","import_lit","import_decorators","import_core","import_lit","import_decorators","import_core","MAX_CANVAS_WIDTH","import_lit","import_core","import_lit","left","width","import_core","state","LIBRARY_DEFAULTS","LIBRARY_DEFAULT_COLOR_MAP","import_core","signal","import_core","import_core","updated","import_core","state","import_core","import_core","import_core","import_engine","import_core","state","import_core","import_core","PREFIX","element","import_core","PREFIX","import_waveform_data","WaveformData","peaksSrc","updatedClip","id","state","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_core","import_lit","import_decorators","import_core","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_repeat"]}
1
+ {"version":3,"sources":["../src/index.ts","<define:__INSTALL_SPECS__>","../src/elements/daw-annotation.ts","../src/elements/daw-annotation-track.ts","../src/elements/daw-annotation-list.ts","../src/utils/annotation-playing.ts","../src/elements/daw-clip.ts","../src/interactions/element-links.ts","../src/elements/daw-track.ts","../src/types.ts","../src/utils/track-mix.ts","../src/elements/daw-waveform.ts","../src/utils/peak-rendering.ts","../src/utils/viewport.ts","../src/elements/daw-piano-roll.ts","../src/elements/daw-playhead.ts","../src/elements/daw-transport.ts","../src/elements/daw-play-button.ts","../src/elements/daw-transport-button.ts","../src/utils/transport-capability.ts","../src/elements/daw-pause-button.ts","../src/elements/daw-stop-button.ts","../src/elements/daw-editor.ts","../src/workers/peaksWorker.ts","../src/workers/waveformDataUtils.ts","../src/workers/peakPipeline.ts","../src/elements/daw-ruler.ts","../src/utils/time-format.ts","../src/utils/smart-scale.ts","../src/utils/musical-tick-cache.ts","../src/elements/daw-track-controls.ts","../src/elements/daw-grid.ts","../src/styles/theme.ts","../src/controllers/viewport-controller.ts","../src/controllers/audio-resume-controller.ts","../src/utils/install-command.ts","../src/controllers/recording-controller.ts","../src/controllers/annotation-controller.ts","../src/controllers/spectrogram-controller.ts","../src/interactions/pointer-handler.ts","../src/interactions/constants.ts","../src/interactions/clip-pointer-handler.ts","../src/interactions/annotation-drag.ts","../src/interactions/track-reorder-handler.ts","../src/utils/time-display-format.ts","../src/interactions/abort.ts","../src/interactions/file-loader.ts","../src/interactions/midi-loader.ts","../src/interactions/recording-clip.ts","../src/interactions/split-handler.ts","../src/interactions/clip-peak-sync.ts","../src/interactions/track-entry.ts","../src/interactions/load-announcer.ts","../src/interactions/arrangement-view.ts","../src/interactions/arrangement-swap.ts","../src/interactions/drag-watch.ts","../src/interactions/clip-rehome.ts","../src/effects/effects-chain-controller.ts","../src/effects/optional-modules.ts","../src/effects/effects-manager.ts","../src/effects/effect-registry.ts","../src/interactions/export-audio.ts","../src/interactions/peaks-loader.ts","../src/controllers/scroll-sync-controller.ts","../src/controllers/animation-controller.ts","../src/controllers/playback-animation-controller.ts","../src/elements/daw-selection.ts","../src/elements/daw-record-button.ts","../src/elements/daw-keyboard-shortcuts.ts","../src/elements/daw-spectrogram.ts","../src/elements/daw-time-display.ts","../src/elements/daw-time-format.ts","../src/elements/daw-player.ts"],"sourcesContent":["import './elements/daw-annotation';\nimport './elements/daw-annotation-track';\nimport './elements/daw-annotation-list';\nimport './elements/daw-clip';\nimport './elements/daw-track';\nimport './elements/daw-waveform';\nimport './elements/daw-piano-roll';\nimport './elements/daw-playhead';\nimport './elements/daw-transport';\nimport './elements/daw-play-button';\nimport './elements/daw-pause-button';\nimport './elements/daw-stop-button';\nimport './elements/daw-editor';\nimport './elements/daw-ruler';\nimport './elements/daw-grid';\nimport './elements/daw-selection';\nimport './elements/daw-track-controls';\nimport './elements/daw-record-button';\nimport './elements/daw-keyboard-shortcuts';\nimport './elements/daw-spectrogram';\nimport './elements/daw-time-display';\nimport './elements/daw-time-format';\nimport './elements/daw-player';\n\nexport { DawAnnotationElement } from './elements/daw-annotation';\nexport { DawAnnotationTrackElement } from './elements/daw-annotation-track';\nexport { DawAnnotationListElement } from './elements/daw-annotation-list';\nexport { DawClipElement } from './elements/daw-clip';\nexport { DawTrackElement } from './elements/daw-track';\nexport { DawWaveformElement } from './elements/daw-waveform';\nexport type { WaveformSegment } from './elements/daw-waveform';\nexport { DawPianoRollElement } from './elements/daw-piano-roll';\nexport { DawPlayheadElement } from './elements/daw-playhead';\nexport { DawTransportElement } from './elements/daw-transport';\nexport { DawTransportButton } from './elements/daw-transport-button';\nexport { DawPlayButtonElement } from './elements/daw-play-button';\nexport { DawPauseButtonElement } from './elements/daw-pause-button';\nexport { DawStopButtonElement } from './elements/daw-stop-button';\nexport { DawEditorElement } from './elements/daw-editor';\nexport { DawRulerElement } from './elements/daw-ruler';\nexport { DawGridElement } from './elements/daw-grid';\nexport { DawSelectionElement } from './elements/daw-selection';\nexport { DawTrackControlsElement } from './elements/daw-track-controls';\nexport { DawRecordButtonElement } from './elements/daw-record-button';\nexport { DawKeyboardShortcutsElement } from './elements/daw-keyboard-shortcuts';\nexport { DawSpectrogramElement } from './elements/daw-spectrogram';\nexport { DawTimeDisplayElement } from './elements/daw-time-display';\nexport { DawTimeFormatElement } from './elements/daw-time-format';\nexport { DawPlayerElement } from './elements/daw-player';\nexport { SpectrogramController } from './controllers/spectrogram-controller';\nexport type {\n PlaybackShortcutMap,\n SplittingShortcutMap,\n UndoShortcutMap,\n} from './elements/daw-keyboard-shortcuts';\n\nexport { AudioResumeController } from './controllers/audio-resume-controller';\nexport { ANNOTATION_LANE_HEIGHT } from './controllers/annotation-controller';\nexport { RecordingController } from './controllers/recording-controller';\nexport type { RecordingOptions, RecordingSession } from './controllers/recording-controller';\nexport { PlaybackAnimationController } from './controllers/playback-animation-controller';\nexport type {\n PlayheadLike,\n PlaybackAnimationOptions,\n} from './controllers/playback-animation-controller';\nexport {\n TIME_DISPLAY_FORMATS,\n isTimeDisplayFormat,\n formatDisplayTime,\n parseDisplayTime,\n} from './utils/time-display-format';\nexport type { TimeDisplayFormat } from './utils/time-display-format';\nexport {\n resolveTransportTarget,\n targetSupports,\n warnOnce,\n warnUnsupportedOnce,\n} from './utils/transport-capability';\n\nexport type {\n TrackDescriptor,\n TrackWithId,\n ClipDescriptor,\n DomClipDescriptor,\n DropClipDescriptor,\n TrackRenderMode,\n TrackConfig,\n ClipConfig,\n EditorCallOptions,\n} from './types';\nexport { isDomClip } from './types';\nexport type { PointerEngineContract } from './interactions/pointer-handler';\nexport { ClipPointerHandler } from './interactions/clip-pointer-handler';\nexport type { ClipPointerHost, ClipEngineContract } from './interactions/clip-pointer-handler';\nexport { splitAtPlayhead } from './interactions/split-handler';\nexport type { SplitHost, SplitEngineContract } from './interactions/split-handler';\n\nexport type {\n DawEventMap,\n DawEvent,\n DawSelectionDetail,\n DawSeekDetail,\n DawTrackSelectDetail,\n DawTrackConnectedDetail,\n DawTrackIdDetail,\n DawTrackUpdateDetail,\n DawTrackErrorDetail,\n DawFilesLoadErrorDetail,\n DawErrorDetail,\n DawTrackControlDetail,\n DawTrackRemoveDetail,\n DawRecordingStartDetail,\n DawRecordingCompleteDetail,\n DawRecordingClipAddDetail,\n DawRecordingErrorDetail,\n DawClipConnectedDetail,\n DawClipUpdateDetail,\n DawClipIdDetail,\n DawClipErrorDetail,\n DawClipMoveDetail,\n DawClipTrimDetail,\n DawClipSplitDetail,\n DawEffectAddDetail,\n DawEffectRemoveDetail,\n DawEffectChangeDetail,\n DawEffectBypassDetail,\n DawEffectReorderDetail,\n DawEffectErrorDetail,\n DawAnnotationConnectedDetail,\n DawAnnotationUpdateDetail,\n DawAnnotationSelectDetail,\n DawAnnotationTrackConnectedDetail,\n DawTimeUpdateDetail,\n DawTimeFormatChangeDetail,\n LoadFilesResult,\n} from './events';\n\n// Effects. The registry (registerEffect, prepareEffect, …) and the definition\n// types live in @waveform-playlist/core, shared with the React hooks.\nexport type { EffectState, SerializedEffectEntry } from './effects/types';\nexport type { ExportOptions, ExportAudioHost } from './interactions/export-audio';\n","{\"@dawcore/faust\":\"@dawcore/faust@^0.0.2-next.1\",\"@dawcore/midi\":\"@dawcore/midi@^0.0.6-next.13\",\"@dawcore/transport\":\"@dawcore/transport@^0.0.16-next.12\",\"@dawcore/wam\":\"@dawcore/wam@^0.0.5-next.0\",\"@waveform-playlist/core\":\"@waveform-playlist/core@^13.0.0-next.12\",\"@waveform-playlist/engine\":\"@waveform-playlist/engine@^14.0.0-next.9\",\"@waveform-playlist/worklets\":\"@waveform-playlist/worklets@^13.0.1-next.0\",\"@waveform-playlist/playout\":\"@waveform-playlist/playout@^13.0.0-next.12\"}","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { AnnotationData } from '@waveform-playlist/core';\n\n/** Valid tick value: finite non-negative integer. */\nfunction isValidTick(value: number): boolean {\n return Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * Declarative annotation data element (light DOM). Its `start`/`end`\n * attributes and text content ARE the single source of truth — the editor's\n * annotation lane and <daw-annotation-list> both derive from them.\n */\n@customElement('daw-annotation')\nexport class DawAnnotationElement extends LitElement {\n /** Start time in seconds. Reflected — attribute writes drive both views. */\n @property({ type: Number, noAccessor: true, reflect: true })\n get start(): number {\n return this._start;\n }\n set start(value: number) {\n if (!Number.isFinite(value) || value < 0) {\n console.warn('[dawcore] daw-annotation start ' + String(value) + ' is invalid — ignored');\n return;\n }\n const old = this._start;\n this._start = value;\n this.requestUpdate('start', old);\n }\n private _start = 0;\n\n /** End time in seconds. Reflected. */\n @property({ type: Number, noAccessor: true, reflect: true })\n get end(): number {\n return this._end;\n }\n set end(value: number) {\n if (!Number.isFinite(value) || value < 0) {\n console.warn('[dawcore] daw-annotation end ' + String(value) + ' is invalid — ignored');\n return;\n }\n const old = this._end;\n this._end = value;\n this.requestUpdate('end', old);\n }\n private _end = 0;\n\n /** Musical start position (ticks). Authoritative when end-tick is also set —\n * start/end seconds become a derived cache the host editor keeps fresh\n * (clip startTick pattern). */\n @property({ type: Number, noAccessor: true, reflect: true, attribute: 'start-tick' })\n get startTick(): number | null {\n return this._startTick;\n }\n set startTick(value: number | null) {\n const old = this._startTick;\n if (value === null) {\n this._startTick = null;\n this.requestUpdate('startTick', old);\n return;\n }\n if (!isValidTick(value)) {\n console.warn(\n '[dawcore] daw-annotation start-tick ' + String(value) + ' is invalid — ignored'\n );\n return;\n }\n this._startTick = value;\n this.requestUpdate('startTick', old);\n }\n private _startTick: number | null = null;\n\n /** Musical end position (ticks). See startTick. */\n @property({ type: Number, noAccessor: true, reflect: true, attribute: 'end-tick' })\n get endTick(): number | null {\n return this._endTick;\n }\n set endTick(value: number | null) {\n const old = this._endTick;\n if (value === null) {\n this._endTick = null;\n this.requestUpdate('endTick', old);\n return;\n }\n if (!isValidTick(value)) {\n console.warn('[dawcore] daw-annotation end-tick ' + String(value) + ' is invalid — ignored');\n return;\n }\n this._endTick = value;\n this.requestUpdate('endTick', old);\n }\n private _endTick: number | null = null;\n\n /** Tick-based iff BOTH tick attributes are set (authority rule). */\n get isTickBased(): boolean {\n return this._startTick !== null && this._endTick !== null;\n }\n\n private _warnedHalfTick = false;\n\n private readonly _generatedId = 'annotation-' + crypto.randomUUID();\n\n /** Stable identity: the id attribute when present, else a generated UUID. */\n get annotationId(): string {\n return this.id || this._generatedId;\n }\n\n toAnnotationData(): AnnotationData {\n const text = this.textContent?.trim() ?? '';\n const data: AnnotationData = {\n id: this.annotationId,\n start: this.start,\n end: this.end,\n lines: text.length > 0 ? text.split('\\n') : [''],\n };\n if (this.isTickBased) {\n data.startTick = this._startTick as number;\n data.endTick = this._endTick as number;\n }\n return data;\n }\n\n // Light DOM — data container only.\n createRenderRoot() {\n return this;\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Data element — its light-DOM text must not render through a host's\n // bare <slot> (e.g. <daw-editor>'s, or a bare <daw-annotation> used\n // outside a track). Views (editor lane, <daw-annotation-list>) present\n // it instead.\n this.style.display = 'none';\n // Deferred so ancestor listeners (editor / annotation track) register first\n // when parsed all-at-once — same pattern as <daw-clip>.\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-annotation-connected', {\n bubbles: true,\n composed: true,\n detail: { annotationId: this.annotationId, element: this },\n })\n );\n }, 0);\n }\n\n private _hasRendered = false;\n\n updated(changed: PropertyValues) {\n // Exactly one tick attribute set is a half-configured state — warn once.\n const halfTick = (this._startTick !== null) !== (this._endTick !== null);\n if (halfTick && !this._warnedHalfTick) {\n this._warnedHalfTick = true;\n console.warn(\n '[dawcore] daw-annotation \"' +\n this.annotationId +\n '\": only one of start-tick/end-tick is set — treated as seconds-based until both are present'\n );\n }\n if (!this._hasRendered) {\n this._hasRendered = true;\n return;\n }\n if (\n changed.has('start') ||\n changed.has('end') ||\n changed.has('startTick') ||\n changed.has('endTick')\n ) {\n this.dispatchEvent(\n new CustomEvent('daw-annotation-update', {\n bubbles: true,\n composed: true,\n detail: { annotationId: this.annotationId },\n })\n );\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-annotation': DawAnnotationElement;\n }\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport {\n updateAnnotationBoundaries,\n resolveAnnotationShortcuts,\n matchesKeyBinding,\n keyBelongsToFocusedControl,\n ANNOTATION_LINK_THRESHOLD_TICKS,\n annotationMinDurationTicks,\n} from '@waveform-playlist/core';\nimport type {\n AnnotationData,\n AnnotationShortcutMap,\n AnnotationShortcutAction,\n KeyBinding,\n} from '@waveform-playlist/core';\nimport type { DawAnnotationElement } from './daw-annotation';\n\n/** Structural view of the host editor — only what this element touches. */\ninterface AnnotationHostEditor extends HTMLElement {\n play(startTime?: number, endTime?: number): Promise<void>;\n seekTo(time: number): void;\n _annotationClampDuration: number;\n _secondsToTicks(seconds: number): number;\n _ticksToSeconds(ticks: number): number;\n ppqn: number;\n}\n\n/**\n * Write boundary-math results back to the <daw-annotation> elements — only\n * edges that actually differ from the element's CURRENT values, so no\n * spurious daw-annotation-update events fire. Targets are resolved by\n * annotation id and diffed against the live element (#609): the math's input\n * snapshot can be ordered differently than the live sorted children mid-drag,\n * so index-paired comparisons are never trustworthy.\n */\nexport function applyBoundaryResults(\n elements: DawAnnotationElement[],\n after: AnnotationData[]\n): void {\n const byId = new Map(elements.map((el) => [el.annotationId, el]));\n for (const next of after) {\n const el = byId.get(next.id);\n if (!el) continue;\n if (el.start !== next.start) el.start = next.start;\n if (el.end !== next.end) el.end = next.end;\n }\n}\n\n/**\n * Tick-space sibling of applyBoundaryResults: `after` carries TICK values in\n * start/end. Id-resolved targets diffed against the element's CURRENT values\n * (#609). A tick-based element gets rounded integer ticks PLUS a re-derived\n * seconds cache in the same write pass; a seconds-based element (converted in\n * for mixed-track link math) gets seconds back in ITS authoritative unit and\n * never gains tick attributes.\n */\nexport function applyTickBoundaryResults(\n elements: DawAnnotationElement[],\n after: AnnotationData[],\n ticksToSeconds: (ticks: number) => number\n): void {\n const byId = new Map(elements.map((el) => [el.annotationId, el]));\n for (const next of after) {\n const el = byId.get(next.id);\n if (!el) continue;\n if (el.isTickBased) {\n const startTick = Math.round(next.start);\n const endTick = Math.round(next.end);\n if (el.startTick !== startTick) {\n el.startTick = startTick;\n el.start = ticksToSeconds(startTick);\n }\n if (el.endTick !== endTick) {\n el.endTick = endTick;\n el.end = ticksToSeconds(endTick);\n }\n } else {\n const start = ticksToSeconds(next.start);\n const end = ticksToSeconds(next.end);\n if (el.start !== start) el.start = start;\n if (el.end !== end) el.end = end;\n }\n }\n}\n\n/** Map an annotation element into tick-space AnnotationData: tick-based\n * elements use their authoritative ticks; seconds-based neighbors are\n * converted so mixed-track link/collision math runs in one unit space. */\nexport function tickSpaceData(\n el: DawAnnotationElement,\n editor: { _secondsToTicks(seconds: number): number }\n): AnnotationData {\n const base = el.toAnnotationData();\n if (el.isTickBased) {\n return { ...base, start: base.startTick as number, end: base.endTick as number };\n }\n return {\n ...base,\n start: editor._secondsToTicks(base.start),\n end: editor._secondsToTicks(base.end),\n };\n}\n\n/**\n * Declarative annotation track (light DOM). Children are <daw-annotation>\n * elements — their attributes are the single source of truth. This element\n * owns the ephemeral selection state and the programmatic API; the host\n * <daw-editor> renders the timeline lane, <daw-annotation-list> renders the\n * text panel.\n */\n@customElement('daw-annotation-track')\nexport class DawAnnotationTrackElement extends LitElement {\n @property({ type: Boolean, reflect: true }) editable = false;\n @property({ type: Boolean, reflect: true, attribute: 'link-endpoints' }) linkEndpoints = false;\n @property({ type: Boolean, reflect: true, attribute: 'continuous-play' }) continuousPlay = false;\n @property({ type: Boolean, reflect: true, attribute: 'keyboard-controls' })\n keyboardControls = false;\n /** Lane box label mode: 'text' (default) | 'id' (sonnet-style: explicit id\n * attribute, else 1-based position) | 'none' (pure region bars). The list\n * always shows full text — this only affects the timeline lane. */\n @property({ reflect: true, attribute: 'box-label' }) boxLabel: 'text' | 'id' | 'none' = 'text';\n /** Display label for the editor's controls-column lane row (mirrors\n * <daw-track name>). Empty = blank spacer (opt-in, no layout change). */\n @property({ reflect: true }) name = '';\n\n // --- Selection (ephemeral UI state — deliberately NOT DOM data) ---\n\n private _activeAnnotationId: string | null = null;\n\n get activeAnnotationId(): string | null {\n return this._activeAnnotationId;\n }\n\n set activeAnnotationId(value: string | null) {\n if (value !== null && !this.annotationElements.some((el) => el.annotationId === value)) {\n console.warn(\n '[dawcore] daw-annotation-track: unknown annotation id \"' + value + '\" — selection ignored'\n );\n return;\n }\n if (value === this._activeAnnotationId) return;\n this._activeAnnotationId = value;\n const active = this._activeElement();\n this.dispatchEvent(\n new CustomEvent('daw-annotation-select', {\n bubbles: true,\n composed: true,\n detail: { annotation: active ? active.toAnnotationData() : null },\n })\n );\n }\n\n // --- Child access ---\n\n /** Child annotation elements, sorted by start time. */\n get annotationElements(): DawAnnotationElement[] {\n return Array.from(this.querySelectorAll<DawAnnotationElement>(':scope > daw-annotation')).sort(\n (a, b) => a.start - b.start\n );\n }\n\n get annotations(): AnnotationData[] {\n return this.annotationElements.map((el) => el.toAnnotationData());\n }\n\n // --- Navigation methods (spec API) ---\n\n selectNext(): void {\n this._selectByOffset(1, 0);\n }\n\n selectPrevious(): void {\n this._selectByOffset(-1, -1);\n }\n\n selectFirst(): void {\n const list = this.annotationElements;\n if (list.length > 0) this.activeAnnotationId = list[0].annotationId;\n }\n\n selectLast(): void {\n const list = this.annotationElements;\n if (list.length > 0) this.activeAnnotationId = list[list.length - 1].annotationId;\n }\n\n clearSelection(): void {\n this.activeAnnotationId = null;\n }\n\n /** offset: +1 next / -1 previous; noSelectionIndex: 0 → first, -1 → last. */\n private _selectByOffset(offset: number, noSelectionIndex: number): void {\n const list = this.annotationElements;\n if (list.length === 0) return;\n const currentIndex = list.findIndex((el) => el.annotationId === this._activeAnnotationId);\n const nextIndex =\n currentIndex === -1\n ? (noSelectionIndex + list.length) % list.length\n : (currentIndex + offset + list.length) % list.length;\n this.activeAnnotationId = list[nextIndex].annotationId;\n }\n\n // --- Playback (spec API) ---\n\n playActive(): void {\n const active = this._activeElement();\n if (!active) return;\n const editor = this._hostEditor();\n if (!editor) {\n console.warn(\n '[dawcore] <daw-annotation-track> playActive: no parent <daw-editor> — call ignored'\n );\n return;\n }\n const data = active.toAnnotationData();\n void editor.play(data.start, this.continuousPlay ? undefined : data.end);\n }\n\n // --- Boundary editing (spec API) ---\n\n moveStartBoundary(deltaMs: number): void {\n this._moveBoundary(deltaMs, true);\n }\n\n moveEndBoundary(deltaMs: number): void {\n this._moveBoundary(deltaMs, false);\n }\n\n private _moveBoundary(deltaMs: number, isStart: boolean): void {\n if (!this.editable) {\n console.warn(\n '[dawcore] daw-annotation-track: boundary editing requires the editable attribute'\n );\n return;\n }\n const elements = this.annotationElements;\n const index = elements.findIndex((el) => el.annotationId === this._activeAnnotationId);\n if (index === -1) return;\n const active = elements[index];\n\n if (active.isTickBased) {\n const editor = this._hostEditor();\n if (!editor) {\n console.warn(\n '[dawcore] daw-annotation-track: tick-based boundary edits need a parent <daw-editor> for tempo conversion — call ignored'\n );\n return;\n }\n // Tick space: siblings converted in; ms delta converted at the edge's\n // local tempo (correct under variable-tempo callbacks).\n const tickData = elements.map((el) => tickSpaceData(el, editor));\n const edgeTick = isStart ? tickData[index].start : tickData[index].end;\n const edgeSeconds = editor._ticksToSeconds(edgeTick);\n const deltaTicks =\n editor._secondsToTicks(edgeSeconds + deltaMs / 1000) - editor._secondsToTicks(edgeSeconds);\n const clamp = this._timelineDuration();\n const updated = updateAnnotationBoundaries(\n {\n annotationIndex: index,\n newTime: edgeTick + deltaTicks,\n isDraggingStart: isStart,\n annotations: tickData,\n duration: clamp === Infinity ? Infinity : editor._secondsToTicks(clamp),\n linkEndpoints: this.linkEndpoints,\n },\n {\n linkThreshold: ANNOTATION_LINK_THRESHOLD_TICKS,\n minDuration: annotationMinDurationTicks(editor.ppqn),\n }\n );\n applyTickBoundaryResults(elements, updated, (t) => editor._ticksToSeconds(t));\n return;\n }\n\n const data = elements.map((el) => el.toAnnotationData());\n const edge = isStart ? data[index].start : data[index].end;\n const updated = updateAnnotationBoundaries({\n annotationIndex: index,\n newTime: edge + deltaMs / 1000,\n isDraggingStart: isStart,\n annotations: data,\n duration: this._timelineDuration(),\n linkEndpoints: this.linkEndpoints,\n });\n applyBoundaryResults(elements, updated);\n }\n\n private _timelineDuration(): number {\n return this._hostEditor()?._annotationClampDuration ?? Infinity;\n }\n\n private _activeElement(): DawAnnotationElement | null {\n if (this._activeAnnotationId === null) return null;\n return (\n this.annotationElements.find((el) => el.annotationId === this._activeAnnotationId) ?? null\n );\n }\n\n private _hostEditor(): AnnotationHostEditor | null {\n return this.closest('daw-editor') as AnnotationHostEditor | null;\n }\n\n // --- Keyboard remapping (accessor pair: cache invalidation on set) ---\n\n private _annotationShortcuts: AnnotationShortcutMap | null = null;\n private _resolvedShortcuts: Array<{\n action: AnnotationShortcutAction;\n binding: KeyBinding;\n }> | null = null;\n\n get annotationShortcuts(): AnnotationShortcutMap | null {\n return this._annotationShortcuts;\n }\n set annotationShortcuts(value: AnnotationShortcutMap | null) {\n this._annotationShortcuts = value;\n this._resolvedShortcuts = null;\n }\n\n private _shortcutEntries(): Array<{ action: AnnotationShortcutAction; binding: KeyBinding }> {\n if (!this._resolvedShortcuts) {\n this._resolvedShortcuts = resolveAnnotationShortcuts(this._annotationShortcuts);\n }\n return this._resolvedShortcuts;\n }\n\n private static readonly _boundaryActions: ReadonlySet<AnnotationShortcutAction> = new Set([\n 'moveStartEarlier',\n 'moveStartLater',\n 'moveEndEarlier',\n 'moveEndLater',\n ]);\n\n // Capture phase: runs before <daw-keyboard-shortcuts>' bubble-phase listener,\n // giving annotation shortcuts deterministic priority (spec rule).\n private _onKeyDownCapture = (e: KeyboardEvent): void => {\n if (!this.keyboardControls) return;\n if (e.repeat) return;\n // <daw-editor>'s drag cancel (a window capture listener, so it runs\n // first) prevented this Escape: it cancelled a drag and does nothing\n // else, so the selection stays (#848).\n if (e.key === 'Escape' && e.defaultPrevented) return;\n // Same rule as the editor shortcuts: a key the focused control uses itself\n // (text entry, Escape in a modal dialog, Space/Enter on a focused button)\n // is not a shortcut. Reads the composed path, so it\n // sees controls inside shadow roots that `e.target` hides at `document`.\n if (keyBelongsToFocusedControl(e)) return;\n const match = this._shortcutEntries().find((entry) => matchesKeyBinding(e, entry.binding));\n if (!match) return;\n\n const hasSelection = this._activeAnnotationId !== null;\n // Escape with no selection falls through so a second press reaches the\n // editor's stop shortcut (spec two-press rule).\n if (match.action === 'clearSelection' && !hasSelection) return;\n // Boundary editing requires editable + a selection; don't eat keys otherwise.\n if (DawAnnotationTrackElement._boundaryActions.has(match.action)) {\n if (!this.editable || !hasSelection) return;\n }\n if (match.action === 'playActive' && !hasSelection) return;\n\n e.preventDefault();\n // stopImmediatePropagation (not stopPropagation): multiple\n // <daw-annotation-track keyboard-controls> elements each register their\n // own capture listener on `document`, and stopPropagation does NOT stop\n // sibling listeners on the same node — only stopImmediatePropagation\n // does (it also implies stopPropagation). Without it, one keypress would\n // act on every annotation track at once. This makes a consumed key act\n // on exactly the first-registered track (DOM order) and also prevents\n // bubble-phase editor shortcuts from firing. Unconsumed keys (Escape\n // with no selection, gated boundary keys) still fall through everywhere\n // via the early returns above.\n e.stopImmediatePropagation();\n try {\n this._runShortcutAction(match.action);\n } catch (err) {\n console.warn('[dawcore] Annotation shortcut failed (key=' + e.key + '): ' + String(err));\n this.dispatchEvent(\n new CustomEvent('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'annotation-shortcut', key: e.key, error: err },\n })\n );\n }\n };\n\n private _runShortcutAction(action: AnnotationShortcutAction): void {\n switch (action) {\n case 'selectPrevious':\n this.selectPrevious();\n break;\n case 'selectNext':\n this.selectNext();\n break;\n case 'selectFirst':\n this.selectFirst();\n break;\n case 'selectLast':\n this.selectLast();\n break;\n case 'clearSelection':\n this.clearSelection();\n break;\n case 'moveStartEarlier':\n this.moveStartBoundary(-10);\n break;\n case 'moveStartLater':\n this.moveStartBoundary(10);\n break;\n case 'moveEndEarlier':\n this.moveEndBoundary(-10);\n break;\n case 'moveEndLater':\n this.moveEndBoundary(10);\n break;\n case 'playActive':\n this.playActive();\n break;\n }\n }\n\n // --- Lifecycle ---\n\n private _childObserver: MutationObserver | null = null;\n\n createRenderRoot() {\n return this;\n }\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n // Data element — its light-DOM text must not render through a host's\n // bare <slot> (e.g. <daw-editor>'s). Views (editor lane,\n // <daw-annotation-list>) present it instead.\n this.style.display = 'none';\n // Upgrade-property dance: a remap assigned before element definition\n // created an own property shadowing the accessor — re-route it.\n if (Object.prototype.hasOwnProperty.call(this, 'annotationShortcuts')) {\n const value = (this as Record<string, unknown>)['annotationShortcuts'];\n delete (this as Record<string, unknown>)['annotationShortcuts'];\n this.annotationShortcuts = value as AnnotationShortcutMap | null;\n }\n this._listeners?.abort();\n this._listeners = new AbortController();\n document.addEventListener('keydown', this._onKeyDownCapture, {\n capture: true, // capture phase\n signal: this._listeners.signal,\n });\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-annotation-track-connected', {\n bubbles: true,\n composed: true,\n detail: { element: this },\n })\n );\n }, 0);\n // Clear selection when the active annotation element is removed.\n this._childObserver = new MutationObserver(() => {\n if (\n this._activeAnnotationId !== null &&\n !this.annotationElements.some((el) => el.annotationId === this._activeAnnotationId)\n ) {\n this.activeAnnotationId = null;\n }\n });\n this._childObserver.observe(this, { childList: true });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n this._childObserver?.disconnect();\n this._childObserver = null;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-annotation-track': DawAnnotationTrackElement;\n }\n}\n","import { LitElement, html, css, nothing } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { ticksToBarBeat } from '@waveform-playlist/core';\nimport type { AnnotationData, MeterEntry } from '@waveform-playlist/core';\nimport type { DawAnnotationTrackElement } from './daw-annotation-track';\nimport type { DawAnnotationElement } from './daw-annotation';\nimport type { DawAnnotationSelectDetail, DawTimeUpdateDetail } from '../events';\nimport { computePlayingAnnotationId } from '../utils/annotation-playing';\n\n/**\n * m:ss.mmm for annotation timestamps (finer than the ruler's m:ss). Milliseconds\n * that round up to 1000 carry into the seconds, so 59.9996 s is `1:00.000`,\n * never `0:59.1000`. A negative, `NaN` or infinite time is 0.\n */\nfunction formatAnnotationTime(seconds: number): string {\n const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;\n const floor = Math.floor(safe);\n const rounded = Math.round((safe - floor) * 1000);\n const whole = rounded === 1000 ? floor + 1 : floor;\n const ms = rounded === 1000 ? 0 : rounded;\n const s = whole % 60;\n const m = (whole - s) / 60;\n return m + ':' + String(s).padStart(2, '0') + '.' + String(ms).padStart(3, '0');\n}\n\n/** Structural view of the host editor — only what bars-mode formatting touches. */\ninterface AnnotationListHostEditor extends HTMLElement {\n _secondsToTicks(seconds: number): number;\n _meterEntries: MeterEntry[];\n ppqn: number;\n}\n\n/**\n * Scrollable text panel over a <daw-annotation-track>'s children — the same\n * <daw-annotation> elements the editor lane renders (single source of truth).\n * Linked via the `for` attribute (id of the track element).\n */\n@customElement('daw-annotation-list')\nexport class DawAnnotationListElement extends LitElement {\n @property() for = '';\n\n /** `'time'` (default): m:ss.mmm clock times, unchanged. `'bars'`: B.b – B.b\n * bar.beat ranges resolved via the host editor's meter map — falls back\n * to time display (and warns once) when no `<daw-editor>` ancestor is\n * found via `this.track?.closest('daw-editor')`. */\n @property({ type: String, attribute: 'time-display', reflect: true })\n timeDisplay: 'time' | 'bars' = 'time';\n\n /** Suppress re-render while a row's text is being edited. */\n @state() private _editingId: string | null = null;\n\n private _activeId: string | null = null;\n /** Playback-following highlight, separate from `_activeId` (selection) so\n * playback never disturbs selection/keyboard editing. Driven by\n * daw-timeupdate, cleared on daw-stop, retained on pause. */\n private _playingId: string | null = null;\n private _observer: MutationObserver | null = null;\n private _observedTrack: DawAnnotationTrackElement | null = null;\n private _warnedMissing = false;\n /** Warn once per resolved `for` target when bars mode can't find a host\n * editor — reset alongside `_warnedMissing` on `for` change so a\n * retargeted list can warn again for its new target. */\n private _warnedNoEditorForBars = false;\n /** Set around `_cancelEdit`'s `span.blur()` so the resulting synchronous\n * blur event doesn't re-enter `_commitEdit` (cancel already restores the\n * text and clears `_editingId` itself). */\n private _cancelling = false;\n\n static styles = css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: block;\n max-height: var(--daw-annotation-list-max-height, 240px);\n overflow-y: auto;\n background: var(--daw-annotation-list-background, #16213e);\n color: var(--daw-annotation-text-color, #e0d4c8);\n font-family: system-ui, sans-serif;\n font-size: 13px;\n }\n .annotation-row {\n display: flex;\n gap: 10px;\n align-items: baseline;\n padding: 6px 10px;\n border-bottom: 1px solid rgba(255, 255, 255, 0.06);\n cursor: pointer;\n }\n .annotation-row.playing {\n background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.12));\n box-shadow: inset 2px 0 0 var(--daw-annotation-box-border, #c49a6c);\n }\n .annotation-row.active {\n background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.25));\n }\n .annotation-row-times {\n font-variant-numeric: tabular-nums;\n font-size: 11px;\n opacity: 0.7;\n white-space: nowrap;\n }\n .annotation-row-text {\n flex: 1;\n min-width: 0;\n }\n .annotation-row-text[contenteditable='true'] {\n cursor: text;\n outline-offset: 2px;\n }\n .annotation-row-text:empty::before {\n content: '—';\n opacity: 0.4;\n }\n `;\n\n get track(): DawAnnotationTrackElement | null {\n if (!this.for) return null;\n const el = document.getElementById(this.for);\n if (!el || el.tagName !== 'DAW-ANNOTATION-TRACK') {\n if (!this._warnedMissing) {\n console.warn(\n el\n ? '[dawcore] <daw-annotation-list for=\"' +\n this.for +\n '\"> target is not a <daw-annotation-track>'\n : '[dawcore] <daw-annotation-list for=\"' + this.for + '\"> target not found'\n );\n this._warnedMissing = true;\n }\n return null;\n }\n return el as DawAnnotationTrackElement;\n }\n\n protected willUpdate(changed: Map<string, unknown>): void {\n // Allow a retargeted list to warn again for its new `for` value.\n if (changed.has('for')) {\n this._warnedMissing = false;\n this._warnedNoEditorForBars = false;\n }\n }\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('daw-annotation-select', this._onSelect as EventListener, { signal });\n document.addEventListener('daw-timeupdate', this._onTimeUpdate as EventListener, { signal });\n document.addEventListener('daw-stop', this._onStop as EventListener, { signal });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n this._observer?.disconnect();\n this._observer = null;\n this._observedTrack = null;\n }\n\n protected shouldUpdate(): boolean {\n // Never clobber an in-progress text edit with a re-render.\n return this._editingId === null;\n }\n\n protected updated(): void {\n this._ensureObserver();\n this._syncRowText();\n }\n\n /**\n * Text content is set imperatively, NOT bound as a Lit expression.\n * contenteditable mutates the span's DOM directly as the user types —\n * that ejects lit-html's ChildPart marker comments for any binding at\n * that position, so a later Lit-driven re-render of the same row throws\n * \"ChildPart has no parentNode\". Keeping the span's children entirely\n * outside Lit's diffing sidesteps the crash; the (soon-to-commit) edited\n * row is skipped via the _editingId check.\n */\n private _syncRowText(): void {\n const annotations = this.track?.annotations ?? [];\n const spans = this.shadowRoot?.querySelectorAll<HTMLElement>('.annotation-row-text') ?? [];\n spans.forEach((span) => {\n const id = span.dataset.id;\n if (id === undefined || id === this._editingId) return;\n const a = annotations.find((x) => x.id === id);\n if (!a) return;\n const text = a.lines.join(' ');\n if (span.textContent !== text) span.textContent = text;\n });\n }\n\n /** (Re)attach the MutationObserver when the resolved track changes. */\n private _ensureObserver(): void {\n const track = this.track;\n if (track === this._observedTrack) return;\n this._observer?.disconnect();\n this._observedTrack = track;\n if (!track) return;\n this._observer = new MutationObserver(() => this.requestUpdate());\n this._observer.observe(track, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n attributeFilter: ['start', 'end', 'id', 'editable'],\n });\n }\n\n private _onSelect = (e: CustomEvent<DawAnnotationSelectDetail>): void => {\n if (e.target !== this.track) return;\n this._activeId = e.detail.annotation?.id ?? null;\n this.requestUpdate();\n void this.updateComplete.then(() => {\n const row = this.shadowRoot?.querySelector('.annotation-row.active');\n // happy-dom lacks scrollIntoView — guard.\n (row as HTMLElement | null)?.scrollIntoView?.({ block: 'center' });\n });\n };\n\n /**\n * Update only on annotation-boundary crossings, not per animation frame.\n * `shouldUpdate()` suppresses the resulting render while a row is being\n * edited (`_editingId`) — intentional, not bypassed here. A boundary\n * crossed mid-edit is caught up on the NEXT crossing after the edit ends;\n * the highlight is briefly stale in that window, which is acceptable\n * (edits are rare and short-lived relative to playback).\n */\n private _onTimeUpdate = (e: CustomEvent<DawTimeUpdateDetail>): void => {\n if (e.target !== this.track?.closest('daw-editor')) return;\n const playingId = computePlayingAnnotationId(this.track?.annotations ?? [], e.detail.time);\n if (playingId === this._playingId) return;\n this._playingId = playingId;\n this.requestUpdate();\n void this.updateComplete.then(() => {\n const row = this.shadowRoot?.querySelector('.annotation-row.playing');\n // happy-dom lacks scrollIntoView — guard.\n (row as HTMLElement | null)?.scrollIntoView?.({ block: 'center' });\n });\n };\n\n private _onStop = (e: Event): void => {\n if (e.target !== this.track?.closest('daw-editor')) return;\n if (this._playingId === null) return;\n this._playingId = null;\n this.requestUpdate();\n };\n\n private _onRowClick(a: AnnotationData): void {\n const track = this.track;\n if (!track) return;\n track.activeAnnotationId = a.id;\n const editor = track.closest('daw-editor') as { seekTo?: (t: number) => void } | null;\n editor?.seekTo?.(a.start);\n }\n\n /** Formats a row's times span per `timeDisplay`. `'bars'` resolves the\n * host editor once (shared across all rows in a render) and falls back\n * to time display, warning once, when no editor is found. */\n private _formatTimes(a: AnnotationData, editor: AnnotationListHostEditor | null): string {\n if (this.timeDisplay === 'bars') {\n if (editor) {\n const isTickBased = a.startTick !== undefined && a.endTick !== undefined;\n const startTick = isTickBased ? (a.startTick as number) : editor._secondsToTicks(a.start);\n const endTick = isTickBased ? (a.endTick as number) : editor._secondsToTicks(a.end);\n const start = ticksToBarBeat(startTick, editor._meterEntries, editor.ppqn);\n const end = ticksToBarBeat(endTick, editor._meterEntries, editor.ppqn);\n return start.bar + '.' + start.beat + ' – ' + end.bar + '.' + end.beat;\n }\n if (!this._warnedNoEditorForBars) {\n console.warn(\n '[dawcore] <daw-annotation-list for=\"' +\n this.for +\n '\" time-display=\"bars\"> found no parent <daw-editor> — falling back to time display'\n );\n this._warnedNoEditorForBars = true;\n }\n }\n return formatAnnotationTime(a.start) + ' – ' + formatAnnotationTime(a.end);\n }\n\n private _annotationElement(id: string): DawAnnotationElement | null {\n return this.track?.annotationElements.find((el) => el.annotationId === id) ?? null;\n }\n\n private _commitEdit(a: AnnotationData, span: HTMLElement): void {\n // A cancel-triggered blur (span.blur() in _cancelEdit) must not commit —\n // cancel already restored the text and cleared _editingId itself.\n if (this._cancelling) return;\n this._editingId = null;\n const el = this._annotationElement(a.id);\n if (el) el.textContent = span.textContent?.trim() ?? '';\n this.requestUpdate();\n }\n\n private _cancelEdit(a: AnnotationData, span: HTMLElement): void {\n this._editingId = null;\n span.textContent = a.lines.join('\\n');\n this._cancelling = true;\n try {\n span.blur();\n } finally {\n this._cancelling = false;\n }\n this.requestUpdate();\n }\n\n render() {\n const track = this.track;\n const annotations = track?.annotations ?? [];\n const editable = track?.editable ?? false;\n const editor =\n this.timeDisplay === 'bars'\n ? ((track?.closest('daw-editor') as AnnotationListHostEditor | null) ?? null)\n : null;\n return html`\n ${annotations.map(\n (a) => html`\n <div\n class=\"annotation-row ${a.id === this._activeId ? 'active' : ''} ${a.id ===\n this._playingId\n ? 'playing'\n : ''}\"\n @click=${(e: Event) => {\n // Ignore clicks that land on the text span while this row is\n // ALREADY the active/selected one and mid-edit — avoids\n // re-seeking (jumping the playhead back to the row's start)\n // on every cursor-repositioning click while typing.\n //\n // Must NOT also fire on the very first click into an unselected\n // row's contenteditable text: browsers dispatch `focus` before\n // `click`, so `_editingId` is already `a.id` by the time this\n // handler runs even though `_onRowClick` (which sets it) never\n // ran yet. Gating on `_activeId === a.id` too lets that first\n // click through. (Not reproducible via `row.click()` in tests —\n // the DOM method skips the native focus-then-click sequence.)\n if (this._editingId === a.id && this._activeId === a.id) return;\n e.stopPropagation();\n this._onRowClick(a);\n }}\n >\n <span class=\"annotation-row-times\"> ${this._formatTimes(a, editor)} </span>\n <span\n class=\"annotation-row-text\"\n data-id=${a.id}\n contenteditable=${editable ? 'true' : nothing}\n @focus=${() => {\n if (editable) this._editingId = a.id;\n }}\n @blur=${(e: Event) => this._commitEdit(a, e.target as HTMLElement)}\n @keydown=${(e: KeyboardEvent) => {\n if (!editable) return;\n e.stopPropagation(); // never leak into shortcut handlers\n if (e.key === 'Enter') {\n e.preventDefault();\n (e.target as HTMLElement).blur(); // blur commits\n } else if (e.key === 'Escape') {\n this._cancelEdit(a, e.target as HTMLElement);\n }\n }}\n ></span>\n </div>\n `\n )}\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-annotation-list': DawAnnotationListElement;\n }\n}\n","import type { AnnotationData } from '@waveform-playlist/core';\n\n/**\n * Playing annotation = first annotation (in start-sorted order) where\n * `start <= time < end`. Returns `null` when `time` falls in a gap between\n * annotations (or before/after all of them).\n *\n * Shared by <daw-annotation-list> and AnnotationController so the lane and\n * the list agree on identical playback-highlight semantics. Seconds domain\n * only — callers pass the view's already-derived seconds cache, which is\n * correct for tick-based annotations too (AnnotationController.deriveSecondsCaches\n * keeps it fresh).\n */\nexport function computePlayingAnnotationId(\n annotations: readonly AnnotationData[],\n time: number\n): string | null {\n const match = annotations.find((a) => a.start <= time && time < a.end);\n return match?.id ?? null;\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { MidiNoteData } from '@waveform-playlist/core';\nimport {\n detachedWarning,\n linkHostOf,\n setCustomState,\n type ClipLinkValues,\n} from '../interactions/element-links';\n\n@customElement('daw-clip')\nexport class DawClipElement extends LitElement {\n @property() src = '';\n @property({ attribute: 'peaks-src' }) peaksSrc = '';\n // --- Live properties (#848): the arrangement's values while the clip is in\n // it; the declaration (attributes, a set before entry) otherwise. Setting\n // one is a request to the arrangement (an undo step) and never writes the\n // attribute. ---\n\n /** Timeline position in seconds. */\n @property({ type: Number, noAccessor: true })\n get start(): number {\n return this._linked('start');\n }\n set start(value: number) {\n this._request('start', value);\n }\n @property({ type: Number, noAccessor: true })\n get duration(): number {\n return this._linked('duration');\n }\n set duration(value: number) {\n this._request('duration', value);\n }\n @property({ type: Number, noAccessor: true })\n get offset(): number {\n return this._linked('offset');\n }\n set offset(value: number) {\n this._request('offset', value);\n }\n @property({ type: Number, noAccessor: true })\n get gain(): number {\n return this._linked('gain');\n }\n set gain(value: number) {\n this._request('gain', value);\n }\n @property({ noAccessor: true })\n get name(): string {\n return this._linked('name');\n }\n set name(value: string) {\n this._request('name', value ?? '');\n }\n @property() color = '';\n @property({ type: Number, attribute: 'fade-in' }) fadeIn = 0;\n @property({ type: Number, attribute: 'fade-out' }) fadeOut = 0;\n @property({ attribute: 'fade-type' }) fadeType = 'linear';\n\n /** MIDI notes — JS property only, not reflected (note arrays are too large for attributes). */\n @property({ attribute: false, noAccessor: true })\n get midiNotes(): MidiNoteData[] | null {\n return this._linked('midiNotes');\n }\n set midiNotes(value: MidiNoteData[] | null) {\n this._request('midiNotes', value ?? null);\n }\n\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n @property({ type: Number, attribute: 'midi-channel', noAccessor: true })\n get midiChannel(): number | null {\n return this._linked('midiChannel');\n }\n set midiChannel(value: number | null) {\n if (\n value !== null &&\n (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15)\n ) {\n console.warn('[dawcore] daw-clip midi-channel ' + value + ' is out of range 0-15 — ignored');\n return;\n }\n this._request('midiChannel', value);\n }\n\n /** MIDI program (GM instrument 0-127). Used by SoundFontToneTrack. */\n @property({ type: Number, attribute: 'midi-program', noAccessor: true })\n get midiProgram(): number | null {\n return this._linked('midiProgram');\n }\n set midiProgram(value: number | null) {\n if (\n value !== null &&\n (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127)\n ) {\n console.warn('[dawcore] daw-clip midi-program ' + value + ' is out of range 0-127 — ignored');\n return;\n }\n this._request('midiProgram', value);\n }\n\n /** What the page declared: the attributes, and a property set before the clip entered. */\n private _declared: ClipLinkValues = {\n start: 0,\n duration: 0,\n offset: 0,\n gain: 1,\n name: '',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n };\n private _fromAttribute = false;\n private _internals: ElementInternals | null = this.attachInternals?.() ?? null;\n\n attributeChangedCallback(name: string, old: string | null, value: string | null): void {\n // An attribute is the declaration, whatever the link state.\n this._fromAttribute = true;\n try {\n super.attributeChangedCallback(name, old, value);\n } finally {\n this._fromAttribute = false;\n }\n }\n\n private get _trackId(): string {\n return (this.closest('daw-track') as { trackId?: string } | null)?.trackId ?? '';\n }\n\n private _linked<K extends keyof ClipLinkValues>(key: K): ClipLinkValues[K] {\n const host = linkHostOf(this);\n const trackId = this._trackId;\n const live =\n host && trackId && host._clipLinkState(trackId, this.clipId) === 'live'\n ? host._clipValues(trackId, this.clipId)\n : null;\n return live ? live[key] : this._declared[key];\n }\n\n private _request<K extends keyof ClipLinkValues>(key: K, value: ClipLinkValues[K]): void {\n const old = this._linked(key);\n const host = linkHostOf(this);\n const trackId = this._trackId;\n const state = host && trackId ? host._clipLinkState(trackId, this.clipId) : 'pending';\n if (this._fromAttribute || state === 'pending') {\n this._declared = { ...this._declared, [key]: value };\n }\n if (state === 'live') {\n host!._requestClipChange(trackId, this.clipId, { [key]: value } as Partial<ClipLinkValues>);\n } else if (state === 'detached') {\n const label = '<daw-clip> of track \"' + trackId + '\"';\n console.warn(detachedWarning(label, key + ' = ' + String(value), host!._detachedReason()));\n }\n this.requestUpdate(key, old);\n }\n\n /** @internal Shown as `:state(detached)` (#848). */\n _setDetached(detached: boolean): void {\n setCustomState(this._internals, 'detached', detached);\n }\n\n readonly clipId = crypto.randomUUID();\n\n // Light DOM — no visual rendering, just a data container\n createRenderRoot() {\n return this;\n }\n\n /**\n * A move with `Node.moveBefore()` (#848; modern-web-guidance\n * `custom-elements`): the browser calls this instead of\n * `disconnectedCallback` → `connectedCallback`, so the element stays\n * connected, and Lit's disconnect and connect do not run. It announces\n * itself again, as a connect does, so the editor sees its new place: a\n * clip in another track, a track back in an editor (#848; a real-Chromium\n * check found both missed with an empty hook).\n */\n connectedMoveCallback(): void {\n this._announceConnected();\n }\n\n connectedCallback() {\n super.connectedCallback();\n this._announceConnected();\n }\n\n /** Tell the editor this element is here (a connect or a moveBefore() move). */\n private _announceConnected(): void {\n // Defer dispatch so:\n // 1. The editor's connectedCallback (which registers the daw-clip-connected\n // listener) has time to run when parsed all-at-once.\n // 2. The parent's deferred daw-track-connected event fires first; the\n // editor reads the <daw-clip> children when the track enters, so this\n // event is the late-append signal (and, from connectedMoveCallback,\n // the signal of a move into another track).\n // _onClipConnected adds the clip to the descriptor of a track that has not\n // entered the arrangement yet, and appends it to an entered track as a\n // loading clip (a loaded one for MIDI) (#848).\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-clip-connected', {\n bubbles: true,\n composed: true,\n detail: { clipId: this.clipId, element: this },\n })\n );\n }, 0);\n }\n\n // Removal is detected by the editor's MutationObserver — detached elements\n // cannot bubble events to ancestors.\n\n private _hasRendered = false;\n\n updated(changed: PropertyValues) {\n if (!this._hasRendered) {\n this._hasRendered = true;\n return;\n }\n const clipProps = [\n 'src',\n 'peaksSrc',\n 'start',\n 'duration',\n 'offset',\n 'gain',\n 'name',\n 'fadeIn',\n 'fadeOut',\n 'fadeType',\n 'midiNotes',\n 'midiChannel',\n 'midiProgram',\n ];\n if (clipProps.some((p) => changed.has(p as keyof this))) {\n // Resolve parent <daw-track> at dispatch time so consumers don't need\n // to walk closest('daw-track') themselves. trackId may be empty if the\n // clip is mounted outside a track (developer error).\n const trackEl = this.closest('daw-track') as { trackId?: string } | null;\n this.dispatchEvent(\n new CustomEvent('daw-clip-update', {\n bubbles: true,\n composed: true,\n detail: { trackId: trackEl?.trackId ?? '', clipId: this.clipId },\n })\n );\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-clip': DawClipElement;\n }\n}\n","/**\n * How `<daw-track>` and `<daw-clip>` are linked to the arrangement the editor\n * plays (#848 PR 3): by id. An element is\n *\n * - pending: not in an editor, or registered and not entered yet. Its\n * properties are its own declaration (the attributes, and any property set\n * before entry, which is the value the track enters with);\n * - live: the arrangement holds its id. Properties read the arrangement, and\n * setting one (or changing its attribute) is a request to it, one undo step;\n * - detached: the editor took it, and the arrangement no longer holds its id\n * (an Undo of its arrival, a removal made on the arrangement, a refusal).\n * Properties read the declaration; a change does nothing, with a warning.\n * The element carries the custom state `detached` (`:state(detached)`).\n *\n * Attributes are never written by the editor.\n */\nimport type { MidiNoteData, PanLaw, TrackKind } from '@waveform-playlist/core';\n\nexport type LinkState = 'pending' | 'live' | 'detached';\n\n/** The `<daw-track>` properties read from the arrangement while live. */\nexport interface TrackLinkValues {\n volume: number;\n pan: number;\n muted: boolean;\n soloed: boolean;\n /** `'auto'` until the track's first decoded audio decides it (#684). */\n panLaw: PanLaw;\n name: string;\n}\n\n/** The `<daw-clip>` properties read from the arrangement while live. */\nexport interface ClipLinkValues {\n start: number;\n duration: number;\n offset: number;\n gain: number;\n name: string;\n midiNotes: MidiNoteData[] | null;\n midiChannel: number | null;\n midiProgram: number | null;\n}\n\n/** What the elements ask the editor that holds them. */\nexport interface ElementLinkHost {\n _trackLinkState(trackId: string): LinkState;\n _clipLinkState(trackId: string, clipId: string): LinkState;\n /** The live values; null when the track is not live. */\n _trackValues(trackId: string): TrackLinkValues | null;\n _clipValues(trackId: string, clipId: string): ClipLinkValues | null;\n _requestTrackChange(trackId: string, partial: Partial<TrackLinkValues>): void;\n _requestClipChange(trackId: string, clipId: string, partial: Partial<ClipLinkValues>): void;\n /** The track's position in the arrangement, -1 when it is not there. */\n _trackIndex(trackId: string): number;\n /** The kind of a track the arrangement holds, null when it holds none. */\n _trackKind(trackId: string): TrackKind | null;\n /** Why an element of this editor is detached, for the warning. */\n _detachedReason(): string;\n}\n\n/** The editor an element belongs to, when it is in one that links elements. */\nexport function linkHostOf(el: Element): ElementLinkHost | null {\n const editor = el.closest('daw-editor') as unknown as Partial<ElementLinkHost> | null;\n return editor && typeof editor._trackLinkState === 'function'\n ? (editor as ElementLinkHost)\n : null;\n}\n\n/** An element that can show it is detached. */\nexport interface DetachableElement {\n _setDetached(detached: boolean): void;\n}\n\n/**\n * Set or clear the `detached` state on every registered track element and\n * its clip elements.\n */\nexport function refreshLinkStates(\n host: ElementLinkHost,\n trackEls: Iterable<[string, Element & DetachableElement]>\n): void {\n for (const [trackId, trackEl] of trackEls) {\n trackEl._setDetached(host._trackLinkState(trackId) === 'detached');\n for (const clipEl of trackEl.querySelectorAll('daw-clip')) {\n const clip = clipEl as unknown as Element & DetachableElement & { clipId: string };\n clip._setDetached(host._clipLinkState(trackId, clip.clipId) === 'detached');\n }\n }\n}\n\n/** The warning for a change on a detached element. */\nexport function detachedWarning(element: string, change: string, reason: string): string {\n return (\n '[dawcore] ' +\n element +\n ' is detached (' +\n reason +\n '): ' +\n change +\n ' changes nothing. Remove the element and insert it again to declare a new one.'\n );\n}\n\n/** Set a custom state on an element's internals; happy-dom and older browsers have none. */\nexport function setCustomState(\n internals: ElementInternals | null,\n name: string,\n on: boolean\n): void {\n const states = internals?.states as unknown as Set<string> | undefined;\n if (!states) return;\n if (on) states.add(name);\n else states.delete(name);\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { PanLaw, RenderMode, SpectrogramConfig, TrackKind } from '@waveform-playlist/core';\nimport type { EffectState as TrackEffectState, SerializedEffectEntry } from '../effects/types';\nimport { normalizeRenderMode } from '../types';\nimport type { DawTrackUpdateDetail } from '../events';\nimport {\n detachedWarning,\n linkHostOf,\n setCustomState,\n type TrackLinkValues,\n} from '../interactions/element-links';\nimport { declaredPanLaw } from '../utils/track-mix';\n\n/** The properties whose change the editor hears about (`daw-track-update`). */\nconst TRACK_PROPS: readonly string[] = [\n 'volume',\n 'pan',\n 'panLaw',\n 'muted',\n 'soloed',\n 'src',\n 'name',\n 'kind',\n 'renderMode',\n 'spectrogramConfig',\n];\n\n/** Structural view of the editor's public per-track effects API (keyed by\n * trackId) — avoids a value-import cycle between daw-track and daw-editor.\n * These are the same methods consumers can call directly on <daw-editor> for\n * element-less (drag-dropped / programmatic) tracks; the element just supplies\n * its own trackId. */\ninterface TrackEffectsDelegate {\n addTrackEffect(trackId: string, type: string, params?: Record<string, number>): string;\n trackEffects(trackId: string): TrackEffectState[];\n removeTrackEffect(trackId: string, effectId: string): void;\n setTrackEffectParams(trackId: string, effectId: string, params: Record<string, number>): void;\n setTrackEffectBypassed(trackId: string, effectId: string, bypassed: boolean): void;\n moveTrackEffect(trackId: string, effectId: string, newIndex: number): void;\n addTrackWamPlugin(trackId: string, url: string, initialState?: unknown): Promise<string>;\n addTrackFaustEffect(\n trackId: string,\n dspCode: string,\n options?: { name?: string }\n ): Promise<string>;\n openTrackEffectGui(\n trackId: string,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement>;\n closeTrackEffectGui(trackId: string, effectId: string): void;\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]>;\n setTrackEffectsState(trackId: string, entries: SerializedEffectEntry[]): Promise<void>;\n}\n\n@customElement('daw-track')\nexport class DawTrackElement extends LitElement {\n @property() src = '';\n\n // --- Live properties (#848): the arrangement's values while the track is\n // in it; the declaration (attributes, a set before entry) otherwise. ---\n\n /** The track's name: the arrangement's, or as declared. Setting it renames the track (an undo step). */\n @property({ noAccessor: true })\n get name(): string {\n return this._linked('name');\n }\n set name(value: string) {\n this._request('name', value ?? '');\n }\n @property({ type: Number, noAccessor: true })\n get volume(): number {\n return this._linked('volume');\n }\n set volume(value: number) {\n this._request('volume', value);\n }\n @property({ type: Number, noAccessor: true })\n get pan(): number {\n return this._linked('pan');\n }\n set pan(value: number) {\n this._request('pan', value);\n }\n /**\n * The track's pan law (#684): `'mono'` (equal power, −3 dB per side at\n * centre) or `'stereo'` (unity at centre, panning folds one channel into\n * the other). `pan-law` declares the law the track enters with; without\n * it the track's first decoded audio decides, and the track then keeps\n * that law whatever clips follow. Live: reads the arrangement's value\n * (`'auto'` while the track has no audio), and the editor writes no\n * attribute. Setting `'mono'` or `'stereo'` on an entered track is a\n * request (an undo step); `'auto'` there changes nothing.\n */\n @property({ attribute: 'pan-law', noAccessor: true })\n get panLaw(): PanLaw {\n return this._linked('panLaw');\n }\n set panLaw(value: PanLaw) {\n this._request('panLaw', declaredPanLaw(value));\n }\n /** The stored mute (a take's mute is not shown here). */\n @property({ type: Boolean, noAccessor: true })\n get muted(): boolean {\n return this._linked('muted');\n }\n set muted(value: boolean) {\n this._request('muted', Boolean(value));\n }\n @property({ type: Boolean, noAccessor: true })\n get soloed(): boolean {\n return this._linked('soloed');\n }\n set soloed(value: boolean) {\n this._request('soloed', Boolean(value));\n }\n\n /** The track's position in the arrangement the editor plays; -1 when it is not there. */\n get index(): number {\n return linkHostOf(this)?._trackIndex(this.trackId) ?? -1;\n }\n\n /** What the page declared: the attributes, and a property set before the track entered. */\n private _declared: TrackLinkValues = {\n name: '',\n volume: 1,\n pan: 0,\n panLaw: 'auto',\n muted: false,\n soloed: false,\n };\n private _fromAttribute = false;\n private _internals: ElementInternals | null = this.attachInternals?.() ?? null;\n\n attributeChangedCallback(name: string, old: string | null, value: string | null): void {\n // An attribute is the declaration, whatever the link state.\n this._fromAttribute = true;\n try {\n super.attributeChangedCallback(name, old, value);\n } finally {\n this._fromAttribute = false;\n }\n }\n\n private _linked<K extends keyof TrackLinkValues>(key: K): TrackLinkValues[K] {\n const host = linkHostOf(this);\n const live =\n host?._trackLinkState(this.trackId) === 'live' ? host._trackValues(this.trackId) : null;\n return live ? live[key] : this._declared[key];\n }\n\n private _request<K extends keyof TrackLinkValues>(key: K, value: TrackLinkValues[K]): void {\n const old = this._linked(key);\n const host = linkHostOf(this);\n const state = host?._trackLinkState(this.trackId) ?? 'pending';\n if (this._fromAttribute || state === 'pending') {\n this._declared = { ...this._declared, [key]: value };\n }\n if (state === 'live') {\n host!._requestTrackChange(this.trackId, { [key]: value } as Partial<TrackLinkValues>);\n } else if (state === 'detached') {\n const label = '<daw-track name=\"' + this._declared.name + '\">';\n console.warn(detachedWarning(label, key + ' = ' + String(value), host!._detachedReason()));\n }\n this.requestUpdate(key, old);\n }\n\n /** @internal Shown as `:state(detached)` (#848). */\n _setDetached(detached: boolean): void {\n setCustomState(this._internals, 'detached', detached);\n }\n\n /**\n * What the track holds: `'audio'` (default) or `'midi'`. Every `<daw-clip>`\n * child must be of this kind (#756). Set it before the track enters: the\n * editor reads it then. Live (#848): once the track has entered, it reads\n * the track's kind, which cannot change; a later change keeps the attribute\n * (the page's declaration) and warns.\n */\n @property({ reflect: true, noAccessor: true })\n get kind(): TrackKind {\n const host = linkHostOf(this);\n const live =\n host?._trackLinkState(this.trackId) === 'live' ? host._trackKind(this.trackId) : null;\n return live ?? this._kind;\n }\n set kind(value: TrackKind) {\n const host = linkHostOf(this);\n const live =\n host?._trackLinkState(this.trackId) === 'live' ? host._trackKind(this.trackId) : null;\n if (live && value !== live) {\n console.warn(\n '[dawcore] <daw-track> \"' +\n (this._declared.name || 'Untitled') +\n '\": kind cannot change after the track has loaded (still \"' +\n live +\n '\"). Remove the track and add one of the other kind.'\n );\n // The attribute is the page's declaration: it keeps what was written.\n if (!this._fromAttribute) return;\n }\n if (value !== 'audio' && value !== 'midi') {\n console.warn(\n '[dawcore] <daw-track kind=\"' +\n String(value) +\n \"\\\"> is not a track kind ('audio' or 'midi'); keeping \\\"\" +\n this._kind +\n '\"'\n );\n return;\n }\n const old = this._kind;\n this._kind = value;\n this.requestUpdate('kind', old);\n }\n private _kind: TrackKind = 'audio';\n\n // Custom getter/setter so we can warn-and-fallback on 'both' (dawcore\n // doesn't yet support rendering waveform + spectrogram simultaneously).\n @property({ attribute: 'render-mode', noAccessor: true })\n get renderMode(): RenderMode {\n return this._renderMode;\n }\n set renderMode(value: RenderMode) {\n const old = this._renderMode;\n // From markup the value is any string, and null when the attribute is\n // removed.\n let next = normalizeRenderMode(value);\n if (next === 'both') {\n console.warn(\n '[dawcore] <daw-track render-mode=\"both\"> is not yet supported; falling back to \\'spectrogram\\''\n );\n next = 'spectrogram';\n }\n this._renderMode = next;\n this.requestUpdate('renderMode', old);\n }\n private _renderMode: RenderMode = 'waveform';\n\n @property({ attribute: false }) spectrogramConfig: SpectrogramConfig | null = null;\n\n readonly trackId = crypto.randomUUID();\n\n // Light DOM so <daw-clip> children are queryable.\n createRenderRoot() {\n return this;\n }\n\n // --- Effects API (delegates to the owning <daw-editor>) ---\n\n addEffect(type: string, params?: Record<string, number>): string {\n return this._effectsEditor().addTrackEffect(this.trackId, type, params);\n }\n\n /** Load a WAM plugin (via the optional @dawcore/wam peer) into this track's chain. */\n addWamPlugin(url: string, initialState?: unknown): Promise<string> {\n return this._effectsEditor().addTrackWamPlugin(this.trackId, url, initialState);\n }\n\n /**\n * Compile Faust DSP source in the browser (via the optional @dawcore/faust\n * peer) and add the resulting WAM to this track's chain. Compile errors\n * keep their Faust line/column diagnostics and leave the chain untouched.\n */\n addFaustEffect(dspCode: string, options?: { name?: string }): Promise<string> {\n return this._effectsEditor().addTrackFaustEffect(this.trackId, dspCode, options);\n }\n\n /** Snapshot this track's chain in its persisted form (see dawcore README). */\n getEffectsState(): Promise<SerializedEffectEntry[]> {\n const editor = this.closest('daw-editor') as TrackEffectsDelegate | null;\n return editor?.getTrackEffectsState(this.trackId) ?? Promise.resolve([]);\n }\n\n /** Replace this track's chain with a persisted snapshot. */\n setEffectsState(entries: SerializedEffectEntry[]): Promise<void> {\n return this._effectsEditor().setTrackEffectsState(this.trackId, entries);\n }\n\n /**\n * Open (lazily creating) the GUI for one of this track's effects into a\n * consumer-provided container. Closing hides without interrupting audio;\n * the element is cached for reopen. See <daw-editor>.openEffectGui.\n */\n openEffectGui(effectId: string, container: HTMLElement): Promise<HTMLElement> {\n return this._effectsEditor().openTrackEffectGui(this.trackId, effectId, container);\n }\n\n /** Hide an effect's GUI (cached for reopen — never destroys). */\n closeEffectGui(effectId: string): void {\n this._effectsEditor().closeTrackEffectGui(this.trackId, effectId);\n }\n\n removeEffect(effectId: string): void {\n this._effectsEditor().removeTrackEffect(this.trackId, effectId);\n }\n\n setEffectParams(effectId: string, params: Record<string, number>): void {\n this._effectsEditor().setTrackEffectParams(this.trackId, effectId, params);\n }\n\n setEffectBypassed(effectId: string, bypassed: boolean): void {\n this._effectsEditor().setTrackEffectBypassed(this.trackId, effectId, bypassed);\n }\n\n moveEffect(effectId: string, newIndex: number): void {\n this._effectsEditor().moveTrackEffect(this.trackId, effectId, newIndex);\n }\n\n get effects(): TrackEffectState[] {\n const editor = this.closest('daw-editor') as TrackEffectsDelegate | null;\n return editor?.trackEffects(this.trackId) ?? [];\n }\n\n private _effectsEditor(): TrackEffectsDelegate {\n const editor = this.closest('daw-editor') as TrackEffectsDelegate | null;\n if (!editor) {\n throw new Error(\n '[waveform-playlist] <daw-track> effects API requires the track to be inside a <daw-editor>'\n );\n }\n return editor;\n }\n\n /**\n * A move with `Node.moveBefore()` (#848; modern-web-guidance\n * `custom-elements`): the browser calls this instead of\n * `disconnectedCallback` → `connectedCallback`, so the element stays\n * connected, and Lit's disconnect and connect do not run. It announces\n * itself again, as a connect does, so the editor sees its new place: a\n * clip in another track, a track back in an editor (#848; a real-Chromium\n * check found both missed with an empty hook).\n */\n connectedMoveCallback(): void {\n this._announceConnected();\n }\n\n connectedCallback() {\n super.connectedCallback();\n this._announceConnected();\n }\n\n /** Tell the editor this element is here (a connect or a moveBefore() move). */\n private _announceConnected(): void {\n // Defer so the editor's connectedCallback (which registers the\n // daw-track-connected listener) has time to run. Without this,\n // tracks parsed before the editor would fire events with no listener.\n setTimeout(() => {\n this.dispatchEvent(\n new CustomEvent('daw-track-connected', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId, element: this },\n })\n );\n }, 0);\n }\n\n // Track removal is detected by the editor's MutationObserver,\n // not by dispatching from disconnectedCallback (detached elements\n // cannot bubble events to ancestors).\n\n private _hasRendered = false;\n\n updated(changed: PropertyValues) {\n // Skip the initial render — all properties appear in `changed` on first\n // update, but the editor handles initial state via daw-track-connected.\n if (!this._hasRendered) {\n this._hasRendered = true;\n return;\n }\n\n // The names go in the event (#843): the editor's _onTrackUpdate takes\n // kind, renderMode, spectrogramConfig and src only when they are among\n // them. The mix and the name do not go through this event: their setters\n // ask the editor directly (#848).\n const trackChanged = TRACK_PROPS.filter((p) => changed.has(p as keyof this));\n\n if (trackChanged.length > 0) {\n const detail: DawTrackUpdateDetail = { trackId: this.trackId, changed: trackChanged };\n this.dispatchEvent(\n new CustomEvent('daw-track-update', {\n bubbles: true,\n composed: true,\n detail,\n })\n );\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-track': DawTrackElement;\n }\n}\n","import type {\n FadeType,\n MidiNoteData,\n PanLaw,\n RenderMode,\n SpectrogramConfig,\n TrackKind,\n} from '@waveform-playlist/core';\n\n// dawcore's name for core's `RenderMode` (the same type).\nexport type TrackRenderMode = RenderMode;\n\nexport interface TrackDescriptor {\n name: string;\n src: string;\n volume: number;\n pan: number;\n /** The pan law: `'auto'` until the track's first decoded audio decides it (#684). */\n panLaw: PanLaw;\n muted: boolean;\n soloed: boolean;\n /** What the track holds: audio clips or MIDI clips, never both (#756). */\n kind: TrackKind;\n /** How an audio track is drawn. A MIDI track is drawn as a piano roll from\n * its `kind`; its `renderMode` is always `'waveform'` and means nothing. */\n renderMode: TrackRenderMode;\n spectrogramConfig?: SpectrogramConfig | null;\n clips: ClipDescriptor[];\n}\n\n/**\n * A render mode from untyped input (an attribute string, a config object from\n * JavaScript). A missing value is `'waveform'`. Anything that is not a render\n * mode is `'waveform'` with a warning; the former `'piano-roll'` gets a hint.\n */\nexport function normalizeRenderMode(value: unknown): TrackRenderMode {\n if (value === null || value === undefined) return 'waveform';\n if (value === 'waveform' || value === 'spectrogram' || value === 'both') return value;\n console.warn(\n '[dawcore] render-mode=\"' +\n String(value) +\n '\" is not a render mode (waveform or spectrogram); using waveform.' +\n (value === 'piano-roll'\n ? ' A piano roll is how a MIDI track is drawn: set kind=\"midi\" on the track.'\n : '')\n );\n return 'waveform';\n}\n\n/**\n * The render mode a track descriptor carries, given its kind. Render modes are\n * for audio tracks; a MIDI track always carries `'waveform'`, so that a\n * `render-mode=\"spectrogram\"` left on it does not start the spectrogram\n * pipeline for a track with no audio.\n */\nexport function trackDescriptorRenderMode(\n kind: TrackKind,\n requested: TrackRenderMode\n): TrackRenderMode {\n return kind === 'midi' ? 'waveform' : requested;\n}\n\n/** The mixer fields of a `TrackDescriptor`. */\nexport type TrackMixFields = 'volume' | 'pan' | 'muted' | 'soloed' | 'panLaw';\n\n/**\n * What `<daw-editor>` stores per track (internal, not exported from the\n * package): a `TrackDescriptor` without its mix. The mix is the arrangement's\n * (#843); `editor.tracks` fills the mix fields in from it.\n */\nexport type StoredTrackDescriptor = Omit<TrackDescriptor, TrackMixFields>;\n\n/**\n * What `<daw-editor>` keeps per track that the arrangement has no field for\n * (internal, #848): how the track is drawn, the `<daw-track src>` shorthand\n * as declared, and each clip's `peaks-src`. Names, times, gains and the mix\n * are read from the arrangement; nothing here is written back to it.\n */\nexport interface TrackExtras {\n kind: TrackKind;\n renderMode: TrackRenderMode;\n spectrogramConfig?: SpectrogramConfig | null;\n /** The `<daw-track src>` shorthand as declared ('' when none). */\n src: string;\n /** A clip's `peaks-src`, by clip id. */\n peaksSrc: ReadonlyMap<string, string>;\n}\n\n/** A `TrackDescriptor` plus its `trackId` — the shape returned by `editor.tracks`\n * so consumers can map a track's name to the `trackId` the per-track APIs\n * (`addTrackEffect`, `removeTrack`, `updateTrack`, …) are keyed by. */\nexport type TrackWithId = TrackDescriptor & { trackId: string };\n\n/**\n * Common fields shared by all clip descriptors regardless of source.\n */\ninterface BaseClipDescriptor {\n src: string;\n peaksSrc: string;\n start: number;\n duration: number;\n offset: number;\n gain: number;\n name: string;\n fadeIn: number;\n fadeOut: number;\n fadeType: FadeType;\n midiNotes: MidiNoteData[] | null;\n midiChannel: number | null;\n midiProgram: number | null;\n}\n\n/**\n * A clip descriptor sourced from a `<daw-clip>` DOM element. `clipId` is\n * always set — `<daw-clip>.clipId` is a `crypto.randomUUID()` generated at\n * construction. The arrangement clip's id is this id (`buildArrangementTrack`,\n * `_loadAndAppendClip`), so the DOM and the arrangement name the same clip.\n */\nexport interface DomClipDescriptor extends BaseClipDescriptor {\n kind: 'dom';\n clipId: string;\n}\n\n/**\n * A clip descriptor synthesized from a non-DOM source — file drops, the\n * `<daw-track src>` shorthand fallback, or recording-clip insertion. There\n * is no DOM element to align with.\n *\n * `clipId` is the arrangement clip's id: set at creation for a recorded take\n * (#659), and written in when a dropped file or the shorthand enters the\n * arrangement (#848). Pass it to `editor.updateClip()` / `removeClip()` to\n * address the clip.\n */\nexport interface DropClipDescriptor extends BaseClipDescriptor {\n kind: 'drop';\n clipId?: string;\n /** A dropped file the clip loads (`src` is then ''): a File cannot be an attribute (#848). */\n file?: File;\n}\n\nexport type ClipDescriptor = DomClipDescriptor | DropClipDescriptor;\n\n/**\n * Type predicate for the `'dom'` discriminator. Use to narrow a\n * `ClipDescriptor` to `DomClipDescriptor` (which has `clipId`) without\n * inline `c.kind === 'dom'` repetition.\n */\nexport function isDomClip(desc: ClipDescriptor): desc is DomClipDescriptor {\n return desc.kind === 'dom';\n}\n\n/**\n * Options of `addTrack`, `addClip` and `loadFiles` (#848). `signal` cancels\n * the call: it rejects with the signal's `reason`, and what it added is\n * taken out for good (see each method), with no undo step left. A Redo list\n * its arrival cleared stays cleared, as after any edit. A signal already\n * aborted rejects at once and adds nothing.\n */\nexport interface EditorCallOptions {\n signal?: AbortSignal;\n}\n\n/**\n * Public input shape for `editor.addTrack(config)`. All fields optional —\n * defaults match the declarative `<daw-track>` defaults.\n */\nexport interface TrackConfig {\n name?: string;\n volume?: number;\n pan?: number;\n /**\n * The pan law (#684): `'mono'` or `'stereo'`. In `addTrack` it is the law\n * the track enters with (default: decided by its first decoded audio); in\n * `updateTrack` it sets the law of an entered track. `'auto'` there, or a\n * value that is not a law, changes nothing.\n */\n panLaw?: PanLaw;\n muted?: boolean;\n soloed?: boolean;\n /**\n * What the track holds. Default `'audio'`, or `'midi'` when `midi` is given.\n * Every clip must be of this kind: a clip of the other kind is not added and\n * is reported through `daw-clip-error`. Creation-only: ignored by `updateTrack`.\n */\n kind?: TrackKind;\n /** How an audio track is drawn. Ignored for a MIDI track (a piano roll). */\n renderMode?: TrackRenderMode;\n spectrogramConfig?: SpectrogramConfig | null;\n clips?: ClipConfig[];\n /**\n * Convenience: makes the track a MIDI track (`kind: 'midi'`) with a single\n * `<daw-clip>` child holding these notes. Equivalent to passing\n * `{ kind: 'midi', clips: [{ midiNotes, midiChannel, midiProgram }] }`.\n *\n * Creation-only — ignored by `updateTrack`. To modify notes after the\n * track is built, use `editor.updateClip(trackId, clipId, { midiNotes })` or\n * mutate the `<daw-clip>` element's `midiNotes` property directly.\n */\n midi?: {\n notes: MidiNoteData[];\n channel?: number;\n program?: number;\n };\n}\n\n/**\n * Public input shape for clips passed via `TrackConfig.clips` or\n * `editor.addClip(trackId, config)`. `src` is optional to support MIDI clips\n * with no audio source. Other fields default to the matching `<daw-clip>`\n * attribute defaults.\n */\nexport interface ClipConfig {\n src?: string;\n peaksSrc?: string;\n start?: number;\n duration?: number;\n offset?: number;\n gain?: number;\n name?: string;\n fadeIn?: number;\n fadeOut?: number;\n fadeType?: FadeType;\n midiNotes?: MidiNoteData[];\n midiChannel?: number;\n midiProgram?: number;\n}\n","/**\n * A track's mix (volume, pan, pan law, mute, solo) as `<daw-editor>` reads it (#843).\n * The arrangement owns the mix of every track it holds; until a track enters\n * it, the editor holds the values the track will start with (the seed).\n */\nimport { isDecidedPanLaw } from '@waveform-playlist/core';\nimport type { ClipTrack, PanLaw } from '@waveform-playlist/core';\nimport type { TrackMixerValues } from '@waveform-playlist/engine';\n\nexport const DEFAULT_TRACK_MIX: Readonly<TrackMixerValues> = Object.freeze({\n volume: 1,\n pan: 0,\n muted: false,\n soloed: false,\n panLaw: 'auto',\n});\n\n/** A pan law from anywhere (an attribute, plain JS): `'mono'`, `'stereo'`, and `'auto'` for everything else. */\nexport function toPanLaw(value: unknown): PanLaw {\n return isDecidedPanLaw(value) ? value : 'auto';\n}\n\n/**\n * A pan law the page gave (#684), with one warning for a value that is not\n * one: `'mono'`, `'stereo'`, `'auto'` (also for none, or an empty attribute).\n */\nexport function declaredPanLaw(value: unknown): PanLaw {\n if (value == null || value === '' || value === 'auto' || isDecidedPanLaw(value)) {\n return toPanLaw(value);\n }\n console.warn(\n '[dawcore] <daw-track pan-law> must be \"mono\", \"stereo\" or \"auto\", got ' + JSON.stringify(value)\n );\n return 'auto';\n}\n\n/** The mix fields of an engine track (the projection: `muted` includes a take's mute). */\nexport function mixOfTrack(track: ClipTrack): TrackMixerValues {\n return {\n volume: track.volume,\n pan: track.pan,\n muted: track.muted,\n soloed: track.soloed,\n panLaw: toPanLaw(track.panLaw),\n };\n}\n\n/** The mix a `<daw-track>` element (or anything with the four fields) asks for. */\nexport function mixOfElement(el: TrackMixerValues): TrackMixerValues {\n return {\n volume: el.volume,\n pan: el.pan,\n muted: el.muted,\n soloed: el.soloed,\n panLaw: toPanLaw(el.panLaw),\n };\n}\n\n/**\n * The fields of `mix` whose names are in `names` (a `daw-track-update`'s\n * `changed` list): the mixer properties an update changed, and no other.\n */\nexport function pickMix(mix: TrackMixerValues, names: Iterable<string>): Partial<TrackMixerValues> {\n const named = new Set(names);\n return {\n ...(named.has('volume') && { volume: mix.volume }),\n ...(named.has('pan') && { pan: mix.pan }),\n ...(named.has('muted') && { muted: mix.muted }),\n ...(named.has('soloed') && { soloed: mix.soloed }),\n ...(named.has('panLaw') && { panLaw: mix.panLaw }),\n };\n}\n\n/** `track` with `mix` written over its mixer fields (a new object). */\nexport function withMix(track: ClipTrack, mix: TrackMixerValues): ClipTrack {\n return { ...track, ...mixOfElement(mix) };\n}\n\n/** A control's value as a number within [min, max]. */\nexport function clampNumber(value: unknown, min: number, max: number): number {\n return Math.max(min, Math.min(max, Number(value)));\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { Peaks, Bits } from '@waveform-playlist/core';\nimport {\n addBarToPath,\n aggregatePeaks,\n scalePeakByGain,\n calculateBarRects,\n type BarRect,\n} from '../utils/peak-rendering';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\n/** A segment mapping a peak-index range to a pixel range within the waveform. */\nexport interface WaveformSegment {\n /** Start position in the peaks array (fractional index). */\n peakStart: number;\n /** End position in the peaks array (fractional index). */\n peakEnd: number;\n /** Start pixel position within the waveform. */\n pixelStart: number;\n /** End pixel position within the waveform. */\n pixelEnd: number;\n}\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n/** Layout/data properties that require a full redraw when changed. */\nconst LAYOUT_PROPS = new Set([\n 'length',\n 'waveHeight',\n 'barWidth',\n 'barGap',\n 'roundedBars',\n 'segments',\n 'gain',\n]);\n\n/**\n * Group dirty peak indices by canvas chunk. Returns bar-pixel-aligned\n * min/max positions per chunk for correct clearRect coordinates,\n * including when barWidth > 1 or barGap > 0.\n */\nfunction groupDirtyByChunk(\n dirtyPixels: Set<number>,\n step: number,\n barWidth: number\n): Map<number, { min: number; max: number }> {\n const dirtyByChunk = new Map<number, { min: number; max: number }>();\n const mark = (chunkIdx: number, barPixel: number) => {\n const existing = dirtyByChunk.get(chunkIdx);\n if (existing) {\n dirtyByChunk.set(chunkIdx, {\n min: Math.min(existing.min, barPixel),\n max: Math.max(existing.max, barPixel),\n });\n } else {\n dirtyByChunk.set(chunkIdx, { min: barPixel, max: barPixel });\n }\n };\n for (const peakIdx of dirtyPixels) {\n // Map peak index to its bar's global pixel position\n const barPixel = Math.floor(peakIdx / step) * step;\n const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);\n mark(chunkIdx, barPixel);\n // A bar straddling the chunk boundary (barWidth+barGap not dividing\n // MAX_CANVAS_WIDTH) has pixels on the NEXT canvas too — mark that chunk\n // dirty for the same bar, or its clipped remainder is a permanent 1-2px\n // gap at every boundary. _drawChunk's loop is global-indexed, so the\n // next chunk draws the bar at a negative local x.\n const endChunkIdx = Math.floor((barPixel + barWidth - 1) / MAX_CANVAS_WIDTH);\n if (endChunkIdx !== chunkIdx) {\n mark(endChunkIdx, barPixel);\n }\n }\n return dirtyByChunk;\n}\n\n@customElement('daw-waveform')\nexport class DawWaveformElement extends LitElement {\n private _peaks: Peaks = new Int16Array(0);\n private _dirtyPixels: Set<number> = new Set();\n private _drawScheduled = false;\n private _rafId = 0;\n /** Chunk indices visible in the last draw pass — used to detect new chunks on scroll. */\n private _drawnChunks: Set<number> = new Set();\n\n set peaks(value: Peaks) {\n this._peaks = value;\n this._markAllDirty();\n this.requestUpdate();\n }\n\n get peaks(): Peaks {\n return this._peaks;\n }\n\n /**\n * Replace the internal peaks reference without marking all dirty.\n * Use with updatePeaks() for incremental recording updates where\n * appendPeaks() returns a new array but only the tail changed.\n */\n setPeaksQuiet(value: Peaks) {\n this._peaks = value;\n }\n\n get bits(): Bits {\n return this._peaks instanceof Int8Array ? 8 : 16;\n }\n\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) waveHeight = 128;\n @property({ type: Number, attribute: false }) barWidth = 1;\n @property({ type: Number, attribute: false }) barGap = 0;\n /** Draw bars with pill-shaped rounded caps (radius barWidth/2). */\n @property({ type: Boolean, attribute: false }) roundedBars = false;\n /** Linear gain applied to the DRAWN bars (clamped to the channel height).\n * Display-only — peaks are untouched, so changing it never regenerates\n * them. The editor feeds it a clip's gain under `gain-scaled-waveforms`. */\n @property({ type: Number, attribute: false }) gain = 1;\n /** Visible viewport start in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n /** Visible viewport end in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n /** This element's left offset on the timeline (for viewport intersection). */\n @property({ type: Number, attribute: false }) originX = 0;\n /** When set, draws per-segment with independent samples-per-pixel ratios. */\n @property({ attribute: false }) segments?: WaveformSegment[];\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n }\n .container {\n position: relative;\n }\n canvas {\n position: absolute;\n top: 0;\n }\n `;\n\n private _getVisibleChunkIndices(): number[] {\n return getVisibleChunkIndices(\n this.length,\n MAX_CANVAS_WIDTH,\n this.visibleStart,\n this.visibleEnd,\n this.originX\n );\n }\n\n /**\n * Mark a range of peak indices as dirty for incremental redraw.\n * The caller must have already updated the underlying peaks array.\n * Does NOT trigger a Lit re-render — bypasses Lit entirely.\n */\n updatePeaks(startIndex: number, endIndex: number) {\n const peakCount = Math.floor(this._peaks.length / 2);\n const clampedStart = Math.max(0, startIndex);\n const clampedEnd = Math.min(peakCount, endIndex);\n for (let i = clampedStart; i < clampedEnd; i++) {\n this._dirtyPixels.add(i);\n }\n this._scheduleDraw();\n }\n\n private _markAllDirty() {\n const peakCount = Math.floor(this._peaks.length / 2);\n for (let i = 0; i < peakCount; i++) {\n this._dirtyPixels.add(i);\n }\n this._scheduleDraw();\n }\n\n private _scheduleDraw() {\n if (!this._drawScheduled) {\n this._drawScheduled = true;\n this._rafId = requestAnimationFrame(() => {\n this._drawScheduled = false;\n this._drawDirty();\n });\n }\n }\n\n private _drawDirty() {\n if (this._dirtyPixels.size === 0 || this.length === 0 || this._peaks.length === 0) {\n this._dirtyPixels.clear();\n return;\n }\n\n const canvases = this.shadowRoot?.querySelectorAll('canvas');\n if (!canvases || canvases.length === 0) {\n // Don't clear _dirtyPixels — canvases may appear after Lit renders.\n // connectedCallback or updated() will reschedule the draw.\n return;\n }\n\n const step = this.barWidth + this.barGap;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const halfHeight = this.waveHeight / 2;\n const bits = this.bits;\n const waveColor =\n getComputedStyle(this).getPropertyValue('--daw-wave-color').trim() || '#c49a6c';\n\n this._drawnChunks.clear();\n\n if (this.segments) {\n // Segment mode: full redraw per chunk (segments have variable SPP)\n for (const canvas of canvases) {\n const chunkIdx = Number(canvas.dataset.index);\n this._drawnChunks.add(chunkIdx);\n this._drawSegments(canvas, chunkIdx, dpr, halfHeight, bits, waveColor);\n }\n } else {\n const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step, this.barWidth);\n for (const canvas of canvases) {\n const chunkIdx = Number(canvas.dataset.index);\n this._drawnChunks.add(chunkIdx);\n const range = dirtyByChunk.get(chunkIdx);\n if (!range) continue;\n this._drawChunk(canvas, chunkIdx, range, step, dpr, halfHeight, bits, waveColor);\n }\n }\n\n this._dirtyPixels.clear();\n }\n\n private _drawChunk(\n canvas: HTMLCanvasElement,\n chunkIdx: number,\n range: { min: number; max: number },\n step: number,\n dpr: number,\n halfHeight: number,\n bits: Bits,\n waveColor: string\n ) {\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n\n const globalOffset = chunkIdx * MAX_CANVAS_WIDTH;\n // range.min/max are bar-pixel-aligned global positions from groupDirtyByChunk\n const clearStart = Math.max(0, range.min - globalOffset);\n const clearEnd = range.max - globalOffset + this.barWidth;\n const clearWidth = clearEnd - clearStart;\n const firstBar = range.min;\n\n ctx.resetTransform();\n ctx.clearRect(clearStart * dpr, 0, clearWidth * dpr, canvas.height);\n ctx.scale(dpr, dpr);\n ctx.fillStyle = waveColor;\n\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, this.length - globalOffset);\n const regionEnd = Math.min(globalOffset + clearEnd, globalOffset + canvasWidth);\n\n // Rounded bars batch into one path with a single fill per region draw.\n const barRadius = this.roundedBars ? this.barWidth / 2 : null;\n if (barRadius !== null) ctx.beginPath();\n\n for (let bar = Math.max(0, firstBar); bar < regionEnd; bar += step) {\n const source = aggregatePeaks(this._peaks, bits, bar, bar + step);\n if (!source) continue;\n const peak = scalePeakByGain(source, this.gain);\n const rects = calculateBarRects(\n bar - globalOffset,\n this.barWidth,\n halfHeight,\n peak.min,\n peak.max,\n 'normal'\n );\n this._drawBarRects(ctx, rects, barRadius);\n }\n\n if (barRadius !== null) ctx.fill();\n }\n\n /** Draw bar rects: fillRect when radius is null, else add rounded bars to the current path. */\n private _drawBarRects(\n ctx: CanvasRenderingContext2D,\n rects: Array<BarRect>,\n radius: number | null\n ) {\n for (const r of rects) {\n if (radius === null) {\n ctx.fillRect(r.x, r.y, r.width, r.height);\n } else {\n addBarToPath(ctx, r, radius);\n }\n }\n }\n\n private _drawSegments(\n canvas: HTMLCanvasElement,\n chunkIdx: number,\n dpr: number,\n halfHeight: number,\n bits: Bits,\n waveColor: string\n ) {\n if (!this.segments) return;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n\n const globalOffset = chunkIdx * MAX_CANVAS_WIDTH;\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, this.length - globalOffset);\n\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.scale(dpr, dpr);\n ctx.fillStyle = waveColor;\n\n const step = Math.max(1, Math.round(this.barWidth + this.barGap));\n const barRadius = this.roundedBars ? this.barWidth / 2 : null;\n if (barRadius !== null) ctx.beginPath();\n\n for (const seg of this.segments) {\n // Skip segments outside this chunk\n if (seg.pixelEnd <= globalOffset || seg.pixelStart >= globalOffset + canvasWidth) continue;\n\n const localStart = Math.max(0, seg.pixelStart - globalOffset);\n const localEnd = Math.min(canvasWidth, seg.pixelEnd - globalOffset);\n const segPixelWidth = seg.pixelEnd - seg.pixelStart;\n const segPeakWidth = seg.peakEnd - seg.peakStart;\n if (segPixelWidth <= 0 || segPeakWidth <= 0) continue;\n\n // Per-segment peaks-per-pixel ratio\n const peaksPerPixel = segPeakWidth / segPixelWidth;\n\n for (let px = Math.floor(localStart); px < Math.ceil(localEnd); px += step) {\n // Map this pixel to a peak index range\n const pxInSeg = px + globalOffset - seg.pixelStart;\n const peakPos = seg.peakStart + pxInSeg * peaksPerPixel;\n const peakEnd = peakPos + step * peaksPerPixel;\n\n const source = aggregatePeaks(this._peaks, bits, Math.floor(peakPos), Math.ceil(peakEnd));\n if (!source) continue;\n const peak = scalePeakByGain(source, this.gain);\n\n const rects = calculateBarRects(\n px,\n this.barWidth,\n halfHeight,\n peak.min,\n peak.max,\n 'normal'\n );\n this._drawBarRects(ctx, rects, barRadius);\n }\n }\n\n if (barRadius !== null) ctx.fill();\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Reschedule draw if dirty pixels survived a disconnect/reconnect cycle\n if (this._dirtyPixels.size > 0) {\n this._scheduleDraw();\n }\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this._drawScheduled) {\n cancelAnimationFrame(this._rafId);\n this._drawScheduled = false;\n }\n // Keep _dirtyPixels — connectedCallback will reschedule if reconnected\n }\n\n render() {\n const indices = this._getVisibleChunkIndices();\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n\n return html`\n <div class=\"container\" style=\"width: ${this.length}px; height: ${this.waveHeight}px;\">\n ${indices.map((i) => {\n const width = Math.min(MAX_CANVAS_WIDTH, this.length - i * MAX_CANVAS_WIDTH);\n return html`\n <canvas\n data-index=${i}\n width=${width * dpr}\n height=${this.waveHeight * dpr}\n style=\"left: ${i * MAX_CANVAS_WIDTH}px; width: ${width}px; height: ${this\n .waveHeight}px;\"\n ></canvas>\n `;\n })}\n </div>\n `;\n }\n\n /** Mark peaks dirty only for chunks that weren't drawn in the previous frame. */\n private _markNewChunksDirty() {\n const currentIndices = this._getVisibleChunkIndices();\n const peakCount = Math.floor(this._peaks.length / 2);\n for (const chunkIdx of currentIndices) {\n if (!this._drawnChunks.has(chunkIdx)) {\n const start = chunkIdx * MAX_CANVAS_WIDTH;\n const end = Math.min(start + MAX_CANVAS_WIDTH, peakCount);\n for (let i = start; i < end; i++) {\n this._dirtyPixels.add(i);\n }\n }\n }\n if (this._dirtyPixels.size > 0) {\n this._scheduleDraw();\n }\n }\n\n updated(changedProperties: Map<string, unknown>) {\n // Layout/data changes require full redraw of all peaks\n const needsFullDirty = [...changedProperties.keys()].some((key) => LAYOUT_PROPS.has(key));\n if (needsFullDirty) {\n this._markAllDirty();\n return;\n }\n // Viewport-only changes: only draw newly visible chunks, skip already-drawn ones\n if (\n changedProperties.has('visibleStart') ||\n changedProperties.has('visibleEnd') ||\n changedProperties.has('originX')\n ) {\n this._markNewChunksDirty();\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-waveform': DawWaveformElement;\n }\n}\n","import type { Peaks, Bits } from '@waveform-playlist/core';\n\nexport type WaveformDrawMode = 'normal' | 'inverted';\n\n/**\n * Result of aggregating peaks over a range.\n *\n * Invariants (assumed from valid waveform input):\n * - min and max are normalized to [-1, 1] by dividing by 2^(bits-1)\n * - min <= max (min-of-mins, max-of-maxes — guaranteed by the interleaved min/max peak format)\n * - Values are finite (derived from integer typed arrays)\n *\n * Construct via aggregatePeaks() — do not create directly.\n */\nexport interface AggregatedPeak {\n min: number;\n max: number;\n}\n\n/**\n * Canvas fillRect parameters for a single waveform bar.\n * width >= 0 and height >= 0 when peak values are in [-1, 1] (guaranteed by\n * the interleaved min/max peak format normalization).\n */\nexport interface BarRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Aggregates peaks over a range of interleaved min/max pairs.\n * Finds min-of-mins and max-of-maxes, normalized by bit depth.\n *\n * @param data - Interleaved peak data [min0, max0, min1, max1, ...]\n * @param bits - Bit depth (8 or 16)\n * @param startIndex - First peak index (not array index — peak i is at data[i*2], data[i*2+1])\n * @param endIndex - One past the last peak index to include\n * @returns Normalized { min, max } or null if startIndex is out of bounds\n */\nexport function aggregatePeaks(\n data: Peaks,\n bits: Bits,\n startIndex: number,\n endIndex: number\n): AggregatedPeak | null {\n if (startIndex * 2 + 1 >= data.length) {\n return null;\n }\n\n const maxValue = 2 ** (bits - 1);\n let minPeak = data[startIndex * 2] / maxValue;\n let maxPeak = data[startIndex * 2 + 1] / maxValue;\n\n for (let p = startIndex + 1; p < endIndex; p++) {\n if (p * 2 + 1 >= data.length) break;\n const pMin = data[p * 2] / maxValue;\n const pMax = data[p * 2 + 1] / maxValue;\n if (pMin < minPeak) minPeak = pMin;\n if (pMax > maxPeak) maxPeak = pMax;\n }\n\n return { min: minPeak, max: maxPeak };\n}\n\nfunction clampToFullScale(value: number): number {\n return Math.max(-1, Math.min(1, value));\n}\n\n/**\n * Scales a drawn peak by a linear gain (a clip's gain), clamped to full\n * scale so a boosted bar never leaves its channel. Display-only: the\n * underlying peak data is untouched, so a gain change needs no peak\n * regeneration. A negative (phase-inverting) gain scales by magnitude; a\n * non-finite gain is ignored.\n *\n * @returns the same object at unity gain (the hot path allocates nothing)\n */\nexport function scalePeakByGain(peak: AggregatedPeak, gain: number): AggregatedPeak {\n if (gain === 1 || !Number.isFinite(gain)) {\n return peak;\n }\n const factor = Math.abs(gain);\n // Clamp BOTH values on BOTH sides. Zoomed in on low-frequency content a\n // bar's min is often positive (or its max negative): {min: 0.6, max: 0.9}\n // at gain 2 would otherwise leave min at 1.2, outside the channel.\n return {\n min: clampToFullScale(peak.min * factor),\n max: clampToFullScale(peak.max * factor),\n };\n}\n\n/**\n * Computes canvas fillRect parameters for a single waveform bar.\n *\n * @param x - Bar x position in canvas coordinates\n * @param barWidth - Width of the bar in pixels\n * @param halfHeight - Half the waveform height (center line y)\n * @param minPeak - Normalized min peak value (negative for below center)\n * @param maxPeak - Normalized max peak value (positive for above center)\n * @param drawMode - 'normal' draws the peak region, 'inverted' draws the non-peak regions\n * @returns Array of BarRect — 1 rect for 'normal', 2 rects for 'inverted'\n */\nexport function calculateBarRects(\n x: number,\n barWidth: number,\n halfHeight: number,\n minPeak: number,\n maxPeak: number,\n drawMode: WaveformDrawMode\n): BarRect[] {\n const min = Math.abs(minPeak * halfHeight);\n const max = Math.abs(maxPeak * halfHeight);\n\n if (drawMode === 'normal') {\n return [{ x, y: halfHeight - max, width: barWidth, height: max + min }];\n }\n\n // Inverted: draw areas WITHOUT audio (top gap + bottom gap)\n return [\n { x, y: 0, width: barWidth, height: halfHeight - max },\n { x, y: halfHeight + min, width: barWidth, height: halfHeight - min },\n ];\n}\n\n/**\n * Adds a bar to the current canvas path with pill-shaped rounded caps.\n * Falls back to square corners on canvases without roundRect\n * (Safari < 16.4, Firefox < 112) instead of throwing.\n *\n * The caller owns beginPath()/fill() so all bars of a chunk batch into a\n * single fill.\n *\n * @param ctx - Canvas context whose current path is being built\n * @param rect - Bar rect from calculateBarRects\n * @param radius - Corner radius (barWidth/2; roundRect spec-clamps on short bars)\n */\nexport function addBarToPath(ctx: CanvasRenderingContext2D, rect: BarRect, radius: number): void {\n if (typeof ctx.roundRect === 'function') {\n ctx.roundRect(rect.x, rect.y, rect.width, rect.height, radius);\n } else {\n ctx.rect(rect.x, rect.y, rect.width, rect.height);\n }\n}\n\n/**\n * Computes the first bar position (in global pixel coordinates) that could\n * affect a given canvas chunk.\n *\n * A bar at position X extends from X to X+barWidth-1, so we need bars where\n * barStart + barWidth > canvasStartGlobal.\n *\n * @param canvasStartGlobal - Global pixel offset of the canvas chunk\n * @param barWidth - Width of each bar in pixels\n * @param step - Bar stride (barWidth + barGap)\n * @returns The first bar's global position (always >= 0 when step >= barWidth; caller clamps to 0)\n */\nexport function calculateFirstBarPosition(\n canvasStartGlobal: number,\n barWidth: number,\n step: number\n): number {\n return Math.floor((canvasStartGlobal - barWidth + step) / step) * step;\n}\n","/**\n * Compute which canvas chunk indices are visible within a viewport range.\n *\n * @param totalWidth - Total pixel width of the content\n * @param chunkWidth - Width of each canvas chunk (e.g. 1000px)\n * @param visibleStart - Viewport start in pixels (relative to timeline origin)\n * @param visibleEnd - Viewport end in pixels (relative to timeline origin)\n * @param originX - Content's left offset on the timeline\n */\nexport function getVisibleChunkIndices(\n totalWidth: number,\n chunkWidth: number,\n visibleStart: number,\n visibleEnd: number,\n originX = 0\n): number[] {\n const totalChunks = Math.ceil(totalWidth / chunkWidth);\n const indices: number[] = [];\n for (let i = 0; i < totalChunks; i++) {\n const chunkStart = originX + i * chunkWidth;\n const chunkEnd = chunkStart + chunkWidth;\n if (chunkEnd > visibleStart && chunkStart < visibleEnd) {\n indices.push(i);\n }\n }\n return indices;\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { MidiNoteData } from '@waveform-playlist/core';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n/** Layout/data properties that require a full redraw when changed. */\nconst LAYOUT_PROPS = new Set([\n 'length',\n 'waveHeight',\n 'samplesPerPixel',\n 'sampleRate',\n 'clipOffsetSeconds',\n 'midiNotes',\n 'selected',\n]);\n\n@customElement('daw-piano-roll')\nexport class DawPianoRollElement extends LitElement {\n @property({ attribute: false }) midiNotes: MidiNoteData[] = [];\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) waveHeight = 128;\n @property({ type: Number, attribute: 'samples-per-pixel', noAccessor: true })\n get samplesPerPixel(): number {\n return this._samplesPerPixel;\n }\n set samplesPerPixel(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-piano-roll samplesPerPixel ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._samplesPerPixel;\n this._samplesPerPixel = value;\n this.requestUpdate('samplesPerPixel', old);\n }\n private _samplesPerPixel = 1024;\n\n @property({ type: Number, attribute: 'sample-rate', noAccessor: true })\n get sampleRate(): number {\n return this._sampleRate;\n }\n set sampleRate(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-piano-roll sampleRate ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._sampleRate;\n this._sampleRate = value;\n this.requestUpdate('sampleRate', old);\n }\n private _sampleRate = 48000;\n @property({ type: Number, attribute: false }) clipOffsetSeconds = 0;\n /** Visible viewport start in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n /** Visible viewport end in pixels (relative to timeline origin). */\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n /** This element's left offset on the timeline (for viewport intersection). */\n @property({ type: Number, attribute: false }) originX = 0;\n @property({ type: Boolean, reflect: true }) selected = false;\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n }\n .container {\n position: relative;\n background: var(--daw-piano-roll-background, #1a1a2e);\n }\n canvas {\n position: absolute;\n top: 0;\n image-rendering: pixelated;\n image-rendering: crisp-edges;\n }\n `;\n\n private _rafHandle: number | null = null;\n\n private _scheduleDraw() {\n if (this._rafHandle !== null) return;\n this._rafHandle = requestAnimationFrame(() => {\n this._rafHandle = null;\n this._draw();\n });\n }\n\n willUpdate(_changed: PropertyValues) {\n this._scheduleDraw();\n }\n\n updated(changedProperties: Map<string, unknown>) {\n // Layout/data changes: willUpdate already scheduled a draw — nothing extra needed.\n const needsFullDraw = [...changedProperties.keys()].some((key) => LAYOUT_PROPS.has(key));\n if (needsFullDraw) return;\n // Viewport-only changes: new canvases may have mounted; schedule a draw so they get painted.\n if (\n changedProperties.has('visibleStart') ||\n changedProperties.has('visibleEnd') ||\n changedProperties.has('originX')\n ) {\n this._scheduleDraw();\n }\n }\n\n private _getPitchRange(): { minMidi: number; maxMidi: number } {\n if (this.midiNotes.length === 0) return { minMidi: 0, maxMidi: 127 };\n let min = 127;\n let max = 0;\n for (const note of this.midiNotes) {\n if (note.midi < min) min = note.midi;\n if (note.midi > max) max = note.midi;\n }\n return {\n minMidi: Math.max(0, min - 1),\n maxMidi: Math.min(127, max + 1),\n };\n }\n\n private _getNoteColor(): string {\n const cs = getComputedStyle(this);\n const note = cs.getPropertyValue('--daw-piano-roll-note-color').trim() || '#2a7070';\n const selectedColor =\n cs.getPropertyValue('--daw-piano-roll-selected-note-color').trim() || '#3d9e9e';\n return this.selected ? selectedColor : note;\n }\n\n private _draw() {\n if (!this.shadowRoot) return;\n const canvases = this.shadowRoot.querySelectorAll('canvas');\n if (canvases.length === 0) return;\n\n const { minMidi, maxMidi } = this._getPitchRange();\n const noteRange = maxMidi - minMidi + 1;\n const noteHeight = Math.max(2, this.waveHeight / noteRange);\n const pixelsPerSecond = this.sampleRate / this.samplesPerPixel;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const color = this._getNoteColor();\n\n for (const canvas of canvases) {\n // Read data-index (matching daw-waveform pattern)\n const chunkIdx = Number((canvas as HTMLCanvasElement).dataset.index);\n const chunkPixelStart = chunkIdx * MAX_CANVAS_WIDTH;\n const canvasWidth = (canvas as HTMLCanvasElement).width / dpr;\n\n const ctx = (canvas as HTMLCanvasElement).getContext('2d');\n if (!ctx) continue;\n\n ctx.resetTransform();\n ctx.clearRect(\n 0,\n 0,\n (canvas as HTMLCanvasElement).width,\n (canvas as HTMLCanvasElement).height\n );\n ctx.imageSmoothingEnabled = false;\n ctx.scale(dpr, dpr);\n\n const chunkStartTime = (chunkPixelStart * this.samplesPerPixel) / this.sampleRate;\n const chunkEndTime =\n ((chunkPixelStart + canvasWidth) * this.samplesPerPixel) / this.sampleRate;\n\n for (const note of this.midiNotes) {\n const noteStart = note.time - this.clipOffsetSeconds;\n const noteEnd = noteStart + note.duration;\n if (noteEnd <= chunkStartTime || noteStart >= chunkEndTime) continue;\n\n const x = noteStart * pixelsPerSecond - chunkPixelStart;\n const w = Math.max(2, note.duration * pixelsPerSecond);\n const y = ((maxMidi - note.midi) / noteRange) * this.waveHeight;\n\n const alpha = 0.3 + note.velocity * 0.7;\n ctx.fillStyle = color;\n ctx.globalAlpha = alpha;\n\n ctx.beginPath();\n ctx.roundRect(x, y, w, noteHeight, 1);\n ctx.fill();\n }\n ctx.globalAlpha = 1;\n }\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Reschedule draw if a RAF was pending during disconnect/reconnect cycle\n this._scheduleDraw();\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this._rafHandle !== null) {\n cancelAnimationFrame(this._rafHandle);\n this._rafHandle = null;\n }\n }\n\n render() {\n if (this.length <= 0)\n return html`<div class=\"container\" style=\"width: 0; height: ${this.waveHeight}px;\"></div>`;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const visibleIndices = getVisibleChunkIndices(\n this.length,\n MAX_CANVAS_WIDTH,\n this.visibleStart,\n this.visibleEnd,\n this.originX\n );\n // Wrap canvases in a .container div with explicit width/height,\n // matching daw-waveform's container pattern. Background is on .container (not :host)\n // so it has the correct measurable size.\n return html`\n <div class=\"container\" style=\"width: ${this.length}px; height: ${this.waveHeight}px;\">\n ${visibleIndices.map((i) => {\n const chunkLeft = i * MAX_CANVAS_WIDTH;\n const chunkWidth = Math.min(this.length - chunkLeft, MAX_CANVAS_WIDTH);\n // Use data-index (not data-chunk-idx) to match daw-waveform pattern\n return html`<canvas\n data-index=${i}\n width=${chunkWidth * dpr}\n height=${this.waveHeight * dpr}\n style=\"left: ${chunkLeft}px; width: ${chunkWidth}px; height: ${this.waveHeight}px;\"\n ></canvas>`;\n })}\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-piano-roll': DawPianoRollElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\n\n@customElement('daw-playhead')\nexport class DawPlayheadElement extends LitElement {\n private _line: HTMLElement | null = null;\n\n static styles = css`\n :host {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n pointer-events: none;\n z-index: 10;\n }\n div {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 1px;\n background: var(--daw-playhead-color, #d08070);\n will-change: transform;\n }\n `;\n\n render() {\n return html`<div></div>`;\n }\n\n firstUpdated() {\n this._line = this.shadowRoot!.querySelector('div');\n }\n\n /** Position the playhead line at an absolute pixel offset on the timeline.\n * The editor's PlaybackAnimationController drives this each frame — the\n * playhead owns no animation loop or time math of its own. */\n setPosition(px: number) {\n if (this._line) {\n this._line.style.transform = `translate3d(${px}px, 0, 0)`;\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-playhead': DawPlayheadElement;\n }\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\n\n@customElement('daw-transport')\nexport class DawTransportElement extends LitElement {\n @property() for = '';\n\n get target(): HTMLElement | null {\n return this.for ? document.getElementById(this.for) : null;\n }\n\n // Light DOM — button children stay in consumer's DOM.\n // No render() needed; light DOM elements don't use <slot>.\n createRenderRoot() {\n return this;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-transport': DawTransportElement;\n }\n}\n","import { html } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\n\n@customElement('daw-play-button')\nexport class DawPlayButtonElement extends DawTransportButton {\n @state() private _isRecording = false;\n private _targetRef: HTMLElement | null = null;\n /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */\n private _targetListeners: AbortController | null = null;\n private _onRecStart = () => {\n this._isRecording = true;\n };\n private _onRecEnd = () => {\n this._isRecording = false;\n };\n\n connectedCallback() {\n super.connectedCallback();\n // Defer so <daw-transport for=\"...\"> and the target editor are resolved\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this._ensureTargetListeners();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._cleanupListeners();\n }\n\n protected override updated() {\n // Re-resolve on every render (pointerenter triggers one via the base\n // class) — a target that upgrades/appears after the one-shot\n // connectedCallback rAF (or a swapped <daw-transport for>) would\n // otherwise never get the recording-state listeners: Play stays enabled\n // during recording (#573, same fix as daw-record-button).\n this._ensureTargetListeners();\n }\n\n private _ensureTargetListeners() {\n const target = this.target;\n if (target === this._targetRef) return;\n if (this._targetRef) {\n // Swapping away from a live target: recording state observed there is\n // stale — a replaced editor (framework remount reusing the id) never\n // fires the complete/error event that would clear it, wedging the\n // button. (A reconnect of the BUTTON has a null _targetRef and keeps\n // its state — the same editor may still be recording.)\n this._isRecording = false;\n }\n this._cleanupListeners();\n if (!target) return;\n this._targetRef = target;\n this._targetListeners = new AbortController();\n const { signal } = this._targetListeners;\n target.addEventListener('daw-recording-start', this._onRecStart, { signal });\n target.addEventListener('daw-recording-complete', this._onRecEnd, { signal });\n target.addEventListener('daw-recording-error', this._onRecEnd, { signal });\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetListeners?.abort();\n this._targetListeners = null;\n this._targetRef = null;\n }\n }\n\n render() {\n return html`\n <button part=\"button\" ?disabled=${this._isRecording} @click=${this._onClick}>\n <slot>Play</slot>\n </button>\n `;\n }\n\n private _onClick() {\n const target = this.target;\n if (!target) {\n console.warn(\n '[dawcore] <daw-play-button> has no target. Check <daw-transport for=\"...\"> references a valid <daw-editor> id.'\n );\n return;\n }\n target.play();\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-play-button': DawPlayButtonElement;\n }\n}\n","import { LitElement, css } from 'lit';\nimport {\n resolveTransportTarget,\n targetSupports,\n targetUndetermined,\n warnNoTargetOnce,\n warnUnsupportedOnce,\n} from '../utils/transport-capability';\n\n/**\n * Base class for transport button elements.\n * Finds target via closest <daw-transport>. Capability detection is\n * duck-typed (#474): subclasses declare requiredTargetMethods and render\n * `?disabled=${!this.targetSupported}`; targets lacking the methods get a\n * disabled control and a one-time console warning on interaction.\n */\nexport class DawTransportButton extends LitElement {\n /** Methods the transport target must implement for this control to be\n * enabled. Empty = works with any target. */\n protected static requiredTargetMethods: readonly string[] = [];\n\n protected get target(): any {\n return resolveTransportTarget(this);\n }\n\n private get _requiredMethods(): readonly string[] {\n return (this.constructor as typeof DawTransportButton).requiredTargetMethods;\n }\n\n /**\n * False when this control declares requirements its target doesn't meet.\n * An undetermined target (missing, or a not-yet-upgraded custom element)\n * gets the benefit of the doubt and stays enabled — click-time resolution\n * warns if it's still unusable.\n */\n protected get targetSupported(): boolean {\n const required = this._requiredMethods;\n if (required.length === 0) return true;\n const target = this.target;\n if (targetUndetermined(target)) return true;\n return targetSupports(target, required);\n }\n\n /** The host's capability listeners, one controller per connection. */\n private _capabilityListeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._capabilityListeners?.abort();\n this._capabilityListeners = new AbortController();\n const { signal } = this._capabilityListeners;\n // Disabled inner buttons swallow clicks — listen on the host so an\n // unsupported control still explains itself on first interaction.\n this.addEventListener('pointerdown', this._onCapabilityPointerDown, { signal });\n // A target that became resolvable since the last render should\n // re-evaluate before the click lands.\n this.addEventListener('pointerenter', this._onCapabilityPointerEnter, { signal });\n // The transport `for` id resolves after connect (target may upgrade\n // later) — re-render once it's resolvable so disabled state is accurate.\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this.requestUpdate();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._capabilityListeners?.abort();\n this._capabilityListeners = null;\n }\n\n private _onCapabilityPointerEnter = () => {\n this.requestUpdate();\n };\n\n private _onCapabilityPointerDown = () => {\n const target = this.target;\n if (!target) {\n // A control with requirements stays enabled when the target is missing\n // (benefit of the doubt) — without this warn, a bad <daw-transport for>\n // id would be silent. Controls with no requirements warn in their own\n // click handlers instead.\n if (this._requiredMethods.length > 0) {\n warnNoTargetOnce(this);\n }\n return;\n }\n if (!this.targetSupported) {\n warnUnsupportedOnce(this, this._requiredMethods);\n }\n };\n\n static styles: import('lit').CSSResultGroup = css`\n button {\n cursor: pointer;\n background: var(--daw-controls-background, #1a1a2e);\n color: var(--daw-controls-text, #e0d4c8);\n border: 1px solid currentColor;\n padding: 4px 8px;\n font: inherit;\n }\n button:hover {\n opacity: 0.8;\n }\n button:disabled {\n opacity: 0.4;\n cursor: default;\n }\n `;\n}\n","import type { DawTransportElement } from '../elements/daw-transport';\n\n/**\n * Transport target resolution + duck-typed capability detection.\n *\n * Transport controls never instanceof-check their target — they probe for the\n * methods they need (`typeof target[m] === 'function'`). This is what lets the\n * same controls drive <daw-editor>, the future <daw-player> (#454), or any\n * conforming element, and lets editor-only controls render disabled against a\n * player (#474, spec \"Transport Compatibility\").\n */\n\n/**\n * Resolve the target of the closest <daw-transport for=\"...\"> ancestor.\n * Walks light-DOM ancestors only (`closest` does not cross shadow boundaries).\n */\nexport function resolveTransportTarget(el: Element): HTMLElement | null {\n const transport = el.closest('daw-transport') as DawTransportElement | null;\n return transport?.target ?? null;\n}\n\n/** True when target exists and every named method is a function on it. */\nexport function targetSupports(target: unknown, methods: readonly string[]): boolean {\n if (!target) return false;\n return methods.every((m) => typeof (target as Record<string, unknown>)[m] === 'function');\n}\n\n/**\n * True when the target cannot be judged yet: it is missing entirely, or it is\n * a custom element that has not upgraded (its methods don't exist until the\n * definition loads). Capability-gated controls give these the benefit of the\n * doubt and stay enabled — click-time resolution warns if still unusable —\n * instead of latching disabled before the app finishes booting.\n */\nexport function targetUndetermined(target: HTMLElement | null): boolean {\n if (!target) return true;\n const name = target.localName;\n return name.includes('-') && customElements.get(name) === undefined;\n}\n\nconst warned = new WeakMap<Element, Set<string>>();\n\n/**\n * One-time console warning for a transport control.\n * Dedup is per element per message — distinct messages on the same element\n * each warn once, while repeats of the same message stay silent. A\n * missing-target warn and an unsupported-target warn no longer suppress each\n * other.\n */\nexport function warnOnce(element: Element, message: string): void {\n let messages = warned.get(element);\n if (!messages) {\n messages = new Set();\n warned.set(element, messages);\n }\n if (messages.has(message)) return;\n messages.add(message);\n console.warn(message);\n}\n\n/**\n * One-time canonical warning for a control whose transport target is missing.\n * Every no-target site uses this single sentence so the message-keyed\n * {@link warnOnce} dedup collapses pointerdown-time and click-time warns into\n * one warning total. An optional suffix appends extra element-specific\n * context after the canonical text (still one message key per suffix).\n */\nexport function warnNoTargetOnce(element: Element, suffix?: string): void {\n warnOnce(\n element,\n `[dawcore] <${element.tagName.toLowerCase()}> has no target. Check ` +\n '<daw-transport for=\"...\"> references a valid element id.' +\n (suffix ?? '')\n );\n}\n\n/**\n * One-time console warning explaining why a control is disabled.\n * Delegates to {@link warnOnce} — an element that already triggered a\n * missing-target warn will not warn again here.\n */\nexport function warnUnsupportedOnce(element: Element, methods: readonly string[]): void {\n warnOnce(\n element,\n `[dawcore] <${element.tagName.toLowerCase()}> is disabled: its transport target ` +\n `does not implement ${methods.join(', ')}. See the transport compatibility ` +\n 'table in the docs for which controls work with which targets.'\n );\n}\n","import { html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\n\n@customElement('daw-pause-button')\nexport class DawPauseButtonElement extends DawTransportButton {\n @state() private _isPaused = false;\n @state() private _isRecording = false;\n private _targetRef: HTMLElement | null = null;\n /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */\n private _targetListeners: AbortController | null = null;\n private _onRecStart = () => {\n this._isRecording = true;\n };\n private _onRecEnd = () => {\n this._isRecording = false;\n this._isPaused = false;\n };\n private _onRecPause = () => {\n this._isPaused = true;\n };\n private _onRecResume = () => {\n this._isPaused = false;\n };\n\n static override styles = [\n DawTransportButton.styles,\n css`\n button[data-paused] {\n background: rgba(255, 255, 255, 0.1);\n border-color: var(--daw-controls-text, #e0d4c8);\n }\n `,\n ];\n\n connectedCallback() {\n super.connectedCallback();\n // Defer so <daw-transport for=\"...\"> and the target editor are resolved\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this._ensureTargetListeners();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._cleanupListeners();\n }\n\n protected override updated() {\n // Re-resolve on every render (pointerenter triggers one via the base\n // class) — a target that upgrades/appears after the one-shot\n // connectedCallback rAF (or a swapped <daw-transport for>) would\n // otherwise never get the recording-state listeners: mid-recording,\n // Pause would pause only the transport while the worklet keeps\n // capturing (#573, same fix as daw-record-button).\n this._ensureTargetListeners();\n }\n\n private _ensureTargetListeners() {\n const target = this.target;\n if (target === this._targetRef) return;\n if (this._targetRef) {\n // Swapping away from a live target: recording/pause state observed\n // there is stale — a replaced editor never fires the events that\n // would clear it, wedging the button into togglePauseRecording\n // routing. (A reconnect of the BUTTON has a null _targetRef and\n // keeps its state.)\n this._isRecording = false;\n this._isPaused = false;\n }\n this._cleanupListeners();\n if (!target) return;\n this._targetRef = target;\n this._targetListeners = new AbortController();\n const { signal } = this._targetListeners;\n target.addEventListener('daw-recording-start', this._onRecStart, { signal });\n target.addEventListener('daw-recording-complete', this._onRecEnd, { signal });\n target.addEventListener('daw-recording-error', this._onRecEnd, { signal });\n target.addEventListener('daw-recording-pause', this._onRecPause, { signal });\n target.addEventListener('daw-recording-resume', this._onRecResume, { signal });\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetListeners?.abort();\n this._targetListeners = null;\n this._targetRef = null;\n }\n }\n\n render() {\n return html`\n <button part=\"button\" ?data-paused=${this._isPaused} @click=${this._onClick}>\n <slot>Pause</slot>\n </button>\n `;\n }\n\n private _onClick() {\n const target = this.target;\n if (!target) {\n console.warn(\n '[dawcore] <daw-pause-button> has no target. Check <daw-transport for=\"...\"> references a valid <daw-editor> id.'\n );\n return;\n }\n\n if (this._isRecording) {\n // Delegate to editor — events keep visual state in sync via\n // daw-recording-pause / daw-recording-resume.\n target.togglePauseRecording();\n } else {\n target.pause();\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-pause-button': DawPauseButtonElement;\n }\n}\n","import { html } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\n\n@customElement('daw-stop-button')\nexport class DawStopButtonElement extends DawTransportButton {\n render() {\n return html`\n <button part=\"button\" @click=${this._onClick}>\n <slot>Stop</slot>\n </button>\n `;\n }\n\n private _onClick() {\n const target = this.target;\n if (!target) {\n console.warn(\n '[dawcore] <daw-stop-button> has no target. Check <daw-transport for=\"...\"> references a valid <daw-editor> id.'\n );\n return;\n }\n // When recording: await stopRecording (which awaits the worklet's\n // done ack) BEFORE calling editor.stop(). Calling stop() in parallel\n // disrupts the audio thread mid-handshake — engine.stop() can pause\n // worklet rendering, which prevents the done message from arriving.\n // ALWAYS run stop() afterward (even if stopRecording rejected), so the\n // engine cleans up; wrap stop() in try/catch since it's synchronous\n // void and can throw.\n if (target.isRecording) {\n target\n .stopRecording()\n .catch((err: unknown) => {\n console.warn('[dawcore] stopRecording failed: ' + String(err));\n })\n .then(() => {\n try {\n target.stop();\n } catch (err) {\n console.warn('[dawcore] stop after stopRecording failed: ' + String(err));\n }\n });\n } else {\n try {\n target.stop();\n } catch (err) {\n console.warn('[dawcore] stop failed: ' + String(err));\n }\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-stop-button': DawStopButtonElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport type {\n ArrangementTrack,\n AudioClip,\n ClipTrack,\n FadeType,\n TrackKind,\n LoadingClip,\n Peaks,\n PeakData,\n SnapTo,\n MeterEntry,\n SpectrogramConfig,\n ColorMapValue,\n} from '@waveform-playlist/core';\nimport type {\n StoredTrackDescriptor,\n TrackExtras,\n TrackRenderMode,\n TrackWithId,\n ClipDescriptor,\n DomClipDescriptor,\n DropClipDescriptor,\n TrackConfig,\n EditorCallOptions,\n ClipConfig,\n} from '../types';\nimport { isDomClip, normalizeRenderMode, trackDescriptorRenderMode } from '../types';\nimport {\n createMixerGesture,\n clipPixelWidth,\n isDecidedPanLaw,\n isLoadingClip,\n trackKind,\n} from '@waveform-playlist/core';\nimport { PeakPipeline } from '../workers/peakPipeline';\nimport type { DawTrackElement } from './daw-track';\nimport type { DawClipElement } from './daw-clip';\nimport type { DawPlayheadElement } from './daw-playhead';\nimport type { WaveformSegment } from './daw-waveform';\n// Register the visual child elements this editor's template always renders.\n// The shadow template emits <daw-playhead>/<daw-waveform>/<daw-ruler> directly,\n// so the editor must guarantee they're defined. Without these side-effect\n// imports, importing daw-editor alone (not the package barrel) leaves the\n// elements un-upgraded — querySelector returns generic HTMLElements, and calls\n// like playhead.setPosition() throw \"is not a function\". (Module caching +\n// @customElement make this safe to import here and from the index barrel.)\nimport './daw-playhead';\nimport './daw-waveform';\nimport './daw-ruler';\nimport { createArrangement, EditorEngine } from '@waveform-playlist/engine';\nimport type {\n Arrangement,\n EngineState,\n MixerChangeOptions,\n PlayoutAdapter,\n TrackMixerValues,\n} from '@waveform-playlist/engine';\nimport {\n DEFAULT_TRACK_MIX,\n clampNumber,\n declaredPanLaw,\n mixOfElement,\n mixOfTrack,\n} from '../utils/track-mix';\nimport '../elements/daw-track-controls';\nimport '../elements/daw-grid';\nimport { hostStyles, clipStyles } from '../styles/theme';\nimport { ViewportController } from '../controllers/viewport-controller';\nimport { AudioResumeController } from '../controllers/audio-resume-controller';\nimport { RecordingController } from '../controllers/recording-controller';\nimport type { RecordingOptions } from '../controllers/recording-controller';\nimport { AnnotationController, ANNOTATION_LANE_HEIGHT } from '../controllers/annotation-controller';\nimport type { DawAnnotationTrackElement } from './daw-annotation-track';\nimport { SpectrogramController } from '../controllers/spectrogram-controller';\nimport { PointerHandler } from '../interactions/pointer-handler';\nimport { ClipPointerHandler } from '../interactions/clip-pointer-handler';\nimport { AnnotationDragHandler } from '../interactions/annotation-drag';\nimport { TrackReorderHandler } from '../interactions/track-reorder-handler';\nimport type {\n DawSelectionDetail,\n DawTrackIdDetail,\n DawTrackControlDetail,\n DawTrackUpdateDetail,\n DawTrackErrorDetail,\n DawTrackReorderDetail,\n DawTrackReorderGrabDetail,\n DawClipErrorDetail,\n DawClipIdDetail,\n DawRecordingErrorDetail,\n DawErrorDetail,\n DawTimeFormatChangeDetail,\n LoadFilesResult,\n} from '../events';\nimport {\n isTimeDisplayFormat,\n TIME_DISPLAY_FORMATS,\n type TimeDisplayFormat,\n} from '../utils/time-display-format';\nimport { loadFiles as loadFilesImpl } from '../interactions/file-loader';\nimport {\n loadMidiImpl,\n type MidiLoaderHost,\n type MidiLoadOptions,\n type MidiLoadResult,\n} from '../interactions/midi-loader';\nimport { addRecordedClip } from '../interactions/recording-clip';\nimport { splitAtPlayhead as performSplitAtPlayhead } from '../interactions/split-handler';\nimport { syncPeaksForChangedClips } from '../interactions/clip-peak-sync';\nimport {\n buildArrangementTrack,\n buildLoadingClip,\n buildMidiClip,\n clipKindError,\n clipSourceOf,\n entryIndex,\n isMidiDescriptor,\n validMidiNotes,\n} from '../interactions/track-entry';\nimport { LoadAnnouncer } from '../interactions/load-announcer';\nimport { clipSeconds, loadedTrack, mixOf } from '../interactions/arrangement-view';\nimport { normalizeHandedIn, swapArrangement } from '../interactions/arrangement-swap';\nimport { clipDragChanged, trackDragChanged } from '../interactions/drag-watch';\nimport { moveClipToTrack, trackHoldingClip } from '../interactions/clip-rehome';\nimport { abortError, isAbortError, PlaySignals, reasonOf } from '../interactions/abort';\nimport {\n refreshLinkStates,\n detachedWarning,\n type ClipLinkValues,\n type LinkState,\n type TrackLinkValues,\n} from '../interactions/element-links';\nimport { EffectsManager } from '../effects/effects-manager';\nimport { exportAudioImpl } from '../interactions/export-audio';\nimport type { ExportOptions } from '../interactions/export-audio';\nimport type { EffectState, SerializedEffectEntry } from '../effects/types';\nimport { loadWaveformDataFromUrl } from '../interactions/peaks-loader';\nimport { extractPeaks } from '../workers/waveformDataUtils';\nimport { ScrollSyncController } from '../controllers/scroll-sync-controller';\nimport { PlaybackAnimationController } from '../controllers/playback-animation-controller';\nimport { installCommand } from '../utils/install-command';\n\n/** Height of the ruler band — single source for the ruler element and the header row. */\nconst RULER_HEIGHT = 30;\n\n/**\n * A track registered and not in the arrangement yet (#848): a `<daw-track>`\n * (read when it enters, with clips `addClip()` gave it meanwhile), or a\n * declaration with no element (`addTrack()`, a dropped file) and its mix.\n */\ntype PendingEntry =\n | { element: DawTrackElement; extraClips: DropClipDescriptor[] }\n | { descriptor: StoredTrackDescriptor; mix: TrackMixerValues };\n\n/** The values a clip change is computed from: the live values with the request applied (#848). */\ntype ClipUpdateValues = ClipLinkValues & { src: string };\n\n/** What a row of the template reads about its track (#848: from the arrangement and the extras). */\ninterface RowInfo {\n name: string;\n kind: TrackKind;\n renderMode: TrackRenderMode;\n}\n\n/** The descriptor of a clip from `addTrack()` / `addClip()` config: no element, a new id. */\nfunction clipDescriptorOf(config: ClipConfig): DropClipDescriptor & { clipId: string } {\n return {\n kind: 'drop',\n clipId: crypto.randomUUID(),\n src: config.src ?? '',\n peaksSrc: config.peaksSrc ?? '',\n start: config.start ?? 0,\n duration: config.duration ?? 0,\n offset: config.offset ?? 0,\n gain: config.gain ?? 1,\n name: config.name ?? '',\n fadeIn: config.fadeIn ?? 0,\n fadeOut: config.fadeOut ?? 0,\n fadeType: config.fadeType ?? 'linear',\n midiNotes: config.midiNotes ?? null,\n midiChannel: config.midiChannel ?? null,\n midiProgram: config.midiProgram ?? null,\n };\n}\n\n/** The extras of a track entering with this declaration: every clip it takes, with its `peaks-src`. */\nfunction extrasOf(descriptor: StoredTrackDescriptor): TrackExtras {\n return {\n kind: descriptor.kind,\n renderMode: descriptor.renderMode,\n spectrogramConfig: descriptor.spectrogramConfig,\n src: descriptor.src,\n peaksSrc: new Map(\n descriptor.clips.flatMap((c) => (c.clipId ? [[c.clipId, c.peaksSrc] as const] : []))\n ),\n };\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst noAdapterError = (): string =>\n 'No PlayoutAdapter set on <daw-editor>. ' +\n 'Set editor.adapter before use.\\n\\n' +\n ' // Option 1: Native Web Audio (no Tone.js)\\n' +\n ' ' +\n installCommand('@dawcore/transport') +\n '\\n' +\n \" import { NativePlayoutAdapter } from '@dawcore/transport';\\n\" +\n ' editor.adapter = new NativePlayoutAdapter(new AudioContext());\\n\\n' +\n ' // Option 2: Tone.js (effects, MIDI synths)\\n' +\n ' ' +\n installCommand('@waveform-playlist/playout') +\n '\\n' +\n \" import { createToneAdapter } from '@waveform-playlist/playout';\\n\" +\n ' editor.adapter = createToneAdapter();';\n\n/** The outcome of `_settleEntry` for a track that entered. */\nconst ENTERED: unique symbol = Symbol('entered');\n\n@customElement('daw-editor')\nexport class DawEditorElement extends LitElement implements MidiLoaderHost {\n @property({ type: Number, attribute: 'samples-per-pixel', noAccessor: true })\n get samplesPerPixel(): number {\n return this._samplesPerPixel;\n }\n set samplesPerPixel(value: number) {\n const old = this._samplesPerPixel;\n if (!Number.isFinite(value) || value <= 0) return;\n const clamped =\n this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel\n ? this._minSamplesPerPixel\n : value;\n if (clamped !== value) {\n console.warn(\n '[dawcore] Zoom ' +\n value +\n ' spp clamped to the peak floor (' +\n this._minSamplesPerPixel +\n ' spp) — peaks for the loaded audio (worker-generated or pre-computed) ' +\n 'can only render at or above that scale'\n );\n }\n this._samplesPerPixel = clamped;\n this.requestUpdate('samplesPerPixel', old);\n }\n private _samplesPerPixel = 1024;\n\n /** Raise the zoom floor and re-clamp the LIVE samplesPerPixel when it's\n * now below the floor. Peaks can only be extracted at >= the floor scale —\n * the setter alone clamps only FUTURE sets, so without the re-clamp an\n * already-finer spp keeps sizing clip containers while the waveforms\n * render at the coarser scale: half/quarter width, misaligned against the\n * ruler and playhead. */\n _raiseZoomFloor(scale: number): void {\n if (!Number.isFinite(scale) || scale <= 0) return;\n if (scale > this._minSamplesPerPixel) {\n this._minSamplesPerPixel = scale;\n }\n if (this._samplesPerPixel < this._minSamplesPerPixel) {\n this.samplesPerPixel = this._minSamplesPerPixel; // setter warns + requestUpdate\n }\n }\n\n /** Recompute the floor from the surviving cached scales (track removal /\n * load cancellation / preview cleanup). Usually LOWERS the floor, freeing\n * finer zoom — but a buffer whose scale never raised the floor (or a mix\n * of scales) can raise it above the live spp, so re-clamp like\n * _raiseZoomFloor. Never mutate _minSamplesPerPixel directly. */\n private _recomputeZoomFloor(): void {\n this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);\n if (this._minSamplesPerPixel > 0 && this._samplesPerPixel < this._minSamplesPerPixel) {\n this.samplesPerPixel = this._minSamplesPerPixel;\n }\n }\n\n private _timeFormat: TimeDisplayFormat = 'hh:mm:ss.sss';\n\n /**\n * Time display format used by <daw-time-display> and (future, #463) the\n * selection inputs. Lives on the editor — the target element owns the\n * state, the transport controls reflect it (native-form style).\n */\n @property({ attribute: 'time-format', reflect: true, noAccessor: true })\n get timeFormat(): TimeDisplayFormat {\n return this._timeFormat;\n }\n set timeFormat(value: TimeDisplayFormat) {\n if (!isTimeDisplayFormat(value)) {\n console.warn(\n '[dawcore] timeFormat: invalid format \"' +\n String(value) +\n '\" ignored. Valid formats: ' +\n TIME_DISPLAY_FORMATS.join(', ')\n );\n // Self-heal the DOM: a rejected attribute value would otherwise stick\n // (reflection never runs for a rejected set), leaving attribute and\n // property permanently divergent.\n if (\n this.hasAttribute('time-format') &&\n this.getAttribute('time-format') !== this._timeFormat\n ) {\n this.setAttribute('time-format', this._timeFormat);\n }\n return;\n }\n if (value === this._timeFormat) return;\n const old = this._timeFormat;\n this._timeFormat = value;\n this.requestUpdate('timeFormat', old);\n this.dispatchEvent(\n new CustomEvent<DawTimeFormatChangeDetail>('daw-time-format-change', {\n bubbles: true,\n composed: true,\n detail: { format: value },\n })\n );\n }\n\n /** Set the time display format. Sugar over the `timeFormat` property. */\n setTimeFormat(format: TimeDisplayFormat): void {\n this.timeFormat = format;\n }\n\n @property({ type: Number, attribute: 'wave-height' }) waveHeight = 128;\n @property({ type: Boolean }) timescale = false;\n @property({ type: Boolean }) mono = false;\n @property({ type: Number, attribute: 'bar-width' }) barWidth = 1;\n @property({ type: Number, attribute: 'bar-gap' }) barGap = 0;\n @property({ type: Boolean, attribute: 'rounded-bars' }) roundedBars = false;\n @property({ type: Boolean, attribute: 'file-drop' }) fileDrop = false;\n @property({ type: Boolean, attribute: 'clip-headers' }) clipHeaders = false;\n /** Scale each clip's drawn waveform by its `gain` (clamped to the channel\n * height), so levelled clips look the way they sound. Off by default:\n * waveforms show source level. Draw-time only — no peak regeneration. */\n @property({ type: Boolean, attribute: 'gain-scaled-waveforms' }) gainScaledWaveforms = false;\n @property({ type: Number, attribute: 'clip-header-height' }) clipHeaderHeight = 20;\n @property({ type: Boolean, attribute: 'interactive-clips' }) interactiveClips = false;\n /**\n * Disable the end-of-timeline auto-stop — the transport rolls until an\n * explicit stop/pause (DAW style). Implies the fill-viewport layout.\n * Recording sessions suppress the auto-stop automatically, so recording\n * UIs usually want `fill-viewport` instead. Parity with the React\n * provider's `indefinitePlayback` prop.\n */\n @property({ type: Boolean, attribute: 'indefinite-playback' }) indefinitePlayback = false;\n /**\n * When true, the timeline fills the visible viewport even if total clip\n * duration is less (layout only — playback still auto-stops at the end).\n * Lets the ruler render before any audio is loaded — useful for empty\n * editors and recording UIs. In beats mode the 32-bar floor already\n * provides this; this attribute controls the temporal mode. Parity with\n * the React provider's `fillViewport` prop.\n */\n @property({ type: Boolean, attribute: 'fill-viewport' }) fillViewport = false;\n /**\n * Enable vertical track reordering UI: grip + move up/down buttons on each\n * track's controls. Reordering is purely organizational.\n */\n @property({ type: Boolean, attribute: 'track-reordering' }) trackReordering = false;\n /**\n * Default spectrogram FFT/render config inherited by tracks with\n * `render-mode=\"spectrogram\"` that do not set their own. Wired into the\n * orchestrator by `SpectrogramController` in Task 14.\n */\n @property({ attribute: false, noAccessor: true })\n get spectrogramConfig(): SpectrogramConfig | null {\n return this._spectrogramConfig;\n }\n set spectrogramConfig(value: SpectrogramConfig | null) {\n const old = this._spectrogramConfig;\n this._spectrogramConfig = value;\n this._spectrogramController?.setEditorConfig(value);\n this.requestUpdate('spectrogramConfig', old);\n }\n private _spectrogramConfig: SpectrogramConfig | null = null;\n\n /**\n * Default color map for spectrogram tracks. Tracks may override via\n * their own per-track property in a future iteration. Separate from\n * `spectrogramConfig` because `ColorMapValue` is not part of the\n * `SpectrogramConfig` shape.\n */\n @property({ attribute: false, noAccessor: true })\n get spectrogramColorMap(): ColorMapValue | null {\n return this._spectrogramColorMap;\n }\n set spectrogramColorMap(value: ColorMapValue | null) {\n const old = this._spectrogramColorMap;\n this._spectrogramColorMap = value;\n this._spectrogramController?.setEditorColorMap(value);\n this.requestUpdate('spectrogramColorMap', old);\n }\n private _spectrogramColorMap: ColorMapValue | null = null;\n\n private _ensureSpectrogramController(): SpectrogramController {\n if (!this._spectrogramController) {\n this._spectrogramController = new SpectrogramController(\n this,\n () =>\n new Worker(new URL('@dawcore/spectrogram/worker/spectrogram.worker', import.meta.url), {\n type: 'module',\n })\n );\n if (this._spectrogramConfig) {\n this._spectrogramController.setEditorConfig(this._spectrogramConfig);\n }\n if (this._spectrogramColorMap) {\n this._spectrogramController.setEditorColorMap(this._spectrogramColorMap);\n }\n }\n return this._spectrogramController;\n }\n\n /** Called by <daw-spectrogram> after transferControlToOffscreen. */\n _spectrogramRegisterCanvas(reg: {\n canvasId: string;\n canvas: OffscreenCanvas;\n clipId: string;\n trackId: string;\n channelIndex: number;\n chunkIndex: number;\n globalPixelOffset: number;\n widthPx: number;\n heightPx: number;\n }): void {\n this._ensureSpectrogramController().registerCanvas(reg);\n }\n\n /** Called by <daw-spectrogram> on chunk unmount / element disconnect. */\n _spectrogramUnregisterCanvas(canvasId: string): void {\n this._spectrogramController?.unregisterCanvas(canvasId);\n }\n\n /**\n * Forward a clip's AudioBuffer to the spectrogram controller if the parent\n * track is in spectrogram render-mode. Eagerly creates the controller via\n * `_ensureSpectrogramController` so the audio data is queued for the first\n * render — even if no canvases have been registered yet.\n */\n private _maybeRegisterSpectrogramClipAudio(trackId: string, clip: AudioClip): void {\n if (this._renderModeOf(trackId) !== 'spectrogram') return;\n // Read the buffer off the clip itself — `_clipBuffers` is mutated in-place\n // by `cleanupOrphanedClipData` during concurrent track loading and may\n // briefly miss this clip even though the clip object still holds the\n // buffer reference.\n const buffer = clip.audioBuffer ?? this._clipBuffers.get(clip.id);\n if (!buffer) return;\n const channelData: Float32Array[] = [];\n for (let i = 0; i < buffer.numberOfChannels; i++) {\n channelData.push(buffer.getChannelData(i));\n }\n this._ensureSpectrogramController().registerClipAudio({\n clipId: clip.id,\n trackId,\n channelData,\n sampleRate: buffer.sampleRate,\n durationSamples: clip.durationSamples,\n offsetSamples: clip.offsetSamples,\n });\n }\n @property({ type: String, attribute: 'scale-mode' })\n scaleMode: 'temporal' | 'beats' = 'temporal';\n @property({ type: Number, attribute: 'ticks-per-pixel', noAccessor: true })\n get ticksPerPixel(): number {\n return this._ticksPerPixel;\n }\n set ticksPerPixel(value: number) {\n const old = this._ticksPerPixel;\n if (!Number.isFinite(value) || value <= 0) return;\n this._ticksPerPixel = value;\n this.requestUpdate('ticksPerPixel', old);\n }\n private _ticksPerPixel = 24;\n @property({ type: Number, noAccessor: true })\n get bpm(): number {\n return this._bpm;\n }\n set bpm(value: number) {\n const old = this._bpm;\n if (!Number.isFinite(value) || value <= 0) return;\n this._bpm = value;\n // Forward to engine (which forwards to adapter's Transport) — unless the\n // consumer provided tick callbacks, in which case the external tempo map\n // is authoritative and bpm is display/grid-only (#407).\n if (this._engine && !this._hasTickCallbacks) {\n this._engine.setTempo(value);\n }\n this.requestUpdate('bpm', old);\n }\n private _bpm = 120;\n @property({ attribute: false })\n timeSignature: [number, number] = [4, 4];\n @property({ attribute: false })\n meterEntries?: MeterEntry[];\n /** MeterEntries for grid/ruler: explicit meterEntries if set, otherwise derived from timeSignature. */\n get _meterEntries(): MeterEntry[] {\n if (this.meterEntries && this.meterEntries.length > 0) return this.meterEntries;\n return [{ tick: 0, numerator: this.timeSignature[0], denominator: this.timeSignature[1] }];\n }\n @property({ type: Number, noAccessor: true })\n get ppqn(): number {\n return this._ppqn;\n }\n set ppqn(value: number) {\n const old = this._ppqn;\n if (!Number.isFinite(value) || value <= 0) return;\n this._ppqn = value;\n this.requestUpdate('ppqn', old);\n }\n private _ppqn = 960;\n @property({ type: String, attribute: 'snap-to' })\n snapTo: SnapTo = 'off';\n /** Optional tempo-aware conversion: seconds → PPQN ticks. When provided\n * together with ticksToSeconds, enables variable tempo AND makes `bpm`\n * display/grid-only (no engine/adapter tempo forwarding — #407). */\n @property({ attribute: false })\n secondsToTicks?: (seconds: number) => number;\n /** Optional tempo-aware conversion: PPQN ticks → seconds. Required alongside\n * secondsToTicks — see that property for the variable-tempo and bpm\n * display-only semantics enabled when both are set (#407). */\n @property({ attribute: false })\n ticksToSeconds?: (ticks: number) => number;\n /** True when the consumer provided BOTH tick conversion callbacks — the\n * external tempo map is authoritative and `bpm` is display/grid-only (#407). */\n get _hasTickCallbacks(): boolean {\n return !!(this.secondsToTicks && this.ticksToSeconds);\n }\n /**\n * Sample rate: the adapter's AudioContext rate. Without an adapter (after a\n * disconnect let it go), the rate of the loaded clips the arrangement holds,\n * else 48000. Decoded audio is at the context's rate, so the two agree.\n */\n get sampleRate(): number {\n return this._externalAdapter?.audioContext.sampleRate ?? this._loadedClipSampleRate() ?? 48000;\n }\n private _loadedClipSampleRate(): number | null {\n for (const track of this._arrangement.getTracks()) {\n for (const clip of track.clips) {\n if ('sampleRate' in clip && typeof clip.sampleRate === 'number') return clip.sampleRate;\n }\n }\n return null;\n }\n /**\n * The editor's own arrangement (#848): the one owner of the tracks, the\n * clips, the mix, the undo history and loading of what the `<daw-track>`\n * children declare. Made with the editor, kept across a disconnect.\n */\n readonly _ownArrangement: Arrangement = createArrangement();\n /** An arrangement the app handed in (`editor.arrangement`), played alone; null: the own one. */\n _handedIn: Arrangement | null = null;\n /** The arrangement played now: a handed-in one, else the editor's own. */\n get _arrangement(): Arrangement {\n return this._handedIn ?? this._ownArrangement;\n }\n /**\n * The arrangement the editor plays (#848 PR 3): one handed in by the app,\n * or else the editor's own, whose content the `<daw-track>` children\n * declare. Setting one plays it alone, like `video.srcObject`: the\n * children are not added to it and show `:state(detached)` while it is\n * set; `null` (or the editor's own) goes back to the own arrangement with\n * what it held. A swap keeps the adapter: playback stops, a new engine is\n * built on the new arrangement. Refused (with a warning) during a take.\n * The editor never disposes or clears an arrangement it was handed.\n * Throws a `TypeError` for a value that is not an arrangement.\n */\n get arrangement(): Arrangement {\n return this._arrangement;\n }\n set arrangement(value: Arrangement | null) {\n swapArrangement(this, normalizeHandedIn(value, this._ownArrangement));\n }\n /** Sends the load events, read from the arrangement played (#848; a new one per swap). */\n private _announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));\n /** Stops following the arrangement played (its sources and its tracks). */\n private _unfollow: () => void = () => {};\n constructor() {\n super();\n this._follow(this._ownArrangement);\n }\n /**\n * Follow the arrangement played: a source that fails changes no track,\n * only `sources` tells of it (the events, the failed look); the elements'\n * link states follow its tracks (a structural change only, not every\n * mixer frame).\n */\n private _follow(arrangement: Arrangement): void {\n this._unfollow();\n const stopSources = arrangement.sources.subscribe(() => {\n this._announceLoading();\n this.requestUpdate();\n });\n let tracksVersion = arrangement.tracksVersion;\n const stopTracks = arrangement.subscribe(() => {\n this._watchDrags();\n if (arrangement.tracksVersion === tracksVersion) return;\n tracksVersion = arrangement.tracksVersion;\n this._refreshLinkStates();\n });\n this._unfollow = () => {\n stopSources();\n stopTracks();\n };\n }\n /**\n * A change to the arrangement while a drag is in progress came from\n * elsewhere (a drag writes nothing until its release): cancel the drag\n * when it changed what is dragged (#848 P2, interactions/drag-watch.ts).\n */\n private _watchDrags(): void {\n const clip = this._clipPointer.draggedClip;\n if (clip && clipDragChanged(this._arrangement, clip)) this._pointer.cancelClipDrag();\n const track = this._trackReorderDrag.draggedTrack;\n if (track && trackDragChanged(this._arrangement, track)) this._trackReorderDrag.cancel();\n }\n // --- The swap (interactions/arrangement-swap.ts) ---\n /** @internal */\n _releaseEngine(): void {\n if (!this._engine) return;\n try {\n this._engine.dispose({ keepAdapter: true });\n } catch (err) {\n console.warn('[dawcore] Error releasing the engine: ' + String(err));\n }\n this._engine = null;\n }\n /** @internal */\n _disposeTrackChain(trackId: string): void {\n this._effectsManager?.disposeTrackChain(trackId);\n }\n /** @internal */\n _playArrangement(next: Arrangement | null): void {\n // The waits on the arrangement played until now end (D2): an addClip()\n // rejects, a loadFiles() wait ends as loaded, a peaks fetch is aborted.\n this._playSignals.swappedOut(\n this._arrangement,\n abortError('the arrangement was swapped out (editor.arrangement) before it finished')\n );\n this._handedIn = next;\n // A new load cycle: every track of the arrangement now played is announced.\n this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));\n this._follow(this._arrangement);\n this._currentTime = 0;\n this._stopPlayhead();\n this._recomputeDuration();\n this._refreshLinkStates();\n this._announceLoading();\n this.requestUpdate();\n }\n /** @internal */\n _buildEngineIfReady(): void {\n if (this._externalAdapter && this.isConnected && !this._engine) this._buildEngineReporting();\n }\n /**\n * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and\n * not yet in the arrangement: they enter at the next flush, once there is\n * an engine (#848).\n */\n private _entryQueue: string[] = [];\n private _entryFlushScheduled = false;\n /**\n * Clips an `addClip()` is waiting for, with their track and the way to\n * reject the call: a removal of the clip or of its track before the clip\n * loads settles it here, without a public event (#917).\n */\n private _awaitedClips = new Map<string, { trackId: string; reject: (error: unknown) => void }>();\n /** Reject the `addClip()` calls waiting for clips that match `which`. */\n private _rejectAwaitedClips(\n which: (clipId: string, trackId: string) => boolean,\n message: string\n ): void {\n for (const [clipId, awaited] of [...this._awaitedClips]) {\n if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));\n }\n }\n /** `.dat` peaks drawn for a clip still loading, by clip id (an editor-only render cache). */\n @state() _previewPeaks: Map<string, PeakData> = new Map();\n /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */\n private _previewWaveforms = new Map<string, import('waveform-data').default>();\n /**\n * Tracks registered and not in the arrangement yet, with their declaration\n * (#848): a `<daw-track>` is read when it enters (its clips and attributes\n * as they are then); a dropped file carries its descriptor. The one place a\n * track's state lives until it enters.\n */\n _pending: Map<string, PendingEntry> = new Map();\n /** What the arrangement has no field for, by track id (#848; render mode, `peaks-src`). */\n @state() _extras: Map<string, TrackExtras> = new Map();\n @state() _peaksData: Map<string, PeakData> = new Map();\n @state() _isPlaying = false;\n @state() _duration = 0;\n @state() _selectedTrackId: string | null = null;\n @state() _dragOver = false;\n // Not @state — updated directly to avoid 60fps Lit re-renders\n _selectionStartTime = 0;\n _selectionEndTime = 0;\n _currentTime = 0;\n // Bounded-playback watermark for the current play(start, end) call\n // (selection/annotation playback). Adapters with the engine's\n // onPlaybackEnded hook (Tone, and native since #636) report their\n // endTime self-stop through the engine's `stop` event; this watermark is\n // the fallback check in the _startPlayhead loop for adapters without the\n // hook, same pattern as the whole-track _duration check.\n _activePlayEndTime: number | null = null;\n @property({ attribute: false })\n set adapter(value: PlayoutAdapter | null) {\n if (value && value.audioContext.state === 'closed') {\n console.warn('[dawcore] Adapter AudioContext is already closed. Ignoring.');\n return;\n }\n if (this._engine) {\n console.warn(\n '[dawcore] adapter set after engine is built. ' +\n 'The engine will continue using the previous adapter.'\n );\n }\n if (this._effectsManager) {\n // Chains are wired into the previous adapter's transport/graph and\n // cannot be migrated. Sever them there BEFORE the swap so the old\n // graph is left clean; consumers re-add effects on the new adapter.\n console.warn(\n '[dawcore] adapter replaced — existing effect chains were disposed. ' +\n 'Re-add effects on the new adapter.'\n );\n this._effectsManager.disposeAll();\n this._effectsManager = null;\n }\n this._externalAdapter = value;\n // The engine is built as soon as the editor is connected with an adapter (#848).\n if (value && this.isConnected && !this._engine) this._buildEngineReporting();\n }\n get adapter(): PlayoutAdapter | null {\n return this._externalAdapter;\n }\n private _externalAdapter: PlayoutAdapter | null = null;\n\n // --- Effects (master chain; per-track chains delegated from <daw-track>) ---\n\n private _effectsManager: EffectsManager | null = null;\n\n private get _effects(): EffectsManager {\n if (!this._effectsManager) {\n this._effectsManager = new EffectsManager(() => this._externalAdapter, this);\n }\n return this._effectsManager;\n }\n\n /**\n * Run a registered effect type's async `prepare` hook (e.g. an\n * `audioWorklet.addModule`) on this editor's audio context. Await it before\n * the synchronous `addEffect`/`addTrackEffect` for effect types that define\n * one; `setEffectsState()` and `exportAudio()` run it themselves. Idempotent\n * per context, and a no-op for types without a hook.\n */\n prepareEffect(type: string): Promise<void> {\n return this._effects.prepareEffect(type);\n }\n\n /** Master effects chain — inserted between the master bus and the destination. */\n addEffect(type: string, params?: Record<string, number>): string {\n return this._effects.addMasterEffect(type, params);\n }\n\n removeEffect(effectId: string): void {\n this._effects.masterOp('remove', effectId);\n }\n\n setEffectParams(effectId: string, params: Record<string, number>): void {\n this._effects.masterOp('setParams', effectId, params);\n }\n\n setEffectBypassed(effectId: string, bypassed: boolean): void {\n this._effects.masterOp('setBypassed', effectId, bypassed);\n }\n\n moveEffect(effectId: string, newIndex: number): void {\n this._effects.masterOp('move', effectId, newIndex);\n }\n\n get effects(): EffectState[] {\n return this._effectsManager?.masterEffects() ?? [];\n }\n\n /** Load a WAM plugin (via the optional @dawcore/wam peer) into the master chain. */\n addWamPlugin(url: string, initialState?: unknown): Promise<string> {\n return this._effects.addMasterWamPlugin(url, initialState);\n }\n\n /**\n * Compile Faust DSP source in the browser (via the optional @dawcore/faust\n * peer) and add the resulting WAM to the master chain. Compile errors keep\n * their Faust line/column diagnostics and leave the chain untouched.\n */\n addFaustEffect(dspCode: string, options?: { name?: string }): Promise<string> {\n return this._effects.addMasterFaustEffect(dspCode, options);\n }\n\n /**\n * Open (lazily creating) the GUI for a master-chain effect into a\n * consumer-provided container. WAM plugins mount their own GUI; plugins\n * without one — and native effects — get the generic parameter panel from\n * @dawcore/wam. The element is cached: closeEffectGui hides it without\n * interrupting audio, reopening remounts the same element.\n */\n openEffectGui(effectId: string, container: HTMLElement): Promise<HTMLElement> {\n return this._effects.openMasterEffectGui(effectId, container);\n }\n\n /** Hide a master-chain effect's GUI (cached for reopen — never destroys). */\n closeEffectGui(effectId: string): void {\n this._effects.closeEffectGui(effectId);\n }\n\n /** Snapshot the master chain in its persisted form (see dawcore README). */\n getEffectsState(): Promise<SerializedEffectEntry[]> {\n return this._effectsManager?.getMasterEffectsState() ?? Promise.resolve([]);\n }\n\n /** Replace the master chain with a persisted snapshot. */\n setEffectsState(entries: SerializedEffectEntry[]): Promise<void> {\n return this._effects.setMasterEffectsState(entries);\n }\n\n /**\n * Render the session offline through all effect chains (per-track +\n * master), including WAM plugins (re-instantiated on the offline context\n * with their live state). Returns the rendered AudioBuffer.\n */\n exportAudio(options?: ExportOptions): Promise<AudioBuffer> {\n return exportAudioImpl(\n {\n effectiveSampleRate: this.effectiveSampleRate,\n duration: this._duration,\n tracks: this._loadedTracks(),\n masterVolume: this._engine?.getState().masterVolume ?? 1,\n getMasterEffectsState: () => this.getEffectsState(),\n getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId),\n },\n options\n );\n }\n\n // --- Per-track effects API (public, keyed by trackId) ---\n // Mirrors the master-chain methods above and the <daw-track> element methods,\n // but addresses a track by id so element-less tracks (drag-dropped, or\n // programmatic tracks the consumer doesn't hold an element for) can carry\n // their own insert chain. Effect events dispatch from the track's <daw-track>\n // element when one exists, else from the editor (see _trackEventTarget).\n\n /** Add a native registry effect to a track's chain. */\n addTrackEffect(trackId: string, type: string, params?: Record<string, number>): string {\n return this._effects.addTrackEffect(trackId, this._trackEventTarget(trackId), type, params);\n }\n\n /** Snapshot of a track's effect chain (empty array for an unknown track). */\n trackEffects(trackId: string): EffectState[] {\n return this._effectsManager?.trackEffects(trackId) ?? [];\n }\n\n removeTrackEffect(trackId: string, effectId: string): void {\n this._effects.trackOp(trackId, this._trackEventTarget(trackId), 'remove', effectId);\n }\n\n setTrackEffectParams(trackId: string, effectId: string, params: Record<string, number>): void {\n this._effects.trackOp(trackId, this._trackEventTarget(trackId), 'setParams', effectId, params);\n }\n\n setTrackEffectBypassed(trackId: string, effectId: string, bypassed: boolean): void {\n this._effects.trackOp(\n trackId,\n this._trackEventTarget(trackId),\n 'setBypassed',\n effectId,\n bypassed\n );\n }\n\n moveTrackEffect(trackId: string, effectId: string, newIndex: number): void {\n this._effects.trackOp(trackId, this._trackEventTarget(trackId), 'move', effectId, newIndex);\n }\n\n /** Load a WAM plugin (via the optional @dawcore/wam peer) into a track's chain. */\n addTrackWamPlugin(trackId: string, url: string, initialState?: unknown): Promise<string> {\n return this._effects.addTrackWamPlugin(\n trackId,\n this._trackEventTarget(trackId),\n url,\n initialState\n );\n }\n\n /** Compile Faust DSP (via the optional @dawcore/faust peer) into a track's chain. */\n addTrackFaustEffect(\n trackId: string,\n dspCode: string,\n options?: { name?: string }\n ): Promise<string> {\n return this._effects.addTrackFaustEffect(\n trackId,\n this._trackEventTarget(trackId),\n dspCode,\n options\n );\n }\n\n /** Open (lazily creating) the GUI for a track-chain effect into a container. */\n openTrackEffectGui(\n trackId: string,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement> {\n return this._effects.openTrackEffectGui(\n trackId,\n this._trackEventTarget(trackId),\n effectId,\n container\n );\n }\n\n /** Hide a track-chain effect's GUI (cached for reopen — never destroys). */\n closeTrackEffectGui(_trackId: string, effectId: string): void {\n this._effects.closeEffectGui(effectId);\n }\n\n /** Snapshot a track's chain in its persisted form (see dawcore README). */\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]> {\n return this._effectsManager?.getTrackEffectsState(trackId) ?? Promise.resolve([]);\n }\n\n /** Replace a track's chain from a persisted snapshot. */\n setTrackEffectsState(trackId: string, entries: SerializedEffectEntry[]): Promise<void> {\n return this._effects.setTrackEffectsState(trackId, this._trackEventTarget(trackId), entries);\n }\n\n /**\n * Event-dispatch source for a per-track effect op: the track's `<daw-track>`\n * element when one exists (so `daw-effect-*` bubble from it exactly as the\n * element-method path does), else the editor itself for element-less tracks\n * (drag-dropped / programmatic). Reads the `_trackElements` index the editor\n * already maintains across the track connect/remove lifecycle — O(1), and the\n * same resolution `removeTrack` uses — rather than re-querying the DOM per op.\n */\n private _trackEventTarget(trackId: string): EventTarget {\n return this._trackElements.get(trackId) ?? this;\n }\n\n get audioContext(): AudioContext {\n if (!this._externalAdapter) {\n throw new Error(noAdapterError());\n }\n return this._externalAdapter.audioContext;\n }\n _engine: EditorEngine | null = null;\n private _warnedMissingTicksToSeconds = false;\n private _warnedMissingSecondsToTicks = false;\n private _peaksCache = new Map<string, Promise<import('waveform-data').default>>();\n _clipBuffers = new Map<string, AudioBuffer>();\n _clipOffsets = new Map<string, { offsetSamples: number; durationSamples: number }>();\n _peakPipeline = new PeakPipeline();\n /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */\n private _minSamplesPerPixel = 0;\n private _trackElements = new Map<string, DawTrackElement>();\n private _childObserver: MutationObserver | null = null;\n private _audioResume = new AudioResumeController(this);\n @property({ attribute: 'eager-resume' })\n eagerResume?: string;\n private _recordingController = new RecordingController(this);\n private _annotations = new AnnotationController(this);\n /** Last engine BPM seen by the statechange handler — re-derives tick\n * annotation seconds caches only when it actually changes. */\n private _lastAnnotationBpm: number | null = null;\n // Closures (not direct references) — _timeToPixels/_getPlayhead are\n // declared later in the class body; class-field init order would read\n // `undefined` for a direct reference here.\n private _playbackAnimation = new PlaybackAnimationController(this, {\n timeToPixels: (time) => this._timeToPixels(time),\n getPlayhead: () => this._getPlayhead(),\n });\n /**\n * True while a seek-while-playing stop+play transition is in flight.\n * Suppresses the transient settle dispatch from the engine 'stop' handler\n * (which would otherwise leak a backward-jumping daw-timeupdate at the\n * play-start position). Non-private: pointer-handler's seek path sets it.\n */\n _inSeekTransition = false;\n /**\n * True while `stop()` (the public API) is actively calling `this._engine.stop()`.\n * Suppresses the engine 'stop' handler's own `daw-stop` dispatch — `stop()`\n * dispatches its own, and without this guard a consumer-initiated stop would\n * fire `daw-stop` twice. See the engine 'stop' handler for the counterpart\n * engine-initiated case this flag does NOT suppress.\n */\n private _inConsumerStop = false;\n private _spectrogramController: SpectrogramController | null = null;\n private _clipPointer = new ClipPointerHandler(this);\n private _annotationDrag = new AnnotationDragHandler(this);\n private _trackReorderDrag = new TrackReorderHandler(this);\n get _clipHandler() {\n return this.interactiveClips ? this._clipPointer : null;\n }\n get engine() {\n return this._engine;\n }\n get renderSamplesPerPixel() {\n return this._renderSpp;\n }\n /** Re-extract peaks for a clip at new offset/duration from cached WaveformData. */\n reextractClipPeaks(\n clipId: string,\n offsetSamples: number,\n durationSamples: number\n ): PeakData | null {\n const buf = this._clipBuffers.get(clipId);\n if (!buf) return null;\n const singleClipBuffers = new Map([[clipId, buf]]);\n const singleClipOffsets = new Map([[clipId, { offsetSamples, durationSamples }]]);\n const result = this._peakPipeline.reextractPeaks(\n singleClipBuffers,\n this._renderSpp,\n this.mono,\n singleClipOffsets\n );\n return result.get(clipId) ?? null;\n }\n\n /**\n * Returns true if the clip is a MIDI clip (has midiNotes).\n * Used by ClipPointerHandler to make trim handles inert for MIDI clips.\n * Returns false for unknown track/clip IDs (defensive).\n */\n isMidiClip(trackId: string, clipId: string): boolean {\n const clip = this._loadedClip(trackId, clipId);\n return clip?.midiNotes != null;\n }\n /** The arrangement's tracks as they are played: loaded clips, the current mix (#848). */\n _loadedTracks(): ClipTrack[] {\n const arrangement = this._arrangement;\n return arrangement\n .getTracks()\n .map((t) =>\n loadedTrack(\n t,\n arrangement.getMixer().get(t.id) ?? mixOfTrack(t as ClipTrack),\n arrangement.recordingTrackIds.has(t.id)\n )\n );\n }\n /** A loaded clip of a track of the arrangement, or undefined. */\n private _loadedClip(trackId: string, clipId: string): AudioClip | undefined {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n const clip = track?.clips.find((c) => c.id === clipId);\n return clip && !isLoadingClip(clip) ? clip : undefined;\n }\n\n private _pointer = new PointerHandler(this);\n private _viewport = (() => {\n const v = new ViewportController(this);\n v.scrollSelector = '.scroll-area';\n return v;\n })();\n private _scrollSync = (() => {\n const s = new ScrollSyncController(this);\n s.scrollSelector = '.scroll-area';\n // xTargetSelector, yTargetSelector, and wheelForwardSelector are kept\n // truthful by updated() — they start empty and are set before any scroll\n // is possible (updated() runs before paint on every reactive update).\n return s;\n })();\n\n static styles = [\n hostStyles,\n css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: flex;\n flex-direction: column;\n position: relative;\n background: var(--daw-background, #1a1a2e);\n overflow: hidden;\n }\n .header-row {\n display: flex;\n flex-shrink: 0;\n }\n .ruler-gap {\n flex-shrink: 0;\n width: var(--daw-controls-width, 180px);\n }\n .ruler-viewport {\n flex: 1;\n position: relative;\n overflow: hidden;\n cursor: text;\n }\n .ruler-content {\n will-change: transform;\n }\n .body {\n flex: 1;\n min-height: 0;\n display: flex;\n }\n .controls-viewport {\n flex-shrink: 0;\n width: var(--daw-controls-width, 180px);\n overflow: hidden;\n }\n .controls-column {\n will-change: transform;\n }\n .scroll-area {\n flex: 1;\n overflow: auto;\n overflow-anchor: none;\n min-height: var(--daw-min-height, 200px);\n }\n .timeline {\n position: relative;\n min-height: 100%;\n cursor: text;\n }\n .track-row {\n position: relative;\n box-sizing: border-box;\n background: var(--daw-track-background, #16213e);\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\n }\n .track-row.selected {\n background: rgba(99, 199, 95, 0.08);\n }\n .track-row[data-track-drag-source] {\n background: rgba(99, 199, 95, 0.08);\n }\n :host([scale-mode='beats']) .track-row {\n background: transparent;\n }\n :host([scale-mode='beats']) .clip-container {\n background: var(--daw-track-background, #16213e);\n }\n :host([scale-mode='beats']) .track-row.selected .clip-container {\n box-shadow: inset 0 0 0 1000px rgba(99, 199, 95, 0.06);\n }\n .timeline.drag-over {\n outline: 2px dashed var(--daw-selection-color, rgba(99, 199, 95, 0.3));\n outline-offset: -2px;\n }\n .annotation-lane {\n position: relative;\n box-sizing: border-box;\n border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));\n background: var(--daw-annotation-lane-background, rgba(0, 0, 0, 0.15));\n user-select: none;\n -webkit-user-drag: none;\n }\n .annotation-lane-spacer {\n box-sizing: border-box;\n border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));\n display: flex;\n align-items: center;\n overflow: hidden;\n }\n .annotation-lane-name {\n padding: 0 10px;\n font-size: 11px;\n color: var(--daw-controls-text, #e0d4c8);\n opacity: 0.8;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .annotation-box {\n position: absolute;\n top: 3px;\n bottom: 3px;\n overflow: hidden;\n display: flex;\n align-items: center;\n border: 1px solid var(--daw-annotation-box-border, #c49a6c);\n border-radius: 3px;\n background: var(--daw-annotation-box-background, rgba(196, 154, 108, 0.2));\n color: var(--daw-annotation-text-color, #e0d4c8);\n font-size: 11px;\n cursor: pointer;\n }\n .annotation-box.playing {\n box-shadow: inset 0 0 0 1px var(--daw-annotation-box-border, #c49a6c);\n background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.32));\n }\n .annotation-box.active {\n background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.45));\n }\n .annotation-box-text {\n padding: 0 6px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n pointer-events: none;\n }\n .annotation-boundary {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 6px;\n cursor: ew-resize;\n flex-shrink: 0;\n }\n .annotation-boundary[data-edge='start'] {\n left: 0;\n }\n .annotation-boundary[data-edge='end'] {\n right: 0;\n }\n `,\n clipStyles,\n ];\n\n get effectiveSampleRate(): number {\n return this.sampleRate;\n }\n /**\n * In beats mode, derive samplesPerPixel from ticksPerPixel so that\n * clip positions, waveforms, and the tick-space grid all align.\n */\n get _renderSpp(): number {\n if (this.scaleMode === 'beats') {\n // Round to integer — WaveformData.resample() uses integer scale math.\n const spp = Math.ceil(\n (60 * this.effectiveSampleRate * this.ticksPerPixel) / (this.ppqn * this.bpm)\n );\n // Floor at the peak pipeline's base scale so peaks can always be extracted.\n // Without this, fine zoom levels request a scale finer than what WaveformData\n // can resample to, causing blank waveforms.\n return this._minSamplesPerPixel > 0 ? Math.max(spp, this._minSamplesPerPixel) : spp;\n }\n return this.samplesPerPixel;\n }\n /** Convert seconds to ticks — uses callback if provided, otherwise single-BPM fallback. */\n _secondsToTicks(seconds: number): number {\n if (this.secondsToTicks) {\n if (!this.ticksToSeconds && !this._warnedMissingTicksToSeconds) {\n this._warnedMissingTicksToSeconds = true;\n console.warn(\n '[waveform-playlist] daw-editor: secondsToTicks is set but ticksToSeconds is missing. Both callbacks are required for variable tempo.'\n );\n }\n return this.secondsToTicks(seconds);\n }\n return (seconds * this.bpm * this.ppqn) / 60;\n }\n /** Convert ticks to seconds — uses callback if provided, otherwise single-BPM fallback. */\n _ticksToSeconds(ticks: number): number {\n if (this.ticksToSeconds) {\n if (!this.secondsToTicks && !this._warnedMissingSecondsToTicks) {\n this._warnedMissingSecondsToTicks = true;\n console.warn(\n '[waveform-playlist] daw-editor: ticksToSeconds is set but secondsToTicks is missing. Both callbacks are required for variable tempo.'\n );\n }\n return this.ticksToSeconds(ticks);\n }\n return (ticks * 60) / (this.bpm * this.ppqn);\n }\n /** Clamp limit for annotation boundary edits. indefinite-playback removes the\n * end-of-timeline bound — annotations may extend past the audio (DAW-style\n * unbounded timeline); the shared boundary math treats Infinity as \"no end cap\". */\n get _annotationClampDuration(): number {\n return this.indefinitePlayback ? Infinity : this._duration;\n }\n private get _totalWidth(): number {\n if (this.scaleMode === 'beats') {\n const contentTicks = this._secondsToTicks(this._duration);\n // Floor at 32 bars so the grid is always visible — DAW convention.\n const [num] = this.timeSignature;\n const minTicks = 32 * num * this.ppqn;\n return Math.ceil(Math.max(contentTicks, minTicks) / this.ticksPerPixel);\n }\n // Extend past the natural (clip-derived) duration to cover annotations\n // that reach beyond the audio — DAW-style unbounded timeline (temporal\n // mode only; beats-mode annotation extent is a documented limitation).\n const naturalDuration = Math.max(this._duration, this._annotations.maxAnnotationEndSeconds);\n const naturalWidth = Math.ceil(\n (naturalDuration * this.effectiveSampleRate) / this.samplesPerPixel\n );\n if (this.indefinitePlayback || this.fillViewport) {\n // Fill the visible viewport when natural duration is shorter — lets the\n // ruler render before any audio is loaded. ViewportController exposes\n // the scroll-area's clientWidth (updated on attach + ResizeObserver).\n return Math.max(naturalWidth, this._viewport.containerWidth);\n }\n return naturalWidth;\n }\n /** Grid height when no tracks exist — matches scroll area's rendered height. */\n private get _emptyGridHeight(): number {\n const scrollArea = this.shadowRoot?.querySelector('.scroll-area') as HTMLElement | null;\n return scrollArea?.clientHeight ?? 200;\n }\n _setSelectedTrackId(trackId: string | null) {\n this._selectedTrackId = trackId;\n }\n /**\n * Every track: those in the arrangement, in its order, then those still\n * waiting to enter (#848). A `<daw-track>` whose track an Undo took out of\n * the arrangement is not listed (its descriptor stays for a Redo).\n */\n get tracks(): TrackWithId[] {\n const listed = this._arrangement.getTracks().map((track) => this._listTrack(track));\n // While a handed-in arrangement is played, the page's tracks waiting for\n // the own one are not listed (P15).\n const queue = this._handedIn\n ? this._entryQueue.filter((id) => !this._trackElements.has(id))\n : this._entryQueue;\n const waiting = queue.flatMap((trackId) => {\n const descriptor = this._pendingDescriptor(trackId);\n return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];\n });\n return [...listed, ...waiting];\n }\n /** A track of the arrangement as `editor.tracks` lists it: everything read from the arrangement. */\n private _listTrack(track: ArrangementTrack): TrackWithId {\n const extras = this._extras.get(track.id);\n // Anywhere in the editor: after an Undo of a move a clip's element sits\n // in another track's element (#848).\n const clipEls = new Map<string, DawClipElement>(\n [...this.querySelectorAll('daw-clip')].map((el) => [\n (el as DawClipElement).clipId,\n el as DawClipElement,\n ])\n );\n const sr = this.effectiveSampleRate;\n const clips: ClipDescriptor[] = track.clips.map((clip) => {\n const el = clipEls.get(clip.id);\n const times = clipSeconds(clip, sr);\n const midi = isLoadingClip(clip) ? null : clip;\n const base = {\n src: typeof clip.src === 'string' ? clip.src : '',\n peaksSrc: extras?.peaksSrc.get(clip.id) ?? this._takenPeaksSrc(clip.id) ?? '',\n ...times,\n gain: clip.gain ?? 1,\n name: clip.name ?? '',\n fadeIn: el?.fadeIn ?? 0,\n fadeOut: el?.fadeOut ?? 0,\n fadeType: ((el?.fadeType as FadeType) ?? 'linear') as FadeType,\n midiNotes: midi?.midiNotes ?? null,\n midiChannel: midi?.midiChannel ?? null,\n midiProgram: midi?.midiProgram ?? null,\n };\n return el\n ? { kind: 'dom' as const, clipId: clip.id, ...base }\n : { kind: 'drop' as const, clipId: clip.id, ...base };\n });\n return {\n trackId: track.id,\n name: track.name ?? '',\n src: extras?.src ?? '',\n kind: trackKind(track),\n renderMode: this._renderModeOf(track.id),\n spectrogramConfig: extras?.spectrogramConfig ?? null,\n clips,\n ...this._mixOf(track.id),\n };\n }\n /** A pending track's declaration: its element's attributes and clips now, or its descriptor. */\n private _pendingDescriptor(trackId: string): StoredTrackDescriptor | null {\n const pending = this._pending.get(trackId);\n if (!pending) return null;\n if (!('element' in pending)) return pending.descriptor;\n const read = this._readTrackDescriptor(pending.element);\n return pending.extraClips.length > 0\n ? { ...read, clips: [...read.clips, ...pending.extraClips] }\n : read;\n }\n /** The extras a track of the arrangement takes when the editor has none for it. */\n private _defaultExtras(trackId: string): TrackExtras | null {\n const track = this._arrangementOf(trackId)\n .getTracks()\n .find((t) => t.id === trackId);\n if (!track) return null;\n const kind = trackKind(track);\n return {\n kind,\n renderMode: trackDescriptorRenderMode(kind, 'waveform'),\n src: '',\n peaksSrc: new Map(),\n };\n }\n /** How a track is drawn: its extras, else from its kind (an undo-restored track has none). */\n _renderModeOf(trackId: string): TrackRenderMode {\n const extras = this._extras.get(trackId);\n if (extras) return extras.renderMode;\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n return trackDescriptorRenderMode(track ? trackKind(track) : 'audio', 'waveform');\n }\n /**\n * A track's mix, from its one owner, the arrangement (#843), as the engine\n * plays it: its projection carries the take's mute, which `getMixer()`\n * leaves out (the stored mute comes back when the take ends). A track still\n * waiting to enter shows what its element declares.\n */\n _mixOf(trackId: string): TrackMixerValues {\n const mix = mixOf(this._arrangement, trackId);\n if (mix) return mix;\n const pending = this._pending.get(trackId);\n if (pending && 'mix' in pending) return pending.mix;\n const el = this._trackElements.get(trackId);\n return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;\n }\n // --- Element links (#848, interactions/element-links.ts) ---\n /** @internal */\n _trackLinkState(trackId: string): LinkState {\n // While a handed-in arrangement is set, the children are not played (P7).\n if (this._handedIn && this._trackElements.has(trackId)) return 'detached';\n if (this._isEntered(trackId)) return 'live';\n return this._extras.has(trackId) && !this._pending.has(trackId) ? 'detached' : 'pending';\n }\n /** @internal */\n _clipLinkState(trackId: string, clipId: string): LinkState {\n const track = this._trackLinkState(trackId);\n if (track !== 'live') return track;\n // Linked by id, wherever the element sits (#848: the editor moves no\n // element, so after an Undo of a move it is in another track's element).\n const held = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));\n if (held) return 'live';\n return this._extras.get(trackId)?.peaksSrc.has(clipId) ? 'detached' : 'pending';\n }\n /** @internal The stored mix (not a take's mute) and the name. */\n _trackValues(trackId: string): TrackLinkValues | null {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n const mix = this._arrangement.getMixer().get(trackId);\n if (!track || !mix) return null;\n return { ...mix, name: track.name ?? '' };\n }\n /** @internal */\n _clipValues(trackId: string, clipId: string): ClipLinkValues | null {\n const clip = this._arrangement\n .getTracks()\n .find((t) => t.id === this._clipHolderId(trackId, clipId))\n ?.clips.find((c) => c.id === clipId);\n if (!clip) return null;\n const midi = isLoadingClip(clip) ? null : clip;\n return {\n ...clipSeconds(clip, this.effectiveSampleRate),\n gain: clip.gain ?? 1,\n name: clip.name ?? '',\n midiNotes: midi?.midiNotes ?? null,\n midiChannel: midi?.midiChannel ?? null,\n midiProgram: midi?.midiProgram ?? null,\n };\n }\n /** @internal A property or attribute set on a live `<daw-track>`: one undo step per field kind. */\n _requestTrackChange(trackId: string, partial: Partial<TrackLinkValues>): void {\n const { name, ...mix } = partial;\n if (Object.keys(mix).length > 0) this._writeMixFields(trackId, mix, this._taskGesture(trackId));\n if (name !== undefined) this._renameTrack(trackId, name || 'Untitled');\n }\n /** One gesture id per track for the rest of this task: mix sets made together are one step (#843). */\n private _taskGestures = new Map<string, string>();\n private _taskGesture(trackId: string): string {\n let id = this._taskGestures.get(trackId);\n if (!id) {\n id = createMixerGesture().id;\n this._taskGestures.set(trackId, id);\n if (this._taskGestures.size === 1) queueMicrotask(() => this._taskGestures.clear());\n }\n return id;\n }\n /** @internal A property or attribute set on a live `<daw-clip>`: one undo step. */\n _requestClipChange(trackId: string, clipId: string, partial: Partial<ClipLinkValues>): void {\n const current = this._clipValues(trackId, clipId);\n if (!current) return;\n const holderId = this._clipHolderId(trackId, clipId);\n const clip = this._arrangement\n .getTracks()\n .find((t) => t.id === holderId)\n ?.clips.find((c) => c.id === clipId);\n const src = clip && typeof clip.src === 'string' ? clip.src : '';\n this._applyClipUpdate(holderId, clipId, { ...current, ...partial, src });\n }\n /**\n * The clips of an entering track that another track of the arrangement\n * holds (the page moved their `<daw-clip>` here while the track waited):\n * the track takes the held clip as it is, and `from` names what leaves\n * where. A held clip of the other kind is refused and stays.\n */\n private _takeOverMovedClips(\n trackId: string,\n track: ArrangementTrack\n ): {\n track: ArrangementTrack;\n from: Map<string, Set<string>>;\n movedIds: Set<string>;\n refused: Array<{ clipId: string; error: Error }>;\n } {\n const from = new Map<string, Set<string>>();\n const movedIds = new Set<string>();\n const refused: Array<{ clipId: string; error: Error }> = [];\n const others = this._arrangement.getTracks().filter((t) => t.id !== trackId);\n const kind = trackKind(track);\n const clips: ArrangementTrack['clips'] = [];\n for (const clip of track.clips) {\n const holder = others.find((t) => t.clips.some((c) => c.id === clip.id));\n const held = holder?.clips.find((c) => c.id === clip.id);\n if (!holder || !held) {\n clips.push(clip);\n continue;\n }\n const isMidi = 'midiNotes' in held && held.midiNotes != null;\n const error = clipKindError(track.name ?? '', kind, isMidi, held.name || held.id);\n if (error) {\n refused.push({ clipId: clip.id, error });\n continue;\n }\n clips.push(held);\n movedIds.add(clip.id);\n const ids = from.get(holder.id) ?? new Set<string>();\n from.set(holder.id, ids.add(clip.id));\n }\n return {\n track: movedIds.size || refused.length ? { ...track, clips } : track,\n from,\n movedIds,\n refused,\n };\n }\n /** Run `fn` as one undo step of each arrangement it changes. */\n private _inOneStep(arrangements: readonly Arrangement[], fn: () => void): void {\n for (const a of arrangements) a.beginTransaction();\n try {\n fn();\n } finally {\n for (const a of arrangements) a.commitTransaction();\n }\n }\n /** The `peaks-src` some track took for a clip element, if any. */\n private _takenPeaksSrc(clipId: string): string | undefined {\n for (const extras of this._extras.values()) {\n const peaksSrc = extras.peaksSrc.get(clipId);\n if (peaksSrc !== undefined) return peaksSrc;\n }\n return undefined;\n }\n /**\n * The arrangement whose history holds a track: the one that holds it now,\n * or else, for a page track, the own one (an Undo took it out there; a\n * handed-in arrangement may be played meanwhile), or else the one played.\n */\n private _historyOf(trackId: string, isPageTrack = this._trackElements.has(trackId)): Arrangement {\n const holder = this._arrangementOf(trackId);\n if (holder.getTracks().some((t) => t.id === trackId)) return holder;\n return isPageTrack ? this._ownArrangement : holder;\n }\n /** The track of the arrangement played that holds a clip: `trackId` when it does, or else the one that does. */\n private _clipHolderId(trackId: string, clipId: string): string {\n const tracks = this._arrangement.getTracks();\n if (tracks.some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId)))\n return trackId;\n return tracks.find((t) => t.clips.some((c) => c.id === clipId))?.id ?? trackId;\n }\n /** @internal */\n _trackKind(trackId: string): TrackKind | null {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n return track ? trackKind(track) : null;\n }\n /** @internal */\n _trackIndex(trackId: string): number {\n return this._arrangement.getTracks().findIndex((t) => t.id === trackId);\n }\n /** @internal */\n _detachedReason(): string {\n return this._handedIn\n ? 'a handed-in arrangement is set (editor.arrangement)'\n : 'its track or clip is not in the arrangement the editor plays';\n }\n /** Set or clear `:state(detached)` on every registered element (#848). */\n private _refreshLinkStates(): void {\n refreshLinkStates(this, this._trackElements);\n }\n /**\n * Change one mixer field of a track: the arrangement's setter with\n * `options` (an undo step; changes with one `gesture` id are one step). A\n * track that has not entered yet changes nothing.\n */\n private _writeMix<K extends keyof TrackMixerValues>(\n trackId: string,\n field: K,\n value: TrackMixerValues[K],\n options?: MixerChangeOptions\n ): void {\n const arrangement = this._arrangement;\n if (field === 'volume') arrangement.setTrackVolume(trackId, value as number, options);\n else if (field === 'pan') arrangement.setTrackPan(trackId, value as number, options);\n else if (field === 'muted') arrangement.setTrackMute(trackId, value as boolean, options);\n else if (field === 'soloed') arrangement.setTrackSolo(trackId, value as boolean, options);\n // A decided track does not go back to 'auto' (#684): only a law is a request.\n else if (field === 'panLaw' && isDecidedPanLaw(value)) {\n arrangement.setTrackPanLaw(trackId, value, options);\n }\n }\n /**\n * Change the given mixer fields of a track as ONE undo step (#843): all\n * of them carry one fresh gesture id. A field left out is not sent.\n */\n private _writeMixFields(\n trackId: string,\n mix: Partial<TrackMixerValues>,\n gesture: string = createMixerGesture().id\n ): void {\n const options: MixerChangeOptions = { gesture };\n if (mix.volume !== undefined) this._writeMix(trackId, 'volume', mix.volume, options);\n if (mix.pan !== undefined) this._writeMix(trackId, 'pan', mix.pan, options);\n if (mix.muted !== undefined) this._writeMix(trackId, 'muted', mix.muted, options);\n if (mix.soloed !== undefined) this._writeMix(trackId, 'soloed', mix.soloed, options);\n if (mix.panLaw !== undefined) this._writeMix(trackId, 'panLaw', mix.panLaw, options);\n }\n get selectedTrackId(): string | null {\n return this._selectedTrackId;\n }\n get selection(): { start: number; end: number } | null {\n if (this._selectionStartTime === 0 && this._selectionEndTime === 0) return null;\n return { start: this._selectionStartTime, end: this._selectionEndTime };\n }\n setSelection(start: number, end: number) {\n this._selectionStartTime = Math.min(start, end);\n this._selectionEndTime = Math.max(start, end);\n if (this._engine) {\n this._engine.setSelection(this._selectionStartTime, this._selectionEndTime);\n }\n this.requestUpdate();\n this.dispatchEvent(\n new CustomEvent<DawSelectionDetail>('daw-selection', {\n bubbles: true,\n composed: true,\n detail: { start: this._selectionStartTime, end: this._selectionEndTime },\n })\n );\n }\n // --- Lifecycle ---\n connectedCallback() {\n super.connectedCallback();\n if (this._connection.signal.aborted) this._connection = new AbortController();\n // Follow the arrangement played again (a disconnect let it go, #848),\n // and show what changed meanwhile (an Undo made while out of the page).\n this._follow(this._arrangement);\n this._refreshLinkStates();\n // Every listener of this connection goes with its signal (D8).\n const { signal } = this._connection;\n // Capture on window: runs before <daw-keyboard-shortcuts>' document listener.\n window.addEventListener('keydown', this._onDragEscape, { capture: true, signal });\n this.addEventListener('daw-track-connected', this._onTrackConnected as EventListener, {\n signal,\n });\n this.addEventListener('daw-track-update', this._onTrackUpdate as EventListener, { signal });\n this.addEventListener('daw-track-control', this._onTrackControl as EventListener, { signal });\n this.addEventListener('daw-track-remove', this._onTrackRemoveRequest as EventListener, {\n signal,\n });\n this.addEventListener('daw-clip-connected', this._onClipConnected as EventListener, {\n signal,\n });\n this.addEventListener(\n 'daw-annotation-track-connected',\n this._onAnnotationTrackConnected as EventListener,\n { signal }\n );\n this.addEventListener('daw-annotation-select', this._onAnnotationSelect as EventListener, {\n signal,\n });\n this.addEventListener('daw-track-reorder', this._onTrackReorder as EventListener, { signal });\n this.addEventListener('daw-track-reorder-grab', this._onTrackReorderGrab as EventListener, {\n signal,\n });\n // Detect track + clip removal via MutationObserver (detached elements can't\n // bubble events). A node present in BOTH removedNodes and addedNodes within\n // one batch is a MOVE (insertBefore fires remove+insert) — treated as a\n // reorder, never a teardown (#612).\n this._childObserver = new MutationObserver((mutations) => {\n const removedTracks = new Map<string, DawTrackElement>();\n const removedClips = new Set<DawClipElement>();\n // The clips that left inside a removed <daw-track>, by its id.\n const clipsOfRemoved = new Map<string, DawClipElement[]>();\n const addedTrackIds = new Set<string>();\n for (const mutation of mutations) {\n for (const node of mutation.addedNodes) {\n if (!(node instanceof HTMLElement)) continue;\n if (node.tagName === 'DAW-TRACK') {\n addedTrackIds.add((node as DawTrackElement).trackId);\n }\n node.querySelectorAll?.('daw-track').forEach((t) => {\n addedTrackIds.add((t as DawTrackElement).trackId);\n });\n }\n for (const node of mutation.removedNodes) {\n if (!(node instanceof HTMLElement)) continue;\n if (node.tagName === 'DAW-TRACK') {\n removedTracks.set((node as DawTrackElement).trackId, node as DawTrackElement);\n } else if (node.tagName === 'DAW-CLIP') {\n removedClips.add(node as DawClipElement);\n }\n node.querySelectorAll?.('daw-track').forEach((t) => {\n removedTracks.set((t as DawTrackElement).trackId, t as DawTrackElement);\n });\n node.querySelectorAll?.('daw-clip').forEach((c) => {\n removedClips.add(c as DawClipElement);\n });\n for (const t of node.tagName === 'DAW-TRACK'\n ? [node]\n : [...(node.querySelectorAll?.('daw-track') ?? [])]) {\n clipsOfRemoved.set((t as DawTrackElement).trackId, [\n ...t.querySelectorAll('daw-clip'),\n ] as DawClipElement[]);\n }\n }\n }\n const movedTrackIds = new Set<string>();\n for (const [trackId] of removedTracks) {\n if (addedTrackIds.has(trackId)) {\n movedTrackIds.add(trackId); // move, not removal\n continue;\n }\n // The track and what its children declared are one undo step: a\n // child may be the element of another track's clip (after an Undo\n // of a move), which goes with it (the maintainer's choice, #848).\n const children = (clipsOfRemoved.get(trackId) ?? []).filter((c) => !c.isConnected);\n // Only the arrangement that holds the track (a page track's children\n // declare clips of the same one): an app's open transaction on\n // another is left alone (review of #919).\n this._inOneStep([this._historyOf(trackId)], () => {\n this._onTrackRemoved(trackId);\n for (const clip of children) {\n removedClips.delete(clip);\n this._onClipRemovedFromDom(clip);\n }\n });\n }\n for (const clip of removedClips) {\n // A clip that moved with its track, or into another track of this\n // editor (its connected event moves it, #848), is still here. One\n // moved out of the editor goes.\n if (clip.isConnected && this.contains(clip)) continue;\n this._onClipRemovedFromDom(clip);\n }\n if (movedTrackIds.size > 0) this._placeMovedTracks(movedTrackIds);\n });\n this._childObserver.observe(this, { childList: true, subtree: true });\n // A <daw-track> the page removed while the editor was detached (the\n // observer was off): its track goes now, as the observer would have done\n // (#917; `_trackElements` is kept across a disconnect).\n for (const [trackId, el] of [...this._trackElements]) {\n if (!this.contains(el)) this._onTrackRemoved(trackId);\n }\n // ... and a <daw-clip> the page removed meanwhile: its clip goes (#848).\n // Present anywhere in the editor: an element may sit in another track's\n // element than the one holding its clip (an Undo of a move, #848).\n const present = new Set(\n [...this.querySelectorAll('daw-clip')].map((c) => (c as DawClipElement).clipId as string)\n );\n for (const [trackId] of this._trackElements) {\n for (const clipId of this._extras.get(trackId)?.peaksSrc.keys() ?? []) {\n if (present.has(clipId)) continue;\n // The track that holds the clip, which may be another one than the\n // element's (an Undo of a move, #848): the removal takes it from there.\n const holder = this._historyOf(trackId)\n .getTracks()\n .find((t) => t.clips.some((c) => c.id === clipId));\n if (holder) {\n this._removeClipFromTrack(holder.id, clipId);\n this._forgetClip(trackId, clipId);\n } else this._dropUnheldClip(trackId, clipId);\n }\n }\n if (this._externalAdapter && !this._engine) this._buildEngineReporting();\n }\n disconnectedCallback() {\n super.disconnectedCallback();\n // A removed editor does not follow its arrangement: a handed-in one would\n // keep it alive and run its listeners (review of #919).\n this._unfollow();\n this._unfollow = () => {};\n // The listeners of this connection go, and its waits end: a track's\n // load wait resolves (the track is kept and loads after a reparent).\n this._connection.abort(abortError('<daw-editor> was disconnected'));\n this._effectsManager?.disposeAll();\n this._effectsManager = null;\n // Before the engine is disposed: every pointer interaction ends here.\n this._cancelDrags(true);\n // No audio loads while detached (the decode context goes with the\n // engine). A dropped file whose track has entered is kept and counts as\n // loaded (the connection's abort above ended its wait): it loads after a\n // reparent, like the page's tracks (maintainer, #917). One not entered\n // yet is not added.\n for (const trackId of this._entryQueue) {\n const pending = this._pending.get(trackId);\n if (!pending || 'element' in pending || !this._entryWaiters.has(trackId)) continue;\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._entryQueue = this._entryQueue.filter((id) => id !== trackId);\n this._settleEntry(\n trackId,\n new Error('<daw-editor> was disconnected before the file entered')\n );\n }\n this._childObserver?.disconnect();\n this._childObserver = null;\n // `_trackElements` is kept (#917): the build on a fresh adapter can run\n // before the children's deferred reconnect, and its descriptor reconcile\n // must still see which tracks have an element.\n this._peaksCache.clear();\n // The worker goes; the pipeline makes a new one on its next use.\n this._peakPipeline.terminate();\n this._spectrogramController?.dispose();\n this._spectrogramController = null;\n this._lastSpectrogramViewport = null;\n const hadEngine = this._engine !== null;\n try {\n this._disposeEngine();\n } catch (err) {\n console.warn('[dawcore] Error disposing engine: ' + String(err));\n }\n // engine.dispose() disposed the CONSUMER's adapter. Some adapters\n // (NativePlayoutAdapter) leave the AudioContext open, so building on it\n // again would decode into a dead transport graph: waveforms, no audio.\n // The editor lets go of it; a fresh editor.adapter builds a new engine\n // on the kept arrangement (#848).\n if (hadEngine) {\n this._externalAdapter = null;\n }\n // The arrangement stays, as a moved <input> keeps its value (#848), and\n // so do the descriptors and the peak caches that draw it: the editor\n // shows its tracks while detached, and a fresh adapter plays them. The\n // children's reconnect finds their descriptors and enters nothing again.\n }\n willUpdate(changedProperties: Map<string, unknown>) {\n if (changedProperties.has('eagerResume')) {\n this._audioResume.target = this.eagerResume;\n }\n // Restart playhead animation when zoom or beats params change during playback\n if (\n (changedProperties.has('samplesPerPixel') ||\n changedProperties.has('ticksPerPixel') ||\n changedProperties.has('bpm') ||\n changedProperties.has('secondsToTicks')) &&\n this._isPlaying\n ) {\n this._startPlayhead();\n }\n // Re-extract peaks at new zoom level from cached WaveformData (near-instant).\n // For worker-generated peaks, baseScale (128) is finest; for pre-computed .dat\n // peaks (only cached when rates match), the file's scale is the limit.\n // In beats mode, _renderSpp changes when ticksPerPixel or bpm changes.\n // `mono` changes the derived peak data too (per-channel vs merged) —\n // without it here, toggling mono keeps the stale channel layout until\n // the next zoom change, then snaps mid-session.\n const peaksInputChanged =\n changedProperties.has('samplesPerPixel') ||\n changedProperties.has('ticksPerPixel') ||\n changedProperties.has('bpm') ||\n changedProperties.has('scaleMode') ||\n changedProperties.has('secondsToTicks') ||\n changedProperties.has('mono');\n if (peaksInputChanged && this._clipBuffers.size > 0) {\n const re = this._peakPipeline.reextractPeaks(\n this._clipBuffers,\n this._renderSpp,\n this.mono,\n this._clipOffsets\n );\n if (re.size > 0) {\n const next = new Map(this._peaksData);\n for (const [id, pd] of re) next.set(id, pd);\n this._peaksData = next;\n }\n }\n }\n\n /**\n * Cache of the last ViewportState forwarded to the spectrogram controller.\n * Lit's `updated()` fires on every reactive state change (`_isPlaying`,\n * `_selectedTrackId`, etc.) — most of which don't affect the spectrogram\n * viewport. Skip the cross-controller call when nothing changed.\n *\n * The orchestrator dedupes identical viewports too, so removing this cache\n * wouldn't change observable behavior — but it would push a fresh\n * `setViewport` call (with object allocation) into every Lit reactive\n * update for properties unrelated to the viewport.\n */\n private _lastSpectrogramViewport: {\n vs: number;\n ve: number;\n spp: number;\n } | null = null;\n\n protected updated(_changed: Map<string, unknown>): void {\n // Keep selectors truthful so the controller can distinguish \"intentionally\n // not rendered\" from \"selector broken\" (it warns on the latter when scrolled).\n this._scrollSync.xTargetSelector = this._showRuler ? '.ruler-content' : '';\n this._scrollSync.yTargetSelector = this._showControls ? '.controls-column' : '';\n this._scrollSync.wheelForwardSelector = [\n this._showControls ? '.controls-viewport' : '',\n this._showRuler ? '.ruler-viewport' : '',\n ]\n .filter(Boolean)\n .join(', ');\n // Re-applies transforms clobbered by the .ruler-content style binding —\n // Lit rewrites the style attribute (width) on _totalWidth changes, wiping\n // the imperatively-set transform. Must run before paint on every update.\n this._scrollSync.sync();\n // Forward viewport + zoom into the spectrogram controller on every update\n // so scroll, resize, and zoom all trigger orchestrator.setViewport.\n if (this._spectrogramController) {\n const vs = this._viewport.visibleStart;\n const ve = this._viewport.visibleEnd;\n const spp = this._renderSpp;\n if (Number.isFinite(vs) && Number.isFinite(ve)) {\n const prev = this._lastSpectrogramViewport;\n if (prev && prev.vs === vs && prev.ve === ve && prev.spp === spp) return;\n this._lastSpectrogramViewport = { vs, ve, spp };\n const span = ve - vs;\n const bufferPad = span * 0.25;\n this._spectrogramController.setViewport({\n visibleStartPx: vs,\n visibleEndPx: ve,\n bufferStartPx: Math.max(0, vs - bufferPad),\n bufferEndPx: ve + bufferPad,\n samplesPerPixel: spp,\n });\n }\n }\n }\n\n // --- Annotation Events ---\n private _onAnnotationTrackConnected = (e: CustomEvent<{ element: HTMLElement }>) => {\n this._annotations.handleTrackConnected(e.detail.element as DawAnnotationTrackElement);\n };\n private _onAnnotationSelect = (e: CustomEvent<{ annotation: { start: number } | null }>) => {\n const annotation = e.detail.annotation;\n if (!annotation) return;\n const scrollArea = this.shadowRoot?.querySelector('.scroll-area') as HTMLElement | null;\n if (!scrollArea) return;\n const px = Math.floor((annotation.start * this.effectiveSampleRate) / this._renderSpp);\n scrollArea.scrollLeft = Math.max(0, px - scrollArea.clientWidth / 2);\n };\n\n // --- Track Events ---\n private _onTrackConnected = (e: CustomEvent) => {\n const trackId = e.detail?.trackId;\n const trackEl = e.detail?.element;\n if (!trackId || !(trackEl instanceof HTMLElement)) {\n console.warn('[dawcore] Invalid daw-track-connected event detail: ' + String(e.detail));\n return;\n }\n // A DOM MOVE sends daw-track-connected again for the SAME trackId: an\n // insertBefore runs disconnectedCallback+connectedCallback, a\n // moveBefore() runs connectedMoveCallback, and both announce (#848). If the track is\n // already registered (loading or fully loaded), this is a reconnect from\n // a move, not a first-time registration: refresh the element mapping and\n // bail out WITHOUT re-reading the descriptor or entering it again. The\n // same holds when the EDITOR itself was reparented: the disconnect keeps\n // the arrangement and the descriptors (#848), so the children's\n // reconnect enters nothing again, also a track an Undo took out.\n if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n return;\n }\n // Its declaration is read when it enters (#848 PR 3).\n this._pending = new Map(this._pending).set(trackId, {\n element: trackEl as DawTrackElement,\n extraClips: [],\n });\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n // It enters the arrangement at the next flush, in DOM position (#848).\n this._queueEntry(trackId);\n };\n private _onTrackRemoved(trackId: string) {\n // Captured before the cleanup below — gates the outbound event so it only\n // fires for a track that was actually registered.\n const existed =\n this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId);\n // Detached (an Undo of its arrival): gone for good, also from the undo\n // and redo states (maintainer's choice, #848).\n const isPageTrack = this._trackElements.has(trackId);\n const history = this._historyOf(trackId, isPageTrack);\n const detached =\n this._extras.has(trackId) &&\n !this._pending.has(trackId) &&\n !history.getTracks().some((t) => t.id === trackId);\n const detachedClipIds = detached ? [...(this._extras.get(trackId)?.peaksSrc.keys() ?? [])] : [];\n // An addClip() waiting for a clip of this track would never settle (the\n // clip may not even have connected yet): reject it (#917).\n this._rejectAwaitedClips(\n (_, awaitedTrackId) => awaitedTrackId === trackId,\n 'the track of the clip was removed before the clip loaded'\n );\n this._entryQueue = this._entryQueue.filter((id) => id !== trackId);\n this._settleEntry(trackId, new Error('track \"' + trackId + '\" was removed before it entered'));\n // A page track removed while a handed-in arrangement is played is the own one's (P7).\n const holder = this._arrangementOf(trackId);\n const arrangementTrack = holder.getTracks().find((t) => t.id === trackId);\n const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];\n this._announcer.forget(trackId, clipIds);\n if (clipIds.some((id) => this._previewPeaks.has(id))) {\n const nextPreview = new Map(this._previewPeaks);\n for (const id of clipIds) nextPreview.delete(id);\n this._previewPeaks = nextPreview;\n }\n for (const id of clipIds) this._previewWaveforms.delete(id);\n this._trackElements.delete(trackId);\n this._effectsManager?.disposeTrackChain(trackId);\n // Clean up per-clip data before removing the track\n if (arrangementTrack) {\n const nextPeaks = new Map(this._peaksData);\n for (const clip of arrangementTrack.clips) {\n this._clipBuffers.delete(clip.id);\n this._clipOffsets.delete(clip.id);\n nextPeaks.delete(clip.id);\n this._spectrogramController?.unregisterClipAudio(clip.id);\n }\n this._peaksData = nextPeaks;\n }\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n const nextExtras = new Map(this._extras);\n nextExtras.delete(trackId);\n this._extras = nextExtras;\n // An undo step; the engine follows (incremental removal, playback goes on).\n if (arrangementTrack) holder.removeTrack(trackId);\n else if (detached) {\n history.removeTrack(trackId, { undoable: false });\n for (const id of detachedClipIds) {\n this._purgeClipCaches(id);\n this._previewWaveforms.delete(id);\n }\n }\n this._recomputeDuration();\n // Recompute zoom floor from remaining cached WaveformData scales\n this._recomputeZoomFloor();\n this._disposeSpectrogramControllerIfEmpty();\n // `existed` gate: the MutationObserver fires this for never-registered\n // <daw-track> churn too (element added+removed before its deferred\n // connect) — that must not rewind the user's cursor on an empty timeline.\n if (existed && this._arrangement.getTracks().length === 0) {\n if (this._engine) {\n // The editor rewinds to 0 when the last track goes away — the engine\n // must follow (engine.removeTrack never touches time), or the next\n // play() resumes from the stale position while the display shows 0.\n // Stop first if rolling: an empty timeline has nothing to play, and\n // without it isPlaying stays true with a dead playhead RAF. Suppress\n // the stop settle — the final resting position is 0, dispatched by\n // _stopPlayhead below.\n if (this._isPlaying) {\n this._withSeekSuppression(() => this._engine!.stop());\n // Announce like every other stop path — transport UIs key on\n // daw-play/daw-stop, and editor.stop() (the usual dispatcher) is\n // bypassed here.\n this.dispatchEvent(new CustomEvent('daw-stop', { bubbles: true, composed: true }));\n }\n this._engine.seek(0);\n }\n this._currentTime = 0;\n this._stopPlayhead();\n }\n // Outbound notification (symmetric with daw-track-ready) — fired after\n // the removal so handlers reading editor.tracks see it.\n // Only for a track that was registered, and never on a detached editor\n // (a bubbling/composed event can't reach ancestors — CLAUDE.md pattern #36).\n if (existed && this.isConnected) {\n this.dispatchEvent(\n new CustomEvent<DawTrackIdDetail>('daw-track-removed', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n }\n }\n private _onTrackUpdate = (e: CustomEvent<DawTrackUpdateDetail>) => {\n const trackId = e.detail?.trackId;\n if (!trackId) return;\n const trackEl = (e.target as HTMLElement).closest('daw-track') as DawTrackElement | null;\n if (!trackEl) return;\n // A track that has not entered is read when it enters; one an Undo took\n // out keeps what it had (#848).\n const old = this._extras.get(trackId);\n if (!old || !this._isEntered(trackId)) return;\n const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];\n // A `kind` change after entry is refused by the element itself (its\n // live property warns, #848).\n // Only what this update changed: an unrelated change (a volume) must\n // not put back a render mode or a config `updateTrack` gave the track.\n const next: TrackExtras = {\n ...old,\n ...(changed.includes('renderMode') && {\n renderMode: trackDescriptorRenderMode(old.kind, trackEl.renderMode),\n }),\n ...(changed.includes('spectrogramConfig') && {\n spectrogramConfig: trackEl.spectrogramConfig,\n }),\n ...(changed.includes('src') && { src: trackEl.src }),\n };\n this._extras = new Map(this._extras).set(trackId, next);\n // The mix and the name are not handled here: the element's setters ask\n // the arrangement directly (#848, element-links.ts).\n if (old.src !== next.src) this._replaceShorthandClips(trackId, trackEl);\n const loaded = this._loadedTracks().find((t) => t.id === trackId)?.clips ?? [];\n // Track switched into spectrogram mode — push existing clip audio into the controller.\n if (next.renderMode === 'spectrogram' && old.renderMode !== 'spectrogram') {\n for (const clip of loaded) this._maybeRegisterSpectrogramClipAudio(trackId, clip);\n }\n // Track switched OUT of spectrogram mode — drop clip audio.\n if (next.renderMode !== 'spectrogram' && old.renderMode === 'spectrogram') {\n if (this._spectrogramController) {\n for (const clip of loaded) this._spectrogramController.unregisterClipAudio(clip.id);\n }\n this._disposeSpectrogramControllerIfEmpty();\n }\n if (next.spectrogramConfig !== old.spectrogramConfig) {\n this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);\n }\n };\n /** The arrangement that holds a track: the one played, else the own one (a page track while handed in). */\n private _arrangementOf(trackId: string): Arrangement {\n const has = (a: Arrangement) => a.getTracks().some((t) => t.id === trackId);\n return has(this._arrangement) || !has(this._ownArrangement)\n ? this._arrangement\n : this._ownArrangement;\n }\n /** Rename a track in the arrangement (an undo step); the same name changes nothing. */\n private _renameTrack(trackId: string, name: string): void {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n if (!track || track.name === name) return;\n this._arrangement.updateTrack(trackId, (current) => ({ ...current, name }));\n }\n\n /** Drop the controller when no spectrogram tracks remain. */\n private _disposeSpectrogramControllerIfEmpty(): void {\n if (!this._spectrogramController) return;\n const stillNeeded = Array.from(this._extras.values()).some(\n (d) => d.renderMode === 'spectrogram'\n );\n if (!stillNeeded) {\n this._spectrogramController.dispose();\n this._spectrogramController = null;\n // A recreated controller diffs new viewports against this cache — a\n // stale entry suppresses the fresh orchestrator's initial setViewport\n // and every canvas stays black until a >=100px scroll or zoom change.\n this._lastSpectrogramViewport = null;\n }\n }\n\n private static _CONTROL_PROPS = new Set(['volume', 'pan', 'muted', 'soloed']);\n private _onTrackControl = (e: CustomEvent<Partial<DawTrackControlDetail>>) => {\n const { trackId, prop, value, gesture } = e.detail ?? {};\n if (!trackId || !prop || !DawEditorElement._CONTROL_PROPS.has(prop)) return;\n // Select the track when interacting with its controls\n if (this._selectedTrackId !== trackId) {\n this._setSelectedTrackId(trackId);\n if (this._engine) {\n this._engine.selectTrack(trackId);\n }\n this.dispatchEvent(\n new CustomEvent('daw-track-select', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n }\n if (this._isEntered(trackId)) {\n // Validated values to the arrangement's setters (also while the track\n // loads, #848). A slider's gesture id makes its drag one undo step\n // (#843); a control without one (mute, solo) is a step per event.\n const options: MixerChangeOptions | undefined =\n typeof gesture === 'string' ? { gesture } : undefined;\n if (prop === 'volume') this._writeMix(trackId, 'volume', clampNumber(value, 0, 1), options);\n if (prop === 'pan') this._writeMix(trackId, 'pan', clampNumber(value, -1, 1), options);\n if (prop === 'muted') this._writeMix(trackId, 'muted', Boolean(value), options);\n if (prop === 'soloed') this._writeMix(trackId, 'soloed', Boolean(value), options);\n }\n // Don't sync back to <daw-track> DOM element — avoids daw-track-update loop.\n // The arrangement holds the control values.\n };\n private _onTrackRemoveRequest = (e: CustomEvent) => {\n const { trackId } = e.detail ?? {};\n if (!trackId) return;\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n trackEl.remove(); // MutationObserver will trigger _onTrackRemoved\n } else {\n this._onTrackRemoved(trackId); // File-dropped tracks: no DOM element\n }\n };\n // --- Clip lifecycle ---\n private _onClipConnected = (e: CustomEvent) => {\n const detail = e.detail as { clipId: string; element: DawClipElement };\n const clipEl = detail.element;\n if (!(clipEl instanceof HTMLElement)) return;\n const trackEl = clipEl.closest('daw-track') as DawTrackElement | null;\n if (!trackEl) return;\n const trackId = trackEl.trackId;\n // Moved here from another track of this editor (#848, choice a): the\n // clip moves with it, one undo step.\n if (this._rehomeClip(trackId, clipEl)) return;\n // The arrangement that holds the track: the own one for a page track\n // while a handed-in arrangement is played (the children declare it, P7).\n const entered = this._arrangementOf(trackId)\n .getTracks()\n .some((t) => t.id === trackId);\n if (!entered && !this._pending.has(trackId) && this._trackLinkState(trackId) === 'detached') {\n // Added under a detached track (an Undo of its arrival): it never\n // enters, also after a Redo. It is taken, so it shows detached\n // (maintainer's choice, #848).\n this._takeClip(trackId, clipEl.clipId, clipEl.peaksSrc || '');\n console.warn(\n detachedWarning(\n '<daw-track> \"' + (trackEl.name || 'Untitled') + '\"',\n 'a <daw-clip> added to it',\n this._detachedReason()\n )\n );\n this._rejectAwaitedClips(\n (id) => id === clipEl.clipId,\n 'addClip: track \"' + trackId + '\" is detached'\n );\n this._refreshLinkStates();\n return;\n }\n if (!entered) {\n // Neither entered nor waiting to enter: an Undo took the track out\n // between an addClip() and this deferred connect, or the arrangement\n // refused it. Nothing will take the clip, so its addClip() is rejected\n // (#917). A track waiting to enter reads its <daw-clip> children when\n // it enters (#848 PR 3), this one included.\n if (!this._entryQueue.includes(trackId)) {\n this._rejectAwaitedClips(\n (id) => id === clipEl.clipId,\n 'addClip: track \"' + trackId + '\" is not in the editor (an Undo took it out)'\n );\n }\n return;\n }\n // A clip the editor took already: read when its track entered (this is\n // its own deferred connect), or a reconnect from a DOM move (custom\n // elements fire disconnectedCallback+connectedCallback on insertBefore).\n if (this._extras.get(trackId)?.peaksSrc.has(clipEl.clipId)) return;\n this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));\n };\n /**\n * A `<daw-clip>` now under `trackId` whose clip another track holds: the\n * clip moves to this track (one undo step) when both have entered the same\n * arrangement; a clip of the other kind stays with `daw-clip-error`.\n * Otherwise the old track lets it go and the element goes on as a new\n * arrival. Returns true when nothing more is to be done.\n */\n private _rehomeClip(trackId: string, clipEl: DawClipElement): boolean {\n const clipId = clipEl.clipId;\n // Declared here already (its own deferred connect, a move inside the\n // track, an Undo that left the element here): not a move.\n if (this._extras.get(trackId)?.peaksSrc.has(clipId)) return true;\n // The arrangement whose history holds the track: the own one for a page\n // track that is waiting or detached while a handed-in one is played.\n const arrangement = this._historyOf(trackId);\n // Back in the track that holds its clip (the page moved it back after an\n // Undo of its move): what the other tracks took comes here.\n if (\n arrangement.getTracks().some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId))\n ) {\n let peaksSrc = clipEl.peaksSrc || '';\n for (const [id, extras] of this._extras) {\n if (id === trackId || !extras.peaksSrc.has(clipId)) continue;\n peaksSrc = extras.peaksSrc.get(clipId) ?? peaksSrc;\n this._forgetClip(id, clipId);\n }\n this._takeClip(trackId, clipId, peaksSrc);\n return true;\n }\n const fromTrackId = trackHoldingClip(arrangement, clipId, trackId);\n if (!fromTrackId) {\n // Taken by another track of this editor and not held now: that one forgets it.\n for (const [id, extras] of this._extras) {\n if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);\n }\n return false;\n }\n const entered = arrangement.getTracks().some((t) => t.id === trackId);\n // Into a track waiting to enter: the clip moves when it enters, as it is,\n // with its arrival (the maintainer's choice c, #848; _enterTrack).\n if (!entered && this._pending.has(trackId)) return true;\n const toExtras = this._extras.get(trackId) ?? this._defaultExtras(trackId);\n if (!entered || !toExtras) {\n // Into a detached track (an Undo took its arrival): refused. The clip\n // stays where it is; the element is taken here, shows detached, and is\n // linked to its clip by id once a Redo brings the track back.\n this._takeClip(trackId, clipId, this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? '');\n console.warn(\n '[dawcore] <daw-clip> cannot move into <daw-track> \"' +\n (this._trackElements.get(trackId)?.name || 'Untitled') +\n '\": the track is not in the arrangement (an Undo took it out). Its clip stays in its track.'\n );\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n clipId,\n error: new Error('track \"' + trackId + '\" is not in the arrangement'),\n },\n })\n );\n this._refreshLinkStates();\n return true;\n }\n const error = moveClipToTrack(arrangement, fromTrackId, trackId, clipId, toExtras.kind);\n if (error) {\n // Refused (a clip of the other kind): nothing changes, no undo step,\n // and the element stays where the page put it (the editor moves no\n // element, #848). It is taken here too, so a later announcement does\n // not try again, and it stays linked to its clip by id.\n this._takeClip(trackId, clipId, this._extras.get(fromTrackId)?.peaksSrc.get(clipId) ?? '');\n console.warn(\n '[dawcore] <daw-clip> cannot move to track \"' +\n (this._trackElements.get(trackId)?.name || 'Untitled') +\n '\" (' +\n String(error) +\n '): its clip stays in its track.'\n );\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error },\n })\n );\n return true;\n }\n const peaksSrc = this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? '';\n // Every other track that took the element forgets it: after an Undo of\n // a move it is still taken where it sat (review of #919, round 2).\n for (const [id, extras] of this._extras) {\n if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);\n }\n if (!this._extras.has(trackId)) this._extras = new Map(this._extras).set(trackId, toExtras);\n this._takeClip(trackId, clipId, peaksSrc);\n return true;\n }\n private _onClipRemovedFromDom(clipEl: DawClipElement) {\n const clipId = clipEl.clipId;\n // The arrangement played, and the own one (a page track's clip while a\n // handed-in arrangement is played).\n for (const arrangement of new Set([this._arrangement, this._ownArrangement])) {\n for (const t of arrangement.getTracks()) {\n if (t.clips.some((c) => c.id === clipId)) {\n this._removeClipFromTrack(t.id, clipId);\n return;\n }\n }\n }\n // A clip the arrangement refused (its kind): it goes from what the editor took.\n for (const [trackId, extras] of this._extras) {\n if (!extras.peaksSrc.has(clipId)) continue;\n this._dropUnheldClip(trackId, clipId);\n return;\n }\n // Removed before its deferred connect, or from a track that has not\n // entered (it reads its clips when it enters) (in the task of its addClip()): the\n // connect will never reach the editor, so the addClip() is rejected (#917).\n this._rejectAwaitedClips((id) => id === clipId, 'the clip was removed before it loaded');\n // No matching engine clip. May be benign (clip was removed before its load\n // completed), but it can also indicate a DOM/engine id mismatch — purge any\n // orphan cache entries and warn so the leak is visible.\n if (\n this._clipBuffers.has(clipId) ||\n this._clipOffsets.has(clipId) ||\n this._peaksData.has(clipId)\n ) {\n console.warn(\n '[dawcore] _onClipRemovedFromDom: orphaned cache entries for clip \"' +\n clipId +\n '\" — purging (DOM/engine id mismatch?)'\n );\n this._purgeClipCaches(clipId);\n }\n }\n /**\n * A `<daw-clip>` appended to a track that has entered: the clip goes in as\n * a loading clip (a loaded one for MIDI), one undo step. Its audio loads\n * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).\n */\n private _loadAndAppendClip(trackId: string, clipDesc: ClipDescriptor & { clipId: string }) {\n const arrangement = this._arrangementOf(trackId);\n const track = arrangement.getTracks().find((t) => t.id === trackId);\n // A track with no extras (a handed-in one, one an Undo brought back)\n // takes the defaults (P14).\n const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);\n if (!extras || !track) return;\n // A <daw-clip>'s clip is taken, also when refused: its own deferred\n // connect must not add it again. One from addClip() has no element.\n if (isDomClip(clipDesc)) this._takeClip(trackId, clipDesc.clipId, clipDesc.peaksSrc);\n const clipIsMidi = isMidiDescriptor(clipDesc);\n const kindError = clipKindError(\n track.name ?? '',\n extras.kind,\n clipIsMidi,\n clipDesc.name || clipDesc.src || clipDesc.clipId\n );\n const clip = clipIsMidi\n ? buildMidiClip(clipDesc, this.effectiveSampleRate)\n : buildLoadingClip(clipDesc);\n if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);\n try {\n if (kindError) throw kindError;\n // The function form: the track's loading clips stay as they are.\n arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: [...current.clips, clip],\n }));\n } catch (err) {\n console.warn('[dawcore] _loadAndAppendClip failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clipDesc.clipId, error: err },\n })\n );\n return;\n }\n if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);\n }\n /**\n * Resolve pre-computed peaks for a clip: fetch the .dat/.json, validate the\n * sample rate matches the AudioContext, return the WaveformData or null.\n * Warns on fetch failure and on sample-rate mismatch — never silent.\n *\n * Used by `_requestPreview` for a clip that is still loading.\n */\n private async _resolvePeaks(peaksSrc: string): Promise<import('waveform-data').default | null> {\n try {\n const wd = await this._fetchPeaks(peaksSrc);\n const contextRate = this.audioContext.sampleRate;\n if (wd.sample_rate === contextRate) return wd;\n console.warn(\n '[dawcore] Pre-computed peaks at ' +\n wd.sample_rate +\n ' Hz do not match AudioContext at ' +\n contextRate +\n ' Hz — ignoring ' +\n peaksSrc +\n ', generating from audio'\n );\n return null;\n } catch (err) {\n if (isAbortError(err)) return null; // a swap: nothing failed\n console.warn(\n '[dawcore] Failed to load peaks from ' +\n peaksSrc +\n ': ' +\n String(err) +\n ' — falling back to AudioBuffer generation'\n );\n return null;\n }\n }\n /** Remove a single clip from all per-clip caches. Used by error rollbacks. */\n private _purgeClipCaches(clipId: string) {\n const nextBuffers = new Map(this._clipBuffers);\n nextBuffers.delete(clipId);\n this._clipBuffers = nextBuffers;\n const nextPeaks = new Map(this._peaksData);\n nextPeaks.delete(clipId);\n this._peaksData = nextPeaks;\n this._clipOffsets.delete(clipId);\n this._spectrogramController?.unregisterClipAudio(clipId);\n }\n /**\n * Replace one loaded clip of a track in the arrangement: an undo step. The\n * function form, so the track's loading clips stay as they are (#848).\n */\n private _replaceClip(trackId: string, clipId: string, clip: AudioClip) {\n this._arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: current.clips.map((c) => (c.id === clipId ? clip : c)),\n }));\n }\n private _applyClipUpdate(trackId: string, clipId: string, clipEl: ClipUpdateValues) {\n const t = this._arrangement.getTracks().find((track) => track.id === trackId);\n if (!t) {\n console.warn('[dawcore] _applyClipUpdate: no track for id \"' + trackId + '\"');\n return;\n }\n const loadedClip = this._loadedClip(trackId, clipId);\n if (!loadedClip) {\n const loading = t.clips.find((c) => c.id === clipId);\n if (loading && isLoadingClip(loading)) {\n this._updateLoadingClip(trackId, loading, clipEl);\n return;\n }\n console.warn(\n '[dawcore] _applyClipUpdate: clip \"' +\n clipId +\n '\" not found in track \"' +\n trackId +\n '\" (DOM/engine clip-id misalignment?)'\n );\n return;\n }\n const oldClip = loadedClip;\n const sr = oldClip.sampleRate ?? this.effectiveSampleRate;\n\n // MIDI clips: rebuild the clip when notes/channel/program change. Detect\n // MIDI by either current or previous state being MIDI. oldClip.midiNotes\n // is an array (possibly empty []) for any clip registered via _buildMidiClip\n // — including placeholders. For audio clips it is undefined.\n // Use loose != null consistently: treats both null and undefined as \"not MIDI\"\n // for both clipEl.midiNotes (DawClipElement defaults to null) and oldClip.midiNotes.\n // A clip with a src is an audio clip even if notes are set on it, as at\n // load (isMidiDescriptor: \"treating as audio, notes will be ignored\").\n const isMidiNow = clipEl.midiNotes != null && !clipEl.src;\n const wasMidi = oldClip.midiNotes != null;\n if (isMidiNow && trackKind(t) !== 'midi') {\n // Notes assigned to a clip of an audio track: the clip would become a\n // MIDI clip on an audio track (#756). Leave the engine clip as it is.\n const kindError = clipKindError(t.name ?? '', 'audio', true, clipEl.name || clipId);\n console.warn('[dawcore] _applyClipUpdate: ' + kindError?.message);\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error: kindError },\n })\n );\n return;\n }\n if (isMidiNow || wasMidi) {\n // The value the arrangement holds already changes nothing (#848).\n if (\n clipEl.midiNotes === oldClip.midiNotes &&\n (clipEl.midiChannel ?? undefined) === oldClip.midiChannel &&\n (clipEl.midiProgram ?? undefined) === oldClip.midiProgram &&\n Math.round(clipEl.start * sr) === oldClip.startSample &&\n Math.round(clipEl.offset * sr) === oldClip.offsetSamples &&\n (clipEl.duration <= 0 || Math.round(clipEl.duration * sr) === oldClip.durationSamples) &&\n clipEl.gain === (oldClip.gain ?? 1) &&\n (clipEl.name || oldClip.name) === oldClip.name\n ) {\n return;\n }\n const notes = validMidiNotes(clipEl.midiNotes ?? []);\n const noteSpanSeconds = notes.length\n ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0)\n : 0;\n const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);\n const requestedDurationSamples =\n clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : sourceDurationSamples;\n\n const updatedClip: AudioClip = {\n ...oldClip,\n audioBuffer: undefined,\n startSample: Math.round(clipEl.start * sr),\n offsetSamples: Math.round(clipEl.offset * sr),\n durationSamples: requestedDurationSamples,\n sourceDurationSamples,\n gain: clipEl.gain,\n name: clipEl.name || oldClip.name,\n midiNotes: notes,\n midiChannel: clipEl.midiChannel ?? undefined,\n midiProgram: clipEl.midiProgram ?? undefined,\n };\n // Drop any audio caches in case this clip was previously loaded as audio.\n this._purgeClipCaches(clipId);\n this._replaceClip(trackId, clipId, updatedClip);\n return;\n }\n\n const newStartSample = Math.round(clipEl.start * sr);\n const newDurationSamples =\n clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : oldClip.durationSamples;\n const newOffsetSamples = Math.round(clipEl.offset * sr);\n const updatedClip = {\n ...oldClip,\n startSample: newStartSample,\n durationSamples: newDurationSamples,\n offsetSamples: newOffsetSamples,\n gain: clipEl.gain,\n name: clipEl.name || oldClip.name,\n };\n // The value the arrangement holds already changes nothing (#848).\n if (\n newStartSample === oldClip.startSample &&\n newDurationSamples === oldClip.durationSamples &&\n newOffsetSamples === oldClip.offsetSamples &&\n updatedClip.gain === (oldClip.gain ?? 1) &&\n updatedClip.name === oldClip.name\n ) {\n return;\n }\n const boundsChanged =\n oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;\n if (boundsChanged) {\n this._clipOffsets.set(clipId, {\n offsetSamples: newOffsetSamples,\n durationSamples: newDurationSamples,\n });\n const peaks = this.reextractClipPeaks(clipId, newOffsetSamples, newDurationSamples);\n if (peaks) {\n this._peaksData = new Map(this._peaksData).set(clipId, peaks);\n }\n }\n\n this._replaceClip(trackId, clipId, updatedClip);\n }\n /**\n * A change to a clip still loading (#848 P10): its times, gain and name in\n * seconds on the `LoadingClip`, one undo step; the audio loads into it.\n */\n private _updateLoadingClip(trackId: string, clip: LoadingClip, values: ClipUpdateValues): void {\n const next: LoadingClip = {\n ...clip,\n start: values.start,\n ...(values.duration > 0 ? { duration: values.duration } : {}),\n offset: values.offset,\n gain: values.gain,\n ...(values.name ? { name: values.name } : {}),\n };\n if (\n (next.start ?? 0) === (clip.start ?? 0) &&\n next.duration === clip.duration &&\n (next.offset ?? 0) === (clip.offset ?? 0) &&\n (next.gain ?? 1) === (clip.gain ?? 1) &&\n next.name === clip.name\n ) {\n return;\n }\n this._arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: current.clips.map((c) => (c.id === clip.id ? next : c)),\n }));\n }\n /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */\n /**\n * An aborted addClip (D3): its clip leaves for good, from the track it\n * entered or from what a waiting track will enter with.\n */\n private _discardAddedClip(trackId: string, clipId: string): void {\n const pending = this._pending.get(trackId);\n if (pending) {\n this._pending = new Map(this._pending).set(\n trackId,\n 'element' in pending\n ? { ...pending, extraClips: pending.extraClips.filter((c) => c.clipId !== clipId) }\n : {\n ...pending,\n descriptor: {\n ...pending.descriptor,\n clips: pending.descriptor.clips.filter((c) => c.clipId !== clipId),\n },\n }\n );\n return;\n }\n const holder = this._arrangementOf(trackId)\n .getTracks()\n .find((t) => t.id === trackId);\n if (holder?.clips.some((c) => c.id === clipId)) {\n this._removeClipFromTrack(trackId, clipId, { undoable: false });\n }\n }\n private _removeClipFromTrack(\n trackId: string,\n clipId: string,\n options: { undoable?: boolean } = {}\n ) {\n const arrangement = this._arrangementOf(trackId);\n const track = arrangement.getTracks().find((t) => t.id === trackId);\n if (!track) {\n console.warn('[dawcore] _removeClipFromTrack: no track for id \"' + trackId + '\"');\n return;\n }\n if (!track.clips.some((c) => c.id === clipId)) {\n console.warn(\n '[dawcore] _removeClipFromTrack: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n this._purgeClipCaches(clipId);\n this._previewWaveforms.delete(clipId);\n if (this._previewPeaks.has(clipId)) {\n const nextPreview = new Map(this._previewPeaks);\n nextPreview.delete(clipId);\n this._previewPeaks = nextPreview;\n }\n this._forgetClip(trackId, clipId);\n const wasLoading = track.clips.some((c) => c.id === clipId && isLoadingClip(c));\n // `undoable: false`: out of every undo and redo state too (an aborted\n // addClip leaves nothing behind, D3).\n if (options.undoable === false) arrangement.removeClip(trackId, clipId, { undoable: false });\n else\n arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: current.clips.filter((c) => c.id !== clipId),\n }));\n // Its load will never be announced (an addClip() waiting for it watches\n // the arrangement and rejects).\n if (wasLoading) this._announcer.forgetClip(clipId);\n }\n /** Record that the editor took a clip of a track (with its `peaks-src`, '' when none). */\n private _takeClip(trackId: string, clipId: string, peaksSrc: string): void {\n const extras = this._extras.get(trackId);\n if (!extras || extras.peaksSrc.get(clipId) === peaksSrc) return;\n const next = new Map(extras.peaksSrc).set(clipId, peaksSrc);\n this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });\n }\n /**\n * A `<daw-clip>` the editor took is removed while the arrangement does not\n * hold its clip (its track or its own arrival undone, or refused): it is\n * gone for good, also from the undo and redo states, so no Redo brings it\n * back (maintainer's choice, #848).\n */\n private _dropUnheldClip(trackId: string, clipId: string): void {\n this._historyOf(trackId).removeClip(trackId, clipId, { undoable: false });\n this._purgeClipCaches(clipId);\n this._previewWaveforms.delete(clipId);\n this._forgetClip(trackId, clipId);\n }\n /** The editor no longer holds anything for a clip of a track. */\n private _forgetClip(trackId: string, clipId: string): void {\n const extras = this._extras.get(trackId);\n if (!extras?.peaksSrc.has(clipId)) return;\n const next = new Map(extras.peaksSrc);\n next.delete(clipId);\n this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });\n }\n private _readTrackDescriptor(trackEl: DawTrackElement): StoredTrackDescriptor {\n const clipEls = trackEl.querySelectorAll('daw-clip') as NodeListOf<DawClipElement>;\n const clips: ClipDescriptor[] = [];\n\n if (clipEls.length === 0 && trackEl.src) {\n // <daw-track src> shorthand — synthetic descriptor with no <daw-clip>\n // backing element. No DOM clipId to align with.\n clips.push({\n kind: 'drop',\n src: trackEl.src,\n peaksSrc: '',\n start: 0,\n duration: 0,\n offset: 0,\n gain: 1,\n name: trackEl.name || '',\n fadeIn: 0,\n fadeOut: 0,\n fadeType: 'linear',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n });\n } else {\n for (const clipEl of clipEls) clips.push(this._readClipDescriptor(clipEl));\n }\n return {\n name: trackEl.name || 'Untitled',\n src: trackEl.src,\n kind: trackEl.kind,\n renderMode: trackDescriptorRenderMode(trackEl.kind, trackEl.renderMode),\n clips,\n };\n }\n private _readClipDescriptor(clipEl: DawClipElement): DomClipDescriptor {\n return {\n kind: 'dom',\n clipId: clipEl.clipId,\n src: clipEl.src,\n peaksSrc: clipEl.peaksSrc,\n start: clipEl.start,\n duration: clipEl.duration,\n offset: clipEl.offset,\n gain: clipEl.gain,\n name: clipEl.name,\n fadeIn: clipEl.fadeIn,\n fadeOut: clipEl.fadeOut,\n fadeType: clipEl.fadeType as FadeType,\n midiNotes: clipEl.midiNotes,\n midiChannel: clipEl.midiChannel,\n midiProgram: clipEl.midiProgram,\n };\n }\n // --- Entering the arrangement (#848) ---\n private _isEntered(trackId: string): boolean {\n return this._arrangement.getTracks().some((t) => t.id === trackId);\n }\n /** Queue a registered track for the next flush. */\n _queueEntry(trackId: string): void {\n if (!this._entryQueue.includes(trackId)) this._entryQueue = [...this._entryQueue, trackId];\n if (this._entryFlushScheduled) return;\n this._entryFlushScheduled = true;\n // A microtask: tracks connected in one task (an innerHTML, a script\n // appending several) enter together, at once. The page's children connect\n // in tasks of their own and enter one by one; the history rule holds for\n // each, because the flush before cleared what it added.\n queueMicrotask(() => {\n this._entryFlushScheduled = false;\n this._flushTrackEntries();\n });\n }\n /**\n * Enter the queued tracks into the arrangement, in DOM order. Without an\n * engine they wait (the sample rate of a MIDI clip comes from the\n * adapter); the engine's build flushes again. The page's tracks entering\n * while the arrangement has no history are not undo steps: the history is\n * cleared after them, so Undo right after load removes nothing (and the\n * next page track finds it empty again).\n */\n _flushTrackEntries(): void {\n if (this._entryQueue.length === 0) return;\n // Without an engine the queue waits, silently (maintainer, #917; play()\n // without an adapter warns and fires daw-error with the no-adapter error).\n if (!this._engine) return;\n // No drag holds a transaction (#848 PR 3): a track enters during a drag\n // as at any other time, an undo step of its own.\n const isPageTrack = (id: string) => this._trackElements.has(id);\n // The children declare the editor's OWN arrangement: while a handed-in\n // one is played they wait (P7); addTrack() and drops go to the one played.\n const queued = this._handedIn\n ? this._entryQueue.filter((id) => !isPageTrack(id))\n : this._entryQueue;\n this._entryQueue = this._handedIn ? this._entryQueue.filter(isPageTrack) : [];\n const domOrder: string[] = [...this.querySelectorAll('daw-track')].map(\n (el) => (el as DawTrackElement).trackId\n );\n const position = (id: string) => {\n const at = domOrder.indexOf(id);\n return at === -1 ? domOrder.length : at;\n };\n const ordered = [...queued].sort((a, b) => position(a) - position(b));\n const arrangement = this._arrangement;\n const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo;\n let pageEntered = false;\n for (const id of ordered.filter(isPageTrack)) {\n if (this._enterTrack(id)) pageEntered = true;\n }\n if (historyWasEmpty && pageEntered) arrangement.clearHistory();\n for (const id of ordered.filter((id) => !isPageTrack(id))) this._enterTrack(id);\n }\n /** Enter one registered track. False when it is gone, already in, or refused. */\n private _enterTrack(trackId: string): boolean {\n const descriptor = this._pendingDescriptor(trackId);\n if (!descriptor || this._isEntered(trackId)) return false;\n const el = this._trackElements.get(trackId);\n const built = buildArrangementTrack(\n trackId,\n descriptor,\n this._mixOf(trackId),\n this.effectiveSampleRate\n );\n // From here the arrangement holds it; the editor keeps only what the\n // arrangement has no field for (#848 PR 3).\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._extras = new Map(this._extras).set(trackId, extrasOf(built.descriptor));\n for (const { clipId, error } of built.refused) {\n console.warn('[dawcore] ' + error.message);\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error },\n })\n );\n }\n const index = el\n ? entryIndex(\n [...this.querySelectorAll('daw-track')] as DawTrackElement[],\n trackId,\n this._arrangement.getTracks().map((t) => t.id)\n )\n : undefined;\n // A child whose clip another track holds was moved here by the page: the\n // clip moves in as it is, in the same undo step as the arrival (the\n // maintainer's choice c, #848). One of the other kind stays where it is.\n const moved = this._takeOverMovedClips(trackId, built.track);\n const entering = moved.track;\n for (const { clipId, error } of moved.refused) {\n console.warn('[dawcore] ' + error.message);\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId, error },\n })\n );\n }\n // Before the add: the announcement it causes counts the refused clips,\n // and a clip whose source is loaded already is still announced ready.\n this._announcer.expect(trackId, built.refused.length + moved.refused.length);\n for (const clip of entering.clips) {\n if (isLoadingClip(clip)) this._announcer.expectClip(clip.id);\n }\n try {\n if (moved.from.size === 0) {\n this._arrangement.addTrack(entering, index === undefined ? undefined : { index });\n } else {\n this._inOneStep([this._arrangement], () => {\n for (const [fromId, clipIds] of moved.from) {\n this._arrangement.updateTrack(fromId, (t) => ({\n ...t,\n clips: t.clips.filter((c) => !clipIds.has(c.id)),\n }));\n for (const clipId of clipIds) this._forgetClip(fromId, clipId);\n }\n this._arrangement.addTrack(entering, index === undefined ? undefined : { index });\n });\n }\n } catch (err) {\n console.warn('[dawcore] Failed to add track \"' + trackId + '\": ' + String(err));\n // An element stays linked to the refused track (it is not added\n // again); a track with no element is gone.\n if (!el) {\n const nextExtras = new Map(this._extras);\n nextExtras.delete(trackId);\n this._extras = nextExtras;\n }\n this._refreshLinkStates();\n this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));\n this.dispatchEvent(\n new CustomEvent<DawTrackErrorDetail>('daw-track-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, error: err },\n })\n );\n return false;\n }\n this._settleEntry(trackId, ENTERED);\n for (const clipDesc of built.descriptor.clips) {\n if (clipDesc.clipId && moved.movedIds.has(clipDesc.clipId)) continue; // loaded as it is\n if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {\n this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);\n }\n }\n return true;\n }\n /**\n * The `<daw-track src>` shorthand changed its src: the entered track gets a\n * new loading clip for it, one undo step. A track whose clips are\n * `<daw-clip>` children keeps them. A track still queued reads the new\n * descriptor when it enters.\n */\n private _replaceShorthandClips(trackId: string, trackEl: DawTrackElement): void {\n const descriptor = this._readTrackDescriptor(trackEl);\n if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;\n const built = buildArrangementTrack(\n trackId,\n descriptor,\n DEFAULT_TRACK_MIX,\n this.effectiveSampleRate\n );\n const extras = this._extras.get(trackId);\n if (extras) {\n this._extras = new Map(this._extras).set(trackId, {\n ...extras,\n peaksSrc: extrasOf(built.descriptor).peaksSrc,\n });\n }\n this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));\n }\n /** Run the load announcements over the arrangement's current state. */\n private _announceLoading(): void {\n this._announcer.update(\n this._arrangement.getTracks(),\n this._arrangement.sources.getSnapshot().sources\n );\n }\n /**\n * Fetch a loading clip's `.dat` peaks and draw them until its audio\n * arrives (an editor-only cache, not the arrangement: writing the clip\n * after it entered would be an undo step).\n */\n private async _requestPreview(clipId: string, peaksSrc: string): Promise<void> {\n const waveformData = await this._resolvePeaks(peaksSrc);\n if (!waveformData) return;\n const clip = this._arrangement\n .getTracks()\n .flatMap((t) => t.clips)\n .find((c) => c.id === clipId);\n // Loaded first (the worker draws it), or gone.\n if (!clip || !isLoadingClip(clip)) return;\n const rate = waveformData.sample_rate;\n const offset = clip.offset ?? 0;\n const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);\n const peakData = extractPeaks(\n waveformData,\n Math.max(this._renderSpp, waveformData.scale),\n this.mono,\n Math.round(offset * rate),\n Math.round(seconds * rate)\n );\n this._previewPeaks = new Map(this._previewPeaks).set(clipId, peakData);\n this._previewWaveforms.set(clipId, waveformData);\n this._raiseZoomFloor(waveformData.scale);\n this._recomputeDuration();\n }\n /** The peak sync made a clip's peaks: its zoom floor holds, its preview goes. */\n _clipPeaksReady(clipId: string, audioBuffer: AudioBuffer): void {\n this._raiseZoomFloor(this._peakPipeline.getCachedScale(audioBuffer));\n if (!this._previewPeaks.has(clipId)) return;\n const next = new Map(this._previewPeaks);\n next.delete(clipId);\n this._previewPeaks = next;\n }\n /** Who waits for a track to enter (addTrack, a dropped file). */\n private _entryWaiters = new Map<\n string,\n { resolve: (trackId: string) => void; reject: (error: unknown) => void }\n >();\n private _waitForEntry(trackId: string): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n this._entryWaiters.set(trackId, { resolve, reject });\n });\n }\n /** Settle the wait for a track's entry: entered (`ENTERED`), or refused or gone (the reason).*/\n private _settleEntry(trackId: string, outcome: unknown): void {\n const waiter = this._entryWaiters.get(trackId);\n if (!waiter) return;\n this._entryWaiters.delete(trackId);\n // Anything but ENTERED rejects, also a falsy abort reason ('', 0, null,\n // false: a signal's reason is passed on as it is; review of #919).\n if (outcome === ENTERED) waiter.resolve(trackId);\n else waiter.reject(outcome);\n }\n /**\n * A dropped file as a track with no element (a File cannot be an attribute):\n * one loading clip whose source is the file. Resolves with the track id once\n * it has entered, an undo step like any track an editor method adds.\n */\n _addDroppedFile(file: File): Promise<string> {\n const trackId = crypto.randomUUID();\n const name = file.name.replace(/\\.\\w+$/, '');\n const descriptor: StoredTrackDescriptor = {\n name,\n src: '',\n kind: 'audio',\n renderMode: trackDescriptorRenderMode('audio', 'waveform'),\n clips: [\n {\n kind: 'drop',\n file,\n src: '',\n peaksSrc: '',\n start: 0,\n duration: 0,\n offset: 0,\n gain: 1,\n name,\n fadeIn: 0,\n fadeOut: 0,\n fadeType: 'linear',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n },\n ],\n };\n this._pending = new Map(this._pending).set(trackId, { descriptor, mix: DEFAULT_TRACK_MIX });\n const entered = this._waitForEntry(trackId);\n // A swap before it enters ends it, as a disconnect does (review of #919).\n this._endEntryOnSwap(trackId, entered);\n this._queueEntry(trackId);\n return entered;\n }\n /**\n * Take a track out for good: no undo step, and no undo or redo brings it\n * back (a dropped file that could not be loaded was never a declaration).\n */\n _discardTrack(trackId: string, from: Arrangement = this._arrangement): void {\n // From the arrangement it entered: after a swap that is no longer the one\n // played (review of #919). The editor shows nothing of that one, so only\n // its own record of the track goes (no event, no playhead change).\n if (from !== this._arrangement) {\n from.removeTrack(trackId, { undoable: false });\n if (this._extras.has(trackId)) {\n const nextExtras = new Map(this._extras);\n nextExtras.delete(trackId);\n this._extras = nextExtras;\n }\n return;\n }\n const track = from.getTracks().find((t) => t.id === trackId);\n this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);\n from.removeTrack(trackId, { undoable: false });\n this._onTrackRemoved(trackId);\n }\n /** One AbortController per arrangement while it is played (D2, interactions/abort.ts). */\n private _playSignals = new PlaySignals();\n /** The signal of the arrangement played now: aborted when it is swapped out. */\n private get _playSignal(): AbortSignal {\n return this._playSignals.signalOf(this._arrangement);\n }\n /** @internal A caller's signal combined with the arrangement played now (loadMidi, D6). */\n _operationSignal(signal?: AbortSignal): AbortSignal {\n return signal ? AbortSignal.any([signal, this._playSignal]) : this._playSignal;\n }\n /** One AbortController per connection: aborted in disconnectedCallback (D8). */\n private _connection = new AbortController();\n /**\n * Resolves once the track has loaded (`daw-track-ready`), or when the\n * editor is disconnected meanwhile (the track is kept and loads after a\n * reparent); rejects when its audio failed (`daw-track-error`).\n */\n _whenTrackLoaded(trackId: string): Promise<void> {\n const state = this._announcer.stateOf(trackId);\n if (state === 'ready') return Promise.resolve();\n if (state === 'failed') return Promise.reject(this._announcer.errorOf(trackId));\n // Ends as loaded when the arrangement is swapped out or the editor is\n // disconnected meanwhile (the track is kept and loads after a reparent).\n const ended = AbortSignal.any([this._playSignal, this._connection.signal]);\n if (ended.aborted) return Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const done = new AbortController();\n const signal = AbortSignal.any([ended, done.signal]);\n this.addEventListener(\n 'daw-track-ready',\n (e: Event) => {\n if ((e as CustomEvent<DawTrackIdDetail>).detail.trackId !== trackId) return;\n done.abort();\n resolve();\n },\n { signal }\n );\n this.addEventListener(\n 'daw-track-error',\n (e: Event) => {\n const detail = (e as CustomEvent<DawTrackErrorDetail>).detail;\n if (detail.trackId !== trackId) return;\n done.abort();\n reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));\n },\n { signal }\n );\n ended.addEventListener('abort', () => resolve(), { signal: done.signal });\n });\n }\n /**\n * Load again every failed source the track's clips name (#848). A track\n * whose audio failed stays in the editor, like a broken `<img>`;\n * `daw-track-ready` follows when it loads.\n */\n retryTrack(trackId: string): void {\n const track = this._arrangement.getTracks().find((t) => t.id === trackId);\n if (!track) {\n console.warn('[dawcore] retryTrack: no track found for id \"' + trackId + '\"');\n return;\n }\n const sources = this._arrangement.sources.getSnapshot().sources;\n const failed = new Set(\n track.clips\n .filter(isLoadingClip)\n .map((clip) => clip.src)\n .filter((src) => sources.get(src)?.status === 'failed')\n );\n for (const src of failed) this._arrangement.retry(src);\n }\n private _fetchPeaks(src: string): Promise<import('waveform-data').default> {\n const cached = this._peaksCache.get(src);\n if (cached) return cached;\n // The fetch belongs to the arrangement played now: a swap aborts it (D2),\n // and an aborted one is dropped from the cache so a later request fetches again.\n const promise = loadWaveformDataFromUrl(src, this._playSignal).catch((err) => {\n this._peaksCache.delete(src);\n throw err;\n });\n this._peaksCache.set(src, promise);\n return promise;\n }\n /**\n * The timeline's duration, the one writer of `_duration`: the loaded clips,\n * and the clips still loading whose length is known (a duration, or `.dat`\n * peaks), so the timeline is as wide as what is drawn (#848).\n */\n _recomputeDuration() {\n const sr = this.effectiveSampleRate;\n let maxSample = 0;\n for (const track of this._loadedTracks()) {\n for (const clip of track.clips) {\n const endSample = clip.startSample + clip.durationSamples;\n if (endSample > maxSample) maxSample = endSample;\n }\n }\n for (const track of this._arrangement.getTracks()) {\n for (const clip of track.clips) {\n if (!isLoadingClip(clip)) continue;\n const seconds = this._placeholderSeconds(clip);\n if (seconds === null) continue;\n maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));\n }\n }\n this._duration = maxSample / sr;\n }\n /** How long a loading clip is drawn: its duration, else what its `.dat` peaks cover; null when unknown. */\n private _placeholderSeconds(clip: LoadingClip): number | null {\n if (clip.duration != null && clip.duration > 0) return clip.duration;\n const waveformData = this._previewWaveforms.get(clip.id);\n if (!waveformData) return null;\n const seconds = waveformData.duration - (clip.offset ?? 0);\n return seconds > 0 ? seconds : null;\n }\n // --- Engine ---\n /**\n * The engine, built now when the editor is connected with an adapter.\n * Rejects without an adapter, and on a detached editor (an engine built\n * there would hold the adapter's graph with nothing to dispose it).\n */\n _ensureEngine(): Promise<EditorEngine> {\n if (this._engine) return Promise.resolve(this._engine);\n try {\n if (!this.isConnected && this._externalAdapter) {\n throw new Error('[dawcore] <daw-editor> is not connected: no engine is built for it.');\n }\n return Promise.resolve(this._buildEngine());\n } catch (err) {\n return Promise.reject(err);\n }\n }\n /** Build the engine from the adapter setter or a connect: a failure is reported, not thrown. */\n private _buildEngineReporting(): void {\n try {\n this._buildEngine();\n } catch (err) {\n console.warn('[dawcore] Failed to build the engine: ' + String(err));\n // An addTrack() waiting to enter would wait for an engine that does not\n // come (#848): it fails with the build's error, and its track goes.\n const error = err instanceof Error ? err : new Error(String(err));\n for (const trackId of [...this._entryQueue]) {\n const pending = this._pending.get(trackId);\n if (!pending || 'element' in pending || !this._entryWaiters.has(trackId)) continue;\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._entryQueue = this._entryQueue.filter((id) => id !== trackId);\n this._settleEntry(trackId, error);\n }\n this.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'engine', error: err },\n })\n );\n }\n }\n /** Last versions the statechange handler worked from; reset for each engine. */\n private _lastTracksVersion = -1;\n private _lastMixerVersion = -1;\n private _buildEngine(): EditorEngine {\n if (!this._externalAdapter) {\n throw new Error(noAdapterError());\n }\n const adapter = this._externalAdapter;\n\n // Forward initial tempo if adapter supports it — skipped when tick\n // callbacks are present (external tempo map is authoritative, #407)\n if (!this._hasTickCallbacks) {\n if (adapter.setTempo) {\n adapter.setTempo(this._bpm);\n } else if (this._bpm !== 120) {\n console.warn(\n '[dawcore] Adapter does not implement setTempo. ' +\n 'Initial BPM ' +\n this._bpm +\n ' will not be applied — clips may use wrong tempo.'\n );\n }\n }\n\n // Try to set the editor's desired PPQN on the adapter, then sync back.\n // Adapter is the source of truth — it may ignore the request.\n adapter.setPpqn?.(this._ppqn);\n this.ppqn = adapter.ppqn;\n\n const engine = new EditorEngine({\n adapter,\n arrangement: this._arrangement,\n sampleRate: adapter.audioContext.sampleRate,\n samplesPerPixel: this.samplesPerPixel,\n bpm: this._bpm,\n zoomLevels: [256, 512, 1024, 2048, 4096, 8192, this.samplesPerPixel]\n .filter((v, i, a) => a.indexOf(v) === i)\n .sort((a, b) => a - b),\n });\n this._lastTracksVersion = -1;\n this._lastMixerVersion = -1;\n engine.on('statechange', (engineState) => this._onEngineState(engineState));\n engine.on('pause', () => {\n this._currentTime = engine.getCurrentTime();\n });\n engine.on('stop', () => this._onEngineStop(engine));\n this._engine = engine;\n // A new engine (a swap, a fresh adapter) plays the selection the editor shows.\n if (this._selectionStartTime !== 0 || this._selectionEndTime !== 0) {\n engine.setSelection(this._selectionStartTime, this._selectionEndTime);\n }\n // A kept arrangement (a reconnect) already has tracks: draw them now,\n // and give a spectrogram track its audio again (the controller went with\n // the disconnect).\n this._onEngineState(engine.getState());\n for (const track of this._loadedTracks()) {\n for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);\n }\n this._flushTrackEntries();\n return engine;\n }\n /**\n * Clips whose audio has just arrived: a `.dat` preview's data goes to the\n * peak pipeline (no worker run), a spectrogram track gets the audio. The\n * peak sync then makes their peaks.\n */\n private _adoptLoadedClips(tracks: readonly ClipTrack[]): void {\n for (const track of tracks) {\n for (const clip of track.clips) {\n const waveformData = this._previewWaveforms.get(clip.id);\n if (waveformData && clip.audioBuffer) {\n if (waveformData.sample_rate === clip.audioBuffer.sampleRate) {\n this._peakPipeline.cacheWaveformData(clip.audioBuffer, waveformData);\n }\n this._previewWaveforms.delete(clip.id);\n }\n if (!this._clipBuffers.has(clip.id))\n this._maybeRegisterSpectrogramClipAudio(track.id, clip);\n }\n }\n }\n /** The engine's state changed: draw it (the rows are read from the arrangement). */\n private _onEngineState(engineState: EngineState): void {\n this._isPlaying = engineState.isPlaying;\n this._selectedTrackId = engineState.selectedTrackId;\n const structuralChange = engineState.tracksVersion !== this._lastTracksVersion;\n // Per-track mixer edits (volume/mute/solo/pan) bump mixerVersion, NOT\n // tracksVersion (#501). Draw again on either so the controls show the\n // current mix — but only run the\n // expensive structural work below for true structural changes, never on\n // every volume/pan drag frame.\n const mixerChange = engineState.mixerVersion !== this._lastMixerVersion;\n if (structuralChange || mixerChange) {\n this._lastTracksVersion = engineState.tracksVersion;\n this._lastMixerVersion = engineState.mixerVersion;\n this.requestUpdate();\n }\n // Sync clip positions when tracks change structurally (moveClip, trimClip,\n // splitClip, setTracks, addTrack, removeTrack).\n if (structuralChange) {\n this._recomputeDuration();\n // Transport setTracks rebuilds TrackNodes, severing effects hookups.\n this._effectsManager?.rewireTrackChains();\n // Regenerate peaks for new or trimmed clips.\n // MIDI tracks have no AudioBuffer — skip them to avoid noisy\n // \"no AudioBuffer\" warnings on every tracksVersion bump.\n const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== 'midi');\n this._adoptLoadedClips(audioTracks);\n syncPeaksForChangedClips(this, audioTracks);\n this._announceLoading();\n }\n // Tick-based annotations: BPM changes move their time-domain positions —\n // re-derive the seconds caches (write-only-on-change; loop-safe).\n if (engineState.bpm !== this._lastAnnotationBpm) {\n this._lastAnnotationBpm = engineState.bpm;\n this._annotations.deriveSecondsCaches();\n }\n }\n private _onEngineStop(engine: EditorEngine): void {\n // Fires synchronously from EditorEngine.stop() (see engine CLAUDE.md\n // \"Bounded playback\" / #608) — reached via EITHER a consumer-initiated\n // stop (editor.stop(), or a seek-adjacent stop+reschedule guarded by\n // _inSeekTransition — pointer-handler seek, seekTo, splitAtPlayhead,\n // empty-timeline rewind) OR the engine's OWN bounded-playback\n // completion path: an adapter (Tone, native) reports `onPlaybackEnded` for a\n // duration-limited play(start, end) (selection/annotation playback),\n // and the engine calls `this.stop()` internally from a queued\n // microtask with no consumer call in sight. That engine-initiated case\n // has no other `daw-stop` dispatcher — mirror it here so consumers\n // still get a daw-stop paired with their earlier daw-play. Consumer\n // stops dispatch their own daw-stop (editor.stop(), guarded by\n // _inConsumerStop) or intentionally suppress it (seek-adjacent stops,\n // guarded by _inSeekTransition) — this handler must not double-fire\n // for those.\n this._currentTime = engine.getCurrentTime();\n this._stopPlayhead();\n this._activePlayEndTime = null;\n if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {\n this.dispatchEvent(new CustomEvent('daw-stop', { bubbles: true, composed: true }));\n }\n }\n private _disposeEngine() {\n if (this._engine) {\n this._engine.dispose();\n this._engine = null;\n }\n }\n // --- File Drop ---\n private _onDragOver = (e: DragEvent) => {\n if (!this.fileDrop) return;\n e.preventDefault();\n if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';\n this._dragOver = true;\n };\n private _onDragLeave = (e: DragEvent) => {\n if (!this.fileDrop) return;\n // relatedTarget is null when cursor leaves the browser window — that's fine,\n // we still want to clear _dragOver in that case.\n const timeline = this.shadowRoot?.querySelector('.timeline');\n if (timeline && !timeline.contains(e.relatedTarget as Node)) {\n this._dragOver = false;\n }\n };\n private _onDrop = async (e: DragEvent) => {\n if (!this.fileDrop) return;\n e.preventDefault();\n this._dragOver = false;\n const files = e.dataTransfer?.files;\n if (!files || files.length === 0) return;\n try {\n await this.loadFiles(files);\n } catch (err) {\n console.warn('[dawcore] File drop failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'file-drop', error: err },\n })\n );\n }\n };\n async loadFiles(\n files: FileList | File[],\n options: EditorCallOptions = {}\n ): Promise<LoadFilesResult> {\n return loadFilesImpl(this, files, options);\n }\n /**\n * Imperatively load a `.mid` file (URL or File) and add N tracks (no\n * element, #848), one per note-bearing MIDI track. On any per-track\n * failure, every track the call added is removed with no undo step, so the\n * editor is as before the call.\n *\n * `options.signal` cancels the fetch, the parse and the tracks still\n * waiting to enter (combined with the arrangement played: a swap cancels\n * too); the call rejects with its `reason` and removes the tracks it added.\n *\n * Requires the optional `@dawcore/midi` peer dep — throws with an install\n * hint (and `console.warn`s the original error) when the dynamic import\n * fails for any reason.\n */\n async loadMidi(source: string | File, options?: MidiLoadOptions): Promise<MidiLoadResult> {\n return loadMidiImpl(this, source, options);\n }\n // --- Programmatic Track API ---\n /**\n * Build the engine if it hasn't been built yet. Lets consumers obtain a\n * non-null `editor.engine` before any track has been loaded — useful for\n * wiring analyzers, effects, or master taps before content arrives.\n */\n async ready(): Promise<EditorEngine> {\n return this._ensureEngine();\n }\n /**\n * Add a track built from `config` to the arrangement the editor plays when\n * it is called, and resolve with its id once it has entered (#848), before\n * its audio has loaded. A swap of `editor.arrangement` before it enters\n * rejects with an `AbortError` and the track enters nowhere; to add to\n * another arrangement, call that arrangement's own `addTrack`. No element is created: the track is drawn and listed like any\n * other, and `<daw-track>` children stay the page's declaration. To follow\n * loading, add the `daw-track-ready` / `daw-track-error` listener BEFORE\n * calling: for a track with nothing to fetch it fires before this\n * resolves. Without `editor.adapter` it waits for one. Rejects when the\n * arrangement refuses the track, when it is removed before it enters, or\n * when the engine cannot be built.\n *\n * `options.signal` (#848): aborting it before the track has entered takes\n * it out of the queue (it never enters) and rejects with its `reason`;\n * after that it changes nothing (the audio goes on loading). A signal\n * already aborted rejects at once and queues nothing.\n */\n addTrack(config: TrackConfig = {}, options: EditorCallOptions = {}): Promise<string> {\n const signal = options.signal;\n if (signal?.aborted) return Promise.reject(reasonOf(signal));\n const trackId = crypto.randomUUID();\n let kind: TrackKind = config.kind ?? (config.midi ? 'midi' : 'audio');\n if (kind !== 'audio' && kind !== 'midi') {\n console.warn(\n '[dawcore] addTrack: kind \"' +\n String(kind) +\n \"\\\" is not a track kind ('audio' or 'midi'); using \\\"audio\\\"\"\n );\n kind = 'audio';\n }\n let renderMode = normalizeRenderMode(config.renderMode);\n if (renderMode === 'both') {\n console.warn(\n '[dawcore] render-mode=\"both\" is not yet supported; falling back to \\'spectrogram\\''\n );\n renderMode = 'spectrogram';\n }\n const clipConfigs: ClipConfig[] = [...(config.clips ?? [])];\n if (config.midi) {\n clipConfigs.push({\n midiNotes: config.midi.notes,\n midiChannel: config.midi.channel,\n midiProgram: config.midi.program,\n });\n }\n const descriptor: StoredTrackDescriptor = {\n name: config.name || 'Untitled',\n src: '',\n kind,\n renderMode: trackDescriptorRenderMode(kind, renderMode),\n spectrogramConfig: config.spectrogramConfig ?? null,\n clips: clipConfigs.map((c) => clipDescriptorOf(c)),\n };\n const mix: TrackMixerValues = {\n volume: config.volume ?? DEFAULT_TRACK_MIX.volume,\n pan: config.pan ?? DEFAULT_TRACK_MIX.pan,\n muted: config.muted ?? false,\n soloed: config.soloed ?? false,\n panLaw: declaredPanLaw(config.panLaw),\n };\n this._pending = new Map(this._pending).set(trackId, { descriptor, mix });\n const entered = this._waitForEntry(trackId);\n // It goes into the arrangement played now: a swap before it enters ends\n // the call (the maintainer's choice, #848: capture it).\n this._endEntryOnSwap(trackId, entered);\n this._queueEntry(trackId);\n if (!signal) return entered;\n const settled = new AbortController();\n signal.addEventListener('abort', () => this._abortEntry(trackId, reasonOf(signal)), {\n signal: settled.signal,\n });\n return entered.finally(() => settled.abort());\n }\n /**\n * A queued track goes into the arrangement played when it was queued: when\n * that one is swapped out first, the track leaves the queue and its wait\n * rejects with the swap's AbortError (addTrack, a dropped file).\n */\n private _endEntryOnSwap(trackId: string, entered: Promise<string>): void {\n const settled = new AbortController();\n this._playSignal.addEventListener(\n 'abort',\n (e) => this._abortEntry(trackId, reasonOf(e.target as AbortSignal)),\n { signal: settled.signal }\n );\n void entered.then(\n () => settled.abort(),\n () => settled.abort()\n );\n }\n /** A track that has not entered leaves the queue and its wait rejects with `reason` (D4). */\n private _abortEntry(trackId: string, reason: unknown): void {\n if (!this._pending.has(trackId) || this._isEntered(trackId)) return;\n // Out of what is waiting; its id left in the queue enters nothing.\n const nextPending = new Map(this._pending);\n nextPending.delete(trackId);\n this._pending = nextPending;\n this._settleEntry(trackId, reason);\n this.requestUpdate();\n }\n /**\n * Remove a track by id: its `<daw-track>` element is removed (the\n * MutationObserver does the rest), or, for a track with no element\n * (`addTrack`, a dropped file, an Undo), the track itself. One undo step.\n * Warns when no track has the id.\n */\n removeTrack(trackId: string): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n trackEl.remove();\n // Detached, the MutationObserver is off: remove the track here (#917).\n if (!this.isConnected) this._onTrackRemoved(trackId);\n } else if (\n this._pending.has(trackId) ||\n this._extras.has(trackId) ||\n this._isEntered(trackId)\n ) {\n // File-dropped and undo-restored tracks have no DOM element.\n this._onTrackRemoved(trackId);\n } else {\n console.warn('[dawcore] removeTrack: no track found for id \"' + trackId + '\"');\n }\n }\n /**\n * Move a track to a 0-based position in the arrangement's order (every\n * track counts, those with no element too; `trackEl.index` and\n * `editor.tracks` give the positions). One undo step; no element moves.\n */\n reorderTrack(trackId: string, toIndex: number): void {\n if (!Number.isFinite(toIndex)) {\n console.warn('[dawcore] reorderTrack: invalid toIndex ' + String(toIndex));\n return;\n }\n if (!this._isEntered(trackId)) {\n console.warn('[dawcore] reorderTrack: no track found for id \"' + trackId + '\"');\n return;\n }\n // The arrangement's order; no element moves (#848: the markup is the\n // starting declaration, order included).\n const last = this._arrangement.getTracks().length - 1;\n this._arrangement.reorderTrack(trackId, Math.max(0, Math.min(Math.trunc(toIndex), last)));\n }\n\n private _onTrackReorder = (e: CustomEvent<DawTrackReorderDetail>) => {\n this.reorderTrack(e.detail.trackId, e.detail.toIndex);\n };\n\n private _onTrackReorderGrab = (e: CustomEvent<DawTrackReorderGrabDetail>) => {\n if (!this.trackReordering) return;\n this._trackReorderDrag.onGrab(e.detail.trackId, e.detail.pointerEvent, e.detail.gripElement);\n };\n\n /**\n * Change a track: the mix (one undo step, #843), the name (an undo step),\n * the render mode and spectrogram config (the editor's). The arrangement\n * is changed, never an element's attributes (#848): a `<daw-track>`'s\n * properties show the change. A track that has not entered yet gets it as\n * the value it enters with.\n */\n updateTrack(trackId: string, partial: Partial<TrackConfig>): void {\n if (!this._isEntered(trackId)) {\n this._updatePendingTrack(trackId, partial);\n return;\n }\n const mix: Partial<TrackMixerValues> = {\n volume: partial.volume,\n pan: partial.pan,\n muted: partial.muted,\n soloed: partial.soloed,\n ...(partial.panLaw !== undefined && { panLaw: declaredPanLaw(partial.panLaw) }),\n };\n this._writeMixFields(trackId, mix);\n if (partial.name !== undefined) this._renameTrack(trackId, partial.name);\n const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);\n if (!extras) return;\n let renderMode =\n partial.renderMode === undefined ? undefined : normalizeRenderMode(partial.renderMode);\n if (renderMode === 'both') {\n console.warn(\n '[dawcore] render-mode=\"both\" is not yet supported; falling back to \\'spectrogram\\''\n );\n renderMode = 'spectrogram';\n }\n if (renderMode === undefined && partial.spectrogramConfig === undefined) return;\n const next: TrackExtras = {\n ...extras,\n ...(renderMode !== undefined && {\n renderMode: trackDescriptorRenderMode(extras.kind, renderMode),\n }),\n ...(partial.spectrogramConfig !== undefined && {\n spectrogramConfig: partial.spectrogramConfig,\n }),\n };\n this._extras = new Map(this._extras).set(trackId, next);\n if (next.spectrogramConfig !== extras.spectrogramConfig) {\n this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);\n }\n }\n /** `updateTrack` on a track waiting to enter: the values it will enter with. */\n private _updatePendingTrack(trackId: string, partial: Partial<TrackConfig>): void {\n const pending = this._pending.get(trackId);\n if (!pending) {\n console.warn('[dawcore] updateTrack: no track found for id \"' + trackId + '\"');\n return;\n }\n if ('element' in pending) {\n // Before entry an element's properties are its declaration (P9).\n const el = pending.element;\n if (partial.name !== undefined) el.name = partial.name;\n if (partial.volume !== undefined) el.volume = partial.volume;\n if (partial.pan !== undefined) el.pan = partial.pan;\n if (partial.panLaw !== undefined) el.panLaw = partial.panLaw;\n if (partial.muted !== undefined) el.muted = partial.muted;\n if (partial.soloed !== undefined) el.soloed = partial.soloed;\n if (partial.renderMode !== undefined) el.renderMode = partial.renderMode;\n if (partial.spectrogramConfig !== undefined) el.spectrogramConfig = partial.spectrogramConfig;\n return;\n }\n const { descriptor, mix } = pending;\n this._pending = new Map(this._pending).set(trackId, {\n descriptor: {\n ...descriptor,\n ...(partial.spectrogramConfig !== undefined && {\n spectrogramConfig: partial.spectrogramConfig,\n }),\n ...(partial.name !== undefined && { name: partial.name }),\n ...(partial.renderMode !== undefined && {\n renderMode: trackDescriptorRenderMode(\n descriptor.kind,\n normalizeRenderMode(partial.renderMode)\n ),\n }),\n },\n mix: {\n volume: partial.volume ?? mix.volume,\n pan: partial.pan ?? mix.pan,\n muted: partial.muted ?? mix.muted,\n soloed: partial.soloed ?? mix.soloed,\n panLaw: partial.panLaw !== undefined ? declaredPanLaw(partial.panLaw) : mix.panLaw,\n },\n });\n }\n /**\n * Add a clip to a track (with or without an element) and resolve with its\n * id once its audio has loaded (`daw-clip-ready`, before its peaks are\n * drawn). The clip enters the arrangement as a loading clip, one undo\n * step; no `<daw-clip>` is created (#848). Rejects when it fails to load,\n * is refused (its kind), or leaves the arrangement before it loads (a\n * removal, an Undo). A clip added while the editor is detached loads once\n * a fresh adapter is set.\n *\n * `options.signal` (#848): aborting it before the clip has loaded rejects\n * with its `reason` and removes the clip for good (no undo step); after it\n * has loaded it changes nothing. A signal already aborted rejects at once\n * and adds nothing. A swap of `editor.arrangement` rejects the call with an\n * `AbortError`; its loading clip stays in the arrangement swapped out.\n */\n addClip(trackId: string, config: ClipConfig, options: EditorCallOptions = {}): Promise<string> {\n const callerSignal = options.signal;\n if (callerSignal?.aborted) return Promise.reject(reasonOf(callerSignal));\n if (!config.src) {\n return Promise.reject(\n new Error(\n 'addClip: config.src is required — pass a URL to load. ' +\n 'Empty/recording clips are not yet supported via addClip.'\n )\n );\n }\n const pending = this._pending.get(trackId);\n if (!this._isEntered(trackId) && !pending) {\n return Promise.reject(\n new Error(\n 'addClip: track \"' +\n trackId +\n '\" is not in the editor (an Undo took it out, the arrangement refused it, or no ' +\n 'track has this id)'\n )\n );\n }\n const clipDesc = clipDescriptorOf(config);\n const clipId = clipDesc.clipId;\n // Settled by daw-clip-ready / daw-clip-error for this clip; and, since a\n // clip that leaves the arrangement before its audio loads (a removal, an\n // Undo, its track removed) is never announced, rejected once it has been\n // in the arrangement and is gone (#917). Every way out removes all three\n // listeners.\n return new Promise<string>((resolve, reject) => {\n let seen = false;\n // One controller for this call: its abort removes every listener.\n const call = new AbortController();\n const cleanup = () => {\n call.abort();\n this._awaitedClips.delete(clipId);\n };\n this.addEventListener(\n 'daw-clip-ready',\n (e: Event) => {\n if ((e as CustomEvent<DawClipIdDetail>).detail.clipId !== clipId) return;\n cleanup();\n resolve(clipId);\n },\n { signal: call.signal }\n );\n this.addEventListener(\n 'daw-clip-error',\n (e: Event) => {\n const detail = (e as CustomEvent<DawClipErrorDetail>).detail;\n if (detail.clipId !== clipId) return;\n cleanup();\n reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));\n },\n { signal: call.signal }\n );\n // One arrangement, the one the clip goes into, subscribed to and read.\n const watched =\n pending && 'element' in pending && !this._isEntered(trackId)\n ? this._ownArrangement\n : this._arrangement;\n const stopWatching = watched.subscribe(() => {\n const present = watched.getTracks().some((t) => t.clips.some((c) => c.id === clipId));\n if (present) {\n seen = true;\n } else if (seen) {\n cleanup();\n reject(new Error('clip \"' + clipId + '\" was removed before its audio loaded'));\n }\n });\n call.signal.addEventListener('abort', stopWatching);\n // That arrangement swapped out (D2): the call ends; the clip stays there.\n this._playSignals.signalOf(watched).addEventListener(\n 'abort',\n (e) => {\n cleanup();\n reject(reasonOf(e.target as AbortSignal));\n },\n { signal: call.signal }\n );\n // The caller's abort (D3): the clip goes for good, and the call rejects.\n callerSignal?.addEventListener(\n 'abort',\n () => {\n cleanup();\n this._discardAddedClip(trackId, clipId);\n reject(reasonOf(callerSignal));\n },\n { signal: call.signal }\n );\n this._awaitedClips.set(clipId, {\n trackId,\n reject: (error) => {\n cleanup();\n reject(error);\n },\n });\n if (this._isEntered(trackId)) {\n seen = true;\n this._loadAndAppendClip(trackId, clipDesc);\n } else if (pending) {\n // It enters with its track.\n this._pending = new Map(this._pending).set(\n trackId,\n 'element' in pending\n ? { ...pending, extraClips: [...pending.extraClips, clipDesc] }\n : {\n ...pending,\n descriptor: {\n ...pending.descriptor,\n clips: [...pending.descriptor.clips, clipDesc],\n },\n }\n );\n }\n });\n }\n /**\n * Remove a clip by id: its `<daw-clip>` when there is one (the observer\n * removes the clip, as `select.remove(i)` removes an option), otherwise\n * the clip itself, one undo step. Undo brings the clip back with no\n * element. No-op with a warning when there is no such clip.\n */\n removeClip(trackId: string, clipId: string): void {\n const trackEl = this._trackElements.get(trackId);\n const clipEl = trackEl\n ? ([...trackEl.querySelectorAll('daw-clip')].find(\n (c) => (c as DawClipElement).clipId === clipId\n ) as DawClipElement | undefined)\n : undefined;\n if (clipEl) {\n clipEl.remove();\n // Detached, the MutationObserver is off: remove the clip here.\n if (!this.isConnected && this._isEntered(trackId)) this._removeClipFromTrack(trackId, clipId);\n return;\n }\n if (this._isEntered(trackId)) {\n this._removeClipFromTrack(trackId, clipId);\n return;\n }\n // A clip addClip() gave a track that has not entered yet.\n const pending = this._pending.get(trackId);\n if (pending) {\n const without = (clips: ClipDescriptor[]) => clips.filter((c) => c.clipId !== clipId);\n this._pending = new Map(this._pending).set(\n trackId,\n 'element' in pending\n ? { ...pending, extraClips: without(pending.extraClips) as DropClipDescriptor[] }\n : {\n ...pending,\n descriptor: { ...pending.descriptor, clips: without(pending.descriptor.clips) },\n }\n );\n this._rejectAwaitedClips((id) => id === clipId, 'the clip was removed before it loaded');\n return;\n }\n console.warn(\n '[dawcore] removeClip: no track found for id \"' + trackId + '\" (clipId \"' + clipId + '\")'\n );\n }\n /**\n * Change a clip's position (start/duration/offset), gain or name: one undo\n * step on the arrangement (#848; a clip still loading changes its loading\n * clip). A `<daw-clip>`'s properties show the change, its attributes do\n * not. Fades are a `<daw-clip>` declaration only (engine-side fades are\n * #489): `fadeIn` / `fadeOut` / `fadeType` here change nothing.\n *\n * Re-decoding (changing `src`) is not supported via this method — remove and\n * re-add the clip instead.\n */\n updateClip(trackId: string, clipId: string, partial: Partial<ClipConfig>): void {\n if (!this._isEntered(trackId)) {\n console.warn('[dawcore] updateClip: no track found for id \"' + trackId + '\"');\n return;\n }\n if (!this._clipValues(trackId, clipId)) {\n console.warn(\n '[dawcore] updateClip: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n const request: Partial<ClipLinkValues> = {};\n if (partial.start !== undefined) request.start = partial.start;\n if (partial.duration !== undefined) request.duration = partial.duration;\n if (partial.offset !== undefined) request.offset = partial.offset;\n if (partial.gain !== undefined) request.gain = partial.gain;\n if (partial.name !== undefined) request.name = partial.name;\n if (partial.midiNotes !== undefined) request.midiNotes = partial.midiNotes;\n if (partial.midiChannel !== undefined) request.midiChannel = partial.midiChannel;\n if (partial.midiProgram !== undefined) request.midiProgram = partial.midiProgram;\n this._requestClipChange(trackId, clipId, request);\n }\n // --- Playback ---\n /**\n * Start playback, optionally seeking to `startTime` first. When `endTime`\n * is provided, playback stops at that time (selection/annotation playback).\n */\n async play(startTime?: number, endTime?: number) {\n try {\n const engine = await this._ensureEngine();\n // Always init — resumes AudioContext if suspended (requires user gesture).\n await engine.init();\n // Register the editor's rAF loop BEFORE starting the low-level engine\n // playback: the catch block below relies on it having been started so\n // it can undo it. Bounded play(start, end) completion does NOT depend\n // on this loop racing the transport: the native transport's timer runs\n // in a Worker (not rAF, #636) and reports its endTime self-stop through\n // the adapter's onPlaybackEnded hook → engine 'stop' → the daw-stop\n // dispatch in the engine stop handler. This loop's own time >= endTime\n // check is a belt-and-braces path for adapters without the hook.\n this._activePlayEndTime = endTime ?? null;\n this._startPlayhead();\n engine.play(startTime, endTime);\n this.dispatchEvent(new CustomEvent('daw-play', { bubbles: true, composed: true }));\n } catch (err) {\n // _startPlayhead() above runs BEFORE engine.play() (see the ordering\n // comment above), so a throwing engine.play() (EditorEngine rolls\n // back its own state and rethrows on adapter.play() failure) leaves a\n // dangling rAF loop unless we undo the pre-start here — mirrors stop().\n this._stopPlayhead();\n this._activePlayEndTime = null;\n console.warn('[dawcore] Playback failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'play', error: err },\n })\n );\n }\n }\n pause() {\n if (!this._engine) return;\n this._engine.pause();\n this._stopPlayhead();\n this.dispatchEvent(new CustomEvent('daw-pause', { bubbles: true, composed: true }));\n }\n stop() {\n if (!this._engine) return;\n this._activePlayEndTime = null;\n // The engine 'stop' handler fires SYNCHRONOUSLY during engine.stop() —\n // bracket it so that handler's own daw-stop dispatch is suppressed and\n // this method remains the single dispatcher for a consumer-initiated stop.\n this._inConsumerStop = true;\n try {\n this._engine.stop();\n } finally {\n this._inConsumerStop = false;\n }\n this._stopPlayhead();\n this.dispatchEvent(new CustomEvent('daw-stop', { bubbles: true, composed: true }));\n }\n /** Toggle between play and pause. */\n togglePlayPause() {\n if (this.isRecording) {\n this.togglePauseRecording();\n } else if (this._isPlaying) {\n this.pause();\n } else {\n this.play();\n }\n }\n /** Run `fn` with the stop-settle daw-timeupdate suppressed. Every\n * stop-adjacent code path that immediately re-positions (seek, split,\n * empty-timeline rewind) must use this — engine.stop() rewinds to the\n * play-start position and the settle would leak a backward-jumping\n * daw-timeupdate to consumers (CLAUDE.md seek-while-playing invariant).\n * The `finally` is load-bearing: a wedged true silently drops every\n * subsequent stop-settle dispatch. */\n private _withSeekSuppression(fn: () => void) {\n this._inSeekTransition = true;\n try {\n fn();\n } finally {\n this._inSeekTransition = false;\n }\n }\n\n seekTo(time: number) {\n if (!this._engine) {\n console.warn('[dawcore] seekTo: engine not ready, call ignored');\n return;\n }\n if (!Number.isFinite(time)) {\n // NaN would reach the adapter clock and wedge playback until a valid seek.\n console.warn('[dawcore] seekTo: ignoring non-finite time ' + String(time));\n return;\n }\n const target = Math.max(0, time);\n if (this._isPlaying) {\n // Transport needs stop+play to reschedule audio sources at the new\n // position — but via DIRECT engine calls (synchronous), not the public\n // stop()/play(): those dispatch daw-stop/daw-play (spurious for a\n // seek — consumers keyed on them misfire on every programmatic seek)\n // and the async play() opens a window where a user pause is overridden\n // by the deferred play. The engine is already initialized while\n // playing. Mirrors the pointer-handler seek path.\n try {\n this._withSeekSuppression(() => this._engine!.stop());\n this._engine.play(target);\n } catch (err) {\n // The engine rethrows adapter failures — surface via daw-error like\n // the public play() path does, instead of an unheralded throw.\n console.warn('[dawcore] seekTo: engine reschedule failed: ' + String(err));\n this.dispatchEvent(\n new CustomEvent('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'seek', error: err },\n })\n );\n return;\n }\n // Seeking past a bounded (selection/annotation) play reschedules via\n // the engine directly (no endTime) — clear the stale watermark so\n // the rAF loop doesn't stop the resumed playback prematurely at the\n // old bound. Mirrors Transport.seek()'s own _endTime clearing.\n this._activePlayEndTime = null;\n this._currentTime = target;\n this._startPlayhead();\n } else {\n this._engine.seek(target);\n this._currentTime = target;\n this._stopPlayhead();\n }\n this.dispatchEvent(\n new CustomEvent('daw-seek', {\n bubbles: true,\n composed: true,\n detail: { time: target },\n })\n );\n }\n\n /**\n * A clip or track drag is in progress: undo and redo do nothing until it\n * ends (#848). A clip counts once its pointer has moved past the drag\n * threshold; annotation drags do not count (annotations are not in the\n * undo history).\n */\n get _dragInProgress(): boolean {\n return this._clipPointer.isDragging || this._trackReorderDrag.isActive;\n }\n\n /**\n * Cancel every drag in progress, as a `pointercancel` would. Returns whether\n * one was. A clip or annotation press that has not moved is not a drag and\n * is left alone, unless `includePresses` (the editor's disconnect, which\n * ends every pointer interaction).\n */\n _cancelDrags(includePresses = false): boolean {\n let cancelled = false;\n if (includePresses || this._clipPointer.isDragging) {\n cancelled = this._pointer.cancelClipDrag() || cancelled;\n }\n if (this._trackReorderDrag.isActive) {\n this._trackReorderDrag.cancel();\n cancelled = true;\n }\n const annotation = this._annotationDrag;\n if (includePresses ? annotation.isActive : annotation.isDragging) {\n annotation.cancel();\n cancelled = true;\n }\n return cancelled;\n }\n\n /**\n * Escape during a drag cancels it and does nothing else: the default is\n * prevented, so `<daw-keyboard-shortcuts>` (core's `handleKeyboardEvent`)\n * does not also stop playback. No `stopPropagation`: an app's own listener\n * can read `defaultPrevented`.\n */\n private _onDragEscape = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return;\n if (this._cancelDrags()) e.preventDefault();\n };\n\n /** Undo the last edit. Does nothing while a drag is in progress. */\n undo(): void {\n if (this._dragInProgress) return;\n if (!this._engine) {\n console.warn('[dawcore] undo: engine not ready, call ignored');\n return;\n }\n this._engine.undo();\n }\n\n /** Redo the last undone edit. Does nothing while a drag is in progress. */\n redo(): void {\n if (this._dragInProgress) return;\n if (!this._engine) {\n console.warn('[dawcore] redo: engine not ready, call ignored');\n return;\n }\n this._engine.redo();\n }\n\n /** Whether undo is available. */\n get canUndo(): boolean {\n return this._engine?.canUndo ?? false;\n }\n\n /** Whether redo is available. */\n get canRedo(): boolean {\n return this._engine?.canRedo ?? false;\n }\n\n /** Split the clip under the playhead on the selected track. */\n splitAtPlayhead(): boolean {\n return performSplitAtPlayhead({\n effectiveSampleRate: this.effectiveSampleRate,\n currentTime: this.currentTime,\n isPlaying: this._isPlaying,\n engine: this._engine,\n dispatchEvent: (e: Event) => this.dispatchEvent(e),\n stop: () => {\n // Suppressed settle: without it every split during playback leaks a\n // backward-jumping daw-timeupdate (30→0→30) before play(time) resumes.\n this._withSeekSuppression(() => {\n this._engine?.stop();\n this._stopPlayhead();\n });\n },\n // Call engine.play directly (synchronous) — not the async editor play()\n // which yields to microtask queue via await engine.init(). Engine is\n // already initialized at split time; the async gap causes audio desync.\n play: (time: number) => {\n this._engine?.play(time);\n this._startPlayhead();\n },\n });\n }\n\n // --- Recording ---\n recordingStream: MediaStream | null = null;\n get currentTime(): number {\n // During playback, read live from engine (not cached _currentTime)\n if (this._isPlaying && this._engine) {\n return this._engine.getCurrentTime();\n }\n return this._currentTime;\n }\n /** Read-only: whether playback is running (HTMLMediaElement-adjacent). */\n get isPlaying(): boolean {\n return this._isPlaying;\n }\n /** Read-only: total content duration in seconds. */\n get duration(): number {\n return this._duration;\n }\n get isRecording(): boolean {\n return this._recordingController.isRecording;\n }\n get isRecordingPaused(): boolean {\n return this._recordingController.isPaused;\n }\n pauseRecording(): void {\n this._recordingController.pauseRecording();\n }\n resumeRecording(): void {\n this._recordingController.resumeRecording();\n // Programmatic resume bypasses togglePauseRecording — clear the\n // ref so the next pause cycle doesn't restart Transport based on\n // stale state from an earlier toggle.\n this._wasPlayingDuringRecording = false;\n }\n /**\n * Audacity-style pause toggle for active recordings: pauses both the\n * worklet capture and (if running) the playback Transport. On resume,\n * Transport restarts only if it was running before — non-overdub\n * recordings stay silent on resume.\n */\n togglePauseRecording(): void {\n if (!this.isRecording) return;\n if (this.isRecordingPaused) {\n // Snapshot the flag before resumeRecording — that method clears\n // the ref defensively (so external callers don't leak it into the\n // next cycle), so reading after the call is too late.\n const wasPlaying = this._wasPlayingDuringRecording;\n this.resumeRecording();\n if (wasPlaying) {\n // play() is async on the editor; fire and forget — caller doesn't await.\n void this.play(this.currentTime);\n }\n } else {\n this.pauseRecording();\n if (this._isPlaying) {\n this._wasPlayingDuringRecording = true;\n this.pause();\n }\n }\n }\n /** Set in togglePauseRecording when Transport is paused alongside the\n * worklet, so resume can restart it. Cleared on resume and on stop. */\n private _wasPlayingDuringRecording = false;\n stopRecording(): Promise<void> {\n this._wasPlayingDuringRecording = false;\n return this._recordingController.stopRecording();\n }\n _addRecordedClip(\n trackId: string,\n buf: AudioBuffer,\n startSample: number,\n durSamples: number,\n offsetSamples = 0,\n clipName?: string\n ) {\n addRecordedClip(this, trackId, buf, startSample, durSamples, offsetSamples, clipName);\n }\n // --- RecordingHost bridge methods for cross-context worklet support ---\n // These delegate to the adapter's context type (native or standardized-audio-context).\n // The RecordingController calls these when available, falling back to native APIs.\n\n addWorkletModule(url: string): Promise<void> {\n return (\n this._externalAdapter?.addWorkletModule?.(url) ??\n this.audioContext.audioWorklet.addModule(url)\n );\n }\n\n createAudioWorkletNode(name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode {\n return (\n this._externalAdapter?.createAudioWorkletNode?.(name, options) ??\n new AudioWorkletNode(this.audioContext, name, options)\n );\n }\n\n createMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode {\n return (\n this._externalAdapter?.createMediaStreamSource?.(stream) ??\n this.audioContext.createMediaStreamSource(stream)\n );\n }\n\n async startRecording(stream?: MediaStream, options?: RecordingOptions): Promise<void> {\n const s = stream ?? this.recordingStream;\n if (!s) {\n console.warn('[dawcore] startRecording: no stream provided and recordingStream is null');\n return;\n }\n // A take is audio: it cannot land on a MIDI track (#756).\n const targetId = options?.trackId ?? this._selectedTrackId;\n const target = targetId\n ? this._arrangement.getTracks().find((t) => t.id === targetId)\n : undefined;\n if (targetId && target && trackKind(target) === 'midi') {\n const error = new Error(\n 'Cannot record onto MIDI track \"' +\n target.name +\n '\": a recording is audio. Select or create an audio track first.'\n );\n console.warn('[dawcore] startRecording: ' + error.message);\n this.dispatchEvent(\n new CustomEvent<DawRecordingErrorDetail>('daw-recording-error', {\n bubbles: true,\n composed: true,\n detail: { trackId: targetId, error },\n })\n );\n return;\n }\n await this._recordingController.startRecording(s, options);\n }\n\n /** Live-recording preview left/width. Beats mode uses the same tick-space\n * math as finalized clips — the sample÷renderSpp path is ceil-quantized,\n * so the take would visibly jump sideways on finalization (drift grows\n * with distance from t=0; CLAUDE.md live-preview parity invariant). */\n private _previewPosition(\n startSample: number,\n audibleSamples: number\n ): { left: number; width: number } {\n if (this.scaleMode === 'beats') {\n const sr = this.effectiveSampleRate;\n const startSec = startSample / sr;\n const startTick = this._secondsToTicks(startSec);\n const endTick = this._secondsToTicks(startSec + audibleSamples / sr);\n const left = Math.round(startTick / this.ticksPerPixel);\n return { left, width: Math.round(endTick / this.ticksPerPixel) - left };\n }\n const renderSpp = this._renderSpp;\n return {\n left: Math.floor(startSample / renderSpp),\n width: Math.floor(audibleSamples / renderSpp),\n };\n }\n\n private _renderRecordingPreview(trackId: string, chH: number) {\n const rs = this._recordingController.getSession(trackId);\n if (!rs) return '';\n // Skip latency samples in the preview — they'll be sliced on finalization.\n // Position stays at startSample (same as finalized clip).\n const audibleSamples = Math.max(0, rs.totalSamples - rs.latencySamples);\n if (audibleSamples === 0) return '';\n const renderSpp = this._renderSpp;\n const latencyPixels = Math.floor(rs.latencySamples / renderSpp);\n const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);\n // Same container + header chrome as finalized clips so the take reads as\n // a clip WHILE it's being captured, and the waveforms sit at the same\n // vertical offset they'll have after finalization. The container's width\n // stays in sync with the growing take: the RecordingController calls\n // requestUpdate() whenever the preview grows a pixel (overflow:hidden on\n // .clip-container would otherwise clip the live canvas growth).\n const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;\n const height = hdrH + chH * rs.peaks.length;\n return html`<div\n class=\"clip-container recording-preview\"\n style=\"left:${left}px;top:0;width:${w}px;height:${height}px;\"\n >\n ${hdrH > 0\n ? html`<div class=\"clip-header\" data-track-id=${trackId}>\n <span>${rs.clipName ?? 'Recording…'}</span>\n </div>`\n : ''}\n ${rs.peaks.map((chPeaks, ch) => {\n // Slice peaks to skip latency prefix (2 entries per pixel: min/max)\n const slicedPeaks = latencyPixels > 0 ? chPeaks.slice(latencyPixels * 2) : chPeaks;\n return html`\n <daw-waveform\n data-recording-track=${trackId}\n data-recording-channel=${ch}\n style=\"position:absolute;left:0;top:${hdrH + ch * chH}px;\"\n .peaks=${slicedPeaks}\n .length=${w}\n .waveHeight=${chH}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${left}\n ></daw-waveform>\n `;\n })}\n </div>`;\n }\n // --- Playback animation (single RAF loop: playhead + daw-timeupdate) ---\n /** Convert playback seconds to a timeline pixel offset for the active mode. */\n private _timeToPixels = (time: number): number => {\n if (this.scaleMode === 'beats') {\n return this._secondsToTicks(time) / this.ticksPerPixel;\n }\n return (time * this.effectiveSampleRate) / this.samplesPerPixel;\n };\n\n _startPlayhead() {\n if (!this._engine) return;\n const engine = this._engine;\n // engine.getAudibleTime(): while playing, engine time minus hardware DAC\n // latency (outputLatency) and scheduler lookahead (0.1s on Tone-backed\n // adapters, 0 native), held at the play-start position during the\n // pre-roll window. Without the subtraction the playhead leads audio by\n // ~100ms with the Tone adapter.\n // Runs even when the playhead element isn't rendered (empty/indefinite\n // editors) so daw-timeupdate consumers still get frames.\n this._playbackAnimation.start(() => {\n // Bounded playback (selection/annotation via play(start, end)): an\n // adapter with the onPlaybackEnded hook reports its endTime self-stop\n // through the engine's `stop` event; this check is the fallback for\n // adapters without it. Checked before the whole-track duration bound\n // below.\n if (\n this._activePlayEndTime !== null &&\n !this.isRecording &&\n engine.getCurrentTime() >= this._activePlayEndTime\n ) {\n this.stop();\n const t = this._currentTime;\n return Number.isFinite(t) ? Math.max(0, t) : 0;\n }\n // Auto-stop at the end of the timeline (player-style default — parity\n // with the React provider's animation loop). `indefinite-playback`\n // opts out (DAW-style: roll until explicit stop), and an active\n // recording session must run past the end of existing material\n // (punch-in takes land beyond the current duration). Raw engine time\n // is the boundary check, matching React's loop.\n if (\n !this.indefinitePlayback &&\n !this.isRecording &&\n engine.getCurrentTime() >= this._duration\n ) {\n this.stop();\n // stop() rewinds to the play-start position via the engine 'stop'\n // handler; settle this frame on that resting position.\n const t = this._currentTime;\n return Number.isFinite(t) ? Math.max(0, t) : 0;\n }\n return engine.getAudibleTime();\n });\n }\n _stopPlayhead() {\n // Resting playhead displays the raw position — latency compensation is a\n // playback-time concept (Transport scheduling vs audible output). A\n // seeked/stopped/paused cursor shows exactly the commanded position.\n // Storage (`_currentTime`) is already raw, so play() resumes correctly.\n const t = this._currentTime;\n const visualTime = Number.isFinite(t) ? Math.max(0, t) : 0;\n this._playbackAnimation.stop(visualTime, { dispatch: !this._inSeekTransition });\n }\n private _getPlayhead(): DawPlayheadElement | null {\n return this.shadowRoot?.querySelector('daw-playhead') as DawPlayheadElement | null;\n }\n\n /** True when the controls column should be rendered (and its selector is valid). */\n private get _showControls(): boolean {\n return this._getOrderedTracks().length > 0 || this.indefinitePlayback || this.fillViewport;\n }\n\n /** True when the ruler header band should be rendered (and its selector is valid). */\n private get _showRuler(): boolean {\n return (\n (this._getOrderedTracks().length > 0 ||\n this.scaleMode === 'beats' ||\n this.indefinitePlayback ||\n this.fillViewport) &&\n this.timescale\n );\n }\n\n /**\n * `<daw-track>` elements the page moved (one MutationObserver batch): each\n * is placed after the arrangement track of the nearest `<daw-track>` before\n * it, in DOM order, as one undo step (#848 P13). Elements whose track is\n * not in the arrangement are left alone (a queued one enters at its DOM\n * position). The arrangement's own order changes (an Undo) move no element.\n */\n private _placeMovedTracks(movedIds: ReadonlySet<string>): void {\n const els = [...this.querySelectorAll('daw-track')] as DawTrackElement[];\n const moved = els.filter((el) => movedIds.has(el.trackId) && this._isEntered(el.trackId));\n if (moved.length === 0) return;\n const arrangement = this._arrangement;\n arrangement.beginTransaction();\n try {\n for (const el of moved) {\n const others = arrangement\n .getTracks()\n .map((t) => t.id)\n .filter((id) => id !== el.trackId);\n // The index it already has changes nothing.\n arrangement.reorderTrack(el.trackId, entryIndex(els, el.trackId, others));\n }\n } finally {\n arrangement.commitTransaction();\n }\n }\n\n /**\n * The rows, in the arrangement's order (#848): each track's loaded clips\n * (the engine's projection, with the current mix) and the clips still loading.\n */\n private _getOrderedTracks(): Array<[string, ClipTrack, LoadingClip[]]> {\n const rows: Array<[string, ClipTrack, LoadingClip[]]> = [];\n for (const track of this._arrangement.getTracks()) {\n const loaded = loadedTrack(\n track,\n this._mixOf(track.id),\n this._arrangement.recordingTrackIds.has(track.id)\n );\n rows.push([track.id, loaded, track.clips.filter(isLoadingClip)]);\n }\n return rows;\n }\n /**\n * A clip still loading: a placeholder box where its length is known, with\n * its `.dat` peaks when they came, drawn failed when its source failed. Its\n * header carries no clip id, so it cannot be dragged.\n */\n private _renderPlaceholder(\n clip: LoadingClip,\n row: { trackId: string; trackHeight: number; descriptor?: RowInfo }\n ) {\n const seconds = this._placeholderSeconds(clip);\n if (seconds === null) return '';\n const sr = this.effectiveSampleRate;\n const spp = this._renderSpp;\n const startSec = clip.start ?? 0;\n let left: number;\n let width: number;\n if (this.scaleMode === 'beats') {\n left = Math.round(this._secondsToTicks(startSec) / this.ticksPerPixel);\n width = Math.round(this._secondsToTicks(startSec + seconds) / this.ticksPerPixel) - left;\n } else {\n const startSample = Math.round(startSec * sr);\n left = Math.floor(startSample / spp);\n width = clipPixelWidth(startSample, Math.round(seconds * sr), spp);\n }\n const failed =\n this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === 'failed';\n const peakData = this._previewPeaks.get(clip.id);\n const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;\n const chH = this.waveHeight;\n return html`<div\n class=\"clip-container placeholder ${failed ? 'failed' : ''}\"\n style=\"left:${left}px;top:0;width:${width}px;height:${row.trackHeight}px;\"\n data-clip-id=${clip.id}\n >\n ${hdrH > 0\n ? html`<div class=\"clip-header\">\n <span>${clip.name || row.descriptor?.name || ''}</span>\n </div>`\n : ''}\n ${(peakData?.data ?? []).map(\n (chPeaks, chIdx) =>\n html`<daw-waveform\n style=\"position:absolute;left:0;top:${hdrH + chIdx * chH}px;\"\n .peaks=${chPeaks}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${left}\n ></daw-waveform>`\n )}\n </div>`;\n }\n\n // --- Render ---\n render() {\n const sr = this.effectiveSampleRate;\n const spp = this._renderSpp;\n // In beats mode, derive selection pixels from tick space (same as clip positions)\n // to avoid 1-2px quantization error from the sample round-trip.\n let selStartPx: number;\n let selEndPx: number;\n if (this.scaleMode === 'beats') {\n const startTick = this._secondsToTicks(this._selectionStartTime);\n const endTick = this._secondsToTicks(this._selectionEndTime);\n selStartPx = startTick / this.ticksPerPixel;\n selEndPx = endTick / this.ticksPerPixel;\n } else {\n selStartPx = (this._selectionStartTime * sr) / spp;\n selEndPx = (this._selectionEndTime * sr) / spp;\n }\n\n // Precompute track info once for both controls column and timeline\n const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {\n // What the template reads about the track: from the arrangement and the extras.\n const descriptor: RowInfo = {\n name: track.name ?? '',\n kind: trackKind(track),\n renderMode: this._renderModeOf(trackId),\n };\n const firstPeaks = [...track.clips, ...loading]\n .map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id))\n .find((p) => p && p.data.length > 0);\n // Use recording session channel count if no finalized clips yet\n const recSession = this._recordingController.getSession(trackId);\n const numChannels = firstPeaks\n ? firstPeaks.data.length\n : recSession\n ? recSession.channelCount\n : 1;\n return {\n trackId,\n track,\n loading,\n descriptor,\n numChannels,\n trackHeight: this.waveHeight * numChannels + (this.clipHeaders ? this.clipHeaderHeight : 0),\n };\n });\n\n const showControls = this._showControls;\n const showRuler = this._showRuler;\n\n return html`\n ${showRuler\n ? html`<div class=\"header-row\" style=\"height: ${RULER_HEIGHT}px;\">\n ${showControls ? html`<div class=\"ruler-gap\"></div>` : ''}\n <div class=\"ruler-viewport\" @pointerdown=${this._pointer.onPointerDown}>\n <div\n class=\"ruler-content\"\n style=\"width: ${this._totalWidth > 0 ? this._totalWidth + 'px' : '100%'};\"\n >\n <daw-ruler\n .samplesPerPixel=${spp}\n .sampleRate=${this.effectiveSampleRate}\n .duration=${this._duration}\n .scaleMode=${this.scaleMode}\n .ticksPerPixel=${this.ticksPerPixel}\n .meterEntries=${this._meterEntries}\n .ppqn=${this.ppqn}\n .totalWidth=${this._totalWidth}\n .rulerHeight=${RULER_HEIGHT}\n ></daw-ruler>\n </div>\n </div>\n </div>`\n : ''}\n <div class=\"body\">\n ${showControls\n ? html`<div class=\"controls-viewport\">\n <div class=\"controls-column\">\n ${this._annotations.tracks.map(\n (track) =>\n html`<div\n class=\"annotation-lane-spacer\"\n style=\"height: ${ANNOTATION_LANE_HEIGHT}px;\"\n >\n <span class=\"annotation-lane-name\">${track.name}</span>\n </div>`\n )}\n ${repeat(\n orderedTracks,\n // Keyed by track: a swap or an outside reorder must not hand\n // a row (and a slider gesture held in it) to another track.\n (t) => t.trackId,\n (t, i) => {\n const mix = this._mixOf(t.trackId);\n return html`\n <daw-track-controls\n style=\"height: ${t.trackHeight}px;\"\n .trackId=${t.trackId}\n .trackName=${t.descriptor?.name ?? 'Untitled'}\n .volume=${mix.volume}\n .pan=${mix.pan}\n .muted=${mix.muted}\n .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}\n .soloed=${mix.soloed}\n .reorderable=${this.trackReordering}\n .trackIndex=${i}\n .trackCount=${orderedTracks.length}\n ></daw-track-controls>\n `;\n }\n )}\n </div>\n </div>`\n : ''}\n <div class=\"scroll-area\">\n <div\n class=\"timeline ${this._dragOver ? 'drag-over' : ''}\"\n style=\"width: ${this._totalWidth > 0 ? this._totalWidth + 'px' : '100%'};\"\n data-playing=${this._isPlaying}\n @pointerdown=${this._pointer.onPointerDown}\n @dragover=${this._onDragOver}\n @dragleave=${this._onDragLeave}\n @drop=${this._onDrop}\n >\n ${this._annotations.renderLanes(\n spp,\n this.effectiveSampleRate,\n this._annotationDrag.onPointerDown,\n this.scaleMode === 'beats' ? this.ticksPerPixel : null\n )}\n ${this.scaleMode === 'beats'\n ? html`<daw-grid\n style=\"top: ${this._annotations.totalLaneHeight}px;\"\n .ticksPerPixel=${this.ticksPerPixel}\n .meterEntries=${this._meterEntries}\n .ppqn=${this.ppqn}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .length=${this._totalWidth}\n .height=${orderedTracks.length > 0\n ? orderedTracks.reduce((sum, t) => sum + t.trackHeight, 0)\n : this._emptyGridHeight}\n ></daw-grid>`\n : ''}\n ${orderedTracks.length > 0 ||\n this.scaleMode === 'beats' ||\n this.indefinitePlayback ||\n this.fillViewport\n ? html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>\n <daw-playhead></daw-playhead>`\n : ''}\n ${repeat(\n orderedTracks,\n (t) => t.trackId,\n (t) => {\n const channelHeight = this.waveHeight;\n return html`\n <div\n class=\"track-row ${t.trackId === this._selectedTrackId ? 'selected' : ''}\"\n style=\"height: ${t.trackHeight}px;\"\n data-track-id=${t.trackId}\n >\n ${t.track.clips.map((clip) => {\n const peakData =\n this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);\n // In beats mode, derive pixel positions from tick space to\n // match grid lines exactly. The sample→spp path introduces\n // 1-2px quantization error from integer sample rounding.\n let clipLeft: number;\n let width: number;\n if (this.scaleMode === 'beats') {\n // Use startTick directly when available — stable across BPM changes.\n // Fall back to sample→seconds→ticks for clips without startTick.\n const startTick =\n clip.startTick !== undefined\n ? clip.startTick\n : this._secondsToTicks(clip.startSample / sr);\n const durSec = clip.durationSamples / sr;\n const startSec =\n clip.startTick !== undefined\n ? this._ticksToSeconds(clip.startTick)\n : clip.startSample / sr;\n const endTick = this._secondsToTicks(startSec + durSec);\n clipLeft = Math.round(startTick / this.ticksPerPixel);\n width = Math.round(endTick / this.ticksPerPixel) - clipLeft;\n } else {\n clipLeft = Math.floor(clip.startSample / spp);\n width = clipPixelWidth(clip.startSample, clip.durationSamples, spp);\n }\n // Per-segment waveform rendering for variable tempo.\n // Uses base-scale (128) peaks directly — segments handle stretching,\n // so no BPM-dependent intermediate resampling needed.\n let clipSegments: WaveformSegment[] | undefined;\n let segmentChannels: Peaks[] | undefined;\n if (this.scaleMode === 'beats' && this.secondsToTicks) {\n const audioBuffer = this._clipBuffers.get(clip.id);\n const basePeaks = audioBuffer\n ? this._peakPipeline.getBaseScalePeaks(\n audioBuffer,\n this.mono,\n clip.offsetSamples,\n clip.durationSamples\n )\n : null;\n if (basePeaks) {\n const baseScale = basePeaks.scale;\n segmentChannels = basePeaks.peaks.data;\n const MIN_RENDER_STEP = 80;\n const stepTicks = Math.max(\n MIN_RENDER_STEP,\n Math.ceil(this.ticksPerPixel)\n );\n const startSec =\n clip.startTick !== undefined\n ? this._ticksToSeconds(clip.startTick)\n : clip.startSample / sr;\n const clipOffsetSec = clip.offsetSamples / sr;\n const segStartTick =\n clip.startTick !== undefined\n ? clip.startTick\n : this._secondsToTicks(startSec);\n const endTick = this._secondsToTicks(\n startSec + clip.durationSamples / sr\n );\n clipSegments = [];\n for (let tick = segStartTick; tick < endTick; tick += stepTicks) {\n const segEndTick = Math.min(tick + stepTicks, endTick);\n const segStartAudioSec =\n this._ticksToSeconds(tick) - startSec + clipOffsetSec;\n const segEndAudioSec =\n this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;\n // Peak indices at base scale (128) — clamped to valid range.\n const segStartSample = Math.round(segStartAudioSec * sr);\n const segEndSample = Math.round(segEndAudioSec * sr);\n const totalPeaks = clip.durationSamples / baseScale;\n clipSegments.push({\n peakStart: Math.max(\n 0,\n (segStartSample - clip.offsetSamples) / baseScale\n ),\n peakEnd: Math.min(\n totalPeaks,\n (segEndSample - clip.offsetSamples) / baseScale\n ),\n pixelStart: (tick - segStartTick) / this.ticksPerPixel,\n pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel,\n });\n }\n }\n }\n const channels: Peaks[] = segmentChannels ??\n peakData?.data ?? [new Int16Array(0)];\n const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;\n const chH = this.waveHeight;\n return html` <div\n class=\"clip-container\"\n style=\"left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;\"\n data-clip-id=${clip.id}\n >\n ${hdrH > 0\n ? html`<div\n class=\"clip-header\"\n data-clip-id=${clip.id}\n data-track-id=${t.trackId}\n ?data-interactive=${this.interactiveClips}\n >\n <span>${clip.name || t.descriptor?.name || ''}</span>\n </div>`\n : ''}\n ${t.descriptor?.kind === 'midi'\n ? html`<daw-piano-roll\n style=\"position:absolute;left:0;top:${hdrH}px;\"\n .midiNotes=${clip.midiNotes ?? []}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH * channels.length}\n .samplesPerPixel=${this._renderSpp}\n .sampleRate=${this.effectiveSampleRate}\n .clipOffsetSeconds=${(clip.offsetSamples ?? 0) /\n this.effectiveSampleRate}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${clipLeft}\n ?selected=${t.trackId === this._selectedTrackId}\n ></daw-piano-roll>`\n : t.descriptor?.renderMode === 'spectrogram'\n ? channels.map(\n (_chPeaks, chIdx) =>\n html`<daw-spectrogram\n style=\"position:absolute;left:0;top:${hdrH +\n chIdx * chH}px;height:${chH}px;width:${peakData?.length ??\n width}px;\"\n .clipId=${clip.id}\n .trackId=${t.trackId}\n .channelIndex=${chIdx}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH}\n .samplesPerPixel=${this._renderSpp}\n .sampleRate=${this.effectiveSampleRate}\n .clipOffsetSeconds=${(clip.offsetSamples ?? 0) /\n this.effectiveSampleRate}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${clipLeft}\n ></daw-spectrogram>`\n )\n : channels.map(\n (chPeaks, chIdx) =>\n html` <daw-waveform\n style=\"position:absolute;left:0;top:${hdrH + chIdx * chH}px;\"\n .peaks=${chPeaks}\n .length=${peakData?.length ?? width}\n .waveHeight=${chH}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n .gain=${this.gainScaledWaveforms ? (clip.gain ?? 1) : 1}\n .visibleStart=${this._viewport.visibleStart}\n .visibleEnd=${this._viewport.visibleEnd}\n .originX=${clipLeft}\n .segments=${clipSegments}\n ></daw-waveform>`\n )}\n ${this.interactiveClips\n ? html` <div\n class=\"clip-boundary\"\n data-boundary-edge=\"left\"\n data-clip-id=${clip.id}\n data-track-id=${t.trackId}\n ></div>\n <div\n class=\"clip-boundary\"\n data-boundary-edge=\"right\"\n data-clip-id=${clip.id}\n data-track-id=${t.trackId}\n ></div>`\n : ''}\n </div>`;\n })}\n ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}\n ${this._renderRecordingPreview(t.trackId, channelHeight)}\n </div>\n `;\n }\n )}\n </div>\n </div>\n </div>\n <slot></slot>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-editor': DawEditorElement;\n }\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 offset += 4;\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 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\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 console.warn('[dawcore] Failed to create peaks worker (CSP restriction?): ' + String(err));\n return {\n generate() {\n return Promise.reject(\n new Error(\n 'Peaks worker unavailable (CSP may block blob: URLs). Add blob: to worker-src directive.'\n )\n );\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 let idCounter = 0;\n\n worker.onmessage = (e: MessageEvent) => {\n const msg = e.data;\n const entry = pending.get(msg.id);\n if (!entry) {\n console.warn('[dawcore] Received worker message for unknown id: ' + String(msg.id));\n return;\n }\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 const reason = e.error ?? new Error(e.message);\n console.warn('[dawcore] Peaks worker crashed: ' + String(reason));\n terminated = true;\n worker.terminate();\n for (const [, entry] of pending) {\n entry.reject(reason);\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","/**\n * Utilities for converting WaveformData to PeakData format.\n * Adapted from @waveform-playlist/browser waveformDataLoader.ts.\n */\n\nimport WaveformData from 'waveform-data';\nimport type { PeakData, Peaks } from '@waveform-playlist/core';\n\n/**\n * Slice and resample WaveformData with aligned source indices.\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 const targetStart = Math.floor(offsetSamples / samplesPerPixel);\n const targetEnd = Math.ceil((offsetSamples + durationSamples) / samplesPerPixel);\n\n const sourceStart = Math.max(0, Math.floor(targetStart * ratio));\n const sourceEnd = Math.min(waveformData.length, Math.ceil(targetEnd * ratio));\n\n if (sourceStart >= sourceEnd) {\n return null;\n }\n\n processedData = processedData.slice({\n startIndex: sourceStart,\n endIndex: sourceEnd,\n });\n processedData = processedData.resample({ scale: samplesPerPixel });\n } else {\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, handling all channels, mono merging,\n * slicing, and resampling.\n */\nexport function extractPeaks(\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 const numChannels = isMono ? 1 : waveformData.channels;\n const emptyData: Peaks[] = Array.from({ length: numChannels }, () =>\n bits === 8 ? new Int8Array(0) : new Int16Array(0)\n );\n return { length: 0, data: emptyData, bits };\n }\n\n const numChannels = processedData.channels;\n const bits = processedData.bits as 8 | 16;\n\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 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 { length: numPeaks, data: [monoPeaks], bits };\n }\n\n const peakLength = channelPeaks.length > 0 ? channelPeaks[0].length / 2 : 0;\n return { length: peakLength, data: channelPeaks, bits };\n}\n","/**\n * Peak generation pipeline: AudioBuffer → web worker → WaveformData → PeakData.\n *\n * Manages worker lifecycle, WaveformData caching per AudioBuffer (WeakMap),\n * inflight dedup, and peak extraction via resample() for any zoom level\n * coarser than the base scale.\n *\n * The base scale determines the finest zoom level that can be rendered without\n * regenerating. Resampling only works to coarser (larger) scales. Set baseScale\n * to the finest zoom level the user might need.\n */\n\nimport type WaveformData from 'waveform-data';\nimport type { PeakData } from '@waveform-playlist/core';\nimport { createPeaksWorker, type PeaksWorkerApi } from './peaksWorker';\nimport { extractPeaks } from './waveformDataUtils';\n\nexport class PeakPipeline {\n private _worker: PeaksWorkerApi | null = null;\n private _cache = new WeakMap<AudioBuffer, WaveformData>();\n private _inflight = new WeakMap<AudioBuffer, Promise<WaveformData>>();\n private _baseScale: number;\n private _bits: 8 | 16;\n\n constructor(baseScale = 128, bits: 8 | 16 = 16) {\n this._baseScale = baseScale;\n this._bits = bits;\n }\n\n /**\n * Inject externally-loaded WaveformData (e.g., from a .dat file) into the cache.\n * Prevents worker generation for this AudioBuffer on all subsequent calls.\n */\n cacheWaveformData(audioBuffer: AudioBuffer, waveformData: WaveformData): void {\n this._cache.set(audioBuffer, waveformData);\n }\n\n /**\n * Generate PeakData for a clip from its AudioBuffer.\n * Uses cached WaveformData when available; otherwise generates via worker.\n * Worker generates at baseScale (default 128); extractPeaks resamples to the requested zoom.\n */\n async generatePeaks(\n audioBuffer: AudioBuffer,\n samplesPerPixel: number,\n isMono: boolean,\n offsetSamples?: number,\n durationSamples?: number\n ): Promise<PeakData> {\n const waveformData = await this._getWaveformData(audioBuffer);\n const effectiveScale = this._clampScale(waveformData, samplesPerPixel);\n try {\n return extractPeaks(waveformData, effectiveScale, isMono, offsetSamples, durationSamples);\n } catch (err) {\n console.warn('[dawcore] extractPeaks failed: ' + String(err));\n throw err;\n }\n }\n\n /**\n * Re-extract peaks for all clips at a new zoom level using cached WaveformData.\n * Returns a new Map of clipId → PeakData. Clips without cached data are skipped.\n * When the requested scale is finer than cached data, peaks are clamped to the\n * cached scale and a single summary warning is logged.\n */\n reextractPeaks(\n clipBuffers: ReadonlyMap<string, AudioBuffer>,\n samplesPerPixel: number,\n isMono: boolean,\n clipOffsets?: ReadonlyMap<string, { offsetSamples: number; durationSamples: number }>\n ): Map<string, PeakData> {\n const result = new Map<string, PeakData>();\n let clampedCount = 0;\n let clampedScale = 0;\n for (const [clipId, audioBuffer] of clipBuffers) {\n const cached = this._cache.get(audioBuffer);\n if (cached) {\n const effectiveScale = this._clampScale(cached, samplesPerPixel, false);\n if (effectiveScale !== samplesPerPixel) {\n clampedCount++;\n clampedScale = effectiveScale;\n }\n try {\n const offsets = clipOffsets?.get(clipId);\n result.set(\n clipId,\n extractPeaks(\n cached,\n effectiveScale,\n isMono,\n offsets?.offsetSamples,\n offsets?.durationSamples\n )\n );\n } catch (err) {\n console.warn('[dawcore] reextractPeaks failed for clip ' + clipId + ': ' + String(err));\n }\n }\n }\n if (clampedCount > 0) {\n console.warn(\n '[dawcore] Requested zoom ' +\n samplesPerPixel +\n ' spp is finer than pre-computed peaks (' +\n clampedScale +\n ' spp) — ' +\n clampedCount +\n ' clip(s) using available resolution'\n );\n }\n return result;\n }\n\n /**\n * Clamp requested scale to cached WaveformData scale.\n * WaveformData.resample() can only go coarser — if the requested zoom is\n * finer than the cached data, use the cached scale. Set warn=true to log\n * (default); reextractPeaks passes false and logs a single summary instead.\n */\n private _clampScale(waveformData: WaveformData, requestedScale: number, warn = true): number {\n if (requestedScale < waveformData.scale) {\n if (warn) {\n console.warn(\n '[dawcore] Requested zoom ' +\n requestedScale +\n ' spp is finer than pre-computed peaks (' +\n waveformData.scale +\n ' spp) — using available resolution'\n );\n }\n return waveformData.scale;\n }\n return requestedScale;\n }\n\n /**\n * Extract peaks at the base scale from cached WaveformData.\n * Returns null if no cached data exists for this buffer.\n * Used by variable-tempo segments which handle stretching themselves.\n */\n getBaseScalePeaks(\n audioBuffer: AudioBuffer,\n isMono: boolean,\n offsetSamples?: number,\n durationSamples?: number\n ): { peaks: PeakData; scale: number } | null {\n const cached = this._cache.get(audioBuffer);\n if (!cached) return null;\n return {\n peaks: extractPeaks(cached, cached.scale, isMono, offsetSamples, durationSamples),\n scale: cached.scale,\n };\n }\n\n /** Scale of the cached WaveformData for this buffer — 0 when not cached.\n * Worker generation caches at baseScale; injected .dat data at its own\n * scale. This is the finest zoom the buffer's peaks can render at. */\n getCachedScale(audioBuffer: AudioBuffer): number {\n return this._cache.get(audioBuffer)?.scale ?? 0;\n }\n\n /**\n * Return the coarsest (largest) scale among cached WaveformData entries\n * that correspond to the given clip buffers. Returns 0 if none are cached.\n */\n getMaxCachedScale(clipBuffers: ReadonlyMap<string, AudioBuffer>): number {\n let max = 0;\n for (const audioBuffer of clipBuffers.values()) {\n const cached = this._cache.get(audioBuffer);\n if (cached && cached.scale > max) max = cached.scale;\n }\n return max;\n }\n\n terminate() {\n this._worker?.terminate();\n this._worker = null;\n }\n\n private async _getWaveformData(audioBuffer: AudioBuffer): Promise<WaveformData> {\n const cached = this._cache.get(audioBuffer);\n if (cached) return cached;\n\n const inflight = this._inflight.get(audioBuffer);\n if (inflight) return inflight;\n\n // Also replace a crashed worker (onerror marks it terminated) — reusing\n // it would reject every later generatePeaks for the editor's lifetime.\n if (!this._worker || this._worker.isTerminated()) {\n this._worker = createPeaksWorker();\n }\n\n // Generate at baseScale — the finest zoom we can resample from\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 const promise = this._worker\n .generate({\n channels,\n length: audioBuffer.length,\n sampleRate: audioBuffer.sampleRate,\n scale: this._baseScale,\n bits: this._bits,\n splitChannels: true,\n })\n .then((waveformData) => {\n this._cache.set(audioBuffer, waveformData);\n this._inflight.delete(audioBuffer);\n return waveformData;\n })\n .catch((err) => {\n this._inflight.delete(audioBuffer);\n console.warn('[dawcore] Peak generation via worker failed: ' + String(err));\n throw err;\n });\n\n this._inflight.set(audioBuffer, promise);\n return promise;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { computeTemporalTicks, type TickData } from '../utils/smart-scale';\nimport { getCachedMusicalTicks } from '../utils/musical-tick-cache';\nimport type { MusicalTickData, MeterEntry } from '@waveform-playlist/core';\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n@customElement('daw-ruler')\nexport class DawRulerElement extends LitElement {\n @property({ type: Number, attribute: false }) samplesPerPixel = 1024;\n @property({ type: Number, attribute: false }) sampleRate = 48000;\n @property({ type: Number, attribute: false }) duration = 0;\n @property({ type: Number, attribute: false }) rulerHeight = 30;\n @property({ type: String, attribute: false }) scaleMode: 'temporal' | 'beats' = 'temporal';\n @property({ type: Number, attribute: false }) ticksPerPixel = 4;\n @property({ attribute: false }) meterEntries: MeterEntry[] = [\n { tick: 0, numerator: 4, denominator: 4 },\n ];\n @property({ type: Number, attribute: false }) ppqn = 960;\n @property({ type: Number, attribute: false }) totalWidth = 0;\n\n private _tickData: TickData | null = null;\n private _musicalTickData: MusicalTickData | null = null;\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n background: var(--daw-ruler-background, #0f0f1a);\n }\n .container {\n position: relative;\n }\n canvas {\n position: absolute;\n top: 0;\n }\n .label {\n position: absolute;\n font-size: 0.7rem;\n line-height: 1;\n white-space: nowrap;\n color: var(--daw-ruler-color, #c49a6c);\n top: 1px;\n }\n .label.centered {\n transform: translateX(-50%);\n }\n `;\n\n willUpdate() {\n if (this.scaleMode === 'beats' && this.totalWidth > 0) {\n this._musicalTickData = getCachedMusicalTicks({\n meterEntries: this.meterEntries,\n ticksPerPixel: this.ticksPerPixel,\n startPixel: 0,\n endPixel: this.totalWidth,\n ppqn: this.ppqn,\n });\n this._tickData = null;\n } else if (this.duration > 0 || this.totalWidth > 0) {\n // Cover the larger of natural duration and viewport-floored width.\n // When indefinite-playback is set, totalWidth can exceed the natural\n // duration's width — use that to keep ruler ticks across the full\n // visible area instead of only the audible portion.\n const widthDerivedDuration = (this.totalWidth * this.samplesPerPixel) / this.sampleRate;\n const effectiveDuration = Math.max(this.duration, widthDerivedDuration);\n this._musicalTickData = null;\n this._tickData = computeTemporalTicks(\n this.samplesPerPixel,\n this.sampleRate,\n effectiveDuration,\n this.rulerHeight\n );\n } else {\n this._musicalTickData = null;\n this._tickData = null;\n }\n }\n\n render() {\n const widthX = this.scaleMode === 'beats' ? this.totalWidth : (this._tickData?.widthX ?? 0);\n if (widthX <= 0) return html``;\n\n const totalChunks = Math.ceil(widthX / MAX_CANVAS_WIDTH);\n const indices = Array.from({ length: totalChunks }, (_, i) => i);\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n\n const beatsLabels =\n this.scaleMode === 'beats' ? (this._musicalTickData?.ticks.filter((t) => t.label) ?? []) : [];\n const temporalLabels = this.scaleMode !== 'beats' ? (this._tickData?.labels ?? []) : [];\n\n return html`\n <div class=\"container\" style=\"width: ${widthX}px; height: ${this.rulerHeight}px;\">\n ${indices.map((i) => {\n const width = Math.min(MAX_CANVAS_WIDTH, widthX - i * MAX_CANVAS_WIDTH);\n return html`\n <canvas\n data-index=${i}\n width=${width * dpr}\n height=${this.rulerHeight * dpr}\n style=\"left: ${i * MAX_CANVAS_WIDTH}px; width: ${width}px; height: ${this\n .rulerHeight}px;\"\n ></canvas>\n `;\n })}\n ${this.scaleMode === 'beats'\n ? beatsLabels.map(\n (t) =>\n html`<span\n class=\"label ${t.pixel > 0 ? 'centered' : ''}\"\n style=\"left: ${t.pixel > 0 ? t.pixel : t.pixel + 4}px;\"\n >${t.label}</span\n >`\n )\n : temporalLabels.map(\n ({ pix, text }) =>\n html`<span class=\"label\" style=\"left: ${pix + 4}px;\">${text}</span>`\n )}\n </div>\n `;\n }\n\n updated() {\n this._drawTicks();\n }\n\n private _drawTicks() {\n const canvases = this.shadowRoot?.querySelectorAll('canvas');\n if (!canvases) return;\n\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const rulerColor =\n getComputedStyle(this).getPropertyValue('--daw-ruler-color').trim() || '#c49a6c';\n const widthX = this.scaleMode === 'beats' ? this.totalWidth : (this._tickData?.widthX ?? 0);\n\n for (const canvas of canvases) {\n const idx = Number(canvas.dataset.index);\n const ctx = canvas.getContext('2d');\n if (!ctx) continue;\n\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, widthX - idx * MAX_CANVAS_WIDTH);\n const globalOffset = idx * MAX_CANVAS_WIDTH;\n\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.scale(dpr, dpr);\n ctx.strokeStyle = rulerColor;\n ctx.lineWidth = 1;\n\n if (this.scaleMode === 'beats' && this._musicalTickData) {\n // Ticks draw upward from the bottom. Leave top ~40% for labels.\n // major=60%, minor=35%, minorMinor=15%\n const h = this.rulerHeight;\n for (const tick of this._musicalTickData.ticks) {\n const localX = tick.pixel - globalOffset;\n if (localX < 0 || localX >= canvasWidth) continue;\n\n const tickH =\n tick.type === 'major' ? h * 0.6 : tick.type === 'minor' ? h * 0.35 : h * 0.15;\n\n ctx.globalAlpha = tick.type === 'major' ? 1.0 : 0.5;\n ctx.beginPath();\n ctx.moveTo(localX + 0.5, h);\n ctx.lineTo(localX + 0.5, h - tickH);\n ctx.stroke();\n }\n ctx.globalAlpha = 1.0;\n } else if (this._tickData) {\n for (const [pix, height] of this._tickData.canvasInfo) {\n const localX = pix - globalOffset;\n if (localX < 0 || localX >= canvasWidth) continue;\n\n ctx.beginPath();\n ctx.moveTo(localX + 0.5, this.rulerHeight);\n ctx.lineTo(localX + 0.5, this.rulerHeight - height);\n ctx.stroke();\n }\n }\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-ruler': DawRulerElement;\n }\n}\n","/**\n * Format milliseconds into a m:ss display string.\n */\nexport function formatTime(milliseconds: number): string {\n const seconds = Math.floor(milliseconds / 1000);\n const s = seconds % 60;\n const m = (seconds - s) / 60;\n\n return `${m}:${String(s).padStart(2, '0')}`;\n}\n","import { formatTime } from './time-format';\n\nconst timeinfo = new Map([\n [700, { marker: 1000, bigStep: 500, smallStep: 100 }],\n [1500, { marker: 2000, bigStep: 1000, smallStep: 200 }],\n [2500, { marker: 2000, bigStep: 1000, smallStep: 500 }],\n [5000, { marker: 5000, bigStep: 1000, smallStep: 500 }],\n [10000, { marker: 10000, bigStep: 5000, smallStep: 1000 }],\n [12000, { marker: 15000, bigStep: 5000, smallStep: 1000 }],\n [Infinity, { marker: 30000, bigStep: 10000, smallStep: 5000 }],\n]);\n\nexport function getScaleInfo(samplesPerPixel: number) {\n for (const [resolution, config] of timeinfo) {\n if (samplesPerPixel < resolution) {\n return config;\n }\n }\n return { marker: 30000, bigStep: 10000, smallStep: 5000 };\n}\n\nexport interface TickData {\n /** Map of pixel position → tick height */\n canvasInfo: Map<number, number>;\n /** Labeled ticks with pixel positions */\n labels: Array<{ pix: number; text: string }>;\n /** Total width in pixels */\n widthX: number;\n}\n\n/**\n * Compute temporal tick data for a ruler.\n *\n * Pure function — no DOM dependencies.\n */\nexport function computeTemporalTicks(\n samplesPerPixel: number,\n sampleRate: number,\n duration: number,\n rulerHeight: number\n): TickData {\n const widthX = Math.ceil((duration * sampleRate) / samplesPerPixel);\n const config = getScaleInfo(samplesPerPixel);\n const { marker, bigStep, smallStep } = config;\n const canvasInfo = new Map<number, number>();\n const labels: Array<{ pix: number; text: string }> = [];\n\n // Each tick's pixel comes from its own time (an integer counter in\n // milliseconds), in one division (#722): the floor of\n // samples / samplesPerPixel, as the editor draws a clip at that time. With\n // an integer zoom both operands are exact integers, so the floor is exact.\n // `(counter / 1000) * pixPerSec` rounds twice and put some ticks one pixel\n // early, also at the default 1024 samples per pixel.\n for (let counter = 0; ; counter += smallStep) {\n const pix = Math.floor((counter * sampleRate) / (1000 * samplesPerPixel));\n // Written as `!(<)` so a NaN width ends the loop too.\n if (!(pix < widthX)) break;\n\n if (counter % marker === 0) {\n canvasInfo.set(pix, rulerHeight);\n labels.push({ pix, text: formatTime(counter) });\n } else if (counter % bigStep === 0) {\n canvasInfo.set(pix, Math.floor(rulerHeight / 2));\n } else if (counter % smallStep === 0) {\n canvasInfo.set(pix, Math.floor(rulerHeight / 5));\n }\n }\n\n return { widthX, canvasInfo, labels };\n}\n","import { computeMusicalTicks } from '@waveform-playlist/core';\nimport type { MusicalTickParams, MusicalTickData, MeterEntry } from '@waveform-playlist/core';\n\nlet cachedParams: MusicalTickParams | null = null;\nlet cachedResult: MusicalTickData | null = null;\n\nfunction meterEntriesMatch(\n a: { tick: number; numerator: number; denominator: number }[],\n b: { tick: number; numerator: number; denominator: number }[]\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (\n a[i].tick !== b[i].tick ||\n a[i].numerator !== b[i].numerator ||\n a[i].denominator !== b[i].denominator\n )\n return false;\n }\n return true;\n}\n\nfunction paramsMatch(a: MusicalTickParams, b: MusicalTickParams): boolean {\n return (\n a.ticksPerPixel === b.ticksPerPixel &&\n a.startPixel === b.startPixel &&\n a.endPixel === b.endPixel &&\n meterEntriesMatch(a.meterEntries, b.meterEntries) &&\n (a.ppqn ?? 960) === (b.ppqn ?? 960)\n );\n}\n\nexport function getCachedMusicalTicks(params: MusicalTickParams): MusicalTickData {\n if (cachedParams && cachedResult && paramsMatch(cachedParams, params)) {\n return cachedResult;\n }\n cachedResult = computeMusicalTicks(params);\n cachedParams = {\n ...params,\n meterEntries: params.meterEntries.map((e: MeterEntry) => ({ ...e })),\n };\n return cachedResult;\n}\n\nexport function clearMusicalTickCache(): void {\n cachedParams = null;\n cachedResult = null;\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { createMixerGesture } from '@waveform-playlist/core';\nimport type { MixerGesture } from '@waveform-playlist/core';\nimport type {\n DawTrackControlDetail,\n DawTrackReorderDetail,\n DawTrackReorderGrabDetail,\n} from '../events';\n\n@customElement('daw-track-controls')\nexport class DawTrackControlsElement extends LitElement {\n /** Track ID — set by the editor to link controls to a track row. */\n @property({ attribute: false }) trackId: string | null = null;\n @property({ attribute: false }) trackName = '';\n @property({ type: Number, attribute: false }) volume = 1;\n @property({ type: Number, attribute: false }) pan = 0;\n @property({ type: Boolean, attribute: false }) muted = false;\n /** A take is recording onto the track: it plays muted, and the M button is disabled. */\n @property({ type: Boolean, attribute: false }) recording = false;\n @property({ type: Boolean, attribute: false }) soloed = false;\n /** Show the reorder grip + move up/down buttons (set by the editor from\n * its track-reordering attribute). */\n @property({ type: Boolean, attribute: false }) reorderable = false;\n @property({ type: Number, attribute: false }) trackIndex = 0;\n @property({ type: Number, attribute: false }) trackCount = 1;\n\n /**\n * One gesture per slider (#843): the `daw-track-control` events of one\n * drag, or of one key press (a held key included), carry the same\n * `gesture` id, and the editor makes them one undo step. Each gesture is\n * attached to its range input while the element is connected.\n */\n private readonly _volumeGesture: MixerGesture = createMixerGesture();\n private readonly _panGesture: MixerGesture = createMixerGesture();\n private _detachGestures: Array<() => void> = [];\n\n static styles = css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n box-sizing: border-box;\n padding: 6px 8px;\n background: var(--daw-controls-background, #0f0f1a);\n color: var(--daw-controls-text, #c49a6c);\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\n font-family: system-ui, sans-serif;\n font-size: 11px;\n overflow: hidden;\n container-type: size;\n }\n .header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 4px;\n margin-bottom: 3px;\n }\n .name {\n flex: 1;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n font-weight: 600;\n font-size: 11px;\n }\n .remove-btn {\n background: none;\n border: none;\n color: var(--daw-controls-text, #c49a6c);\n cursor: pointer;\n padding: 0 2px;\n font-size: 14px;\n line-height: 1;\n opacity: 0.4;\n }\n .remove-btn:hover {\n opacity: 1;\n color: #d08070;\n }\n .grip {\n background: none;\n border: none;\n color: var(--daw-controls-text, #c49a6c);\n cursor: grab;\n padding: 0 2px;\n font-size: 12px;\n line-height: 1;\n opacity: 0.4;\n touch-action: none;\n }\n .grip:hover {\n opacity: 1;\n }\n .buttons {\n display: flex;\n gap: 3px;\n margin-bottom: 3px;\n }\n .btn {\n background: rgba(255, 255, 255, 0.06);\n border: 1px solid rgba(255, 255, 255, 0.1);\n border-radius: 3px;\n color: var(--daw-controls-text, #c49a6c);\n cursor: pointer;\n font-size: 10px;\n font-weight: 600;\n padding: 2px 8px;\n text-align: center;\n }\n .btn:hover {\n background: rgba(255, 255, 255, 0.12);\n }\n .btn.active {\n background: rgba(99, 199, 95, 0.25);\n border-color: rgba(99, 199, 95, 0.5);\n color: #63c75f;\n }\n .btn.muted-active {\n background: rgba(208, 128, 112, 0.25);\n border-color: rgba(208, 128, 112, 0.5);\n color: #d08070;\n }\n .btn:disabled {\n opacity: 0.3;\n cursor: default;\n }\n .slider-row {\n display: flex;\n align-items: center;\n gap: 4px;\n height: 16px;\n }\n .slider-label {\n width: 50px;\n font-size: 9px;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n opacity: 0.6;\n flex-shrink: 0;\n display: flex;\n justify-content: space-between;\n }\n .slider-label-name {\n opacity: 0.5;\n }\n .slider-label-value {\n font-family: 'Courier New', monospace;\n }\n input[type='range'] {\n flex: 1;\n min-width: 0;\n height: 20px;\n margin: 0;\n -webkit-appearance: none;\n appearance: none;\n background: transparent;\n cursor: pointer;\n }\n input[type='range']::-webkit-slider-runnable-track {\n height: 3px;\n background: rgba(255, 255, 255, 0.12);\n border-radius: 2px;\n }\n input[type='range']::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background: var(--daw-controls-text, #c49a6c);\n margin-top: -4.5px;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);\n }\n input[type='range']::-moz-range-track {\n height: 3px;\n background: rgba(255, 255, 255, 0.12);\n border-radius: 2px;\n border: none;\n }\n input[type='range']::-moz-range-thumb {\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background: var(--daw-controls-text, #c49a6c);\n border: none;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);\n }\n /* Compact modes: drop sliders when the row is too short for the full\n stack. Thresholds are CONTENT-BOX heights — the host is border-box\n with 12px vertical padding + 1px border, so an editor-given height H\n enters compact mode at H <= 89px (Pan hidden) and H <= 73px (Vol also\n hidden). NOTE: container-type: size requires an explicit height on\n the host — the editor always provides one; standalone consumers must\n too (see the firstUpdated guard). */\n @container (max-height: 76px) {\n .pan-row {\n display: none;\n }\n }\n @container (max-height: 60px) {\n .vol-row {\n display: none;\n }\n }\n `;\n\n connectedCallback(): void {\n super.connectedCallback();\n // A reconnect (the element was moved): the inputs are still in the\n // shadow root. On the first connect they do not exist yet; firstUpdated\n // attaches.\n if (this.hasUpdated) this._attachGestures();\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this._detachAllGestures();\n }\n\n private _attachGestures(): void {\n this._detachAllGestures();\n const volumeInput = this.shadowRoot?.querySelector<HTMLInputElement>('.vol-row input');\n const panInput = this.shadowRoot?.querySelector<HTMLInputElement>('.pan-row input');\n const detach: Array<() => void> = [];\n if (volumeInput) detach.push(this._volumeGesture.attach(volumeInput));\n if (panInput) detach.push(this._panGesture.attach(panInput));\n this._detachGestures = detach;\n }\n\n private _detachAllGestures(): void {\n for (const detach of this._detachGestures) detach();\n this._detachGestures = [];\n }\n\n protected firstUpdated(): void {\n this._attachGestures();\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n const rect = this.getBoundingClientRect();\n // width > 0 proves a real layout engine ran (happy-dom reports 0×0,\n // so unit tests stay quiet); height 0 then means size containment\n // collapsed the element because no explicit height was provided.\n if (rect.width > 0 && rect.height === 0) {\n console.warn(\n '[dawcore] <daw-track-controls> has zero height: container-type: size requires an explicit height on the element (the editor sets one automatically; standalone usage must too). The controls are currently invisible.'\n );\n }\n });\n }\n\n private _onVolumeInput = (e: Event) => {\n const value = Number((e.target as HTMLInputElement).value);\n if (Number.isFinite(value)) this._dispatchControl('volume', value, this._volumeGesture.id);\n };\n\n private _onPanInput = (e: Event) => {\n const value = Number((e.target as HTMLInputElement).value);\n if (Number.isFinite(value)) this._dispatchControl('pan', value, this._panGesture.id);\n };\n\n private _onMuteClick = () => {\n if (this.recording) return;\n this._dispatchControl('muted', !this.muted);\n };\n\n private _onSoloClick = () => {\n this._dispatchControl('soloed', !this.soloed);\n };\n\n private _onRemoveClick = () => {\n if (!this.trackId) return;\n this.dispatchEvent(\n new CustomEvent('daw-track-remove', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId },\n })\n );\n };\n\n /** `gesture` for the sliders only: each mute or solo click is a step. */\n private _dispatchControl(prop: string, value: number | boolean, gesture?: string) {\n if (!this.trackId) return;\n const detail: DawTrackControlDetail =\n gesture === undefined\n ? { trackId: this.trackId, prop, value }\n : { trackId: this.trackId, prop, value, gesture };\n this.dispatchEvent(\n new CustomEvent<DawTrackControlDetail>('daw-track-control', {\n bubbles: true,\n composed: true,\n detail,\n })\n );\n }\n\n private _dispatchReorder(toIndex: number) {\n if (!this.trackId) return;\n this.dispatchEvent(\n new CustomEvent<DawTrackReorderDetail>('daw-track-reorder', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId, fromIndex: this.trackIndex, toIndex },\n })\n );\n }\n\n private _onMoveUp = () => this._dispatchReorder(this.trackIndex - 1);\n private _onMoveDown = () => this._dispatchReorder(this.trackIndex + 1);\n\n private _onGripPointerDown = (e: PointerEvent) => {\n if (!this.trackId) return;\n e.preventDefault();\n this.dispatchEvent(\n new CustomEvent<DawTrackReorderGrabDetail>('daw-track-reorder-grab', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: this.trackId,\n pointerEvent: e,\n gripElement: e.currentTarget as HTMLElement,\n },\n })\n );\n };\n\n render() {\n const volPercent = Math.round(this.volume * 100);\n const panPercent = Math.round(Math.abs(this.pan) * 100);\n const panDisplay = this.pan === 0 ? 'C' : (this.pan > 0 ? 'R' : 'L') + panPercent;\n\n return html`\n <div class=\"header\">\n ${this.reorderable\n ? html`<button\n class=\"grip\"\n title=\"Drag to reorder track\"\n aria-label=\"Drag to reorder track\"\n @pointerdown=${this._onGripPointerDown}\n >\n ⠿\n </button>`\n : ''}\n <span class=\"name\" title=${this.trackName}>${this.trackName || 'Untitled'}</span>\n <button class=\"remove-btn\" @click=${this._onRemoveClick} title=\"Remove track\">\n &times;\n </button>\n </div>\n <div class=\"buttons\">\n <button\n class=\"btn ${this.muted ? 'muted-active' : ''}\"\n @click=${this._onMuteClick}\n ?disabled=${this.recording}\n title=\"Mute\"\n >\n M\n </button>\n <button class=\"btn ${this.soloed ? 'active' : ''}\" @click=${this._onSoloClick} title=\"Solo\">\n S\n </button>\n ${this.reorderable\n ? html`<button\n class=\"btn reorder-up\"\n title=\"Move track up\"\n aria-label=\"Move track up\"\n ?disabled=${this.trackIndex <= 0}\n @click=${this._onMoveUp}\n >\n ▲\n </button>\n <button\n class=\"btn reorder-down\"\n title=\"Move track down\"\n aria-label=\"Move track down\"\n ?disabled=${this.trackIndex >= this.trackCount - 1}\n @click=${this._onMoveDown}\n >\n ▼\n </button>`\n : ''}\n </div>\n <div class=\"slider-row vol-row\">\n <span class=\"slider-label\">\n <span class=\"slider-label-name\">Vol</span>\n <span class=\"slider-label-value\">${volPercent}%</span>\n </span>\n <input\n type=\"range\"\n min=\"0\"\n max=\"1\"\n step=\"0.01\"\n .value=${String(this.volume)}\n @input=${this._onVolumeInput}\n />\n </div>\n <div class=\"slider-row pan-row\">\n <span class=\"slider-label\">\n <span class=\"slider-label-name\">Pan</span>\n <span class=\"slider-label-value\">${panDisplay}</span>\n </span>\n <input\n type=\"range\"\n min=\"-1\"\n max=\"1\"\n step=\"0.01\"\n .value=${String(this.pan)}\n @input=${this._onPanInput}\n />\n </div>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-track-controls': DawTrackControlsElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { MIN_PIXELS_PER_UNIT } from '@waveform-playlist/core';\nimport type { MusicalTickData, MeterEntry } from '@waveform-playlist/core';\nimport { getCachedMusicalTicks } from '../utils/musical-tick-cache';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\nconst MAX_CANVAS_WIDTH = 1000;\n\n/**\n * `<daw-grid>` renders a musical grid overlay behind waveforms using the\n * Audacity three-tier model:\n *\n * - **Zebra stripes**: Alternating bar backgrounds at 2% white opacity.\n * - **Major lines** (bars): 10% white opacity, full height.\n * - **Minor lines** (beats): 6% white opacity, full height.\n * - **MinorMinor** (subdivisions): Ruler ticks only — no grid lines.\n *\n * Uses chunked 1000px canvases with virtual scrolling (same as daw-waveform).\n *\n * CSS custom properties:\n * --daw-grid-bar-highlight Alternating bar fill (default: rgba(255,255,255,0.02))\n * --daw-grid-major-line Bar line color (default: rgba(255,255,255,0.1))\n * --daw-grid-minor-line Beat line color (default: rgba(255,255,255,0.06))\n */\n@customElement('daw-grid')\nexport class DawGridElement extends LitElement {\n @property({ type: Number, attribute: false }) ticksPerPixel = 24;\n @property({ attribute: false }) meterEntries: MeterEntry[] = [\n { tick: 0, numerator: 4, denominator: 4 },\n ];\n @property({ type: Number, attribute: false }) ppqn = 960;\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) height = 200;\n\n private _tickData: MusicalTickData | null = null;\n\n static styles = css`\n :host {\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n pointer-events: none;\n z-index: 0;\n }\n .container {\n position: relative;\n }\n canvas {\n position: absolute;\n top: 0;\n }\n `;\n\n willUpdate() {\n if (this.length > 0) {\n this._tickData = getCachedMusicalTicks({\n ticksPerPixel: this.ticksPerPixel,\n meterEntries: this.meterEntries,\n ppqn: this.ppqn,\n startPixel: 0,\n endPixel: this.length,\n });\n } else {\n this._tickData = null;\n }\n }\n\n render() {\n if (!this._tickData) return html``;\n\n const totalWidth = this.length;\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const indices = getVisibleChunkIndices(\n totalWidth,\n MAX_CANVAS_WIDTH,\n this.visibleStart,\n this.visibleEnd\n );\n\n return html`\n <div class=\"container\" style=\"width: ${totalWidth}px; height: ${this.height}px;\">\n ${indices.map((i) => {\n const width = Math.min(MAX_CANVAS_WIDTH, totalWidth - i * MAX_CANVAS_WIDTH);\n return html`\n <canvas\n data-index=${i}\n width=${width * dpr}\n height=${this.height * dpr}\n style=\"left: ${i * MAX_CANVAS_WIDTH}px; width: ${width}px; height: ${this.height}px;\"\n ></canvas>\n `;\n })}\n </div>\n `;\n }\n\n updated() {\n this._drawGrid();\n }\n\n private _drawGrid() {\n if (!this._tickData) return;\n\n const canvases = this.shadowRoot?.querySelectorAll('canvas');\n if (!canvases) return;\n\n const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n const style = getComputedStyle(this);\n const barHighlight =\n style.getPropertyValue('--daw-grid-bar-highlight').trim() || 'rgba(255,255,255,0.02)';\n const majorLine =\n style.getPropertyValue('--daw-grid-major-line').trim() || 'rgba(255,255,255,0.1)';\n const minorLine =\n style.getPropertyValue('--daw-grid-minor-line').trim() || 'rgba(255,255,255,0.06)';\n\n const { ticks, pixelsPerQuarterNote } = this._tickData;\n\n for (const canvas of canvases) {\n const idx = Number(canvas.dataset.index);\n const ctx = canvas.getContext('2d');\n if (!ctx) continue;\n\n const chunkLeft = idx * MAX_CANVAS_WIDTH;\n const canvasWidth = Math.min(MAX_CANVAS_WIDTH, this.length - chunkLeft);\n\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.scale(dpr, dpr);\n\n // Zebra stripes: use barIndex from tick data for exact alignment with grid lines.\n // Draw a stripe from each odd-barIndex major tick to the next major tick.\n // Threshold: show stripes when a 4-beat bar would be >= MIN_PIXELS_PER_UNIT wide.\n if (pixelsPerQuarterNote * 4 >= MIN_PIXELS_PER_UNIT) {\n ctx.fillStyle = barHighlight;\n const majorTicks = ticks.filter((t) => t.type === 'major');\n for (let i = 0; i < majorTicks.length; i++) {\n if (majorTicks[i].barIndex % 2 === 1) {\n const x = majorTicks[i].pixel - chunkLeft;\n // Use actual next major tick pixel for exact bar width (handles variable meter).\n // Last bar: use the last meter entry's numerator for correct width.\n const lastMeter = this.meterEntries[this.meterEntries.length - 1];\n const lastBarWidth =\n pixelsPerQuarterNote * lastMeter.numerator * (4 / lastMeter.denominator);\n const nextX =\n i + 1 < majorTicks.length ? majorTicks[i + 1].pixel - chunkLeft : x + lastBarWidth;\n ctx.fillRect(x, 0, nextX - x, this.height);\n }\n }\n }\n\n // Grid lines: major (bars) and minor (beats) only.\n // Subdivisions (minorMinor) get ruler ticks but no grid lines.\n ctx.lineWidth = 1;\n for (const tick of ticks) {\n if (tick.type === 'minorMinor') continue;\n\n const localX = tick.pixel - chunkLeft;\n if (localX < 0 || localX >= canvasWidth) continue;\n\n ctx.strokeStyle = tick.type === 'major' ? majorLine : minorLine;\n ctx.beginPath();\n ctx.moveTo(localX + 0.5, 0);\n ctx.lineTo(localX + 0.5, this.height);\n ctx.stroke();\n }\n }\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-grid': DawGridElement;\n }\n}\n","import { css } from 'lit';\n\n/**\n * Default CSS custom properties for dawcore elements.\n * Consumers override these on <daw-editor> or any ancestor.\n * Values inherit through Shadow DOM boundaries automatically.\n */\nexport const hostStyles = css`\n :host {\n --daw-wave-color: #c49a6c;\n --daw-progress-color: #63c75f;\n --daw-playhead-color: #d08070;\n --daw-background: #1a1a2e;\n --daw-track-background: #16213e;\n --daw-ruler-color: #c49a6c;\n --daw-ruler-background: #0f0f1a;\n --daw-controls-background: #1a1a2e;\n --daw-controls-text: #e0d4c8;\n --daw-selection-color: rgba(99, 199, 95, 0.3);\n --daw-clip-header-background: rgba(0, 0, 0, 0.4);\n --daw-clip-header-text: #e0d4c8;\n }\n`;\n\n/** Clip container and header styles for the editor timeline. */\nexport const clipStyles = css`\n .clip-container {\n position: absolute;\n overflow: hidden;\n }\n /* A clip whose audio is still loading (#848). */\n .clip-container.placeholder {\n opacity: var(--daw-placeholder-clip-opacity, 0.5);\n background: color-mix(in srgb, var(--daw-wave-color, #c49a6c) 35%, transparent);\n }\n /* A clip whose audio failed to load: it stays, like a broken <img>. */\n .clip-container.placeholder.failed {\n opacity: 1;\n background: color-mix(in srgb, var(--daw-clip-failed-color, #e06c75) 15%, transparent);\n outline: 2px dashed var(--daw-clip-failed-color, #e06c75);\n outline-offset: -2px;\n }\n .clip-header {\n position: relative;\n z-index: 1;\n height: 20px;\n background: var(--daw-clip-header-background, rgba(0, 0, 0, 0.4));\n border-bottom: 1px solid rgba(255, 255, 255, 0.08);\n display: flex;\n align-items: center;\n padding: 0 6px;\n user-select: none;\n -webkit-user-drag: none;\n }\n .clip-header span {\n font-size: 10px;\n font-weight: 500;\n letter-spacing: 0.02em;\n font-family: system-ui, sans-serif;\n color: var(--daw-clip-header-text, #e0d4c8);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n opacity: 0.8;\n }\n .clip-boundary {\n position: absolute;\n top: 0;\n width: 8px;\n height: 100%;\n z-index: 2;\n cursor: col-resize;\n background: transparent;\n border: none;\n touch-action: none;\n user-select: none;\n -webkit-user-drag: none;\n transition: background 0.1s, border-color 0.1s;\n }\n .clip-boundary[data-boundary-edge='left'] {\n left: 0;\n }\n .clip-boundary[data-boundary-edge='right'] {\n right: 0;\n }\n .clip-boundary[data-boundary-edge='left']:hover {\n background: rgba(255, 255, 255, 0.2);\n border-left: 2px solid rgba(255, 255, 255, 0.5);\n }\n .clip-boundary[data-boundary-edge='right']:hover {\n background: rgba(255, 255, 255, 0.2);\n border-right: 2px solid rgba(255, 255, 255, 0.5);\n }\n .clip-boundary[data-boundary-edge='left'].dragging {\n background: rgba(255, 255, 255, 0.4);\n border-left: 2px solid rgba(255, 255, 255, 0.8);\n }\n .clip-boundary[data-boundary-edge='right'].dragging {\n background: rgba(255, 255, 255, 0.4);\n border-right: 2px solid rgba(255, 255, 255, 0.8);\n }\n .clip-header[data-interactive] {\n cursor: grab;\n }\n .clip-header[data-interactive]:active {\n cursor: grabbing;\n }\n`;\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport { getVisibleChunkIndices } from '../utils/viewport';\n\nexport { getVisibleChunkIndices };\n\nconst OVERSCAN_MULTIPLIER = 1.5;\nconst SCROLL_THRESHOLD = 100;\n\nexport class ViewportController implements ReactiveController {\n private _host: ReactiveControllerHost & HTMLElement;\n private _scrollContainer: HTMLElement | null = null;\n private _lastScrollLeft = 0;\n private _resizeObserver: ResizeObserver | null = null;\n /** The scroll listener on `_scrollContainer`, aborted when it is replaced or the host disconnects. */\n private _scrollListener: AbortController | null = null;\n\n // Permissive defaults: render everything until scroll container is attached\n visibleStart = -Infinity;\n visibleEnd = Infinity;\n containerWidth = 0;\n\n constructor(host: ReactiveControllerHost & HTMLElement) {\n this._host = host;\n host.addController(this);\n }\n\n /** CSS selector for the scroll container inside the host's Shadow DOM. */\n scrollSelector = '';\n\n hostConnected() {\n // Defer to allow Shadow DOM to render before querying\n requestAnimationFrame(() => {\n if (!this._host.isConnected) return;\n const container = this.scrollSelector\n ? (this._host.shadowRoot?.querySelector(this.scrollSelector) as HTMLElement)\n : this._host;\n if (container) {\n this._attachScrollContainer(container);\n } else if (this.scrollSelector) {\n console.warn(\n '[dawcore] ViewportController: scroll container not found for \"' +\n this.scrollSelector +\n '\"'\n );\n }\n });\n }\n\n hostDisconnected() {\n this._scrollListener?.abort();\n this._scrollListener = null;\n this._resizeObserver?.disconnect();\n this._resizeObserver = null;\n this._scrollContainer = null;\n }\n\n private _attachScrollContainer(container: HTMLElement) {\n this._scrollListener?.abort();\n this._resizeObserver?.disconnect();\n this._scrollContainer = container;\n this._scrollListener = new AbortController();\n container.addEventListener('scroll', this._onScroll, {\n passive: true,\n signal: this._scrollListener.signal,\n });\n this._update(container.scrollLeft, container.clientWidth);\n if (typeof ResizeObserver !== 'undefined') {\n this._resizeObserver = new ResizeObserver(() => {\n if (!this._scrollContainer) return;\n const next = this._scrollContainer.clientWidth;\n if (next === this.containerWidth) return;\n this._update(this._scrollContainer.scrollLeft, next);\n this._host.requestUpdate();\n });\n this._resizeObserver.observe(container);\n }\n this._host.requestUpdate();\n }\n\n private _onScroll = () => {\n if (!this._scrollContainer) return;\n const { scrollLeft, clientWidth } = this._scrollContainer;\n if (Math.abs(scrollLeft - this._lastScrollLeft) >= SCROLL_THRESHOLD) {\n this._update(scrollLeft, clientWidth);\n this._host.requestUpdate();\n }\n };\n\n private _update(scrollLeft: number, containerWidth: number) {\n this._lastScrollLeft = scrollLeft;\n this.containerWidth = containerWidth;\n const buffer = containerWidth * OVERSCAN_MULTIPLIER;\n this.visibleStart = scrollLeft - buffer;\n this.visibleEnd = scrollLeft + containerWidth + buffer;\n }\n}\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\nexport interface AudioResumeHost extends ReactiveControllerHost, HTMLElement {\n /** Returns the AudioContext to resume on user gesture */\n readonly audioContext: AudioContext;\n}\n\nexport class AudioResumeController implements ReactiveController {\n private _host: AudioResumeHost;\n private _target: EventTarget | null = null;\n /** The gesture listeners on `_target`: one controller per attach. */\n private _listeners: AbortController | null = null;\n private _attached = false;\n private _generation = 0;\n\n /** CSS selector, or 'document'. When undefined, controller is inert. */\n target?: string;\n\n constructor(host: AudioResumeHost) {\n this._host = host;\n host.addController(this);\n }\n\n hostConnected() {\n // Defer to next frame so Lit's willUpdate() can set `target` from\n // the host's attribute before we read it. Same pattern as ViewportController.\n const gen = ++this._generation;\n requestAnimationFrame(() => {\n if (gen !== this._generation) return; // stale callback from previous connect\n if (!this._host.isConnected || this._attached || this.target === undefined) return;\n\n let resolvedTarget: EventTarget | null;\n try {\n resolvedTarget = this._resolveTarget();\n } catch (err) {\n console.warn(\n '[dawcore] AudioResumeController: failed to resolve target \"' +\n this.target +\n '\": ' +\n String(err)\n );\n return;\n }\n if (!resolvedTarget) return;\n\n this._target = resolvedTarget;\n this._attached = true;\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n resolvedTarget.addEventListener('pointerdown', this._onGesture, {\n once: true,\n capture: true,\n signal,\n });\n resolvedTarget.addEventListener('keydown', this._onGesture, {\n once: true,\n capture: true,\n signal,\n });\n });\n }\n\n hostDisconnected() {\n this._removeListeners();\n this._attached = false;\n }\n\n private _onGesture = () => {\n let ctx: AudioContext;\n try {\n ctx = this._host.audioContext;\n } catch (err) {\n if (err instanceof Error && err.message.includes('No PlayoutAdapter set')) {\n // No adapter set yet — nothing to resume. Will be resumed on first play().\n this._removeListeners();\n return;\n }\n console.warn(\n '[dawcore] AudioResumeController: unexpected error accessing audioContext: ' + String(err)\n );\n this._removeListeners();\n return;\n }\n if (ctx.state === 'closed') {\n console.warn('[dawcore] AudioResumeController: AudioContext is closed, cannot resume.');\n } else if (ctx.state === 'suspended') {\n ctx.resume().catch((err) => {\n console.warn(\n '[dawcore] AudioResumeController: eager resume failed, will retry on play: ' + String(err)\n );\n });\n }\n // The fired listener was removed by { once: true }; this removes the other.\n this._removeListeners();\n };\n\n private _resolveTarget(): EventTarget | null {\n const t = this.target;\n if (t === undefined) return null;\n if (t === '') return this._host;\n if (t === 'document') return document;\n\n const el = document.querySelector(t);\n if (!el) {\n console.warn(\n '[dawcore] AudioResumeController: target \"' +\n t +\n '\" not found in DOM at attach time, falling back to host element. ' +\n 'Ensure the target exists before <daw-editor> connects.'\n );\n return this._host;\n }\n return el;\n }\n\n private _removeListeners() {\n if (!this._target) return;\n this._listeners?.abort();\n this._listeners = null;\n this._target = null;\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), and dawcore's peer ranges are\n * `>=` floors, which also admit a later breaking release. So each name carries\n * a caret on the version this build was made with, which lies inside dawcore's\n * peer range; where the floor does not admit that version yet, the peer range\n * itself (see `hintRange` in the script below). playout, which is no peer, gets\n * a caret too.\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 dawcore Vite examples alias this\n * source) prints the bare name; the website uses the built `dist`.\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 { ReactiveController, ReactiveControllerHost } from 'lit';\nimport type { Bits } from '@waveform-playlist/core';\nimport type { DawWaveformElement } from '../elements/daw-waveform';\nimport { installCommand } from '../utils/install-command';\nimport {\n appendPeaks,\n concatenateAudioData,\n createAudioBuffer,\n resolveRecordingOffsetSamples,\n} from '@waveform-playlist/core';\nimport type {\n DawRecordingStartDetail,\n DawRecordingCompleteDetail,\n DawRecordingErrorDetail,\n DawRecordingPauseDetail,\n DawRecordingResumeDetail,\n} from '../events';\n\nexport interface RecordingOptions {\n trackId?: string;\n bits?: 8 | 16;\n /** Fallback channel count when stream doesn't report one via getSettings(). Must be 1 or 2. */\n channelCount?: 1 | 2;\n startSample?: number;\n /** Start playback during recording so user hears existing tracks. */\n overdub?: boolean;\n /**\n * Latency offset to skip at the start of the recording, in **seconds**.\n * Absolute replacement for the auto-computed `outputLatency`-based value —\n * use this to apply an externally-measured round-trip latency. `0` disables\n * compensation; when omitted, the auto-computed value is used.\n * Negative or non-finite values are treated as 0.\n */\n latencyOffset?: number;\n /**\n * Display name for the take: shown in the live-preview clip header while\n * recording (falls back to \"Recording…\") and used as the finalized clip's\n * name (falls back to \"Recording\").\n */\n clipName?: string;\n}\n\nexport interface RecordingSession {\n readonly trackId: string;\n readonly stream: MediaStream;\n readonly source: { disconnect(): void; connect(dest: unknown): void };\n readonly workletNode: { port: MessagePort; disconnect(): void };\n readonly chunks: Float32Array[][];\n totalSamples: number;\n readonly peaks: (Int8Array | Int16Array)[];\n readonly startSample: number;\n readonly channelCount: number;\n /** Sample rate of the AudioContext the worklet captured at. The finalized\n * AudioBuffer must be labeled with THIS rate — the host's sticky\n * effectiveSampleRate can lag after a context swap, mislabeling the take\n * (~8.9% off-speed for 44.1k vs 48k). */\n readonly captureSampleRate: number;\n readonly bits: Bits;\n isFirstMessage: boolean;\n /** Latency samples to skip in live preview (outputLatency only). */\n readonly latencySamples: number;\n /** Display name for the take (preview header + finalized clip name). */\n readonly clipName?: string;\n readonly wasOverdub: boolean;\n /** Set during stopRecording, cleared by the done message from the worklet. */\n stopAckResolve: (() => void) | null;\n /** In-flight stop completion — re-entrant stopRecording calls await this\n * instead of running a second handshake. */\n stopPromise: Promise<void> | null;\n /** True from the start of stopRecording until the session is deleted.\n * Guards pauseRecording / resumeRecording so a mid-drain pause toggle\n * can't dispatch events for a session that's already terminating. */\n stopping: boolean;\n}\n\n/** Readonly view of a recording session for external consumers. */\nexport type ReadonlyRecordingSession = Readonly<\n Omit<RecordingSession, 'chunks' | 'peaks' | 'latencySamples'>\n> & {\n readonly latencySamples: number;\n readonly chunks: ReadonlyArray<ReadonlyArray<Float32Array>>;\n readonly peaks: ReadonlyArray<Int8Array | Int16Array>;\n};\n\n/** Narrow interface for the host editor. */\nexport interface RecordingHost extends ReactiveControllerHost {\n readonly audioContext: AudioContext;\n readonly samplesPerPixel: number;\n /** Render-space samples-per-pixel. In beats mode this is derived from\n * ticksPerPixel/bpm and differs from samplesPerPixel — live-preview peaks\n * must be generated at THIS scale or the drawn waveform disagrees with the\n * preview container's width/position. */\n readonly renderSamplesPerPixel: number;\n readonly effectiveSampleRate: number;\n readonly _selectedTrackId: string | null;\n /** Live playhead position in seconds. Must read from the engine during\n * playback — a cached field only written on pause/stop/seek lags the real\n * position and misplaces punch-in (record-during-playback) clips. */\n readonly currentTime: number;\n readonly shadowRoot: ShadowRoot | null;\n _addRecordedClip?(\n trackId: string,\n buf: AudioBuffer,\n startSample: number,\n durSamples: number,\n offsetSamples?: number,\n clipName?: string\n ): void;\n /** Structural view of the editor's engine for the take's mute (#843):\n * punch-in replaces the overlapped content, so the recorded-over track's\n * existing material must not play under the take. The track a take is\n * recording onto plays muted; that mute is outside the undo history and\n * leaves the stored mute alone. Optional — hosts without an engine skip\n * it. */\n _engine?: {\n setTrackRecording(trackId: string, recording: boolean): void;\n } | null;\n play?(startTime?: number): Promise<void>;\n stop?(): void;\n dispatchEvent(event: Event): boolean;\n /**\n * Register a worklet module URL on the adapter's AudioContext.\n * Abstracts native vs standardized-audio-context differences.\n * When absent, falls back to native audioContext.audioWorklet.addModule().\n */\n addWorkletModule?(url: string): Promise<void>;\n /**\n * Create an AudioWorkletNode on the adapter's context.\n * When absent, falls back to new AudioWorkletNode(audioContext, ...).\n */\n createAudioWorkletNode?(name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode;\n /**\n * Create a MediaStreamSource on the adapter's context.\n * When absent, falls back to audioContext.createMediaStreamSource().\n */\n createMediaStreamSource?(stream: MediaStream): MediaStreamAudioSourceNode;\n}\n\n/** Bookkeeping for a startRecording still in its async setup window\n * (session not yet in _sessions). */\ninterface StartingEntry {\n /** Set by stopRecording — the in-flight start consults this after its\n * awaits and aborts instead of losing the stop. */\n stopRequested: boolean;\n /** Resolves when the in-flight start settles (session live OR aborted) —\n * a session-less stopRecording returns this so `await stop(); start()`\n * sequences correctly instead of hitting the still-held _starting guard. */\n done: Promise<void>;\n}\n\nexport class RecordingController implements ReactiveController {\n private _host: RecordingHost & HTMLElement;\n private _sessions = new Map<string, RecordingSession>();\n /** Each session's mic-unplug listener, aborted when the session ends. */\n private _trackEndedListeners = new WeakMap<RecordingSession, AbortController>();\n /** Track IDs with a startRecording in flight (session not yet in _sessions).\n * The session is only set after several awaits — without this, two rapid\n * start calls both pass the _sessions guard and build two capture\n * pipelines feeding one session (garbled audio + a leaked worklet). */\n private _starting = new Map<string, StartingEntry>();\n /** True between hostDisconnected and hostConnected. An in-flight\n * startRecording consults this after its awaits so a teardown mid-setup\n * doesn't leak a live capture session on a detached editor. */\n private _hostDisconnected = false;\n private _workletLoadedCtx: AudioContext | null = null;\n /** Tracks worklet pause state explicitly so external consumers (editor,\n * pause button, spacebar) can share one source of truth. */\n private _isPaused = false;\n\n constructor(host: RecordingHost & HTMLElement) {\n this._host = host;\n host.addController(this);\n }\n\n hostConnected() {\n this._hostDisconnected = false;\n }\n\n hostDisconnected() {\n this._hostDisconnected = true;\n for (const trackId of [...this._sessions.keys()]) {\n // notifyError: captured audio is silently discarded here — without an\n // event, record buttons living in a still-connected <daw-transport>\n // stay wedged in their recording state forever.\n this._cleanupSession(trackId, true);\n }\n this._workletLoadedCtx = null;\n }\n\n get isRecording(): boolean {\n // The start window counts: <daw-stop-button> gates stopRecording() on\n // this getter, so excluding _starting would make the stop-during-start\n // cancel path unreachable from the stop button.\n return this._sessions.size > 0 || this._starting.size > 0;\n }\n\n get isPaused(): boolean {\n return this._isPaused && this._sessions.size > 0;\n }\n\n getSession(trackId: string): ReadonlyRecordingSession | undefined {\n return this._sessions.get(trackId);\n }\n\n async startRecording(stream: MediaStream, options: RecordingOptions = {}): Promise<void> {\n const trackId = options.trackId ?? this._host._selectedTrackId;\n if (!trackId) {\n console.warn('[dawcore] RecordingController: No track selected for recording');\n return;\n }\n if (this._sessions.has(trackId) || this._starting.has(trackId)) {\n console.warn('[dawcore] RecordingController: Already recording on track \"' + trackId + '\"');\n return;\n }\n let resolveStartSettled!: () => void;\n const startEntry: StartingEntry = {\n stopRequested: false,\n done: new Promise<void>((resolve) => {\n resolveStartSettled = resolve;\n }),\n };\n this._starting.set(trackId, startEntry);\n\n const bits: Bits = options.bits ?? 16;\n\n try {\n const rawCtx = this._host.audioContext;\n\n // A suspended context delivers no samples while the UI shows recording\n // (worklet process() never runs). Resume before wiring the capture\n // graph — parity with the React hook, which resumes at record start.\n if (rawCtx.state === 'suspended') {\n await rawCtx.resume();\n }\n\n // Load worklet module — guard tied to context identity so a\n // swapped AudioContext gets the module re-registered.\n if (!this._workletLoadedCtx || this._workletLoadedCtx !== rawCtx) {\n let addRecordingWorkletModule: (addModule: (url: string) => Promise<void>) => Promise<void>;\n try {\n ({ addRecordingWorkletModule } = await import('@waveform-playlist/worklets'));\n } catch (importErr) {\n throw new Error(\n 'Recording requires @waveform-playlist/worklets. ' +\n 'Install it: ' +\n installCommand('@waveform-playlist/worklets') +\n ' (cause: ' +\n String(importErr) +\n ')'\n );\n }\n const addModule = this._host.addWorkletModule\n ? (url: string) => this._host.addWorkletModule!(url)\n : (url: string) => rawCtx.audioWorklet.addModule(url);\n await addRecordingWorkletModule(addModule);\n this._workletLoadedCtx = rawCtx;\n }\n\n // A stop request or host disconnect that arrived during the awaits\n // above (context resume, worklet module load — 50-300ms on first use)\n // must cancel the start. Without this re-check the stop is silently\n // lost (recording runs on) or a live capture session leaks on a\n // torn-down editor. Nothing is wired yet at this point, so bailing\n // needs no cleanup — but it must be OBSERVABLE: no daw-recording-start\n // ever fires, so without an error event an awaiting consumer cannot\n // distinguish \"recording\" from \"cancelled\".\n // NOTE: this re-check must stay AFTER every await that precedes\n // _sessions.set() — inserting a new await below it reopens the race.\n if (startEntry.stopRequested || this._hostDisconnected) {\n this._dispatchRecordingError(\n trackId,\n new Error(\n this._hostDisconnected\n ? 'Recording start cancelled: editor was disconnected during setup'\n : 'Recording start cancelled: stop requested before setup completed'\n )\n );\n return;\n }\n\n // Detect channel count from stream (not source.channelCount — defaults to 2 per spec).\n // Fall back to user-provided channelCount option, then 1.\n const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;\n if (detectedChannelCount === undefined && options.channelCount !== undefined) {\n console.warn(\n '[dawcore] Could not detect stream channel count, using fallback: ' + options.channelCount\n );\n }\n const channelCount = detectedChannelCount ?? options.channelCount ?? 1;\n\n const startSample =\n options.startSample ?? Math.floor(this._host.currentTime * this._host.effectiveSampleRate);\n\n // Compute latency offset once at start (doesn't change during session).\n // An explicit latencyOffset option (seconds) replaces the outputLatency\n // estimate; native transport has no scheduler look-ahead (lookAhead: 0).\n const latencySamples = resolveRecordingOffsetSamples({\n overrideSeconds: options.latencyOffset,\n outputLatency: rawCtx.outputLatency ?? 0,\n lookAhead: 0,\n sampleRate: rawCtx.sampleRate,\n });\n\n // Use host methods when available (supports standardized-audio-context),\n // fall back to native AudioContext methods.\n const source = this._host.createMediaStreamSource\n ? this._host.createMediaStreamSource(stream)\n : rawCtx.createMediaStreamSource(stream);\n const workletNode = this._host.createAudioWorkletNode\n ? this._host.createAudioWorkletNode('recording-processor', {\n channelCount,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n })\n : new AudioWorkletNode(rawCtx, 'recording-processor', {\n channelCount,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n });\n\n // Listen on MediaStreamTrack (not MediaStream — MediaStream has no 'ended' event)\n const audioTrack = stream.getAudioTracks()[0] ?? null;\n const onTrackEnded = audioTrack\n ? () => {\n if (this._sessions.has(trackId)) {\n this.stopRecording(trackId);\n }\n }\n : null;\n\n const session: RecordingSession = {\n trackId,\n stream,\n source,\n workletNode,\n chunks: Array.from({ length: channelCount }, () => []),\n totalSamples: 0,\n peaks: Array.from({ length: channelCount }, () =>\n bits === 8 ? new Int8Array(0) : new Int16Array(0)\n ),\n startSample,\n channelCount,\n captureSampleRate: rawCtx.sampleRate,\n bits,\n isFirstMessage: true,\n latencySamples,\n clipName: options.clipName,\n wasOverdub: options.overdub ?? false,\n stopAckResolve: null,\n stopPromise: null,\n stopping: false,\n };\n this._sessions.set(trackId, session);\n\n // dawcore CLAUDE.md: wire onmessage BEFORE source.connect() and postMessage start\n workletNode.port.onmessage = (e: MessageEvent) => {\n this._onWorkletMessage(trackId, e.data);\n };\n source.connect(workletNode);\n workletNode.port.postMessage({ command: 'start', channelCount });\n\n // Attach mic-unplug listener (stored in session for cleanup)\n if (audioTrack && onTrackEnded) {\n const listener = new AbortController();\n this._trackEndedListeners.set(session, listener);\n audioTrack.addEventListener('ended', onTrackEnded, { signal: listener.signal });\n }\n\n // Mute the track the take is recording onto — punch-in replaces\n // whatever the take overlaps (#579), so the doomed material must not\n // play under the overdub. The take's mute is the engine's (#843): the\n // track plays muted and the engine's tracks carry `muted: true`, which\n // the track controls and an export read; the stored mute is untouched\n // and the take's mute is no undo step, so a mute changed during the\n // take stays after it. Cleared by _clearTakeMute on every\n // session-teardown path. Must engage BEFORE the overdub host.play()\n // below so the track never blips.\n this._host._engine?.setTrackRecording(trackId, true);\n\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingStartDetail>('daw-recording-start', {\n bubbles: true,\n composed: true,\n detail: { trackId, stream },\n })\n );\n\n this._host.requestUpdate();\n\n // Overdub: start playback so user hears existing tracks and playhead advances\n if (options.overdub && typeof this._host.play === 'function') {\n await this._host.play(this._host.currentTime);\n }\n } catch (err) {\n // Clean up partially-created session to prevent stuck isRecording state\n this._cleanupSession(trackId);\n console.warn('[dawcore] RecordingController: Failed to start recording: ' + String(err));\n this._dispatchRecordingError(trackId, err);\n } finally {\n this._starting.delete(trackId);\n resolveStartSettled();\n }\n }\n\n pauseRecording(trackId?: string): void {\n const id = trackId ?? [...this._sessions.keys()][0];\n if (!id) return;\n const session = this._sessions.get(id);\n // Skip if the session is already on its way out — would otherwise\n // dispatch a pause event for a session about to be deleted.\n if (!session || session.stopping) return;\n session.workletNode.port.postMessage({ command: 'pause' });\n this._isPaused = true;\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingPauseDetail>('daw-recording-pause', {\n bubbles: true,\n composed: true,\n detail: { trackId: id },\n })\n );\n }\n\n resumeRecording(trackId?: string): void {\n const id = trackId ?? [...this._sessions.keys()][0];\n if (!id) return;\n const session = this._sessions.get(id);\n if (!session || session.stopping) return;\n session.workletNode.port.postMessage({ command: 'resume' });\n this._isPaused = false;\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingResumeDetail>('daw-recording-resume', {\n bubbles: true,\n composed: true,\n detail: { trackId: id },\n })\n );\n }\n\n async stopRecording(trackId?: string): Promise<void> {\n // Fall back to an in-flight start's trackId too — the stop button fires\n // with no id, and during the async start window there's no session yet.\n // (Single-session assumption: with a live session AND an in-flight start\n // on different tracks, a no-arg stop targets the session.)\n const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];\n if (!id) return;\n\n const session = this._sessions.get(id);\n if (!session) {\n // startRecording is still in its async setup — flag it to abort after\n // its awaits instead of losing the stop, and resolve only once the\n // start has actually settled so `await stop(); start()` doesn't hit\n // the still-held _starting guard.\n const starting = this._starting.get(id);\n if (starting) {\n starting.stopRequested = true;\n return starting.done;\n }\n return;\n }\n\n // Re-entrant stop (stop-button double-click, unmount cleanup) during the\n // ack/drain window must not build a second AudioBuffer or dispatch a\n // second complete event — both callers observe the same in-flight stop.\n if (session.stopping) {\n return session.stopPromise ?? undefined;\n }\n // Block any further pause/resume/stop calls on this session — they could\n // race with the drain loop and dispatch events for a session that's\n // about to be deleted.\n session.stopping = true;\n const stopPromise = this._finishStopRecording(id, session);\n session.stopPromise = stopPromise;\n return stopPromise;\n }\n\n private async _finishStopRecording(id: string, session: RecordingSession): Promise<void> {\n try {\n await this._finalizeRecording(id, session);\n } catch (err) {\n // A throw anywhere in the stop pipeline (host.stop(), chunk\n // concatenation RangeError on a long take, AudioBuffer creation, clip\n // insertion) must not strand the session with stopping=true — that\n // wedges isRecording, keeps the mic graph connected, and leaves the\n // track playing muted. Resolve (not reject) and surface\n // the failure via daw-recording-error, matching the no-audio/too-short\n // error-path convention — fire-and-forget callers (stop button,\n // mic-unplug handler) only observe the event.\n const sessionWasActive = this._sessions.has(id);\n console.warn('[dawcore] RecordingController: Failed to finalize recording: ' + String(err));\n this._cleanupSession(id);\n this._host.requestUpdate();\n // If the session was already finalized, daw-recording-complete has\n // fired and the take was delivered — the throw came from clip\n // insertion. A daw-recording-error for the same take would contradict\n // the complete event, so only the warn above reports it.\n if (sessionWasActive) {\n this._dispatchRecordingError(id, err);\n }\n }\n }\n\n private async _finalizeRecording(id: string, session: RecordingSession): Promise<void> {\n // Capture whether we were paused — pause already flushed the partial\n // buffer, so there's no full-buffer backlog to wait for on stop.\n const wasPaused = this._isPaused;\n this._isPaused = false;\n\n // Stop playback only if this was an overdub session\n if (session.wasOverdub && typeof this._host.stop === 'function') {\n this._host.stop();\n }\n\n // Send stop. If the recording was already paused, pause's flushBuffers()\n // already drained the partial buffer — no need to await the terminal\n // message (and the worklet's audio thread may have throttled back while\n // paused, making the round-trip slow / unreliable).\n if (wasPaused) {\n session.workletNode.port.postMessage({ command: 'stop' });\n // No ack await here — the paused audio thread may be throttled, making\n // the done round-trip slow/unreliable. But posting `stop` does NOT mean\n // earlier messages were delivered: the pause-time flush (and any\n // backlog) can still be in transit, so the queue must still be drained\n // or those chunks are silently dropped from the finalized clip.\n await this._drainWorkletQueue(session);\n } else {\n // Active recording: await the worklet's terminal flush so the partial\n // buffer at stop time isn't silently dropped.\n const stopAck = new Promise<void>((resolve) => {\n session.stopAckResolve = resolve;\n });\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n // Safety timeout (1s). Prevents infinite hang on a real failure\n // (worklet crashed, context closed). The drain loop below catches any\n // straggler flush messages that were queued before the timeout fired,\n // so this is purely a circuit breaker — not a data-correctness budget.\n const timeout = new Promise<void>((resolve) => {\n timeoutId = setTimeout(resolve, 1000);\n });\n session.workletNode.port.postMessage({ command: 'stop' });\n await Promise.race([stopAck, timeout]);\n clearTimeout(timeoutId);\n session.stopAckResolve = null;\n\n await this._drainWorkletQueue(session);\n }\n session.source.disconnect();\n session.workletNode.disconnect();\n\n // Remove mic-unplug listener\n this._removeTrackEndedListener(session);\n\n // Build AudioBuffer from accumulated chunks\n if (session.totalSamples === 0) {\n this._abandonFinalize(id, session, 'No audio data captured');\n return;\n }\n const stopCtx = this._host.audioContext;\n const channelData = session.chunks.map((chunkArr) => concatenateAudioData(chunkArr));\n const audioBuffer = createAudioBuffer(\n stopCtx,\n channelData,\n session.captureSampleRate,\n session.channelCount\n );\n\n // Latency compensation: use the offset computed at start time\n const latencyOffsetSamples = session.latencySamples;\n const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);\n\n if (effectiveDuration === 0) {\n this._abandonFinalize(\n id,\n session,\n 'Recording too short for latency compensation',\n 'Recording too short to save'\n );\n return;\n }\n\n // Dispatch cancelable event\n const event = new CustomEvent<DawRecordingCompleteDetail>('daw-recording-complete', {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n trackId: id,\n audioBuffer,\n startSample: session.startSample,\n durationSamples: effectiveDuration,\n offsetSamples: latencyOffsetSamples,\n },\n });\n const notPrevented = this._host.dispatchEvent(event);\n\n // Clean up session\n this._clearTakeMute(session);\n this._sessions.delete(id);\n this._host.requestUpdate();\n\n if (notPrevented) {\n this._createClipFromRecording(\n id,\n audioBuffer,\n session.startSample,\n effectiveDuration,\n latencyOffsetSamples,\n session.clipName\n );\n }\n }\n\n /** Drain the event-loop queue of pending worklet flush messages. During\n * recording the worklet posts a flush every ~16ms; if main was slower,\n * messages back up. Yield repeatedly until session.totalSamples stabilizes\n * (no new messages processed) for several consecutive ticks — at that\n * point the queue is empty and chunks are complete. */\n private async _drainWorkletQueue(session: RecordingSession): Promise<void> {\n let lastSamples = -1;\n let stable = 0;\n for (let i = 0; i < 50; i++) {\n if (session.totalSamples === lastSamples) {\n if (++stable >= 3) break;\n } else {\n stable = 0;\n lastSamples = session.totalSamples;\n }\n await new Promise<void>((r) => setTimeout(r, 5));\n }\n }\n\n // Session fields are mutated in place on the hot path (~60fps worklet messages).\n // This is intentional — creating new session objects + Map entries per message\n // would cause significant GC pressure. Mutations are confined to the controller's\n // private map and do not affect Lit's reactive rendering.\n private _onWorkletMessage(trackId: string, data: unknown) {\n const session = this._sessions.get(trackId);\n if (!session) return;\n\n const { channels, done } = data as { channels: Float32Array[]; done?: boolean };\n\n // Resolve the stop barrier in a finally block so a throw in peak generation\n // (e.g. samplesPerPixel=0 transient, host shadowRoot churn) doesn't strand\n // the await in stopRecording for the full 1000ms safety timeout.\n try {\n const hasSamples = !!(\n channels &&\n channels.length > 0 &&\n channels[0] &&\n channels[0].length > 0\n );\n if (!hasSamples) return;\n this._processWorkletSamples(trackId, session, channels);\n } finally {\n if (done && session.stopAckResolve) {\n const resolve = session.stopAckResolve;\n session.stopAckResolve = null;\n resolve();\n }\n }\n }\n\n private _processWorkletSamples(\n trackId: string,\n session: RecordingSession,\n channels: Float32Array[]\n ) {\n // Capture pre-increment value for appendPeaks\n const samplesProcessedBefore = session.totalSamples;\n\n // Accumulate chunks per channel — always do this, even during stop,\n // so the AudioBuffer captures every sample.\n for (let ch = 0; ch < session.channelCount; ch++) {\n if (channels[ch]) {\n session.chunks[ch].push(channels[ch]);\n }\n }\n session.totalSamples += channels[0].length;\n\n // If stop is already in flight, skip peak generation and live-preview\n // waveform updates. The recording is ending; the AudioBuffer's final\n // peaks will be regenerated by the consumer. Skipping this drains the\n // backlog of queued flush messages faster, getting us to the terminal\n // `done` message sooner.\n if (session.stopAckResolve !== null) return;\n\n // Generate peaks per channel and update live preview waveforms\n for (let ch = 0; ch < session.channelCount; ch++) {\n if (!channels[ch]) continue;\n const oldPeakCount = Math.floor(session.peaks[ch].length / 2);\n (session.peaks as (Int8Array | Int16Array)[])[ch] = appendPeaks(\n session.peaks[ch],\n channels[ch],\n // Render-space scale — in beats mode this differs from\n // samplesPerPixel, and the preview container is laid out in\n // render space (see RecordingHost.renderSamplesPerPixel).\n this._host.renderSamplesPerPixel,\n samplesProcessedBefore,\n session.bits\n );\n const newPeakCount = Math.floor(session.peaks[ch].length / 2);\n\n // Update live preview waveform — host is already & HTMLElement so shadowRoot is typed\n const waveformSelector = `daw-waveform[data-recording-track=\"${trackId}\"][data-recording-channel=\"${ch}\"]`;\n const waveformEl = this._host.shadowRoot?.querySelector(\n waveformSelector\n ) as DawWaveformElement | null;\n if (waveformEl) {\n if (session.isFirstMessage) {\n waveformEl.peaks = session.peaks[ch];\n } else {\n waveformEl.setPeaksQuiet(session.peaks[ch]);\n waveformEl.updatePeaks(Math.max(0, oldPeakCount - 1), newPeakCount);\n }\n }\n }\n\n session.isFirstMessage = false;\n\n // Throttle requestUpdate — only when container width needs to grow\n const newPixelWidth = Math.floor(session.totalSamples / this._host.renderSamplesPerPixel);\n const oldPixelWidth = Math.floor(\n (session.totalSamples - channels[0].length) / this._host.renderSamplesPerPixel\n );\n if (newPixelWidth > oldPixelWidth) {\n this._host.requestUpdate();\n }\n }\n\n private _createClipFromRecording(\n trackId: string,\n audioBuffer: AudioBuffer,\n startSample: number,\n durationSamples: number,\n offsetSamples = 0,\n clipName?: string\n ) {\n if (typeof this._host._addRecordedClip === 'function') {\n this._host._addRecordedClip(\n trackId,\n audioBuffer,\n startSample,\n durationSamples,\n offsetSamples,\n clipName\n );\n } else {\n console.warn(\n '[dawcore] RecordingController: host does not implement _addRecordedClip — clip not created for track \"' +\n trackId +\n '\"'\n );\n }\n }\n\n private _removeTrackEndedListener(session: RecordingSession) {\n this._trackEndedListeners.get(session)?.abort();\n this._trackEndedListeners.delete(session);\n }\n\n private _dispatchRecordingError(trackId: string, error: unknown) {\n this._host.dispatchEvent(\n new CustomEvent<DawRecordingErrorDetail>('daw-recording-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, error },\n })\n );\n }\n\n /** Shared teardown for finalize paths that end without a take (no data\n * captured / too short after latency compensation): clear the take's mute, drop\n * the session, and notify via daw-recording-error so record buttons reset\n * their state. */\n private _abandonFinalize(\n id: string,\n session: RecordingSession,\n warnMessage: string,\n errorMessage: string = warnMessage\n ) {\n console.warn('[dawcore] RecordingController: ' + warnMessage);\n this._clearTakeMute(session);\n this._sessions.delete(id);\n this._host.requestUpdate();\n this._dispatchRecordingError(id, new Error(errorMessage));\n }\n\n /** Clear the take's mute on the session's track, by its id. Each teardown\n * path calls this once, right before it drops the session from the map, so\n * a later path never reaches the same session; clearing an id that is not\n * set is a no-op in the engine. Another session's mute on another track is\n * left alone. */\n private _clearTakeMute(session: RecordingSession) {\n this._host._engine?.setTrackRecording(session.trackId, false);\n }\n\n /** @param notifyError dispatch daw-recording-error after cleanup — used by\n * disposal paths that would otherwise discard the session silently. The\n * startRecording catch path passes false (it dispatches its own error). */\n private _cleanupSession(trackId: string, notifyError = false) {\n const session = this._sessions.get(trackId);\n if (!session) return;\n try {\n this._clearTakeMute(session);\n this._removeTrackEndedListener(session);\n session.workletNode.port.postMessage({ command: 'stop' });\n session.source.disconnect();\n session.workletNode.disconnect();\n } catch (err) {\n console.warn(\n '[dawcore] RecordingController: disconnect error during cleanup for track \"' +\n trackId +\n '\": ' +\n String(err)\n );\n }\n this._sessions.delete(trackId);\n if (this._sessions.size === 0) {\n // A leftover pause flag would misreport isPaused for the next session\n // and send its stop down the no-ack fast path.\n this._isPaused = false;\n }\n if (notifyError) {\n this._dispatchRecordingError(\n trackId,\n new Error('Recording cancelled: editor was disconnected mid-recording')\n );\n }\n }\n}\n","import { html } from 'lit';\nimport type { ReactiveController, ReactiveControllerHost, TemplateResult } from 'lit';\nimport type { AnnotationData } from '@waveform-playlist/core';\nimport type { DawAnnotationTrackElement } from '../elements/daw-annotation-track';\nimport type { DawTimeUpdateDetail } from '../events';\nimport { computePlayingAnnotationId } from '../utils/annotation-playing';\n\n/**\n * Fixed lane height. A TS constant (not a CSS var) because the frozen-panes\n * controls-column spacer and the beats-grid top offset need it in layout math.\n */\nexport const ANNOTATION_LANE_HEIGHT = 32;\n\nexport interface AnnotationControllerHost extends ReactiveControllerHost, HTMLElement {\n effectiveSampleRate: number;\n seekTo(time: number): void;\n /** Tick→seconds conversion (fixed BPM or variable-tempo callbacks) —\n * the editor owns tempo; the controller derives annotation seconds caches. */\n _ticksToSeconds(ticks: number): number;\n}\n\n/**\n * Registers <daw-annotation-track> light-DOM children and renders their\n * timeline lanes inside the editor's shadow DOM. Rendering only — drag\n * interactions live in interactions/annotation-drag.ts.\n */\nexport class AnnotationController implements ReactiveController {\n private _host: AnnotationControllerHost;\n private _tracks: DawAnnotationTrackElement[] = [];\n private _removalObserver: MutationObserver | null = null;\n /** Playback-following highlight per track, separate from each track's\n * `activeAnnotationId` (selection) so playback never disturbs selection.\n * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.\n * Replaced immutably (a fresh Map) on every change. */\n private _playingIds: Map<DawAnnotationTrackElement, string | null> = new Map();\n\n constructor(host: AnnotationControllerHost) {\n this._host = host;\n host.addController(this);\n }\n\n get tracks(): readonly DawAnnotationTrackElement[] {\n return this._tracks;\n }\n\n /** Current playback-following highlight id for a track, or `null` when the\n * playhead isn't inside any of the track's annotations. */\n getPlayingAnnotationId(track: DawAnnotationTrackElement): string | null {\n return this._playingIds.get(track) ?? null;\n }\n\n get totalLaneHeight(): number {\n return this._tracks.length * ANNOTATION_LANE_HEIGHT;\n }\n\n /** Max annotation end (seconds) across registered tracks — 0 when none.\n * Lets the editor extend the timeline so annotations past the audio stay\n * reachable/scrollable. */\n get maxAnnotationEndSeconds(): number {\n return this._tracks.reduce(\n (max, track) => track.annotations.reduce((m, a) => Math.max(m, a.end), max),\n 0\n );\n }\n\n /** The host listeners of this connection, aborted in hostDisconnected. */\n private _listeners: AbortController | null = null;\n\n hostConnected(): void {\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n this._host.addEventListener('daw-annotation-update', this._onDataChange, { signal });\n this._host.addEventListener('daw-annotation-select', this._onDataChange, { signal });\n this._host.addEventListener('daw-annotation-connected', this._onDataChange, { signal });\n // The host IS the editor and daw-timeupdate/daw-stop are dispatched on\n // it directly (see playback-animation-controller.ts) — no document-level\n // listening or target filtering needed, unlike <daw-annotation-list>.\n this._host.addEventListener('daw-timeupdate', this._onTimeUpdate as EventListener, { signal });\n this._host.addEventListener('daw-stop', this._onStop, { signal });\n // Removals can't bubble — observe childList like the editor's track observer.\n this._removalObserver = new MutationObserver((mutations) => {\n let changed = false;\n for (const m of mutations) {\n for (const node of Array.from(m.removedNodes)) {\n if (!(node instanceof HTMLElement)) continue;\n if (node.tagName === 'DAW-ANNOTATION-TRACK') {\n this._tracks = this._tracks.filter((t) => t !== node);\n changed = true;\n } else if (node.tagName === 'DAW-ANNOTATION') {\n changed = true;\n }\n // A wrapper element containing a track (rather than the track\n // itself) is removed — recurse into the subtree like the editor's\n // track observer, or the nested track is never unregistered.\n const nestedTracks = node.querySelectorAll?.('daw-annotation-track');\n if (nestedTracks) {\n for (const nested of nestedTracks) {\n this._tracks = this._tracks.filter((t) => t !== nested);\n changed = true;\n }\n }\n const nestedAnnotations = node.querySelectorAll?.('daw-annotation');\n if (nestedAnnotations && nestedAnnotations.length > 0) {\n changed = true;\n }\n }\n }\n if (changed) this._host.requestUpdate();\n });\n this._removalObserver.observe(this._host, { childList: true, subtree: true });\n }\n\n hostDisconnected(): void {\n this._listeners?.abort();\n this._listeners = null;\n this._removalObserver?.disconnect();\n this._removalObserver = null;\n this._tracks = [];\n this._playingIds = new Map();\n }\n\n private _onDataChange = (): void => {\n this.deriveSecondsCaches();\n this._host.requestUpdate();\n };\n\n /**\n * Update only on annotation-boundary crossings, not per animation frame.\n */\n private _onTimeUpdate = (e: CustomEvent<DawTimeUpdateDetail>): void => {\n const time = e.detail.time;\n let changed = false;\n const next = new Map(this._playingIds);\n for (const track of this._tracks) {\n const playingId = computePlayingAnnotationId(track.annotations, time);\n if (playingId !== (this._playingIds.get(track) ?? null)) {\n next.set(track, playingId);\n changed = true;\n }\n }\n if (!changed) return;\n this._playingIds = next;\n this._host.requestUpdate();\n };\n\n private _onStop = (): void => {\n if (this._playingIds.size === 0) return;\n this._playingIds = new Map();\n this._host.requestUpdate();\n };\n\n handleTrackConnected(el: DawAnnotationTrackElement): void {\n if (this._tracks.includes(el)) return;\n this._tracks = [...this._tracks, el];\n this._host.requestUpdate();\n this.deriveSecondsCaches();\n }\n\n /**\n * Keep the seconds attributes (derived cache) of tick-based annotations in\n * sync with the host's tempo. Write-only-on-change: a write fires\n * daw-annotation-update → _onDataChange → this sweep again → values equal →\n * no write → the loop settles (idempotent).\n */\n deriveSecondsCaches(): void {\n for (const track of this._tracks) {\n for (const el of track.annotationElements) {\n if (!el.isTickBased) continue;\n const startSeconds = this._host._ticksToSeconds(el.startTick as number);\n const endSeconds = this._host._ticksToSeconds(el.endTick as number);\n if (el.start !== startSeconds) el.start = startSeconds;\n if (el.end !== endSeconds) el.end = endSeconds;\n }\n }\n }\n\n /** Pixel geometry for one annotation box. Tick-based annotations in beats\n * mode use CLIP-IDENTICAL tick math (round(tick / ticksPerPixel)) so they\n * align pixel-exactly with <daw-grid>; everything else uses the floor-based\n * seconds math (temporal mode reads the always-fresh seconds cache). */\n boxGeometry(\n a: AnnotationData,\n spp: number,\n sampleRate: number,\n ticksPerPixel: number | null = null\n ): { left: number; width: number } {\n if (\n ticksPerPixel !== null &&\n ticksPerPixel > 0 &&\n a.startTick !== undefined &&\n a.endTick !== undefined\n ) {\n const left = Math.round(a.startTick / ticksPerPixel);\n const width = Math.round(a.endTick / ticksPerPixel) - left;\n return { left, width };\n }\n const left = Math.floor((a.start * sampleRate) / spp);\n const width = Math.floor((a.end * sampleRate) / spp) - left;\n return { left, width };\n }\n\n /**\n * Lane templates for the editor's .timeline. onPointerDown is supplied by\n * the editor and dispatches into the drag interaction (Task 9).\n */\n renderLanes(\n spp: number,\n sampleRate: number,\n onPointerDown: (e: PointerEvent, track: DawAnnotationTrackElement) => void = () => {},\n ticksPerPixel: number | null = null\n ): TemplateResult[] {\n return this._tracks.map((track) => {\n const activeId = track.activeAnnotationId;\n const playingId = this._playingIds.get(track) ?? null;\n const elements = track.annotationElements;\n return html`\n <div\n class=\"annotation-lane\"\n style=\"height: ${ANNOTATION_LANE_HEIGHT}px;\"\n @pointerdown=${(e: PointerEvent) => onPointerDown(e, track)}\n >\n ${elements.map((el, i) => {\n const a = el.toAnnotationData();\n const geo = this.boxGeometry(a, spp, sampleRate, ticksPerPixel);\n const label =\n track.boxLabel === 'none'\n ? ''\n : track.boxLabel === 'id'\n ? el.id || String(i + 1)\n : a.lines.join(' ');\n return html`\n <div\n class=\"annotation-box ${a.id === activeId ? 'active' : ''} ${a.id === playingId\n ? 'playing'\n : ''}\"\n data-annotation-id=${a.id}\n style=\"left: ${geo.left}px; width: ${geo.width}px;\"\n >\n ${track.editable\n ? html`<div class=\"annotation-boundary\" data-edge=\"start\"></div>`\n : ''}\n <span class=\"annotation-box-text\">${label}</span>\n ${track.editable\n ? html`<div class=\"annotation-boundary\" data-edge=\"end\"></div>`\n : ''}\n </div>\n `;\n })}\n </div>\n `;\n });\n }\n}\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport {\n SpectrogramOrchestrator,\n type ClipRegistration,\n type CanvasRegistration,\n type ViewportState,\n} from '@dawcore/spectrogram';\nimport type { SpectrogramConfig, ColorMapValue } from '@waveform-playlist/core';\nimport {\n SPECTROGRAM_DEFAULTS as LIBRARY_DEFAULTS,\n DEFAULT_SPECTROGRAM_COLOR_MAP as LIBRARY_DEFAULT_COLOR_MAP,\n} from '@waveform-playlist/core';\n\nexport interface SpectrogramControllerHost extends ReactiveControllerHost {\n dispatchEvent(event: Event): boolean;\n}\n\n/**\n * Lit reactive controller that owns a `SpectrogramOrchestrator` for the\n * `<daw-editor>` host. Creates the orchestrator lazily on first canvas\n * registration so editors without spectrogram tracks pay nothing.\n *\n * Holds editor-level defaults and per-track overrides separately; merges\n * them down to a single (config, colorMap) pair for the orchestrator on\n * each change.\n *\n * v1 limitation: orchestrator accepts ONE config / colorMap at a time, so\n * the \"first registered track wins\" rule applies when multiple tracks are\n * in spectrogram mode with different overrides. Multi-track per-clip\n * configs are deferred to a follow-up.\n */\nexport class SpectrogramController implements ReactiveController {\n private host: SpectrogramControllerHost;\n private workerFactory: () => Worker;\n private orchestrator: SpectrogramOrchestrator | null = null;\n\n private editorConfig: SpectrogramConfig | null = null;\n private editorColorMap: ColorMapValue | null = null;\n private trackConfigs = new Map<string, SpectrogramConfig | null>();\n private trackColorMaps = new Map<string, ColorMapValue | null>();\n\n constructor(host: SpectrogramControllerHost, workerFactory: () => Worker) {\n this.host = host;\n this.workerFactory = workerFactory;\n this.host.addController(this);\n }\n\n hostConnected(): void {\n // Lazy — orchestrator created on first registerCanvas.\n }\n\n hostDisconnected(): void {\n this.dispose();\n }\n\n setEditorConfig(config: SpectrogramConfig | null): void {\n this.editorConfig = config;\n this.reapply();\n }\n\n setEditorColorMap(colorMap: ColorMapValue | null): void {\n this.editorColorMap = colorMap;\n this.reapply();\n }\n\n setTrackConfig(trackId: string, config: SpectrogramConfig | null): void {\n if (config === null) {\n this.trackConfigs.delete(trackId);\n } else {\n this.trackConfigs.set(trackId, config);\n }\n this.reapply();\n }\n\n setTrackColorMap(trackId: string, colorMap: ColorMapValue | null): void {\n if (colorMap === null) {\n this.trackColorMaps.delete(trackId);\n } else {\n this.trackColorMaps.set(trackId, colorMap);\n }\n this.reapply();\n }\n\n registerClipAudio(reg: ClipRegistration): void {\n this.ensureOrchestrator().registerClip(reg);\n }\n\n unregisterClipAudio(clipId: string): void {\n this.orchestrator?.unregisterClip(clipId);\n }\n\n registerCanvas(reg: CanvasRegistration): void {\n this.ensureOrchestrator().registerCanvas(reg);\n }\n\n unregisterCanvas(canvasId: string): void {\n this.orchestrator?.unregisterCanvas(canvasId);\n }\n\n setViewport(state: ViewportState): void {\n this.orchestrator?.setViewport(state);\n }\n\n dispose(): void {\n if (this.orchestrator) {\n this.orchestrator.dispose();\n this.orchestrator = null;\n }\n }\n\n private ensureOrchestrator(): SpectrogramOrchestrator {\n if (!this.orchestrator) {\n this.orchestrator = new SpectrogramOrchestrator({\n workerFactory: this.workerFactory,\n workerPoolSize: 2,\n config: this.mergedConfig(),\n colorMap: this.mergedColorMap(),\n });\n this.orchestrator.addEventListener('viewport-ready', (e: Event) => {\n const detail = (e as CustomEvent<{ trackId: string; generation: number }>).detail;\n this.host.dispatchEvent(\n new CustomEvent('daw-spectrogram-ready', {\n detail: { trackId: detail.trackId, generation: detail.generation },\n bubbles: true,\n composed: true,\n })\n );\n });\n this.orchestrator.addEventListener('viewport-error', (e: Event) => {\n const detail = (e as CustomEvent<{ trackId: string; generation: number; error: Error }>)\n .detail;\n this.host.dispatchEvent(\n new CustomEvent('daw-spectrogram-error', {\n detail: {\n trackId: detail.trackId,\n generation: detail.generation,\n error: detail.error,\n },\n bubbles: true,\n composed: true,\n })\n );\n });\n this.reapply();\n }\n return this.orchestrator;\n }\n\n private reapply(): void {\n if (!this.orchestrator) return;\n this.orchestrator.setConfig(this.mergedConfig());\n this.orchestrator.setColorMap(this.mergedColorMap());\n }\n\n private mergedConfig(): SpectrogramConfig {\n // First track override wins (v1 limitation noted above).\n let track: SpectrogramConfig | null = null;\n for (const c of this.trackConfigs.values()) {\n track = c;\n break;\n }\n return { ...LIBRARY_DEFAULTS, ...(this.editorConfig ?? {}), ...(track ?? {}) };\n }\n\n private mergedColorMap(): ColorMapValue {\n for (const c of this.trackColorMaps.values()) {\n return c ?? LIBRARY_DEFAULT_COLOR_MAP;\n }\n return this.editorColorMap ?? LIBRARY_DEFAULT_COLOR_MAP;\n }\n}\n","import { pixelsToSeconds, snapTickToGrid } from '@waveform-playlist/core';\nimport type { SnapTo, MeterEntry } from '@waveform-playlist/core';\nimport { DRAG_THRESHOLD } from './constants';\n\n/** Narrow engine contract for pointer interactions. */\nexport interface PointerEngineContract {\n setSelection(start: number, end: number): void;\n stop(): void;\n play(time: number): void;\n seek(time: number): void;\n selectTrack(trackId: string | null): void;\n}\n\n/** Manages pointer interactions on the timeline: click-to-seek and drag-to-select. */\nexport interface PointerHandlerHost {\n readonly samplesPerPixel: number;\n readonly _engine: PointerEngineContract | null;\n readonly _isPlaying: boolean;\n readonly effectiveSampleRate: number;\n _currentTime: number;\n _selectionStartTime: number;\n _selectionEndTime: number;\n _dragOver: boolean;\n /** Suppresses the transient settle daw-timeupdate during stop+play seeks. */\n _inSeekTransition: boolean;\n _setSelectedTrackId(trackId: string | null): void;\n _startPlayhead(): void;\n _stopPlayhead(): void;\n dispatchEvent(event: Event): boolean;\n shadowRoot: ShadowRoot | null;\n requestUpdate(): void;\n readonly _clipHandler: {\n tryHandle(target: Element, e: PointerEvent): boolean;\n onPointerMove(e: PointerEvent): void;\n onPointerUp(e: PointerEvent): void;\n onPointerCancel(e: PointerEvent): void;\n isActive: boolean;\n } | null;\n readonly scaleMode: 'temporal' | 'beats';\n readonly ticksPerPixel: number;\n readonly bpm: number;\n readonly ppqn: number;\n readonly _meterEntries: MeterEntry[];\n readonly snapTo: SnapTo;\n readonly _secondsToTicks: (seconds: number) => number;\n readonly _ticksToSeconds: (ticks: number) => number;\n}\n\nexport class PointerHandler {\n private _host: PointerHandlerHost;\n private _isDragging = false;\n private _dragStartPx = 0;\n private _dragStartTime = 0;\n private _timeline: HTMLElement | null = null;\n // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag\n private _timelineRect: DOMRect | null = null;\n /** Pointer that started the current interaction — a pointercancel from any\n * OTHER pointer (palm rejection on touch) must not kill the active drag. */\n private _activePointerId: number | null = null;\n // Selection values at pointerdown — restored on cancel so an interrupted\n // drag doesn't destroy a previously committed selection (which the engine\n // still holds; zeroing only the host would desync the two).\n private _preDragSelectionStart = 0;\n private _preDragSelectionEnd = 0;\n\n constructor(host: PointerHandlerHost) {\n this._host = host;\n }\n\n private _pxFromPointer(e: PointerEvent): number {\n if (!this._timelineRect) {\n console.warn('[dawcore] _pxFromPointer called without timeline reference');\n return 0;\n }\n // .timeline is wider than :host (which has overflow-x: auto).\n // getBoundingClientRect().left already reflects scroll position\n // (goes negative when scrolled), so no scrollLeft adjustment needed.\n return e.clientX - this._timelineRect.left;\n }\n\n private _pxToTime(px: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n let tick = px * h.ticksPerPixel;\n tick = snapTickToGrid(tick, h.snapTo, h._meterEntries, h.ppqn);\n return h._ticksToSeconds(tick);\n }\n return pixelsToSeconds(px, h.samplesPerPixel, h.effectiveSampleRate);\n }\n\n private _timeToPx(time: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n const tick = h._secondsToTicks(time);\n return tick / h.ticksPerPixel;\n }\n return (time * h.effectiveSampleRate) / h.samplesPerPixel;\n }\n\n /** The timeline's listeners of the seek / selection press in progress. */\n private _seekGesture: AbortController | null = null;\n\n /** Cancels the armed clip drag; set while one is armed (#848). */\n private _cancelArmedClipDrag: (() => void) | null = null;\n\n /**\n * Cancel an armed clip move or trim as a `pointercancel` would: the clip\n * handler reverts it and the timeline's listeners and pointer capture are\n * released. Returns whether a clip drag was armed.\n */\n cancelClipDrag(): boolean {\n const cancel = this._cancelArmedClipDrag;\n if (!cancel) return false;\n cancel();\n return true;\n }\n\n onPointerDown = (e: PointerEvent) => {\n // Check if click landed on an interactive clip element\n const clipHandler = this._host._clipHandler;\n if (clipHandler) {\n const target = e.composedPath()[0] as Element;\n if (target && clipHandler.tryHandle(target, e)) {\n // Prevent browser native drag (globe icon) and text selection\n e.preventDefault();\n // Clip handler took over — wire move/up to it\n this._timeline = this._host.shadowRoot?.querySelector('.timeline') as HTMLElement | null;\n if (this._timeline) {\n try {\n this._timeline.setPointerCapture(e.pointerId);\n } catch (err) {\n console.warn('[dawcore] setPointerCapture failed: ' + String(err));\n }\n const onMove = (me: Event) => clipHandler.onPointerMove(me as PointerEvent);\n // This clip drag's listeners: aborted on every way it ends.\n const gesture = new AbortController();\n const detach = (pointerId: number) => {\n this._cancelArmedClipDrag = null;\n gesture.abort();\n try {\n this._timeline?.releasePointerCapture(pointerId);\n } catch (err) {\n console.warn(\n '[dawcore] releasePointerCapture failed (may already be released): ' + String(err)\n );\n }\n this._timeline = null;\n };\n const onUp = (ue: Event) => {\n clipHandler.onPointerUp(ue as PointerEvent);\n detach((ue as PointerEvent).pointerId);\n };\n // pointercancel fires INSTEAD of pointerup on touch interruption /\n // pen leaving range / OS gestures — the clip drag must be reverted\n // or it stays armed and its transaction stays open. Only the\n // initiating pointer's cancel counts (palm rejection cancels the\n // palm's pointer, not the drag).\n const downPointerId = e.pointerId;\n const onCancel = (ce: Event) => {\n if ((ce as PointerEvent).pointerId !== downPointerId) return;\n clipHandler.onPointerCancel(ce as PointerEvent);\n detach((ce as PointerEvent).pointerId);\n };\n // Escape and the editor's disconnect cancel the drag the same way (#848).\n this._cancelArmedClipDrag = () => {\n clipHandler.onPointerCancel(\n new PointerEvent('pointercancel', { pointerId: downPointerId })\n );\n detach(downPointerId);\n };\n const { signal } = gesture;\n this._timeline.addEventListener('pointermove', onMove, { signal });\n this._timeline.addEventListener('pointerup', onUp, { signal });\n this._timeline.addEventListener('pointercancel', onCancel, { signal });\n }\n return;\n }\n }\n\n this._timeline = this._host.shadowRoot?.querySelector('.timeline') as HTMLElement | null;\n if (!this._timeline) {\n console.warn(\n '[dawcore] PointerHandler: .timeline not found in shadow root — seek/selection ignored'\n );\n return;\n }\n\n this._timelineRect = this._timeline.getBoundingClientRect();\n this._dragStartPx = this._pxFromPointer(e);\n this._isDragging = false;\n this._activePointerId = e.pointerId;\n this._preDragSelectionStart = this._host._selectionStartTime;\n this._preDragSelectionEnd = this._host._selectionEndTime;\n\n try {\n this._timeline.setPointerCapture(e.pointerId);\n } catch (err) {\n console.warn('[dawcore] setPointerCapture failed: ' + String(err));\n }\n // A press while one is in progress (a second touch) keeps one set of\n // listeners, as adding the same listeners again did.\n this._seekGesture?.abort();\n this._seekGesture = new AbortController();\n const { signal } = this._seekGesture;\n this._timeline.addEventListener('pointermove', this._onPointerMove, { signal });\n this._timeline.addEventListener('pointerup', this._onPointerUp, { signal });\n this._timeline.addEventListener('pointercancel', this._onPointerCancel, { signal });\n };\n\n private _onPointerMove = (e: PointerEvent) => {\n if (!this._timeline) return;\n\n const currentPx = this._pxFromPointer(e);\n\n if (!this._isDragging && Math.abs(currentPx - this._dragStartPx) > DRAG_THRESHOLD) {\n this._isDragging = true;\n // Cache snapped start time once — don't recompute every frame\n this._dragStartTime = this._pxToTime(this._dragStartPx);\n }\n\n if (this._isDragging) {\n const h = this._host;\n const startTime = this._dragStartTime;\n const endTime = this._pxToTime(currentPx);\n // Mutate host fields directly (not @state) and update <daw-selection>\n // imperatively to avoid triggering Lit re-renders at 60fps during drag\n h._selectionStartTime = Math.min(startTime, endTime);\n h._selectionEndTime = Math.max(startTime, endTime);\n const sel = h.shadowRoot?.querySelector('daw-selection') as\n | { startPx: number; endPx: number }\n | undefined;\n if (sel) {\n sel.startPx = this._timeToPx(h._selectionStartTime);\n sel.endPx = this._timeToPx(h._selectionEndTime);\n }\n }\n };\n\n /** Detach the drag listeners and release capture — shared by the up and\n * cancel terminals so a new listener added to onPointerDown can't be\n * missed on one of them. */\n private _detachTimeline(e: PointerEvent) {\n if (!this._timeline) return;\n try {\n this._timeline.releasePointerCapture(e.pointerId);\n } catch (err) {\n console.warn(\n '[dawcore] releasePointerCapture failed (may already be released): ' + String(err)\n );\n }\n this._seekGesture?.abort();\n this._seekGesture = null;\n }\n\n private _resetInteractionState() {\n this._isDragging = false;\n this._timeline = null;\n this._timelineRect = null;\n this._activePointerId = null;\n }\n\n private _onPointerUp = (e: PointerEvent) => {\n if (!this._timeline) return;\n\n this._detachTimeline(e);\n\n try {\n if (this._isDragging) {\n this._finalizeSelection();\n } else {\n this._handleSeekClick(e);\n }\n } catch (err) {\n console.warn('[dawcore] Pointer interaction failed: ' + String(err));\n } finally {\n this._resetInteractionState();\n }\n };\n\n /** pointercancel fires INSTEAD of pointerup on touch interruption / pen\n * leaving range / OS gestures — discard the interaction (no seek, no\n * selection finalize) and detach the drag listeners, or the still-attached\n * move handler keeps mutating the selection on hover with a stale rect. */\n private _onPointerCancel = (e: PointerEvent) => {\n if (!this._timeline) return;\n // Only the initiating pointer's cancel ends the interaction — a palm\n // touch that the OS rejects fires pointercancel for the PALM's pointer.\n if (e.pointerId !== this._activePointerId) return;\n\n this._detachTimeline(e);\n\n if (this._isDragging) {\n // Cancel = as if the drag never happened: restore the pre-drag\n // selection (the engine still holds it — zeroing only the host would\n // desync the two and destroy a committed selection).\n const h = this._host;\n h._selectionStartTime = this._preDragSelectionStart;\n h._selectionEndTime = this._preDragSelectionEnd;\n const sel = h.shadowRoot?.querySelector('daw-selection') as\n | { startPx: number; endPx: number }\n | undefined;\n if (sel) {\n sel.startPx = this._timeToPx(this._preDragSelectionStart);\n sel.endPx = this._timeToPx(this._preDragSelectionEnd);\n }\n h.requestUpdate();\n }\n\n this._resetInteractionState();\n };\n\n private _finalizeSelection() {\n const h = this._host;\n if (h._engine) {\n h._engine.setSelection(h._selectionStartTime, h._selectionEndTime);\n }\n h.dispatchEvent(\n new CustomEvent('daw-selection', {\n bubbles: true,\n composed: true,\n detail: { start: h._selectionStartTime, end: h._selectionEndTime },\n })\n );\n h.requestUpdate();\n }\n\n private _handleSeekClick(e: PointerEvent) {\n const h = this._host;\n const px = this._pxFromPointer(e);\n const time = this._pxToTime(px);\n\n // Clear selection\n h._selectionStartTime = 0;\n h._selectionEndTime = 0;\n\n // Detect which track was clicked by Y position\n if (this._timeline) {\n const trackRows = this._timeline.querySelectorAll('.track-row');\n for (const row of trackRows) {\n const rowRect = row.getBoundingClientRect();\n if (e.clientY >= rowRect.top && e.clientY < rowRect.bottom) {\n const trackId = (row as HTMLElement).dataset.trackId;\n if (trackId) {\n this._selectTrack(trackId);\n }\n break;\n }\n }\n }\n\n // Capture playing state before engine calls (stop emits statechange\n // which synchronously flips _isPlaying — use wasPlaying for all guards)\n const wasPlaying = h._isPlaying;\n\n if (h._engine) {\n h._engine.setSelection(0, 0);\n if (wasPlaying) {\n // Tone.js needs stop + play to reschedule audio sources.\n // Suppress the transient settle dispatch — engine.stop() rewinds to\n // the play-start position and the editor's engine-'stop' handler would\n // leak a backward-jumping daw-timeupdate before frames resume at the\n // seek target.\n h._inSeekTransition = true;\n try {\n h._engine.stop();\n } finally {\n h._inSeekTransition = false;\n }\n h._engine.play(time);\n h._startPlayhead();\n } else {\n h._engine.seek(time);\n }\n }\n\n h._currentTime = time;\n if (!wasPlaying) {\n h._stopPlayhead();\n }\n\n h.dispatchEvent(\n new CustomEvent('daw-seek', {\n bubbles: true,\n composed: true,\n detail: { time },\n })\n );\n h.requestUpdate();\n }\n\n private _selectTrack(trackId: string) {\n const h = this._host;\n if (h._engine) {\n try {\n h._engine.selectTrack(trackId);\n // Engine sets _selectedTrackId via statechange — don't set locally\n } catch (err) {\n console.warn(\n '[dawcore] selectTrack via engine failed, falling back to local: ' + String(err)\n );\n // Fall through to local selection below\n h._setSelectedTrackId(trackId);\n }\n } else {\n // No engine — set locally (will be lost when engine builds, acceptable for Phase 2)\n h._setSelectedTrackId(trackId);\n }\n h.dispatchEvent(\n new CustomEvent('daw-track-select', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n }\n}\n","/** Minimum pixel movement before a drag is activated (click vs drag). */\nexport const DRAG_THRESHOLD = 3;\n\n// Boundary width (8px) is defined in CSS (styles/theme.ts .clip-boundary).\n// Not exported as a JS constant since CSS template literals can't import it.\n","import { snapTickToGrid } from '@waveform-playlist/core';\nimport type { AudioClip, SnapTo, MeterEntry } from '@waveform-playlist/core';\nimport { constrainClipDrag } from '@waveform-playlist/engine';\nimport type { DraggedClip } from './drag-watch';\nimport { DRAG_THRESHOLD } from './constants';\n\n/** Snapshot of a clip's bounds for trim constraint computation. */\nexport interface ClipBounds {\n readonly offsetSamples: number;\n readonly durationSamples: number;\n readonly startSample: number;\n readonly sourceDurationSamples: number;\n}\n\n/** Narrow engine contract for clip move/trim interactions. */\nexport interface ClipEngineContract {\n /** Move a clip; returns the delta actually applied. One undo step. */\n moveClip(trackId: string, clipId: string, deltaSamples: number): number;\n trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): void;\n /** The loaded clips of each track (a move collides with them, as `moveClip` does). */\n getState(): { tracks: readonly { id: string; clips: readonly AudioClip[] }[] };\n /** Get a clip's full bounds for trim constraint computation. */\n getClipBounds(trackId: string, clipId: string): ClipBounds | null;\n /** Constrain a trim delta using the engine's collision/bounds logic. */\n constrainTrimDelta(\n trackId: string,\n clipId: string,\n boundary: 'left' | 'right',\n deltaSamples: number\n ): number;\n}\n\n/** Peak data returned by reextractClipPeaks for imperative waveform updates. */\nexport interface ClipPeakSlice {\n data: ArrayLike<number>[];\n length: number;\n}\n\n/** Host interface required by ClipPointerHandler. */\nexport interface ClipPointerHost {\n readonly samplesPerPixel: number;\n /** In beats mode, the tick-derived SPP used for rendering. */\n readonly renderSamplesPerPixel: number;\n readonly effectiveSampleRate: number;\n readonly interactiveClips: boolean;\n readonly engine: ClipEngineContract | null;\n readonly shadowRoot: ShadowRoot | null;\n readonly scaleMode: 'temporal' | 'beats';\n readonly ticksPerPixel: number;\n readonly bpm: number;\n readonly ppqn: number;\n readonly _meterEntries: MeterEntry[];\n readonly snapTo: SnapTo;\n readonly _secondsToTicks: (seconds: number) => number;\n readonly _ticksToSeconds: (ticks: number) => number;\n dispatchEvent(event: Event): boolean;\n /** Re-extract peaks for a clip at new offset/duration from cached WaveformData. */\n reextractClipPeaks(\n clipId: string,\n offsetSamples: number,\n durationSamples: number\n ): ClipPeakSlice | null;\n /**\n * Returns true if the clip is a MIDI clip (has midiNotes).\n * Trim handles are inert for MIDI clips — note slicing is not yet implemented.\n */\n isMidiClip(trackId: string, clipId: string): boolean;\n}\n\ntype DragMode = 'move' | 'trim-left' | 'trim-right';\n\n/**\n * Handles pointer interactions for clip move and trim drag operations.\n * Converts pixel deltas to sample deltas and delegates to the engine.\n *\n * Both show the drag in the view and change the arrangement once, on release\n * (#848): nothing is written while the pointer moves, so an arrangement change\n * during a drag always came from outside.\n *\n * Move: the clip container's `left` follows the pointer, constrained by the\n * track's other loaded clips as `moveClip` will be; one `moveClip` on release.\n * Trim: updates clip container CSS and peaks imperatively during drag, then\n * applies the cumulative delta to the engine once on release.\n */\nexport class ClipPointerHandler {\n private _host: ClipPointerHost;\n private _mode: DragMode | null = null;\n private _clipId = '';\n private _trackId = '';\n private _startPx = 0;\n private _isDragging = false;\n private _cumulativeDeltaSamples = 0;\n // Trim visual feedback: snapshot of original clip state\n private _clipContainer: HTMLElement | null = null;\n private _boundaryEl: HTMLElement | null = null;\n private _originalLeft = 0;\n private _originalWidth = 0;\n private _originalOffsetSamples = 0;\n private _originalDurationSamples = 0;\n private _originalStartSample = 0;\n // Move: the dragged clip and the track's loaded clips, sorted, at drag start\n private _moveClip: AudioClip | null = null;\n private _moveSorted: AudioClip[] = [];\n\n constructor(host: ClipPointerHost) {\n this._host = host;\n }\n\n /**\n * Convert a pixel delta to samples, snapping in tick space when in beats mode.\n *\n * The anchor is the absolute sample position being moved (e.g., clip start\n * for move/left-trim, clip end for right-trim). Snapping the absolute\n * position — not just the delta — ensures clips land exactly on grid lines\n * even if they started off-grid.\n */\n private _snapDeltaToSamples(totalDeltaPx: number, anchorSample: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n const anchorSeconds = anchorSample / h.effectiveSampleRate;\n const anchorTick = h._secondsToTicks(anchorSeconds);\n const deltaTicks = totalDeltaPx * h.ticksPerPixel;\n const targetTick = anchorTick + deltaTicks;\n const snappedTick =\n h.snapTo !== 'off'\n ? snapTickToGrid(targetTick, h.snapTo, h._meterEntries, h.ppqn)\n : targetTick;\n const snappedSeconds = h._ticksToSeconds(snappedTick);\n const snappedSample = Math.round(snappedSeconds * h.effectiveSampleRate);\n return snappedSample - anchorSample;\n }\n return Math.round(totalDeltaPx * h.renderSamplesPerPixel);\n }\n\n /** A sample delta from `anchorSample` in pixels: in tick space in beats mode,\n * so the drawn position does not drift from the sample round-trip. */\n private _samplesToPx(anchorSample: number, deltaSamples: number): number {\n const h = this._host;\n if (h.scaleMode === 'beats') {\n const anchorSec = anchorSample / h.effectiveSampleRate;\n const anchorTick = h._secondsToTicks(anchorSec);\n const newTick = h._secondsToTicks(anchorSec + deltaSamples / h.effectiveSampleRate);\n return Math.round((newTick - anchorTick) / h.ticksPerPixel);\n }\n return Math.round(deltaSamples / h.renderSamplesPerPixel);\n }\n\n /** Returns true if a drag interaction is currently in progress. */\n get isActive(): boolean {\n return this._mode !== null;\n }\n\n /** True once the pointer of the current press has moved past the drag\n * threshold: a press that has not moved is not a drag (#848). */\n get isDragging(): boolean {\n return this._isDragging;\n }\n\n /**\n * The clip being dragged (past the threshold) with its bounds at the drag's\n * start, or null; null too while the release makes its one arrangement\n * call, so that call is not taken for an outside change (#848).\n */\n get draggedClip(): DraggedClip | null {\n if (!this._isDragging || this._committing) return null;\n return {\n trackId: this._trackId,\n clipId: this._clipId,\n startSample: this._originalStartSample,\n durationSamples: this._originalDurationSamples,\n offsetSamples: this._originalOffsetSamples,\n };\n }\n private _committing = false;\n\n /**\n * Attempts to handle a pointerdown event on the given target element.\n * Returns true if the target is a recognized clip interaction element.\n */\n tryHandle(target: Element, e: PointerEvent): boolean {\n if (!this._host.interactiveClips) return false;\n\n // Walk up from click target to find clip interaction elements.\n // composedPath()[0] may be a child (e.g. <span> inside .clip-header).\n const boundary = (target as HTMLElement).closest?.('.clip-boundary') as HTMLElement | null;\n const header = (target as HTMLElement).closest?.('.clip-header') as HTMLElement | null;\n\n // Check boundary first (higher z-index, overlaps header at corners)\n if (boundary && boundary.dataset.boundaryEdge !== undefined) {\n const clipId = boundary.dataset.clipId;\n const trackId = boundary.dataset.trackId;\n const edge = boundary.dataset.boundaryEdge as 'left' | 'right';\n if (!clipId || !trackId || (edge !== 'left' && edge !== 'right')) return false;\n\n // Trim is not supported for MIDI clips — note slicing is a follow-up PR.\n // Consume the event: no trim drag starts, but prevent the click from\n // falling through to the timeline seek handler.\n if (this._host.isMidiClip(trackId, clipId)) return true;\n\n this._beginDrag(edge === 'left' ? 'trim-left' : 'trim-right', clipId, trackId, e);\n this._boundaryEl = boundary;\n return true;\n }\n\n // Check for clip header (move target)\n if (header && header.dataset.interactive !== undefined) {\n const clipId = header.dataset.clipId;\n const trackId = header.dataset.trackId;\n if (!clipId || !trackId) return false;\n\n this._beginDrag('move', clipId, trackId, e);\n return true;\n }\n\n return false;\n }\n\n private _beginDrag(mode: DragMode, clipId: string, trackId: string, e: PointerEvent): void {\n this._mode = mode;\n this._clipId = clipId;\n this._trackId = trackId;\n this._startPx = e.clientX;\n this._isDragging = false;\n\n this._cumulativeDeltaSamples = 0;\n }\n\n /**\n * The press has become a drag (the pointer passed the threshold): take the\n * clip's bounds now, not at the press, so a drag after an undo made during\n * the press starts from the clip as the undo left it (#848, review of\n * #915). Returns false when the clip is gone (the undo removed it): the\n * press is dropped.\n */\n private _startDrag(): boolean {\n const engine = this._host.engine;\n const trackId = this._trackId;\n const clipId = this._clipId;\n // Snapshot clip start position for snap calculations\n if (engine) {\n const bounds = engine.getClipBounds(trackId, clipId);\n if (!bounds) return false;\n this._originalStartSample = bounds.startSample;\n this._originalOffsetSamples = bounds.offsetSamples;\n this._originalDurationSamples = bounds.durationSamples;\n if (this._mode === 'move') {\n const track = engine.getState().tracks.find((t) => t.id === trackId);\n const clip = track?.clips.find((c) => c.id === clipId) ?? null;\n if (!track || !clip) return false;\n this._moveClip = clip;\n this._moveSorted = [...track.clips].sort((a, b) => a.startSample - b.startSample);\n }\n } else {\n console.warn('[dawcore] drag start: engine unavailable, the drag will not be applied');\n }\n\n // Snapshot the clip container's current position/width for the preview\n {\n const container = this._host.shadowRoot?.querySelector(\n `.clip-container[data-clip-id=\"${clipId}\"]`\n ) as HTMLElement | null;\n if (container) {\n this._clipContainer = container;\n this._originalLeft = parseFloat(container.style.left) || 0;\n this._originalWidth = parseFloat(container.style.width) || 0;\n } else {\n console.warn('[dawcore] clip container not found for drag visual feedback: ' + clipId);\n }\n }\n return true;\n }\n\n /** Processes pointermove events during an active drag. */\n onPointerMove(e: PointerEvent): void {\n if (this._mode === null) return;\n\n const totalDeltaPx = e.clientX - this._startPx;\n\n // Activate drag after threshold is exceeded\n if (!this._isDragging && Math.abs(totalDeltaPx) > DRAG_THRESHOLD) {\n if (!this._startDrag()) {\n this._reset();\n return;\n }\n this._isDragging = true;\n // Apply .dragging class to boundary element for active drag styling\n if (this._boundaryEl) {\n this._boundaryEl.classList.add('dragging');\n }\n }\n\n if (!this._isDragging) return;\n\n const engine = this._host.engine;\n if (!engine) return;\n\n if (this._mode === 'move') {\n // Move: snap the clip start, constrain against the track's clips as\n // moveClip will on release, and draw the clip there. Nothing is written.\n const totalSnappedDelta = this._snapDeltaToSamples(totalDeltaPx, this._originalStartSample);\n const clip = this._moveClip;\n const index = clip ? this._moveSorted.indexOf(clip) : -1;\n const delta =\n clip && index !== -1\n ? constrainClipDrag(clip, totalSnappedDelta, this._moveSorted, index)\n : totalSnappedDelta;\n this._cumulativeDeltaSamples = delta;\n if (this._clipContainer) {\n const deltaPx = this._samplesToPx(this._originalStartSample, delta);\n this._clipContainer.style.left = this._originalLeft + deltaPx + 'px';\n }\n } else {\n // Trim: constrain delta using engine's full collision/bounds logic,\n // then track for visual feedback. Engine called once at pointerup.\n const boundary = this._mode === 'trim-left' ? 'left' : 'right';\n // Anchor = the boundary edge being dragged\n // Left trim: snap the left edge (startSample)\n // Right trim: snap the right edge (startSample + durationSamples)\n const anchor =\n boundary === 'left'\n ? this._originalStartSample\n : this._originalStartSample + this._originalDurationSamples;\n const rawDeltaSamples = this._snapDeltaToSamples(totalDeltaPx, anchor);\n const deltaSamples = engine.constrainTrimDelta(\n this._trackId,\n this._clipId,\n boundary,\n rawDeltaSamples\n );\n const deltaPx = this._samplesToPx(anchor, deltaSamples);\n\n this._cumulativeDeltaSamples = deltaSamples;\n\n // Visual feedback: update clip container CSS and re-extract peaks\n if (this._clipContainer) {\n if (this._mode === 'trim-left') {\n // Left trim: container shifts and resizes\n const newLeft = this._originalLeft + deltaPx;\n const newWidth = this._originalWidth - deltaPx;\n if (newWidth > 0) {\n this._clipContainer.style.left = newLeft + 'px';\n this._clipContainer.style.width = newWidth + 'px';\n // Re-extract peaks at new offset/duration from cached WaveformData.\n // New peaks cover the full new bounds, so waveforms stay at left:0\n // (no shift needed — the container position handles global alignment).\n const newOffset = this._originalOffsetSamples + deltaSamples;\n const newDuration = this._originalDurationSamples - deltaSamples;\n if (this._updateWaveformPeaks(newOffset, newDuration)) {\n // Peaks updated — reset waveform positions to fill container\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (const wf of waveforms) {\n (wf as HTMLElement).style.left = '0px';\n }\n } else {\n // No cached peaks — fall back to shifting waveforms for visual stability\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (const wf of waveforms) {\n (wf as HTMLElement).style.left = -deltaPx + 'px';\n }\n }\n }\n } else {\n // Right trim: extend/shrink right edge — left stays fixed\n const newWidth = this._originalWidth + deltaPx;\n if (newWidth > 0) {\n this._clipContainer.style.width = newWidth + 'px';\n // Re-extract peaks at new duration from cached WaveformData\n const newDuration = this._originalDurationSamples + deltaSamples;\n this._updateWaveformPeaks(this._originalOffsetSamples, newDuration);\n }\n }\n }\n }\n }\n\n /** Processes pointerup events to finalize and dispatch result events. */\n onPointerUp(_e: PointerEvent): void {\n if (this._mode === null) return;\n\n try {\n if (!this._isDragging || this._cumulativeDeltaSamples === 0) {\n // Restore original CSS if the drag didn't produce a delta\n this._restoreVisual();\n return;\n }\n\n const engine = this._host.engine;\n this._committing = true;\n\n if (this._mode === 'move') {\n // Back to where the clip was drawn; the re-render after the move puts it there.\n this._restoreVisual();\n if (engine) {\n // The one arrangement call of the drag: an undo step.\n const applied = engine.moveClip(\n this._trackId,\n this._clipId,\n this._cumulativeDeltaSamples\n );\n if (applied !== 0) {\n this._host.dispatchEvent(\n new CustomEvent('daw-clip-move', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: this._trackId,\n clipId: this._clipId,\n deltaSamples: applied,\n },\n })\n );\n }\n } else {\n console.warn(\n '[dawcore] engine unavailable at move drop — move not applied for clip ' + this._clipId\n );\n }\n } else {\n // Restore visual before engine applies — Lit will re-render with correct values\n this._restoreVisual();\n\n // Trim: apply cumulative delta to engine in one shot (adapter updated internally)\n const boundary = this._mode === 'trim-left' ? 'left' : 'right';\n if (engine) {\n engine.trimClip(this._trackId, this._clipId, boundary, this._cumulativeDeltaSamples);\n this._host.dispatchEvent(\n new CustomEvent('daw-clip-trim', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: this._trackId,\n clipId: this._clipId,\n boundary,\n deltaSamples: this._cumulativeDeltaSamples,\n },\n })\n );\n } else {\n console.warn(\n '[dawcore] engine unavailable at trim drop — trim not applied for clip ' + this._clipId\n );\n }\n }\n } finally {\n this._committing = false;\n this._reset();\n }\n }\n\n /** Processes pointercancel — reverts the in-progress drag.\n *\n * pointercancel fires INSTEAD of pointerup on touch interruption, pen\n * leaving hover range, or OS gestures. Without this handler the drag stays\n * armed (hover keeps moving the clip). The drag wrote nothing to the\n * arrangement, so reverting is putting the view back. */\n onPointerCancel(_e: PointerEvent): void {\n if (this._mode === null) return;\n try {\n this._restoreVisual();\n } finally {\n this._reset();\n }\n }\n\n /** Re-extract peaks from cache and set on waveform elements during trim drag.\n * Returns true if peaks were successfully updated. */\n private _updateWaveformPeaks(offsetSamples: number, durationSamples: number): boolean {\n if (!this._clipContainer || durationSamples <= 0) return false;\n const peakSlice = this._host.reextractClipPeaks(this._clipId, offsetSamples, durationSamples);\n if (!peakSlice) return false;\n\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (let i = 0; i < waveforms.length; i++) {\n const wf = waveforms[i] as HTMLElement & { peaks: unknown; length: number };\n const channelPeaks = peakSlice.data[i];\n if (channelPeaks) {\n wf.peaks = channelPeaks;\n wf.length = peakSlice.length;\n }\n }\n return true;\n }\n\n /** Restore clip container CSS AND waveform peaks to original values after\n * a drag's visual preview. Peaks matter: a trim wrote re-extracted peak\n * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and\n * a cancelled/zero-delta drag makes no engine mutation — so no statechange\n * re-render will ever repair them. */\n private _restoreVisual(): void {\n if (this._clipContainer) {\n this._clipContainer.style.left = this._originalLeft + 'px';\n this._clipContainer.style.width = this._originalWidth + 'px';\n // Restore waveform positions (shifted during left trim preview)\n const waveforms = this._clipContainer.querySelectorAll('daw-waveform');\n for (const wf of waveforms) {\n (wf as HTMLElement).style.left = '0px';\n }\n // Re-extract at the original bounds (no-op when the peak cache is\n // unavailable — in that case the drag never overwrote peaks either).\n this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);\n }\n }\n\n private _reset(): void {\n // Remove .dragging class from boundary element\n if (this._boundaryEl) {\n this._boundaryEl.classList.remove('dragging');\n this._boundaryEl = null;\n }\n this._mode = null;\n this._clipId = '';\n this._trackId = '';\n this._startPx = 0;\n this._isDragging = false;\n\n this._cumulativeDeltaSamples = 0;\n this._clipContainer = null;\n this._originalLeft = 0;\n this._originalWidth = 0;\n this._originalOffsetSamples = 0;\n this._originalDurationSamples = 0;\n this._originalStartSample = 0;\n this._moveClip = null;\n this._moveSorted = [];\n }\n}\n","import { updateAnnotationBoundaries, snapTickToGrid } from '@waveform-playlist/core';\nimport {\n ANNOTATION_LINK_THRESHOLD_TICKS,\n annotationMinDurationTicks,\n} from '@waveform-playlist/core';\nimport type { AnnotationData, SnapTo, MeterEntry } from '@waveform-playlist/core';\nimport {\n applyBoundaryResults,\n applyTickBoundaryResults,\n tickSpaceData,\n type DawAnnotationTrackElement,\n} from '../elements/daw-annotation-track';\nimport { DRAG_THRESHOLD } from './constants';\n\nexport interface AnnotationDragHost {\n effectiveSampleRate: number;\n _renderSpp: number;\n _annotationClampDuration: number;\n seekTo(time: number): void;\n scaleMode: string;\n ticksPerPixel: number;\n snapTo: SnapTo;\n _meterEntries: MeterEntry[];\n ppqn: number;\n _secondsToTicks(seconds: number): number;\n _ticksToSeconds(ticks: number): number;\n}\n\ninterface DragState {\n track: DawAnnotationTrackElement;\n captureEl: HTMLElement;\n /** The listeners on `captureEl`: aborted when this drag ends. */\n listeners: AbortController;\n pointerId: number;\n startClientX: number;\n moved: boolean;\n /** Boundary drag only (null = box click candidate). */\n edge: 'start' | 'end' | null;\n annotationId: string;\n /** 'ticks' when the dragged annotation is tick-based; 'seconds' otherwise. */\n mode: 'seconds' | 'ticks';\n /** Snapshot at drag start — pointercancel restores it. In 'ticks' mode this\n * is tick-space data (see tickSpaceData); in 'seconds' mode it's the\n * ordinary AnnotationData snapshot. */\n snapshot: AnnotationData[];\n /** Edge time at drag start (boundary drags). Ticks in 'ticks' mode,\n * seconds in 'seconds' mode. */\n edgeTime: number;\n}\n\n/**\n * Pointer interaction for annotation lanes: boundary drag (write-through via\n * core boundary math), box click-to-select+seek, cancel-restores-snapshot.\n * Wired by <daw-editor> as the renderLanes pointerdown callback.\n */\nexport class AnnotationDragHandler {\n private _host: AnnotationDragHost;\n private _drag: DragState | null = null;\n\n constructor(host: AnnotationDragHost) {\n this._host = host;\n }\n\n onPointerDown = (e: PointerEvent, track: DawAnnotationTrackElement): void => {\n const target = e.target as HTMLElement;\n const boundary = target.closest('.annotation-boundary') as HTMLElement | null;\n const box = target.closest('.annotation-box') as HTMLElement | null;\n if (!box) return; // empty lane space — fall through to timeline seek\n\n const annotationId = box.getAttribute('data-annotation-id') ?? '';\n const isBoundary = boundary !== null && track.editable;\n if (boundary !== null && !track.editable) {\n // Boundary handles are only rendered when editable, but guard anyway.\n return;\n }\n\n e.stopPropagation();\n e.preventDefault();\n\n const elements = track.annotationElements;\n const el = elements.find((x) => x.annotationId === annotationId);\n if (!el) return;\n const mode: 'seconds' | 'ticks' = el.isTickBased ? 'ticks' : 'seconds';\n const snapshot =\n mode === 'ticks' ? elements.map((x) => tickSpaceData(x, this._host)) : track.annotations;\n const index = snapshot.findIndex((a) => a.id === annotationId);\n if (index === -1) return;\n\n const edge = isBoundary ? (boundary.getAttribute('data-edge') as 'start' | 'end') : null;\n const captureEl = isBoundary ? boundary : box;\n\n // A press while another drag is in progress (a second touch) replaces\n // it: its listeners go, as they did when the same element was pressed.\n this._drag?.listeners.abort();\n const listeners = new AbortController();\n this._drag = {\n track,\n captureEl,\n listeners,\n pointerId: e.pointerId,\n startClientX: e.clientX,\n moved: false,\n edge,\n annotationId,\n mode,\n snapshot,\n // edgeTime holds ticks in 'ticks' mode, seconds in 'seconds' mode.\n edgeTime: edge === 'start' ? snapshot[index].start : snapshot[index].end,\n };\n\n try {\n captureEl.setPointerCapture(e.pointerId);\n } catch {\n // Fabricated pointerIds (tests) or detached elements — capture is best-effort.\n }\n const { signal } = listeners;\n captureEl.addEventListener('pointermove', this._onPointerMove as EventListener, { signal });\n captureEl.addEventListener('pointerup', this._onPointerUp as EventListener, { signal });\n captureEl.addEventListener('pointercancel', this._onPointerCancel as EventListener, { signal });\n };\n\n /** Non-private (underscore convention) so tests can drive moves directly. */\n _onPointerMove = (e: PointerEvent): void => {\n const drag = this._drag;\n if (!drag || e.pointerId !== drag.pointerId) return;\n const deltaPx = e.clientX - drag.startClientX;\n if (Math.abs(deltaPx) >= DRAG_THRESHOLD) drag.moved = true;\n if (drag.edge === null || !drag.moved) return;\n\n const elements = drag.track.annotationElements;\n const index = drag.snapshot.findIndex((a) => a.id === drag.annotationId);\n if (index === -1) return;\n\n if (drag.mode === 'ticks') {\n // px → tick delta: beats mode is tick-linear; temporal mode converts\n // through seconds at the edge's local tempo.\n const deltaTicks =\n this._host.scaleMode === 'beats'\n ? deltaPx * this._host.ticksPerPixel\n : this._host._secondsToTicks(\n this._host._ticksToSeconds(drag.edgeTime) +\n (deltaPx * this._host._renderSpp) / this._host.effectiveSampleRate\n ) - drag.edgeTime;\n let newTick = drag.edgeTime + deltaTicks;\n if (this._host.scaleMode === 'beats' && this._host.snapTo !== 'off') {\n newTick = snapTickToGrid(\n newTick,\n this._host.snapTo,\n this._host._meterEntries,\n this._host.ppqn\n );\n }\n const clamp = this._host._annotationClampDuration;\n const updated = updateAnnotationBoundaries(\n {\n annotationIndex: index,\n newTime: newTick,\n isDraggingStart: drag.edge === 'start',\n annotations: drag.snapshot,\n duration: clamp === Infinity ? Infinity : this._host._secondsToTicks(clamp),\n linkEndpoints: drag.track.linkEndpoints,\n },\n {\n linkThreshold: ANNOTATION_LINK_THRESHOLD_TICKS,\n minDuration: annotationMinDurationTicks(this._host.ppqn),\n }\n );\n applyTickBoundaryResults(elements, updated, (t) => this._host._ticksToSeconds(t));\n return;\n }\n\n const deltaSeconds = (deltaPx * this._host._renderSpp) / this._host.effectiveSampleRate;\n // Compute from the drag-start snapshot each move — cumulative deltas\n // against live state would compound the link/collision adjustments.\n const updated = updateAnnotationBoundaries({\n annotationIndex: index,\n newTime: drag.edgeTime + deltaSeconds,\n isDraggingStart: drag.edge === 'start',\n annotations: drag.snapshot,\n duration: this._host._annotationClampDuration,\n linkEndpoints: drag.track.linkEndpoints,\n });\n applyBoundaryResults(elements, updated);\n };\n\n _onPointerUp = (e: PointerEvent): void => {\n const drag = this._drag;\n if (!drag || e.pointerId !== drag.pointerId) return;\n if (!drag.moved && drag.edge === null) {\n // Click: select + seek to the annotation start.\n const data = drag.track.annotations.find((a) => a.id === drag.annotationId);\n if (data) {\n drag.track.activeAnnotationId = drag.annotationId;\n this._host.seekTo(data.start);\n }\n }\n this._teardown();\n };\n\n _onPointerCancel = (e: PointerEvent): void => {\n const drag = this._drag;\n if (!drag || e.pointerId !== drag.pointerId) return;\n this._restoreAndTeardown(drag);\n };\n\n /** True from pointerdown on an annotation until the drag ends or is cancelled. */\n get isActive(): boolean {\n return this._drag !== null;\n }\n\n /** True once the pointer has moved at least `DRAG_THRESHOLD` px (an edge\n * drag, or a box press that moved): a press that has not moved (a click on\n * the box) is not a drag (#848). */\n get isDragging(): boolean {\n return this._drag?.moved ?? false;\n }\n\n /** Cancel the drag in progress (Escape, editor disconnect): the boundaries\n * go back to where they were when it began (#848). */\n cancel(): void {\n if (this._drag) this._restoreAndTeardown(this._drag);\n }\n\n /** Restore the drag-start snapshot — a cancelled drag must not commit. */\n private _restoreAndTeardown(drag: DragState): void {\n const elements = drag.track.annotationElements;\n if (drag.mode === 'ticks') {\n applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));\n } else {\n applyBoundaryResults(elements, drag.snapshot);\n }\n this._teardown();\n }\n\n private _teardown(): void {\n const drag = this._drag;\n if (!drag) return;\n try {\n drag.captureEl.releasePointerCapture(drag.pointerId);\n } catch {\n // Already released or never captured.\n }\n drag.listeners.abort();\n this._drag = null;\n }\n}\n","/**\n * Vertical track-reorder drag for the controls column. Follows the\n * pointer-handler host pattern: pointerdown on the grip (surfaced from\n * <daw-track-controls>' shadow DOM via daw-track-reorder-grab) +\n * setPointerCapture, Y-midpoint hit testing against control rows, translate\n * preview, commit on pointerup, revert on pointercancel. Covers mouse,\n * touch, and pen uniformly.\n */\n\nimport type { DraggedTrack } from './drag-watch';\n\nexport interface TrackReorderHost {\n readonly isConnected: boolean;\n shadowRoot: ShadowRoot | null;\n reorderTrack(trackId: string, toIndex: number): void;\n}\n\ninterface RowInfo {\n el: HTMLElement;\n top: number;\n height: number;\n trackId: string;\n}\n\nexport class TrackReorderHandler {\n private _host: TrackReorderHost;\n private _trackId: string | null = null;\n private _pointerId = -1;\n private _startY = 0;\n private _rows: RowInfo[] = [];\n private _lanes: (RowInfo | null)[] = []; // aligned with _rows indices; null = lane not found\n private _fromIndex = 0;\n private _targetIndex = 0;\n private _gripEl: HTMLElement | null = null;\n /** The grip's listeners of the drag in progress: one controller per drag. */\n private _gesture: AbortController | null = null;\n\n constructor(host: TrackReorderHost) {\n this._host = host;\n }\n\n private static _reducedMotion(): boolean {\n return (\n typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n }\n\n onGrab = (trackId: string, e: PointerEvent, gripEl: HTMLElement): void => {\n if (this._trackId !== null) return; // one drag at a time\n const column = this._host.shadowRoot?.querySelector('.controls-column');\n if (!column) return;\n const rows = [...column.querySelectorAll('daw-track-controls')] as HTMLElement[];\n this._rows = rows.map((el) => {\n const rect = el.getBoundingClientRect();\n return {\n el,\n top: rect.top,\n height: rect.height,\n trackId: (el as HTMLElement & { trackId: string | null }).trackId ?? '',\n };\n });\n this._fromIndex = this._rows.findIndex((r) => r.trackId === trackId);\n if (this._fromIndex === -1) {\n this._rows = [];\n return;\n }\n this._trackId = trackId;\n this._targetIndex = this._fromIndex;\n this._pointerId = e.pointerId;\n this._startY = e.clientY;\n this._gripEl = gripEl;\n\n // Waveform-lane parity (drag-preview spec): snapshot the shadow timeline's\n // .track-row lanes by trackId. Transform-only mirroring: the lanes' DOM\n // order does not change during the drag; the release is one reorderTrack.\n const timeline = this._host.shadowRoot?.querySelector('.timeline');\n const laneEls = timeline ? ([...timeline.querySelectorAll('.track-row')] as HTMLElement[]) : [];\n this._lanes = this._rows.map((r) => {\n const el = laneEls.find((l) => l.getAttribute('data-track-id') === r.trackId) ?? null;\n if (!el) return null;\n const rect = el.getBoundingClientRect();\n return { el, top: rect.top, height: rect.height, trackId: r.trackId };\n });\n\n const draggedLane = this._lanes[this._fromIndex];\n if (draggedLane) {\n draggedLane.el.setAttribute('data-track-drag-source', '');\n draggedLane.el.style.zIndex = '10';\n draggedLane.el.style.position = 'relative';\n }\n if (!TrackReorderHandler._reducedMotion()) {\n // Displaced rows and ALL lanes animate; the dragged CONTROLS row does not\n // (it pixel-follows the pointer, a transition would make it lag).\n for (let i = 0; i < this._rows.length; i++) {\n if (i !== this._fromIndex) this._rows[i].el.style.transition = 'transform 150ms ease';\n const lane = this._lanes[i];\n if (lane) lane.el.style.transition = 'transform 150ms ease';\n }\n }\n\n try {\n gripEl.setPointerCapture(e.pointerId);\n } catch {\n // Fabricated pointerIds (tests) can't be captured — listeners still work.\n }\n this._gesture = new AbortController();\n const { signal } = this._gesture;\n gripEl.addEventListener('pointermove', this._onPointerMove, { signal });\n gripEl.addEventListener('pointerup', this._onPointerUp, { signal });\n gripEl.addEventListener('pointercancel', this._onPointerCancel, { signal });\n };\n\n /** The dragged track and the order of the rows at the grab (#848), or null. */\n get draggedTrack(): DraggedTrack | null {\n if (this._trackId === null) return null;\n return { trackId: this._trackId, order: this._rows.map((r) => r.trackId) };\n }\n\n /** True from the grab until the drag ends or is cancelled. */\n get isActive(): boolean {\n return this._trackId !== null;\n }\n\n /** Abort any in-progress drag and reset state. Called by the editor on\n * disconnect — without this, a drag interrupted by editor removal (with no\n * pointercancel delivered) would leave the handler wedged and silently\n * block every future grab. */\n cancel(): void {\n this._cleanup();\n }\n\n private _onPointerMove = (e: PointerEvent): void => {\n if (e.pointerId !== this._pointerId || this._trackId === null) return;\n const dragged = this._rows[this._fromIndex];\n const dy = e.clientY - this._startY;\n dragged.el.style.transform = 'translateY(' + dy + 'px)';\n dragged.el.style.zIndex = '10';\n dragged.el.style.position = 'relative';\n\n // Target slot: crossing another row's midpoint claims its slot.\n let target = this._fromIndex;\n for (let i = 0; i < this._rows.length; i++) {\n if (i === this._fromIndex) continue;\n const mid = this._rows[i].top + this._rows[i].height / 2;\n if (i < this._fromIndex && e.clientY < mid) {\n target = i;\n break;\n }\n if (i > this._fromIndex && e.clientY > mid) {\n target = i;\n }\n }\n this._targetIndex = target;\n\n // Shift displaced rows out of the way.\n for (let i = 0; i < this._rows.length; i++) {\n if (i === this._fromIndex) continue;\n const row = this._rows[i];\n let shift = 0;\n if (i > this._fromIndex && i <= target) shift = -dragged.height;\n else if (i < this._fromIndex && i >= target) shift = dragged.height;\n row.el.style.transform = shift === 0 ? '' : 'translateY(' + shift + 'px)';\n }\n\n // Mirror the preview onto the waveform lanes.\n const draggedLaneInfo = this._lanes[this._fromIndex];\n for (let i = 0; i < this._lanes.length; i++) {\n const lane = this._lanes[i];\n if (!lane || !draggedLaneInfo) continue;\n if (i === this._fromIndex) {\n // Slot-snap the dragged lane to the target slot (not pixel-follow).\n let offset = 0;\n const targetLane = this._lanes[target];\n if (targetLane && target > this._fromIndex) {\n offset =\n targetLane.top + targetLane.height - (draggedLaneInfo.top + draggedLaneInfo.height);\n } else if (targetLane && target < this._fromIndex) {\n offset = targetLane.top - draggedLaneInfo.top;\n }\n lane.el.style.transform = offset === 0 ? '' : 'translateY(' + offset + 'px)';\n continue;\n }\n let laneShift = 0;\n if (i > this._fromIndex && i <= target) laneShift = -draggedLaneInfo.height;\n else if (i < this._fromIndex && i >= target) laneShift = draggedLaneInfo.height;\n lane.el.style.transform = laneShift === 0 ? '' : 'translateY(' + laneShift + 'px)';\n }\n };\n\n private _onPointerUp = (e: PointerEvent): void => {\n if (e.pointerId !== this._pointerId || this._trackId === null) return;\n const trackId = this._trackId;\n const target = this._targetIndex;\n const from = this._fromIndex;\n this._cleanup();\n if (target !== from) {\n this._host.reorderTrack(trackId, target);\n }\n };\n\n private _onPointerCancel = (e: PointerEvent): void => {\n if (e.pointerId !== this._pointerId) return;\n this._cleanup();\n };\n\n private _cleanup(): void {\n for (const row of this._rows) {\n row.el.style.transform = '';\n row.el.style.zIndex = '';\n row.el.style.position = '';\n row.el.style.transition = '';\n }\n for (const lane of this._lanes) {\n if (!lane) continue;\n lane.el.style.transform = '';\n lane.el.style.transition = '';\n lane.el.style.zIndex = '';\n lane.el.style.position = '';\n lane.el.removeAttribute('data-track-drag-source');\n }\n this._lanes = [];\n const grip = this._gripEl;\n if (grip) {\n this._gesture?.abort();\n this._gesture = null;\n try {\n grip.releasePointerCapture(this._pointerId);\n } catch {\n // already released / fabricated pointerId\n }\n }\n this._gripEl = null;\n this._trackId = null;\n this._pointerId = -1;\n this._rows = [];\n }\n}\n","/**\n * Time display formats for <daw-time-display> / <daw-time-format> and the\n * editor's `time-format` attribute. The three formats come from the\n * web-components-migration spec (\"Element Registry\": hh:mm:ss.sss | hh:mm:ss\n * | seconds). parseDisplayTime exists for the selection inputs (#463).\n */\nexport type TimeDisplayFormat = 'hh:mm:ss.sss' | 'hh:mm:ss' | 'seconds';\n\nexport const TIME_DISPLAY_FORMATS: readonly TimeDisplayFormat[] = [\n 'hh:mm:ss.sss',\n 'hh:mm:ss',\n 'seconds',\n];\n\nexport function isTimeDisplayFormat(value: unknown): value is TimeDisplayFormat {\n return TIME_DISPLAY_FORMATS.includes(value as TimeDisplayFormat);\n}\n\nfunction clockFormat(totalSeconds: number, decimals: number): string {\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor(totalSeconds / 60) % 60;\n const secsRem = totalSeconds % 60;\n // Truncate (not round) to prevent overflow across the minute boundary\n // (59.9999s -> 59.999, not 60.000). The epsilon compensates for binary\n // float representation (1.001 * 1000 === 1000.9999...; plain floor would\n // render it 1ms low); the Math.min clamp keeps the boundary guard airtight\n // for values the epsilon would otherwise push over (59.9999999...).\n let secs: string;\n if (decimals === 0) {\n secs = String(Math.min(Math.floor(secsRem + 1e-6), 59)).padStart(2, '0');\n } else {\n const factor = 10 ** decimals;\n const truncated = Math.min(Math.floor(secsRem * factor + 1e-6), 60 * factor - 1);\n secs = (truncated / factor).toFixed(decimals).padStart(decimals + 3, '0');\n }\n return String(hours).padStart(2, '0') + ':' + String(minutes).padStart(2, '0') + ':' + secs;\n}\n\n/** Format seconds for display. Non-finite or negative input renders as 0. */\nexport function formatDisplayTime(seconds: number, format: TimeDisplayFormat): string {\n const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;\n switch (format) {\n case 'seconds':\n // 'seconds' rounds via toFixed; clock formats truncate. Rounding is safe here since no minute-boundary overflow can occur in plain seconds.\n return safe.toFixed(3);\n case 'hh:mm:ss':\n return clockFormat(safe, 0);\n case 'hh:mm:ss.sss':\n default:\n return clockFormat(safe, 3);\n }\n}\n\n/**\n * A non-negative decimal number with nothing around it: `5`, `1.5`, `1.`, `.5`.\n * Each string has one way to match (the point is not optional inside the\n * digits), so a long digit string that fails is refused in linear time.\n */\nconst DECIMAL = /^(\\d+(\\.\\d*)?|\\.\\d+)$/;\n/** A whole number of hours or minutes. */\nconst WHOLE = /^\\d+$/;\nconst SECONDS_PER_UNIT = [3600, 60, 1];\n\n/**\n * Read `s`, `m:s` or `h:m:s`. Only the last part (the seconds) may have\n * decimals; the first part may be any size, and each later part must be\n * under 60. The same rule as `parseTime` in `@waveform-playlist/ui-components`\n * (`src/utils/timeFormat.ts`): keep the two in step.\n */\nfunction parseClock(text: string): number | null {\n const parts = text.split(':');\n if (parts.length > 3) return null;\n const units = SECONDS_PER_UNIT.slice(3 - parts.length);\n let total = 0;\n for (let i = 0; i < parts.length; i++) {\n const isLast = i === parts.length - 1;\n if (!(isLast ? DECIMAL : WHOLE).test(parts[i])) return null;\n const value = Number(parts[i]);\n if (i > 0 && value >= 60) return null;\n total += value * units[i];\n }\n return Number.isFinite(total) ? total : null;\n}\n\n/**\n * Parse text typed for a time back to seconds, or `null` when it is not a\n * time: empty text, a negative number, letters, a number followed by\n * anything else, a number too large to be finite, or a value that is not a\n * string. Spaces around the text are ignored. `seconds` reads a plain\n * number; the clock formats also read `1.5` (seconds) and `1:30` (minutes and\n * seconds) besides `01:02:03.500`. Segment ranges are checked: `00:75:00` is\n * not a time.\n */\nexport function parseDisplayTime(value: string, format: TimeDisplayFormat): number | null {\n // Plain-JS callers can pass anything.\n if (typeof value !== 'string') return null;\n const text = value.trim();\n if (format !== 'seconds') return parseClock(text);\n if (!DECIMAL.test(text)) return null;\n const seconds = Number(text);\n return Number.isFinite(seconds) ? seconds : null;\n}\n","/**\n * Cancellation (#848, the maintainer's design D1-D8): every abort is an\n * `AbortError` DOMException whose message names the cause, as `fetch()`\n * rejects (modern-web-guidance `js`: callers check `err.name`). A caller's\n * own signal rejects with that signal's `reason`.\n */\n\n/** An `AbortError` with a message that names why. */\nexport function abortError(message: string): DOMException {\n return new DOMException(message, 'AbortError');\n}\n\n/** True for an abort (`AbortError`), the kind a caller asked for or a swap caused. */\nexport function isAbortError(error: unknown): boolean {\n return (error as { name?: unknown } | null)?.name === 'AbortError';\n}\n\n/**\n * The reason of an aborted signal, as it is: a call rejects with it, as\n * `fetch()` does (`abort()` without one gives an `AbortError` DOMException).\n */\nexport function reasonOf(signal: AbortSignal): unknown {\n return signal.reason;\n}\n\n/**\n * One AbortController per arrangement while the editor plays it, aborted\n * when it is swapped out (D2). Keyed by the arrangement, so a swap ends only\n * the waits of the one leaving: a clip added to the editor's own arrangement\n * while a handed-in one plays is not rejected when the own one comes back.\n */\nexport class PlaySignals {\n private _controllers = new WeakMap<object, AbortController>();\n\n /** The signal of an arrangement: aborted when it is next swapped out. */\n signalOf(arrangement: object): AbortSignal {\n let controller = this._controllers.get(arrangement);\n if (!controller) {\n controller = new AbortController();\n this._controllers.set(arrangement, controller);\n }\n return controller.signal;\n }\n\n /** The arrangement leaves play: its waits end with `reason`; a later play gets a new signal. */\n swappedOut(arrangement: object, reason: DOMException): void {\n const controller = this._controllers.get(arrangement);\n this._controllers.delete(arrangement);\n controller?.abort(reason);\n }\n}\n\n/** `promise`, or a rejection with the signal's reason as soon as it aborts. */\nexport function untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(reasonOf(signal));\n return new Promise<T>((resolve, reject) => {\n const done = new AbortController();\n signal.addEventListener('abort', () => reject(reasonOf(signal)), { signal: done.signal });\n promise.then(\n (value) => {\n done.abort();\n resolve(value);\n },\n (error: unknown) => {\n done.abort();\n reject(error);\n }\n );\n });\n}\n","/**\n * File loading (#848): each dropped file enters the editor's arrangement as a\n * track with one loading clip whose source is the `File` itself (a File\n * cannot be an attribute, so a dropped track has no `<daw-track>` element).\n * The arrangement reads and decodes it. A file that cannot be loaded is\n * removed again without an undo step: it was never a declaration.\n */\n\nimport type { DawFilesLoadErrorDetail, LoadFilesResult } from '../events';\nimport { reasonOf, untilAborted } from './abort';\nimport type { EditorCallOptions } from '../types';\nimport type { Arrangement } from '@waveform-playlist/engine';\n\nexport interface FileLoaderHost {\n readonly isConnected: boolean;\n /** Add the file as a track; resolves with its id once it has entered. */\n _addDroppedFile(file: File): Promise<string>;\n /** Resolves when the track has loaded or the editor was disconnected; rejects when its audio failed. */\n _whenTrackLoaded(trackId: string): Promise<void>;\n /** Take a track out for good: no undo step, and no undo brings it back. */\n _discardTrack(trackId: string, from?: Arrangement): void;\n /** The arrangement played (the tracks enter it). */\n readonly arrangement: Arrangement;\n /** The signal of the arrangement played: aborted when it is swapped out. */\n _operationSignal(signal?: AbortSignal): AbortSignal;\n dispatchEvent(event: Event): boolean;\n}\n\n/**\n * `options.signal` (#848, D5): an abort rejects with its reason; the files\n * not started are skipped, and every track this call added is removed for\n * good (no undo step). A signal already aborted rejects at once.\n */\nexport async function loadFiles(\n host: FileLoaderHost,\n files: FileList | File[],\n options: EditorCallOptions = {}\n): Promise<LoadFilesResult> {\n const signal = options.signal;\n if (signal?.aborted) throw reasonOf(signal);\n if (!files) {\n console.warn('[dawcore] loadFiles called with null/undefined');\n return { loaded: [], failed: [] };\n }\n\n const fileArray = Array.from(files);\n // The arrangement the files enter, and its signal: a swap ends the call as\n // a disconnect does (the file loading is kept; the rest fail).\n const target = host.arrangement;\n const played = host._operationSignal();\n const loaded: string[] = [];\n const failed: Array<{ file: File; error: unknown }> = [];\n\n const dispatchLoadError = (file: File, error: unknown) => {\n failed.push({ file, error });\n if (host.isConnected) {\n host.dispatchEvent(\n new CustomEvent<DawFilesLoadErrorDetail>('daw-files-load-error', {\n bubbles: true,\n composed: true,\n detail: { file, error },\n })\n );\n }\n };\n\n for (const file of fileArray) {\n // A disconnect ends the call: the file loading then is kept (it loads\n // after a reparent); the ones not started are not added (#917).\n if (!host.isConnected) {\n dispatchLoadError(file, new Error('<daw-editor> was disconnected'));\n continue;\n }\n if (played.aborted) {\n dispatchLoadError(file, reasonOf(played));\n continue;\n }\n // file.type can be '' for valid audio (.opus on some browsers) — only\n // reject explicitly non-audio MIME types.\n if (file.type && !file.type.startsWith('audio/')) {\n const error = new Error('Non-audio MIME type: ' + file.type);\n console.warn('[dawcore] Skipping non-audio file: ' + file.name + ' (' + file.type + ')');\n dispatchLoadError(file, error);\n continue;\n }\n let trackId: string | null = null;\n try {\n // Sequential on purpose: preserves drop order as track order.\n const adding = host._addDroppedFile(file);\n trackId = await untilAborted(adding, signal).catch((err: unknown) => {\n // Aborted while it entered: it is taken out once it has.\n if (signal?.aborted)\n void adding.then(\n (id) => host._discardTrack(id, target),\n () => {}\n );\n throw err;\n });\n await untilAborted(host._whenTrackLoaded(trackId), signal);\n loaded.push(trackId);\n } catch (err) {\n if (signal?.aborted) {\n // The caller's abort: everything this call added goes, and it rejects.\n for (const id of [...loaded, ...(trackId !== null ? [trackId] : [])])\n host._discardTrack(id, target);\n throw reasonOf(signal);\n }\n console.warn('[dawcore] Failed to load file: ' + file.name + ' — ' + String(err));\n if (trackId !== null) host._discardTrack(trackId, target);\n dispatchLoadError(file, err);\n }\n }\n\n return { loaded, failed };\n}\n","/**\n * MIDI loading logic extracted from daw-editor. Operates on the editor via a\n * narrow host interface (`addTrack`, `_discardTrack`, `_operationSignal`) —\n * `<daw-editor>` satisfies it.\n *\n * Numbered steps below match the Data Flow diagram in\n * `docs/specs/2026-05-23-dawcore-load-midi-design.md`.\n */\n\nimport type { MidiLoadOptions, MidiLoadResult } from '@dawcore/midi';\nimport type { EditorCallOptions, TrackConfig } from '../types';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport { installCommand } from '../utils/install-command';\nimport { reasonOf } from './abort';\n\nexport type { MidiLoadOptions, MidiLoadResult };\n\n/**\n * Minimal host surface needed by `loadMidiImpl`. `<daw-editor>` satisfies this\n * structurally. A track `addTrack` added is taken out for good on a failure\n * or an abort; a track whose entry was refused never entered, so there is\n * nothing to remove (#848: `addTrack` makes no element).\n */\nexport interface MidiLoaderHost {\n /** Resolves with the track id once the track has entered (#848). */\n addTrack(config: TrackConfig, options?: EditorCallOptions): Promise<string>;\n /** Take a track out for good: no undo step, and no undo brings it back. */\n _discardTrack(trackId: string, from?: Arrangement): void;\n /** The arrangement played (the tracks enter it). */\n readonly arrangement: Arrangement;\n /** The caller's signal combined with the arrangement played (D6). */\n _operationSignal(signal?: AbortSignal): AbortSignal;\n}\n\n// Built when thrown, so a bundler can drop it with the code that throws it.\nconst installHint = (): string =>\n '@dawcore/midi is required for loadMidi(). Install with: ' + installCommand('@dawcore/midi');\n\n/**\n * Loads a `.mid` file (URL or `File`) and adds N tracks, one per note-bearing\n * MIDI track. On any per-track failure or an abort, every track added during\n * this call is removed for good (no undo step), so the editor is as before\n * the call.\n *\n * `options.signal` reaches the fetch and the parse and, combined with the\n * arrangement played (a swap aborts it too), the `addTrack` waits (#848, D6).\n */\nexport async function loadMidiImpl(\n host: MidiLoaderHost,\n source: string | File,\n options: MidiLoadOptions = {}\n): Promise<MidiLoadResult> {\n // Reject NaN / Infinity / negative startTime up front. Without this, every\n // clip silently inherits the bogus value and the timeline corrupts.\n const startTime = options.startTime ?? 0;\n if (!Number.isFinite(startTime) || startTime < 0) {\n throw new RangeError(\n 'loadMidi: startTime must be a non-negative finite number (got ' +\n String(options.startTime) +\n ')'\n );\n }\n\n // (1) Dynamic-import the optional peer dep. Log the original error so\n // debugging isn't blocked when the failure is something other than\n // \"not installed\" (broken exports map, 404 chunk, CSP, etc.). Targeting\n // ES2020 means we can't use Error.cause yet; console.warn carries the\n // diagnostic detail.\n const signal = host._operationSignal(options.signal);\n // The arrangement the tracks enter: a cleanup after a swap removes them there.\n const target = host.arrangement;\n if (signal.aborted) throw reasonOf(signal);\n let midiModule: typeof import('@dawcore/midi');\n try {\n midiModule = await import('@dawcore/midi');\n } catch (originalErr) {\n console.warn('[dawcore] @dawcore/midi dynamic import failed: ' + String(originalErr));\n throw new Error(installHint());\n }\n const { parseMidiUrl, parseMidiFile } = midiModule;\n\n // (2) Branch on source type. Wrap the File path so a failed disk read\n // surfaces with file context instead of a bare DOMException.\n let parsed;\n if (typeof source === 'string') {\n parsed = await parseMidiUrl(source, undefined, signal);\n } else {\n let buffer: ArrayBuffer;\n try {\n buffer = await source.arrayBuffer();\n } catch (err) {\n throw new Error(\n 'loadMidi: failed to read File \"' +\n source.name +\n '\" (' +\n source.size +\n ' bytes): ' +\n String(err)\n );\n }\n parsed = parseMidiFile(buffer);\n }\n if (signal.aborted) throw reasonOf(signal);\n\n // (4) Concurrent addTrack with allSettled so we can wait for every settlement\n // before deciding. Promise.all would early-reject while other addTrack calls\n // keep running, leaving orphan tracks after cleanup.\n const settlements = await Promise.allSettled(\n parsed.tracks.map((t) =>\n host.addTrack(\n {\n name: t.name,\n kind: 'midi',\n clips: [\n {\n midiNotes: t.notes,\n midiChannel: t.channel,\n midiProgram: t.programNumber,\n start: startTime,\n },\n ],\n },\n { signal }\n )\n )\n );\n\n // (5) Partition fulfilled vs rejected. Capture EVERY rejection (not just\n // the first) for diagnosability of multi-track failures.\n const succeeded: string[] = [];\n const rejections: unknown[] = [];\n for (const s of settlements) {\n if (s.status === 'fulfilled') {\n succeeded.push(s.value);\n } else {\n rejections.push(s.reason);\n }\n }\n\n // (6) On any rejection: remove every track added during this call, then\n // throw a summary Error and console.warn each additional rejection so\n // multi-track failure modes stay diagnosable.\n if (rejections.length > 0) {\n for (const trackId of succeeded) {\n try {\n host._discardTrack(trackId, target);\n } catch (cleanupErr) {\n console.warn('[dawcore] loadMidi cleanup failed for a track: ' + String(cleanupErr));\n }\n }\n // Aborted: the abort is the outcome, not the per-track rejections it caused.\n if (signal.aborted) throw reasonOf(signal);\n\n // Log every rejection beyond the first so multi-track failure modes are\n // diagnosable (the thrown Error only carries the first). AggregateError\n // would be ideal here but requires ES2021+; defer until the project\n // bumps its lib target.\n for (let i = 1; i < rejections.length; i++) {\n console.warn(\n '[dawcore] loadMidi: additional track failure (' +\n i +\n '): ' +\n stringifyReason(rejections[i])\n );\n }\n const first = rejections[0];\n if (rejections.length > 1) {\n const message =\n 'loadMidi: ' +\n rejections.length +\n ' of ' +\n settlements.length +\n ' tracks failed; first: ' +\n (first instanceof Error ? first.message : stringifyReason(first));\n throw new Error(message);\n }\n throw first instanceof Error ? first : new Error(stringifyReason(first));\n }\n\n // (7) Build the result.\n return {\n trackIds: succeeded,\n bpm: parsed.bpm,\n timeSignature: parsed.timeSignature,\n duration: parsed.duration,\n name: parsed.name,\n };\n}\n\n/**\n * Render a non-Error rejection reason as a useful string. Plain `String(x)`\n * gives `\"[object Object]\"` for object rejections, losing all structured info.\n */\nfunction stringifyReason(reason: unknown): string {\n if (reason === null) return 'null';\n if (reason === undefined) return 'undefined';\n if (typeof reason === 'object') {\n try {\n return JSON.stringify(reason);\n } catch {\n return Object.prototype.toString.call(reason);\n }\n }\n return String(reason);\n}\n","/**\n * Recording clip creation extracted from daw-editor to keep the editor under 800 lines.\n * Operates on the editor instance via a narrow interface.\n */\n\nimport type { AudioClip, LoadingClip, PeakData } from '@waveform-playlist/core';\nimport { carveClipRange, createClip, isLoadingClip } from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport type { PeakPipeline } from '../workers/peakPipeline';\nimport type { DawErrorDetail, DawRecordingClipAddDetail } from '../events';\n\nexport interface RecordingClipHost {\n readonly samplesPerPixel: number;\n /** Render-space samples-per-pixel — tick-derived in beats mode. Finalized\n * peaks MUST be generated at this scale (containers are laid out in render\n * space); the temporal samplesPerPixel draws the wrong width. */\n readonly renderSamplesPerPixel: number;\n readonly mono: boolean;\n readonly isConnected: boolean;\n readonly effectiveSampleRate: number;\n /** The take goes into the editor's arrangement (#848); the engine follows it. */\n _arrangement: Arrangement;\n _peaksData: Map<string, PeakData>;\n _clipBuffers: Map<string, AudioBuffer>;\n _clipOffsets: Map<string, { offsetSamples: number; durationSamples: number }>;\n /** Raise the editor zoom floor (recording worker-caches peaks at the\n * pipeline base scale like any other load — the floor must cover them). */\n _raiseZoomFloor(scale: number): void;\n _peakPipeline: PeakPipeline;\n dispatchEvent(event: Event): boolean;\n}\n\nexport function addRecordedClip(\n host: RecordingClipHost,\n trackId: string,\n buf: AudioBuffer,\n startSample: number,\n durSamples: number,\n offsetSamples = 0,\n clipName?: string\n) {\n // Slice off latency samples so peaks and playback only cover the audible portion\n let trimmedBuf = buf;\n if (offsetSamples > 0 && offsetSamples < buf.length) {\n const trimmed = new AudioBuffer({\n numberOfChannels: buf.numberOfChannels,\n length: durSamples,\n sampleRate: buf.sampleRate,\n });\n for (let ch = 0; ch < buf.numberOfChannels; ch++) {\n const source = buf.getChannelData(ch);\n trimmed.copyToChannel(source.subarray(offsetSamples, offsetSamples + durSamples), ch);\n }\n trimmedBuf = trimmed;\n }\n\n const clip = createClip({\n audioBuffer: trimmedBuf,\n startSample,\n durationSamples: durSamples,\n offsetSamples: 0, // offset already applied by slicing\n gain: 1,\n name: clipName ?? 'Recording',\n });\n host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);\n // Record the offsets like every other clip-insertion path — without this\n // entry the statechange peak-sync treats the clip as uncached and re-runs\n // the worker after EVERY recording.\n host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });\n host._peakPipeline\n .generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono)\n .then((pd) => {\n if (!host._arrangement.getTracks().some((t) => t.id === trackId)) {\n // Track was removed during peak generation — clean up the orphaned\n // buffer and never insert the peaks entry (this clip never reaches\n // the engine, so nothing else would ever delete it).\n const next = new Map(host._clipBuffers);\n next.delete(clip.id);\n host._clipBuffers = next;\n host._clipOffsets.delete(clip.id);\n return;\n }\n host._peaksData = new Map(host._peaksData).set(clip.id, pd);\n // The same floor policy as every loaded clip (_clipPeaksReady): the worker cached this\n // buffer's WaveformData at the base scale — zooming finer than it\n // would render the recorded waveform squeezed in its container.\n host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));\n // One undo step, in the function form so the track's loading clips\n // stay. Punch-in replace (#579): the recorded clip owns [startSample,\n // startSample + durSamples) — carve overlapped LOADED content out\n // before inserting (parity with the React provider); a clip still\n // loading has no samples to carve and is kept as it is.\n host._arrangement.updateTrack(trackId, (current) => ({\n ...current,\n clips: [\n ...current.clips.flatMap((c): (AudioClip | LoadingClip)[] =>\n isLoadingClip(c) ? [c] : carveClipRange([c], startSample, startSample + durSamples)\n ),\n clip,\n ],\n }));\n // daw-recording-complete fires BEFORE the clip exists (it is\n // cancelable), so it cannot carry the id. This follow-up fires once\n // the clip is in the engine and addressable (#659).\n if (host.isConnected) {\n host.dispatchEvent(\n new CustomEvent<DawRecordingClipAddDetail>('daw-recording-clip-add', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clip.id },\n })\n );\n }\n })\n .catch((err) => {\n console.warn('[dawcore] Failed to generate peaks for recorded clip: ' + String(err));\n const next = new Map(host._clipBuffers);\n next.delete(clip.id);\n host._clipBuffers = next;\n host._clipOffsets.delete(clip.id);\n if (host.isConnected) {\n host.dispatchEvent(\n new CustomEvent<DawErrorDetail>('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'recording-peaks', error: err },\n })\n );\n }\n });\n}\n","import type { AudioClip, ClipTrack } from '@waveform-playlist/core';\nimport type { DawClipSplitDetail } from '../events';\n\n// ---------------------------------------------------------------------------\n// Contracts\n// ---------------------------------------------------------------------------\n\n/** Narrow engine contract for split operations. */\nexport interface SplitEngineContract {\n getState(): { selectedTrackId: string | null; tracks: readonly ClipTrack[] };\n splitClip(trackId: string, clipId: string, atSample: number): void;\n}\n\n/** Host interface for splitAtPlayhead. */\nexport interface SplitHost {\n readonly effectiveSampleRate: number;\n readonly currentTime: number;\n readonly isPlaying: boolean;\n readonly engine: SplitEngineContract | null;\n dispatchEvent(event: Event): boolean;\n stop(): void;\n play(time: number): void;\n}\n\n// ---------------------------------------------------------------------------\n// splitAtPlayhead\n// ---------------------------------------------------------------------------\n\n/**\n * Split the clip under the playhead on the selected track.\n * Stops playback before split and resumes after to avoid duplicate audio\n * from Transport rescheduling during playback.\n *\n * Returns true if the split occurred and dispatched a daw-clip-split event.\n * Returns false for any guard failure or engine no-op.\n */\nexport function splitAtPlayhead(host: SplitHost): boolean {\n const wasPlaying = host.isPlaying;\n const time = host.currentTime;\n\n // Check guards before stopping playback — don't interrupt audio for a no-op\n if (!canSplitAtTime(host, time)) return false;\n\n if (wasPlaying) {\n host.stop();\n }\n\n let result: boolean;\n try {\n result = performSplit(host, time);\n } catch (err) {\n console.warn('[dawcore] splitAtPlayhead failed: ' + String(err));\n result = false;\n }\n\n // Always resume if was playing — even on failed split, don't leave audio stopped\n if (wasPlaying) {\n host.play(time);\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\n/** Pre-flight check — can a split happen at this time without touching playback? */\nfunction canSplitAtTime(host: SplitHost, time: number): boolean {\n const { engine } = host;\n if (!engine) return false;\n\n const state = engine.getState();\n if (!state.selectedTrackId) return false;\n\n const track = state.tracks.find((t) => t.id === state.selectedTrackId);\n if (!track) return false;\n\n const atSample = Math.round(time * host.effectiveSampleRate);\n const clip = findClipAtSample(track.clips, atSample);\n // A MIDI clip splits like an audio clip: both halves keep its notes, each a\n // window on them (#838).\n return clip !== undefined;\n}\n\n/** Core split logic — finds clip at position, calls engine, diffs state for the right half's new id. */\nfunction performSplit(host: SplitHost, time: number): boolean {\n const { engine } = host;\n if (!engine) return false;\n\n const stateBefore = engine.getState();\n const { selectedTrackId, tracks } = stateBefore;\n\n if (!selectedTrackId) return false;\n\n const track = tracks.find((t) => t.id === selectedTrackId);\n if (!track) return false;\n\n const atSample = Math.round(time * host.effectiveSampleRate);\n\n const clip = findClipAtSample(track.clips, atSample);\n if (!clip) return false;\n\n const originalClipId = clip.id;\n const clipIdsBefore = new Set(track.clips.map((c) => c.id));\n\n engine.splitClip(selectedTrackId, originalClipId, atSample);\n\n const stateAfter = engine.getState();\n const trackAfter = stateAfter.tracks.find((t) => t.id === selectedTrackId);\n if (!trackAfter) {\n console.warn(\n '[dawcore] splitAtPlayhead: track \"' + selectedTrackId + '\" disappeared after split'\n );\n return false;\n }\n\n // The left half keeps the original's id (#848); the right half is the one new id.\n const leftClip = trackAfter.clips.find((c) => c.id === originalClipId);\n const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));\n if (!leftClip || newClips.length !== 1) {\n if (newClips.length > 0) {\n console.warn(\n '[dawcore] splitAtPlayhead: expected the original clip and 1 new clip after split but got ' +\n newClips.length +\n ' new'\n );\n }\n return false;\n }\n const leftClipId = leftClip.id;\n const rightClipId = newClips[0].id;\n\n host.dispatchEvent(\n new CustomEvent<DawClipSplitDetail>('daw-clip-split', {\n bubbles: true,\n composed: true,\n detail: {\n trackId: selectedTrackId,\n originalClipId,\n leftClipId,\n rightClipId,\n },\n })\n );\n\n return true;\n}\n\n/**\n * Finds a clip that strictly contains the given sample position.\n * The position must be > clip.startSample and < clip.startSample + clip.durationSamples.\n */\nfunction findClipAtSample(clips: AudioClip[], atSample: number): AudioClip | undefined {\n return clips.find(\n (c) => atSample > c.startSample && atSample < c.startSample + c.durationSamples\n );\n}\n","import type { AudioClip, ClipTrack, PeakData } from '@waveform-playlist/core';\nimport type { PeakPipeline } from '../workers/peakPipeline';\n\n/** Host interface for clip peak synchronization. */\nexport interface ClipPeakSyncHost {\n /** The effective samplesPerPixel for rendering (tick-derived in beats mode). */\n readonly renderSamplesPerPixel: number;\n readonly mono: boolean;\n _clipBuffers: Map<string, AudioBuffer>;\n _clipOffsets: Map<string, { offsetSamples: number; durationSamples: number }>;\n _peaksData: Map<string, PeakData>;\n _peakPipeline: PeakPipeline;\n /** Told when a clip's peaks are made (the zoom floor, a preview to drop). */\n _clipPeaksReady?(clipId: string, audioBuffer: AudioBuffer): void;\n}\n\n/**\n * Regenerate peaks for clips that are new or whose offset/duration changed.\n * Handles split (the left half keeps its id with a shorter duration, the\n * right half is a new id; #848) and trim (same ID, changed bounds).\n *\n * Called from the statechange handler when tracksVersion changes.\n */\nexport function syncPeaksForChangedClips(\n host: ClipPeakSyncHost,\n tracks: readonly ClipTrack[]\n): void {\n // Collect all current clip IDs for orphan detection\n const currentClipIds = new Set<string>();\n\n for (const track of tracks) {\n for (const clip of track.clips) {\n currentClipIds.add(clip.id);\n\n // Check if peaks need regeneration: new clip or changed offset/duration\n const cached = host._clipOffsets.get(clip.id);\n const needsPeaks =\n !host._peaksData.has(clip.id) ||\n !cached ||\n cached.offsetSamples !== clip.offsetSamples ||\n cached.durationSamples !== clip.durationSamples;\n\n if (!needsPeaks) continue;\n\n const audioBuffer =\n clip.audioBuffer ??\n host._clipBuffers.get(clip.id) ??\n findAudioBufferForClip(host, clip, track);\n if (!audioBuffer) {\n console.warn(\n '[dawcore] syncPeaksForChangedClips: no AudioBuffer for clip ' +\n clip.id +\n ' — waveform will be blank'\n );\n continue;\n }\n\n // Update cached state\n host._clipBuffers = new Map(host._clipBuffers).set(clip.id, audioBuffer);\n host._clipOffsets = new Map(host._clipOffsets).set(clip.id, {\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n });\n\n // Generate peaks asynchronously\n host._peakPipeline\n .generatePeaks(\n audioBuffer,\n host.renderSamplesPerPixel,\n host.mono,\n clip.offsetSamples,\n clip.durationSamples\n )\n .then((peakData) => {\n host._peaksData = new Map(host._peaksData).set(clip.id, peakData);\n host._clipPeaksReady?.(clip.id, audioBuffer);\n })\n .catch((err) => {\n console.warn(\n '[dawcore] Failed to generate peaks for clip ' + clip.id + ': ' + String(err)\n );\n });\n }\n }\n\n // Clean up orphaned entries for clip IDs no longer in any track\n // (e.g., a clip removed, or a whole track undone away)\n cleanupOrphanedClipData(host, currentClipIds);\n}\n\n/**\n * Remove entries from per-clip Maps for clip IDs that no longer exist in any track.\n * Prevents memory leaks from orphaned AudioBuffer references after split operations.\n */\nfunction cleanupOrphanedClipData(host: ClipPeakSyncHost, currentClipIds: Set<string>): void {\n let buffersChanged = false;\n let peaksChanged = false;\n\n for (const id of host._clipBuffers.keys()) {\n if (!currentClipIds.has(id)) {\n host._clipBuffers.delete(id);\n buffersChanged = true;\n }\n }\n let offsetsChanged = false;\n for (const id of host._clipOffsets.keys()) {\n if (!currentClipIds.has(id)) {\n host._clipOffsets.delete(id);\n offsetsChanged = true;\n }\n }\n for (const id of host._peaksData.keys()) {\n if (!currentClipIds.has(id)) {\n host._peaksData.delete(id);\n peaksChanged = true;\n }\n }\n\n // Reassign Maps that changed — _peaksData is @state() (triggers Lit re-render),\n // _clipBuffers uses reference identity for change detection in syncPeaksForChangedClips\n if (buffersChanged) {\n host._clipBuffers = new Map(host._clipBuffers);\n }\n if (offsetsChanged) {\n host._clipOffsets = new Map(host._clipOffsets);\n }\n if (peaksChanged) {\n host._peaksData = new Map(host._peaksData);\n }\n}\n\n/** Find an AudioBuffer for a clip by checking siblings on the same track. */\nfunction findAudioBufferForClip(\n host: ClipPeakSyncHost,\n clip: AudioClip,\n track: ClipTrack\n): AudioBuffer | null {\n for (const sibling of track.clips) {\n if (sibling.id === clip.id) continue;\n const buf = host._clipBuffers.get(sibling.id);\n if (buf) return buf;\n }\n return null;\n}\n","/**\n * How a track the page (or an editor method) declared becomes a track of the\n * editor's arrangement (#848): each audio clip a `LoadingClip` that the\n * arrangement loads, each MIDI clip a loaded clip built at the editor's\n * sample rate, a clip of the wrong kind refused. Pure functions; the editor\n * calls the arrangement.\n */\nimport { createClip, createTrack, isDecidedPanLaw } from '@waveform-playlist/core';\nimport type {\n ArrangementTrack,\n AudioClip,\n ClipSource,\n LoadingClip,\n MidiNoteData,\n TrackKind,\n} from '@waveform-playlist/core';\nimport type { TrackMixerValues } from '@waveform-playlist/engine';\nimport type { ClipDescriptor, StoredTrackDescriptor } from '../types';\nimport { isDomClip } from '../types';\n\n/**\n * Keep only notes with finite, in-range fields; warn for each one dropped.\n * Prevents NaN reaching the timeline.\n */\nexport function validMidiNotes(notes: MidiNoteData[]): MidiNoteData[] {\n return notes.filter((n) => {\n const ok =\n Number.isFinite(n.time) &&\n n.time >= 0 &&\n Number.isFinite(n.duration) &&\n n.duration > 0 &&\n Number.isInteger(n.midi) &&\n n.midi >= 0 &&\n n.midi <= 127 &&\n Number.isFinite(n.velocity) &&\n n.velocity >= 0 &&\n n.velocity <= 1;\n if (!ok) {\n console.warn('[dawcore] dropping malformed MIDI note: ' + JSON.stringify(n));\n }\n return ok;\n });\n}\n\n/** What a clip descriptor loads: its `File` (a dropped file) or its `src` URL; '' for none. */\nexport function clipSourceOf(clipDesc: ClipDescriptor): ClipSource | '' {\n return (!isDomClip(clipDesc) && clipDesc.file) || clipDesc.src;\n}\n\n/**\n * A clip descriptor is MIDI when it has nothing to load. Includes placeholder\n * MIDI clips (no notes, no duration yet: a 1 s span; notes arrive through a\n * clip update). Warns when a clip has both a source and notes: it is audio,\n * and the notes are ignored.\n */\nexport function isMidiDescriptor(clipDesc: ClipDescriptor): boolean {\n if (clipSourceOf(clipDesc)) {\n if (clipDesc.midiNotes != null) {\n console.warn(\n '[dawcore] clip \"' +\n (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : '?')) +\n '\" has both src and midiNotes — treating as audio (notes will be ignored)'\n );\n }\n return false;\n }\n return true;\n}\n\n/**\n * The error for a clip whose kind is not its track's (#756), or null. A clip\n * with nothing to load is a MIDI clip (see isMidiDescriptor).\n */\nexport function clipKindError(\n trackName: string,\n kind: TrackKind,\n clipIsMidi: boolean,\n clipLabel: string\n): Error | null {\n if (clipIsMidi === (kind === 'midi')) return null;\n return new Error(\n clipIsMidi\n ? 'clip \"' +\n clipLabel +\n '\" is a MIDI clip (no src) on audio track \"' +\n trackName +\n '\". A track holds one kind of clip: set kind=\"midi\" on the <daw-track>' +\n \" (or kind: 'midi' in addTrack) for a track of MIDI clips.\"\n : 'clip \"' +\n clipLabel +\n '\" is an audio clip on MIDI track \"' +\n trackName +\n '\". A track holds one kind of clip: put the clip on an audio track.'\n );\n}\n\n/**\n * A MIDI clip from its descriptor, at `sampleRate`. Always a clip: no notes\n * or no declared duration give a 1 s placeholder span, so later notes find it.\n */\nexport function buildMidiClip(clipDesc: ClipDescriptor, sampleRate: number): AudioClip {\n const notes = validMidiNotes(clipDesc.midiNotes ?? []);\n const noteSpanSeconds = notes.length\n ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0)\n : 0;\n const sourceDurationSamples = Math.ceil(\n Math.max(noteSpanSeconds, clipDesc.duration, 1) * sampleRate\n );\n const requestedDurationSamples =\n clipDesc.duration > 0 ? Math.round(clipDesc.duration * sampleRate) : sourceDurationSamples;\n const clip = createClip({\n startSample: Math.round(clipDesc.start * sampleRate),\n durationSamples: requestedDurationSamples,\n offsetSamples: Math.round(clipDesc.offset * sampleRate),\n sampleRate,\n sourceDurationSamples,\n gain: clipDesc.gain,\n name: clipDesc.name,\n midiNotes: notes,\n midiChannel: clipDesc.midiChannel ?? undefined,\n midiProgram: clipDesc.midiProgram ?? undefined,\n });\n if (clipDesc.clipId) clip.id = clipDesc.clipId;\n return clip;\n}\n\n/**\n * The loading clip of an audio clip descriptor (its `clipId` must be set):\n * the source, the times in seconds and the gain. A duration of 0 means the\n * whole source from the offset. Fades are not carried: the load path never\n * applied `<daw-clip>` fades (engine-side fades are #489).\n */\nexport function buildLoadingClip(clipDesc: ClipDescriptor & { clipId: string }): LoadingClip {\n return {\n id: clipDesc.clipId,\n src: clipSourceOf(clipDesc) as ClipSource,\n start: clipDesc.start,\n offset: clipDesc.offset,\n gain: clipDesc.gain,\n ...(clipDesc.duration > 0 && { duration: clipDesc.duration }),\n ...(clipDesc.name && { name: clipDesc.name }),\n };\n}\n\n/** A clip descriptor with an id: a drop descriptor without one gets a new id. */\nexport function withClipId(clipDesc: ClipDescriptor): ClipDescriptor & { clipId: string } {\n if (clipDesc.clipId) return clipDesc as ClipDescriptor & { clipId: string };\n return { ...clipDesc, clipId: crypto.randomUUID() };\n}\n\n/** A clip of the descriptor that was refused for its kind. */\nexport interface RefusedClip {\n clipId: string;\n error: Error;\n}\n\nexport interface BuiltTrack {\n track: ArrangementTrack;\n /** The descriptor with an id on every clip (the same object when none was missing). */\n descriptor: StoredTrackDescriptor;\n refused: RefusedClip[];\n}\n\n/**\n * The arrangement track for a declared track: `trackId`, its name, kind and\n * the mix it enters with; a loading clip per audio clip and a loaded clip per\n * MIDI clip. A clip of the wrong kind is left out and listed in `refused`\n * (the arrangement throws for a track that holds both kinds).\n */\nexport function buildArrangementTrack(\n trackId: string,\n descriptor: StoredTrackDescriptor,\n mix: TrackMixerValues,\n sampleRate: number\n): BuiltTrack {\n const clips: (AudioClip | LoadingClip)[] = [];\n const refused: RefusedClip[] = [];\n let changed = false;\n const descClips = descriptor.clips.map((clipDesc) => {\n const identified = withClipId(clipDesc);\n if (identified !== clipDesc) changed = true;\n const isMidi = isMidiDescriptor(identified);\n const source = clipSourceOf(identified);\n const sourceName =\n typeof source === 'string' ? source : source instanceof File ? source.name : '';\n const label = identified.name || sourceName || identified.clipId;\n const kindError = clipKindError(descriptor.name, descriptor.kind, isMidi, label);\n if (kindError) refused.push({ clipId: identified.clipId, error: kindError });\n else clips.push(isMidi ? buildMidiClip(identified, sampleRate) : buildLoadingClip(identified));\n return identified;\n });\n const { panLaw, ...fields } = mix;\n const base = {\n ...createTrack({ name: descriptor.name, kind: descriptor.kind, clips: [], ...fields }),\n // The law the track enters with (#684); 'auto' is the arrangement's default.\n ...(isDecidedPanLaw(panLaw) && { panLaw }),\n };\n const track: ArrangementTrack = { ...base, id: trackId, clips };\n return { track, descriptor: changed ? { ...descriptor, clips: descClips } : descriptor, refused };\n}\n\n/**\n * Where a `<daw-track>` enters among the arrangement's tracks: after the\n * arrangement track of the nearest `<daw-track>` before it (in document\n * order) that has entered; first when there is none.\n */\nexport function entryIndex(\n trackEls: readonly { trackId: string }[],\n trackId: string,\n arrangementIds: readonly string[]\n): number {\n const at = trackEls.findIndex((el) => el.trackId === trackId);\n for (let i = at - 1; i >= 0; i--) {\n const position = arrangementIds.indexOf(trackEls[i].trackId);\n if (position !== -1) return position + 1;\n }\n return 0;\n}\n","/**\n * The editor's load events, read from its arrangement (#848): the tracks\n * (which clips are still loading) and `sources` (which sources failed). Each\n * event is sent once per transition. The announcer remembers what it last\n * announced, so that a statechange and a sources change telling of the same\n * transition do not both dispatch, and so that a track that comes back by an\n * undo or a redo is not announced again.\n *\n * - `daw-clip-error` when a clip's source goes into failed (again after a\n * retry that fails, since the error is a new object).\n * - `daw-clip-ready` when a clip that was loading has loaded.\n * - `daw-track-ready` when no clip of the track is pending and one loaded,\n * or the track asked for no audio; again each time it has loaded again\n * after it was pending or failed (a clip added later, a retry).\n * - `daw-track-error` when every clip of the track failed, also when they\n * were refused for their kind (the track stays, like a broken `<img>`).\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, ClipSource } from '@waveform-playlist/core';\nimport type { ArrangementSourceState } from '@waveform-playlist/engine';\nimport type {\n DawClipErrorDetail,\n DawClipIdDetail,\n DawTrackErrorDetail,\n DawTrackIdDetail,\n} from '../events';\n\ntype TrackLoadState = 'pending' | 'ready' | 'failed';\n\ninterface TrackRecord {\n state: TrackLoadState | null;\n /** Clips refused for their kind when the track entered (never in the arrangement). */\n refused: number;\n /** What `daw-track-error` carried, while the track is failed. */\n error?: Error;\n}\n\nexport class LoadAnnouncer {\n private _tracks = new Map<string, TrackRecord>();\n /** The failure each clip was last announced with. */\n private _clipErrors = new Map<string, Error>();\n /** Clips seen while loading, and not yet announced as loaded. */\n private _loadingClips = new Set<string>();\n\n constructor(private readonly _dispatch: (event: Event) => void) {}\n\n /** A track is about to enter, with `refused` clips left out for their kind. */\n expect(trackId: string, refused: number): void {\n this._tracks.set(trackId, { state: null, refused });\n }\n\n /**\n * A clip is about to enter while loading: it is announced ready when it\n * loads, also when its source was loaded already and it is never seen\n * loading.\n */\n expectClip(clipId: string): void {\n this._loadingClips.add(clipId);\n }\n\n /** A loading clip was removed: its load will not be announced. */\n forgetClip(clipId: string): void {\n this._loadingClips.delete(clipId);\n this._clipErrors.delete(clipId);\n }\n\n /** The error a failed track was announced with. */\n errorOf(trackId: string): Error {\n return this._tracks.get(trackId)?.error ?? new Error('track \"' + trackId + '\" failed to load');\n }\n\n /** A track was removed by the page or an editor method: nothing more is said of it. */\n forget(trackId: string, clipIds: Iterable<string>): void {\n this._tracks.delete(trackId);\n for (const id of clipIds) {\n this._clipErrors.delete(id);\n this._loadingClips.delete(id);\n }\n }\n\n /** The state a track was last announced in (`null` before its first announcement). */\n stateOf(trackId: string): TrackLoadState | null {\n return this._tracks.get(trackId)?.state ?? null;\n }\n\n update(\n tracks: readonly ArrangementTrack[],\n sources: ReadonlyMap<ClipSource, ArrangementSourceState>\n ): void {\n for (const track of tracks) this._updateTrack(track, sources);\n }\n\n private _updateTrack(\n track: ArrangementTrack,\n sources: ReadonlyMap<ClipSource, ArrangementSourceState>\n ): void {\n const record = this._tracks.get(track.id) ?? { state: null, refused: 0 };\n this._tracks.set(track.id, record);\n let pending = 0;\n let failed = 0;\n let loaded = 0;\n let firstError: Error | null = null;\n for (const clip of track.clips) {\n if (!isLoadingClip(clip)) {\n loaded++;\n if (this._loadingClips.delete(clip.id)) {\n this._clipErrors.delete(clip.id);\n this._send<DawClipIdDetail>('daw-clip-ready', { trackId: track.id, clipId: clip.id });\n }\n continue;\n }\n this._loadingClips.add(clip.id);\n const source = sources.get(clip.src);\n if (source?.status !== 'failed') {\n pending++;\n this._clipErrors.delete(clip.id);\n continue;\n }\n failed++;\n const error = source.error ?? new Error('the audio of clip \"' + clip.id + '\" failed to load');\n firstError ??= error;\n if (this._clipErrors.get(clip.id) !== error) {\n this._clipErrors.set(clip.id, error);\n this._send<DawClipErrorDetail>('daw-clip-error', {\n trackId: track.id,\n clipId: clip.id,\n error,\n });\n }\n }\n const next: TrackLoadState =\n pending > 0 ? 'pending' : loaded > 0 || failed + record.refused === 0 ? 'ready' : 'failed';\n if (next === record.state) return;\n record.state = next;\n record.error = undefined;\n if (next === 'ready') {\n this._send<DawTrackIdDetail>('daw-track-ready', { trackId: track.id });\n } else if (next === 'failed') {\n const requested = failed + record.refused;\n const error =\n requested === 1 && firstError\n ? firstError\n : new Error(\n 'all ' + requested + ' clip(s) failed to load — see prior daw-clip-error events'\n );\n record.error = error;\n this._send<DawTrackErrorDetail>('daw-track-error', { trackId: track.id, error });\n }\n }\n\n private _send<T>(type: string, detail: T): void {\n this._dispatch(new CustomEvent<T>(type, { bubbles: true, composed: true, detail }));\n }\n}\n","/**\n * What `<daw-editor>` draws and reports, read from its arrangement (#848):\n * the editor keeps no projection of the tracks. Pure functions; the one\n * cache (`loadedTrack`'s) is keyed by the arrangement's track objects and\n * never written back.\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { ArrangementTrack, AudioClip, ClipTrack, LoadingClip } from '@waveform-playlist/core';\nimport type { Arrangement, TrackMixerValues } from '@waveform-playlist/engine';\n\ninterface Cached {\n mix: TrackMixerValues;\n recording: boolean;\n view: ClipTrack;\n}\n\nconst views = new WeakMap<ArrangementTrack, Cached>();\n\nfunction sameMix(a: TrackMixerValues, b: TrackMixerValues): boolean {\n return (\n a.volume === b.volume &&\n a.pan === b.pan &&\n a.muted === b.muted &&\n a.soloed === b.soloed &&\n a.panLaw === b.panLaw\n );\n}\n\n/**\n * A track as it is played: its loaded clips with the current mix (muted\n * while a take records onto it). The same object for the same track object\n * and the same mix, so a row whose track did not change is not drawn again.\n */\nexport function loadedTrack(\n track: ArrangementTrack,\n mix: TrackMixerValues,\n recording: boolean\n): ClipTrack {\n const cached = views.get(track);\n if (cached && cached.recording === recording && sameMix(cached.mix, mix)) return cached.view;\n const view: ClipTrack = {\n ...track,\n clips: track.clips.filter((c): c is AudioClip => !isLoadingClip(c)),\n volume: mix.volume,\n pan: mix.pan,\n muted: mix.muted || recording,\n soloed: mix.soloed,\n // What both exports pan the track with (core's trackPanLaw, #684).\n panLaw: mix.panLaw,\n };\n views.set(track, { mix: { ...mix }, recording, view });\n return view;\n}\n\n/**\n * A track's mix from its one owner, the arrangement: the stored values,\n * muted while a take records onto it (as the engine plays it). Null for an\n * id the arrangement does not hold.\n */\nexport function mixOf(arrangement: Arrangement, trackId: string): TrackMixerValues | null {\n const mix = arrangement.getMixer().get(trackId);\n if (!mix) return null;\n return arrangement.recordingTrackIds.has(trackId) ? { ...mix, muted: true } : mix;\n}\n\n/** A clip's place in seconds, for a loaded clip and for one still loading (0 where unknown). */\nexport function clipSeconds(\n clip: AudioClip | LoadingClip,\n fallbackSampleRate: number\n): { start: number; duration: number; offset: number } {\n if (isLoadingClip(clip)) {\n return { start: clip.start ?? 0, duration: clip.duration ?? 0, offset: clip.offset ?? 0 };\n }\n const sr = clip.sampleRate ?? fallbackSampleRate;\n return {\n start: clip.startSample / sr,\n duration: clip.durationSamples / sr,\n offset: clip.offsetSamples / sr,\n };\n}\n","/**\n * Setting `editor.arrangement` (#848 PR 3, P5): the editor plays the\n * arrangement it is given alone, like `video.srcObject`, and goes back to its\n * own on `null`. One assignment for the app; this module is the sequence.\n */\nimport { isArrangement, type Arrangement } from '@waveform-playlist/engine';\n\n/** What the swap needs from `<daw-editor>`. */\nexport interface ArrangementSwapHost {\n readonly _ownArrangement: Arrangement;\n readonly _handedIn: Arrangement | null;\n readonly isRecording: boolean;\n readonly isPlaying: boolean;\n /** The arrangement played now (handed-in ?? own). */\n readonly _arrangement: Arrangement;\n _cancelDrags(): boolean;\n stop(): void;\n /** Let the engine go without disposing the adapter (`dispose({ keepAdapter: true })`). */\n _releaseEngine(): void;\n /** Dispose the effects chain of a track id. */\n _disposeTrackChain(trackId: string): void;\n /** Point the editor at `next` (null: its own) and follow it (subscriptions, a fresh announcer). */\n _playArrangement(next: Arrangement | null): void;\n /** Build an engine on the arrangement played now, when connected with an adapter. */\n _buildEngineIfReady(): void;\n}\n\n/**\n * The value to play: `null` for the editor's own arrangement (given `null`,\n * `undefined` or the own arrangement itself). Throws a `TypeError` for a\n * value that is not an arrangement.\n */\nexport function normalizeHandedIn(value: unknown, own: Arrangement): Arrangement | null {\n if (value === null || value === undefined || value === own) return null;\n if (!isArrangement(value)) {\n throw new TypeError(\n '[dawcore] editor.arrangement must be an arrangement made by createArrangement() ' +\n \"(@waveform-playlist/engine), or null for the editor's own.\"\n );\n }\n return value as Arrangement;\n}\n\n/**\n * Play `next` (null: the editor's own arrangement). Refused during a take: the\n * take's track would be in neither. Drags are cancelled, playback stops, the\n * engine is let go without its adapter and a new one is built on `next` with\n * the same adapter; effects chains of tracks `next` does not hold are\n * disposed. The editor never disposes or clears an arrangement it was handed.\n */\nexport function swapArrangement(host: ArrangementSwapHost, next: Arrangement | null): void {\n if (next === host._handedIn) return;\n if (host.isRecording) {\n console.warn(\n '[dawcore] editor.arrangement was not changed: a take is recording. ' +\n 'Set it after stopRecording() resolves.'\n );\n return;\n }\n host._cancelDrags();\n if (host.isPlaying) host.stop();\n const before = host._arrangement.getTracks().map((t) => t.id);\n host._releaseEngine();\n host._playArrangement(next);\n const kept = new Set(host._arrangement.getTracks().map((t) => t.id));\n for (const id of before) if (!kept.has(id)) host._disposeTrackChain(id);\n host._buildEngineIfReady();\n}\n","/**\n * Whether a change to the arrangement made during a drag changed what is\n * dragged (#848 PR 3, P2). A drag writes nothing until its release (P1), so\n * any change while it is in progress came from elsewhere (an app's or an\n * agent's undo, reorder or removal). The drag is cancelled, like a\n * `pointercancel`, only when the change touched it: the dragged clip is gone\n * or no longer where the drag started from, or the dragged track is gone or\n * the order of the tracks changed. A mix change, another clip loading or an\n * edit elsewhere let the drag go on; its release applies to the arrangement\n * as it is then.\n */\nimport { isLoadingClip } from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\n\n/** A clip drag past its threshold, with the clip's bounds when it started. */\nexport interface DraggedClip {\n trackId: string;\n clipId: string;\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n}\n\n/** A track drag, with the order of the tracks at the grab. */\nexport interface DraggedTrack {\n trackId: string;\n order: readonly string[];\n}\n\n/** True when the arrangement no longer holds the dragged clip where the drag started from. */\nexport function clipDragChanged(arrangement: Arrangement, drag: DraggedClip): boolean {\n const clip = arrangement\n .getTracks()\n .find((t) => t.id === drag.trackId)\n ?.clips.find((c) => c.id === drag.clipId);\n if (!clip || isLoadingClip(clip)) return true;\n return (\n clip.startSample !== drag.startSample ||\n clip.durationSamples !== drag.durationSamples ||\n clip.offsetSamples !== drag.offsetSamples\n );\n}\n\n/** True when the dragged track is gone or the order of the tracks is not the one at the grab. */\nexport function trackDragChanged(arrangement: Arrangement, drag: DraggedTrack): boolean {\n const ids = arrangement.getTracks().map((t) => t.id);\n if (!ids.includes(drag.trackId) || ids.length !== drag.order.length) return true;\n return ids.some((id, i) => id !== drag.order[i]);\n}\n","/**\n * A `<daw-clip>` the page moves into another `<daw-track>` of the same\n * editor (#848, the maintainer's choice a). Like a `<track>` moved to another\n * `<video>`, its clip leaves the old track and enters the new one, as it is\n * (its times, its audio), in one undo step. On `dev` the new track took the\n * clip and the old one kept it.\n */\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport type { TrackKind } from '@waveform-playlist/core';\nimport { clipKindError } from './track-entry';\n\n/** The track of an arrangement that holds a clip, other than `exceptTrackId`. */\nexport function trackHoldingClip(\n arrangement: Arrangement,\n clipId: string,\n exceptTrackId: string\n): string | null {\n const track = arrangement\n .getTracks()\n .find((t) => t.id !== exceptTrackId && t.clips.some((c) => c.id === clipId));\n return track?.id ?? null;\n}\n\n/**\n * Move a clip from one track to another: one undo step (a transaction).\n * Returns the error that refused it (a clip of the other kind) and changes\n * nothing then.\n */\nexport function moveClipToTrack(\n arrangement: Arrangement,\n fromTrackId: string,\n toTrackId: string,\n clipId: string,\n toKind: TrackKind\n): Error | null {\n const tracks = arrangement.getTracks();\n const clip = tracks.find((t) => t.id === fromTrackId)?.clips.find((c) => c.id === clipId);\n const to = tracks.find((t) => t.id === toTrackId);\n if (!clip || !to) return new Error('clip \"' + clipId + '\" or track \"' + toTrackId + '\" is gone');\n const isMidi = 'midiNotes' in clip && clip.midiNotes != null;\n const kindError = clipKindError(to.name ?? '', toKind, isMidi, clip.name || clipId);\n if (kindError) return kindError;\n arrangement.beginTransaction();\n try {\n arrangement.updateTrack(fromTrackId, (t) => ({\n ...t,\n clips: t.clips.filter((c) => c.id !== clipId),\n }));\n arrangement.updateTrack(toTrackId, (t) => ({ ...t, clips: [...t.clips, clip] }));\n } catch (err) {\n arrangement.abortTransaction();\n return err instanceof Error ? err : new Error(String(err));\n }\n arrangement.commitTransaction();\n return null;\n}\n","import type { EffectChainItem, EffectState, SerializedEffectEntry } from './types';\n\ninterface ChainEntry extends EffectChainItem {\n id: string;\n bypassed: boolean;\n}\n\nlet idCounter = 0;\n\n/**\n * An ordered insert-effects chain. Owns `input`/`output` gain nodes; entries\n * are wired in series between them (empty chain = straight passthrough).\n *\n * Topology changes (add/remove/move/disconnect-bypass) rebuild the internal\n * wiring; parameter changes never do. Only the controller's own outgoing\n * edges are severed during a rebuild — the consumer's edges into `input` and\n * out of `output` are untouched.\n */\nexport class EffectsChainController {\n private _input: GainNode;\n private _output: GainNode;\n private _entries: ChainEntry[] = [];\n private _disposed = false;\n\n constructor(audioContext: BaseAudioContext) {\n this._input = audioContext.createGain();\n this._output = audioContext.createGain();\n this._input.connect(this._output);\n }\n\n /** Connect the upstream source (track mute node, master gain) into this. */\n get input(): AudioNode {\n return this._input;\n }\n\n /** Route this onward (to the master bus / destination). */\n get output(): AudioNode {\n return this._output;\n }\n\n get entries(): EffectState[] {\n return this._entries.map((entry) => ({\n id: entry.id,\n kind: entry.kind,\n type: entry.type,\n params: { ...entry.params },\n bypassed: entry.bypassed,\n ...(entry.url !== undefined ? { url: entry.url } : {}),\n ...(entry.source !== undefined ? { source: { ...entry.source } } : {}),\n ...(entry.label !== undefined ? { label: entry.label } : {}),\n ...(entry.error !== undefined ? { error: entry.error } : {}),\n }));\n }\n\n /** Snapshot the chain in its persisted form. WAM entries are asked for\n * their live state; placeholders re-emit the state they were saved with. */\n serialize(): Promise<SerializedEffectEntry[]> {\n return Promise.all(\n this._entries.map(async (entry): Promise<SerializedEffectEntry> => {\n if (entry.kind === 'wam') {\n // Faust entries persist their DSP source (recompiled on restore);\n // url-loaded entries persist their URL.\n const sourceFields =\n entry.source?.faust !== undefined\n ? {\n faustDsp: entry.source.faust,\n ...(entry.label !== undefined ? { faustName: entry.label } : {}),\n }\n : { url: entry.url ?? '' };\n if (entry.placeholder) {\n return {\n kind: 'wam',\n ...sourceFields,\n bypassed: entry.placeholder.bypassed,\n ...(entry.placeholder.state !== undefined ? { state: entry.placeholder.state } : {}),\n // Lets offline export skip this entry (live playback silently\n // skips it too); restore ignores the flag and retries.\n placeholder: true,\n };\n }\n let state: unknown;\n try {\n state = await entry.instance.getState?.();\n } catch (err) {\n // One misbehaving plugin must not poison the whole snapshot —\n // emit the entry without state and let the consumer persist the rest.\n console.warn(\n '[waveform-playlist] serialize: plugin \"' +\n (entry.url ?? entry.label ?? entry.type) +\n '\" getState failed: ' +\n String(err)\n );\n }\n return {\n kind: 'wam',\n ...sourceFields,\n bypassed: entry.bypassed,\n ...(state !== undefined ? { state } : {}),\n };\n }\n if (entry.placeholder) {\n // Native placeholder (e.g. unregistered custom type on restore):\n // re-emit the SAVED params/bypassed so the snapshot round-trips.\n return {\n kind: 'native',\n type: entry.type,\n params: { ...entry.params },\n bypassed: entry.placeholder.bypassed,\n placeholder: true,\n };\n }\n return {\n kind: 'native',\n type: entry.type,\n params: { ...entry.params },\n bypassed: entry.bypassed,\n };\n })\n );\n }\n\n get disposed(): boolean {\n return this._disposed;\n }\n\n /** Internal (manager-facing): the live entry — including its instance —\n * for GUI wiring. Returns undefined (no warning) when the id is unknown. */\n getEntry(effectId: string): (EffectChainItem & { id: string; bypassed: boolean }) | undefined {\n return this._entries.find((e) => e.id === effectId);\n }\n\n add(item: EffectChainItem, index?: number): string {\n if (this._disposed) {\n throw new Error(\n '[waveform-playlist] EffectsChainController.add: chain is disposed — entries cannot be added'\n );\n }\n const id = 'effect-' + ++idCounter;\n const entry: ChainEntry = { ...item, params: { ...item.params }, id, bypassed: false };\n const at =\n index === undefined\n ? this._entries.length\n : Math.max(0, Math.min(index, this._entries.length));\n this._entries = [...this._entries.slice(0, at), entry, ...this._entries.slice(at)];\n this._rebuild();\n return id;\n }\n\n remove(effectId: string): void {\n const entry = this._find('remove', effectId);\n if (!entry) return;\n this._entries = this._entries.filter((e) => e.id !== effectId);\n entry.instance.output.disconnect();\n entry.instance.dispose?.();\n this._rebuild();\n }\n\n /** Returns the index the entry actually landed at (the requested index is\n * clamped to the chain bounds), or -1 for an unknown effectId — event\n * dispatchers must report the actual index, not the raw request. */\n move(effectId: string, newIndex: number): number {\n const entry = this._find('move', effectId);\n if (!entry) return -1;\n const without = this._entries.filter((e) => e.id !== effectId);\n const at = Math.max(0, Math.min(newIndex, without.length));\n this._entries = [...without.slice(0, at), entry, ...without.slice(at)];\n this._rebuild();\n return at;\n }\n\n setParams(effectId: string, params: Record<string, number>): void {\n const entry = this._find('setParams', effectId);\n if (!entry) return;\n entry.params = { ...entry.params, ...params };\n if (entry.bypassed && entry.wetParam && entry.wetParam in params) {\n // Store the new wet level but keep the audible wet at 0 while bypassed.\n const { [entry.wetParam]: _stored, ...rest } = params;\n if (Object.keys(rest).length > 0) {\n entry.instance.applyParams(rest);\n }\n return;\n }\n entry.instance.applyParams(params);\n }\n\n setBypassed(effectId: string, bypassed: boolean): void {\n const entry = this._find('setBypassed', effectId);\n if (!entry || entry.bypassed === bypassed) return;\n entry.bypassed = bypassed;\n\n if (entry.wetParam) {\n // Wet-style bypass: zero the wet level, restore the stored value later.\n const wet = bypassed ? 0 : (entry.params[entry.wetParam] ?? 0);\n entry.instance.applyParams({ [entry.wetParam]: wet });\n return;\n }\n // No wet param: take the entry out of the series, keep the instance alive.\n this._rebuild();\n }\n\n dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._severOwnEdges();\n for (const entry of this._entries) {\n entry.instance.dispose?.();\n }\n this._entries = [];\n try {\n this._output.disconnect();\n } catch {\n // Output may already be detached by the consumer.\n }\n }\n\n private _find(op: string, effectId: string): ChainEntry | undefined {\n const entry = this._entries.find((e) => e.id === effectId);\n if (!entry) {\n console.warn(\n '[waveform-playlist] EffectsChainController.' + op + ': unknown effectId \"' + effectId + '\"'\n );\n }\n return entry;\n }\n\n /** Sever only this chain's outgoing edges — never the consumer's. */\n private _severOwnEdges(): void {\n this._input.disconnect();\n for (const entry of this._entries) {\n entry.instance.output.disconnect();\n }\n }\n\n private _rebuild(): void {\n this._severOwnEdges();\n let previous: AudioNode = this._input;\n for (const entry of this._entries) {\n if (entry.bypassed && !entry.wetParam) {\n continue;\n }\n previous.connect(entry.instance.input);\n previous = entry.instance.output;\n }\n previous.connect(this._output);\n }\n}\n","import { installCommand } from '../utils/install-command';\n\nconst PREFIX = '[waveform-playlist] ';\n\n/**\n * Dynamic-import an optional peer dep with an actionable error. The thrown\n * message carries BOTH the install hint and the underlying import error —\n * \"not installed\" is only one of the ways a dynamic import fails (dead dev\n * server, broken exports map, CSP, network), and hiding the cause behind a\n * generic hint sends people down the wrong path.\n */\nasync function loadOptionalModule<T>(\n importer: () => Promise<T>,\n packageName: string,\n feature: string\n): Promise<T> {\n try {\n return await importer();\n } catch (originalErr) {\n console.warn(PREFIX + packageName + ' dynamic import failed: ' + String(originalErr));\n throw new Error(\n PREFIX +\n packageName +\n ' is required for ' +\n feature +\n '. Install with: ' +\n installCommand(packageName) +\n ' (import failed: ' +\n String(originalErr) +\n ')'\n );\n }\n}\n\nexport function loadWamModule(feature: string): Promise<typeof import('@dawcore/wam')> {\n return loadOptionalModule(() => import('@dawcore/wam'), '@dawcore/wam', feature);\n}\n\nexport function loadFaustModule(feature: string): Promise<typeof import('@dawcore/faust')> {\n return loadOptionalModule(() => import('@dawcore/faust'), '@dawcore/faust', feature);\n}\n","import { EffectsChainController } from './effects-chain-controller';\nimport { loadWamModule, loadFaustModule } from './optional-modules';\nimport {\n createEffectInstance,\n ensureEffectPrepared,\n getEffectDefinitions,\n needsPrepare,\n prepareEffect,\n} from '@waveform-playlist/core';\nimport './effect-registry'; // registers the native-* built-ins\nimport type { EffectChainItem, EffectState, SerializedEffectEntry } from './types';\n\nconst PREFIX = '[waveform-playlist] ';\n\n/** The transport surface the effects system needs — satisfied by @dawcore/transport's Transport. */\nexport interface EffectsTransportLike {\n /** PRE-FADER track insert (#660): clips → input … output → volume → pan →\n * mute. The transport wires both edges, including the chain's return. */\n connectTrackEffects(trackId: string, input: AudioNode, output: AudioNode): void;\n disconnectTrackEffects(trackId: string): void;\n connectMasterOutput(node: AudioNode): void;\n disconnectMasterOutput(): void;\n readonly masterOutputNode: AudioNode;\n}\n\ninterface AdapterLike {\n audioContext?: AudioContext;\n transport?: EffectsTransportLike;\n}\n\n/** A created (and cached) GUI element plus its idempotent destroyer. */\ninterface GuiRecord {\n element: HTMLElement;\n destroy: () => void;\n /** True for manager-built generic parameter panels — they bake values at\n * build time, so reopen rebuilds them instead of reusing the cache\n * (plugin-provided GUIs manage their own state and stay cached). */\n isFallback: boolean;\n}\n\nfunction makeGuiRecord(\n element: HTMLElement,\n destroyImpl: () => void,\n isFallback = false\n): GuiRecord {\n let destroyed = false;\n return {\n element,\n isFallback,\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n destroyImpl();\n },\n };\n}\n\n/**\n * Owns all effect chains for one editor: the master chain plus one chain per\n * track. Track chains are PRE-FADER inserts (clips → chain → volume → pan →\n * mute); the master chain sits after the master gain. Wires chains into the\n * adapter's transport hooks and dispatches the\n * daw-effect-* events from the owning element (track element for track\n * chains, the editor for the master chain) so they bubble track → editor.\n */\nexport class EffectsManager {\n private _getAdapter: () => AdapterLike | null;\n private _masterTarget: EventTarget;\n private _masterChain: EffectsChainController | null = null;\n private _trackChains = new Map<string, EffectsChainController>();\n /** Per-chain restore ownership — a newer setEffectsState supersedes a stale in-flight one. */\n private _restoreTokens = new WeakMap<EffectsChainController, symbol>();\n /** Cached GUI elements by effectId — close hides, only removal destroys. */\n private _guis = new Map<string, GuiRecord>();\n /** In-flight GUI creation by effectId — concurrent opens share one build. */\n private _guiPending = new Map<string, Promise<GuiRecord>>();\n /** Live WAM plugin nodes across all chains, fed to the wam-transport bridge. */\n private _wamNodes = new Set<import('@dawcore/wam').WamTransportNode>();\n private _transportBridge: { notifyNodeAdded(node: unknown): void; dispose(): void } | null = null;\n /** One-time warn when the adapter transport can't host the wam-transport bridge. */\n private _transportBridgeWarned = false;\n\n constructor(getAdapter: () => AdapterLike | null, masterEventTarget: EventTarget) {\n this._getAdapter = getAdapter;\n this._masterTarget = masterEventTarget;\n }\n\n // --- Master chain ---\n\n addMasterEffect(type: string, params?: Record<string, number>): string {\n const chain = this._ensureMasterChain();\n return this._addToChain(chain, this._masterTarget, type, params);\n }\n\n masterEffects(): EffectState[] {\n return this._masterChain?.entries ?? [];\n }\n\n masterOp(\n op: 'remove' | 'setParams' | 'setBypassed' | 'move',\n effectId: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arg?: any\n ): void {\n this._runOp(this._masterChain, this._masterTarget, op, effectId, arg);\n }\n\n addMasterWamPlugin(url: string, initialState?: unknown): Promise<string> {\n const chain = this._ensureMasterChain();\n return this._addWamToChain(chain, this._masterTarget, url, initialState);\n }\n\n addMasterFaustEffect(dspCode: string, options?: { name?: string }): Promise<string> {\n const chain = this._ensureMasterChain();\n return this._addFaustToChain(chain, this._masterTarget, dspCode, { name: options?.name });\n }\n\n getMasterEffectsState(): Promise<SerializedEffectEntry[]> {\n return this._masterChain?.serialize() ?? Promise.resolve([]);\n }\n\n async setMasterEffectsState(entries: SerializedEffectEntry[]): Promise<void> {\n validateSerializedEntries(entries);\n await this._restoreChain(this._ensureMasterChain(), this._masterTarget, entries);\n }\n\n /** Run a registered effect's async `prepare` hook on the adapter's\n * context, so the synchronous addEffect() can create it. */\n async prepareEffect(type: string): Promise<void> {\n await prepareEffect(type, this._requireWiring().audioContext);\n }\n\n // --- Track chains ---\n\n addTrackEffect(\n trackId: string,\n target: EventTarget,\n type: string,\n params?: Record<string, number>\n ): string {\n const chain = this._ensureTrackChain(trackId);\n return this._addToChain(chain, target, type, params);\n }\n\n addTrackWamPlugin(\n trackId: string,\n target: EventTarget,\n url: string,\n initialState?: unknown\n ): Promise<string> {\n const chain = this._ensureTrackChain(trackId);\n return this._addWamToChain(chain, target, url, initialState);\n }\n\n addTrackFaustEffect(\n trackId: string,\n target: EventTarget,\n dspCode: string,\n options?: { name?: string }\n ): Promise<string> {\n const chain = this._ensureTrackChain(trackId);\n return this._addFaustToChain(chain, target, dspCode, { name: options?.name });\n }\n\n trackEffects(trackId: string): EffectState[] {\n return this._trackChains.get(trackId)?.entries ?? [];\n }\n\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]> {\n return this._trackChains.get(trackId)?.serialize() ?? Promise.resolve([]);\n }\n\n async setTrackEffectsState(\n trackId: string,\n target: EventTarget,\n entries: SerializedEffectEntry[]\n ): Promise<void> {\n validateSerializedEntries(entries);\n await this._restoreChain(this._ensureTrackChain(trackId), target, entries);\n }\n\n trackOp(\n trackId: string,\n target: EventTarget,\n op: 'remove' | 'setParams' | 'setBypassed' | 'move',\n effectId: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arg?: any\n ): void {\n this._runOp(this._trackChains.get(trackId) ?? null, target, op, effectId, arg);\n }\n\n // --- Effect GUIs ---\n\n /** Open (lazily creating) the GUI for a master-chain effect. */\n openMasterEffectGui(effectId: string, container: HTMLElement): Promise<HTMLElement> {\n return this._openGui(this._masterChain, this._masterTarget, effectId, container);\n }\n\n /** Open (lazily creating) the GUI for a track-chain effect. */\n openTrackEffectGui(\n trackId: string,\n target: EventTarget,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement> {\n return this._openGui(this._trackChains.get(trackId) ?? null, target, effectId, container);\n }\n\n /** Hide an open GUI. The element stays cached so reopen is instant —\n * audio processing is never interrupted. */\n closeEffectGui(effectId: string): void {\n const record = this._guis.get(effectId);\n if (!record) {\n console.warn(PREFIX + 'closeEffectGui: no open GUI for effectId \"' + effectId + '\"');\n return;\n }\n record.element.remove();\n }\n\n // --- Lifecycle ---\n\n /** Transport setTracks rebuilds TrackNodes, severing chain hookups — re-wire. */\n rewireTrackChains(): void {\n const transport = this._getAdapter()?.transport;\n if (!transport) return;\n for (const [trackId, chain] of this._trackChains) {\n // The transport owns the chain's return edge (output → fader) and\n // released the old one when it disposed/replaced the track node.\n transport.connectTrackEffects(trackId, chain.input, chain.output);\n }\n }\n\n disposeTrackChain(trackId: string): void {\n const chain = this._trackChains.get(trackId);\n if (!chain) return;\n this._trackChains.delete(trackId);\n for (const entry of chain.entries) {\n this._destroyGui(entry.id);\n }\n try {\n this._getAdapter()?.transport?.disconnectTrackEffects(trackId);\n } catch (err) {\n console.warn(PREFIX + 'EffectsManager: error disconnecting track output: ' + String(err));\n }\n chain.dispose();\n }\n\n disposeAll(): void {\n this._transportBridge?.dispose();\n this._transportBridge = null;\n this._wamNodes.clear();\n for (const trackId of [...this._trackChains.keys()]) {\n this.disposeTrackChain(trackId);\n }\n if (this._masterChain) {\n for (const entry of this._masterChain.entries) {\n this._destroyGui(entry.id);\n }\n try {\n this._getAdapter()?.transport?.disconnectMasterOutput();\n } catch (err) {\n console.warn(PREFIX + 'EffectsManager: error disconnecting master output: ' + String(err));\n }\n this._masterChain.dispose();\n this._masterChain = null;\n }\n }\n\n // --- Private ---\n\n private _requireWiring(): { audioContext: AudioContext; transport: EffectsTransportLike } {\n const adapter = this._getAdapter();\n if (!adapter) {\n throw new Error(\n PREFIX + 'effects require an adapter — set editor.adapter before adding effects.'\n );\n }\n const { audioContext, transport } = adapter;\n if (!audioContext || !transport || typeof transport.connectTrackEffects !== 'function') {\n const outdated =\n typeof (transport as { connectTrackOutput?: unknown } | undefined)?.connectTrackOutput ===\n 'function';\n throw new Error(\n PREFIX +\n (outdated\n ? 'the current adapter exposes the old post-fader effects hook (transport.connectTrackOutput). ' +\n 'Track effects are pre-fader inserts now — upgrade @dawcore/transport (>= 0.0.16) or ' +\n '@waveform-playlist/playout (>= 13) for transport.connectTrackEffects.'\n : 'the current adapter does not expose effects hooks (transport.connectTrackEffects / connectMasterOutput).')\n );\n }\n return { audioContext, transport };\n }\n\n /** Dynamic-import the optional @dawcore/wam peer with an actionable error. */\n private _loadWamModule(feature: string): Promise<typeof import('@dawcore/wam')> {\n return loadWamModule(feature);\n }\n\n /** Dynamic-import the optional @dawcore/faust peer with an actionable error. */\n private _loadFaustModule(feature: string): Promise<typeof import('@dawcore/faust')> {\n return loadFaustModule(feature);\n }\n\n private async _openGui(\n chain: EffectsChainController | null,\n target: EventTarget,\n effectId: string,\n container: HTMLElement\n ): Promise<HTMLElement> {\n if (!container || typeof container.appendChild !== 'function') {\n throw new Error(PREFIX + 'openEffectGui: container must be a DOM element');\n }\n const entry = chain?.getEntry(effectId);\n if (!chain || !entry) {\n throw new Error(PREFIX + 'openEffectGui: unknown effectId \"' + effectId + '\"');\n }\n if (entry.error !== undefined) {\n throw new Error(\n PREFIX +\n 'openEffectGui: effect \"' +\n effectId +\n '\" is a failed-plugin placeholder (' +\n entry.error +\n ') — no GUI is available. Remove it or retry the restore.'\n );\n }\n\n const cached = this._guis.get(effectId);\n if (cached && !cached.isFallback) {\n container.appendChild(cached.element);\n return cached.element;\n }\n // A cached FALLBACK panel is rebuilt instead of reused: generic panels\n // bake their slider values at build time, so an API-side setEffectParams\n // while the panel was closed would show stale values (and the first drag\n // would snap the audio back to the stale position). The old panel is kept\n // until the rebuild succeeds — a transient failure (dynamic-import blip)\n // must not destroy a working panel.\n\n let pending = this._guiPending.get(effectId);\n if (!pending) {\n pending = this._createGuiRecord(chain, target, entry, effectId).finally(() => {\n this._guiPending.delete(effectId);\n });\n this._guiPending.set(effectId, pending);\n }\n let record: GuiRecord;\n try {\n record = await pending;\n } catch (err) {\n if (cached) {\n console.warn(\n PREFIX +\n 'openEffectGui: rebuilding the parameter panel for \"' +\n effectId +\n '\" failed — serving the cached panel (values may be stale): ' +\n String(err)\n );\n container.appendChild(cached.element);\n return cached.element;\n }\n throw err;\n }\n if (cached && cached !== record) {\n cached.element.remove();\n }\n\n // The effect (or its whole chain) may have been removed while the GUI\n // was building — a late mount would leak a GUI for a destroyed plugin.\n if (chain.disposed || !chain.getEntry(effectId)) {\n this._guis.delete(effectId);\n record.element.remove();\n try {\n record.destroy();\n } catch (err) {\n console.warn(\n PREFIX +\n 'openEffectGui: destroying a late GUI for \"' +\n effectId +\n '\" failed: ' +\n String(err)\n );\n }\n throw new Error(\n PREFIX +\n 'openEffectGui: effect \"' +\n effectId +\n '\" was removed while its GUI was loading; the GUI was discarded.'\n );\n }\n\n this._guis.set(effectId, record);\n container.appendChild(record.element);\n return record.element;\n }\n\n /** Build a GUI record: the plugin's own GUI when available, otherwise the\n * generic parameter panel from @dawcore/wam. */\n private async _createGuiRecord(\n chain: EffectsChainController,\n target: EventTarget,\n entry: EffectChainItem & { id: string },\n effectId: string\n ): Promise<GuiRecord> {\n const { instance } = entry;\n if (typeof instance.createGui === 'function') {\n try {\n const element: unknown = await instance.createGui();\n // The WAM SDK's base createGui() exists on every plugin and resolves\n // undefined when the plugin ships no GUI module — \"no GUI\", not a\n // failure. Anything that is not an element takes the fallback below.\n if (element instanceof HTMLElement) {\n return makeGuiRecord(element, () => instance.destroyGui?.(element));\n }\n } catch (err) {\n console.warn(\n PREFIX +\n 'openEffectGui: plugin createGui failed for \"' +\n effectId +\n '\" — falling back to the generic parameter panel: ' +\n String(err)\n );\n }\n }\n const element = await this._createFallbackPanel(chain, target, entry, effectId);\n // The generic panel is plain DOM owned by this manager — removal from the\n // document (done by _destroyGui) is its entire teardown.\n return makeGuiRecord(element, () => {}, true);\n }\n\n /** The generic parameter panel — one code path for \"no custom GUI\":\n * native entries render from the registry's params metadata, WAM entries\n * from getParameterInfo(). Edits route through the regular setParams op so\n * they hit the audio (applyParams → setParameterValues for WAM) AND\n * dispatch daw-effect-change like any other parameter edit. */\n private async _createFallbackPanel(\n chain: EffectsChainController,\n target: EventTarget,\n entry: EffectChainItem & { id: string },\n effectId: string\n ): Promise<HTMLElement> {\n const wamModule = await this._loadWamModule('openEffectGui() parameter panels');\n const onChange = (paramId: string, value: number) => {\n this._runOp(chain, target, 'setParams', effectId, { [paramId]: value });\n };\n\n if (entry.kind === 'native') {\n const definition = getEffectDefinitions().get(entry.type);\n if (!definition) {\n throw new Error(\n PREFIX + 'openEffectGui: no registry definition for effect type \"' + entry.type + '\"'\n );\n }\n const params = Object.entries(definition.params).map(([id, def]) => ({\n id,\n min: def.min,\n max: def.max,\n ...(def.step !== undefined ? { step: def.step } : {}),\n ...(def.unit !== undefined ? { unit: def.unit } : {}),\n value: entry.params[id] ?? definition.defaults[id],\n }));\n return wamModule.createParameterPanel(params, onChange);\n }\n\n if (typeof entry.instance.getParameterInfo !== 'function') {\n throw new Error(\n PREFIX +\n 'openEffectGui: effect \"' +\n effectId +\n '\" has no GUI and exposes no parameter info — nothing to render.'\n );\n }\n return wamModule.createWamParameterPanel(\n { getParameterInfo: () => entry.instance.getParameterInfo!() },\n { onParamChange: onChange }\n );\n }\n\n /** Detach + destroy a cached GUI. Called only from removal paths — close\n * never destroys. Safe when no GUI was ever opened. */\n private _destroyGui(effectId: string): void {\n const record = this._guis.get(effectId);\n if (!record) return;\n this._guis.delete(effectId);\n record.element.remove();\n try {\n record.destroy();\n } catch (err) {\n console.warn(PREFIX + 'destroyGui failed for effect \"' + effectId + '\": ' + String(err));\n }\n }\n\n private _ensureMasterChain(): EffectsChainController {\n if (this._masterChain) return this._masterChain;\n const { audioContext, transport } = this._requireWiring();\n const chain = new EffectsChainController(audioContext);\n transport.connectMasterOutput(chain.input);\n chain.output.connect(audioContext.destination);\n this._masterChain = chain;\n return chain;\n }\n\n private _ensureTrackChain(trackId: string): EffectsChainController {\n const existing = this._trackChains.get(trackId);\n if (existing) return existing;\n const { audioContext, transport } = this._requireWiring();\n const chain = new EffectsChainController(audioContext);\n // Pre-fader insert: the track's volume, pan and mute come AFTER the\n // chain, so the fader never drives a compressor (#660).\n transport.connectTrackEffects(trackId, chain.input, chain.output);\n this._trackChains.set(trackId, chain);\n return chain;\n }\n\n private _addToChain(\n chain: EffectsChainController,\n target: EventTarget,\n type: string,\n params?: Record<string, number>\n ): string {\n const audioContext = this._requireWiring().audioContext;\n const created = createEffectInstance(type, audioContext, params);\n const effectId = chain.add({\n kind: 'native',\n type,\n instance: created.instance,\n params: created.params,\n wetParam: created.wetParam,\n });\n const index = chain.entries.findIndex((e) => e.id === effectId);\n this._dispatch(target, 'daw-effect-add', {\n effectId,\n kind: 'native',\n type,\n params: { ...created.params },\n index,\n });\n return effectId;\n }\n\n /**\n * Load a WAM plugin (via the optional @dawcore/wam peer dep) and add it to\n * a chain as a kind:'wam' entry. WAM entries participate in every chain\n * operation with no special-casing: remove destroys the plugin (via the\n * entry's dispose), bypass uses disconnection semantics (no wet param),\n * and setParams maps onto the plugin's setParameterValues.\n */\n private async _addWamToChain(\n chain: EffectsChainController,\n target: EventTarget,\n url: string,\n initialState?: unknown\n ): Promise<string> {\n const { audioContext } = this._requireWiring();\n const wamModule = await this._loadWamModule('addWamPlugin()');\n const { hostGroupId } = await wamModule.ensureWamHost(audioContext);\n const plugin = await wamModule.createWamInstance(url, audioContext, hostGroupId, {\n initialState,\n });\n return this._insertWamPlugin(chain, target, wamModule, plugin, { url });\n }\n\n /**\n * Compile Faust DSP source in the browser (via the optional @dawcore/faust\n * peer) and add the resulting WAM to a chain. Compilation happens BEFORE\n * any chain work, so a Faust error (with its line/column diagnostics intact)\n * leaves the chain untouched. The entry lands as kind:'wam' with a\n * `source: { faust }` marker so persistence recompiles instead of fetching.\n */\n private async _addFaustToChain(\n chain: EffectsChainController,\n target: EventTarget,\n dspCode: string,\n opts: { name?: string; initialState?: unknown }\n ): Promise<string> {\n if (typeof dspCode !== 'string' || dspCode.trim().length === 0) {\n throw new Error(PREFIX + 'addFaustEffect: dspCode must be a non-empty string');\n }\n this._requireWiring();\n const faustModule = await this._loadFaustModule('addFaustEffect()');\n // Faust compile errors propagate unchanged — the diagnostics are\n // user-facing (the user wrote the DSP).\n const compiled = await faustModule.compileFaustToWam(dspCode, { name: opts.name });\n\n const { audioContext } = this._requireWiring();\n const wamModule = await this._loadWamModule('addFaustEffect()');\n const { hostGroupId } = await wamModule.ensureWamHost(audioContext);\n const plugin = await wamModule.createWamInstanceFromFactory(\n compiled.factory as import('@dawcore/wam').WamFactory,\n audioContext,\n hostGroupId,\n { initialState: opts.initialState, label: compiled.name }\n );\n return this._insertWamPlugin(chain, target, wamModule, plugin, {\n source: { faust: compiled.dspCode },\n });\n }\n\n /**\n * Wire a live WAM plugin instance into a chain as a kind:'wam' entry —\n * shared by the url path (addWamPlugin) and the Faust path (addFaustEffect).\n * WAM entries participate in every chain operation with no special-casing:\n * remove destroys the plugin (via the entry's dispose), bypass uses\n * disconnection semantics (no wet param), and setParams maps onto the\n * plugin's setParameterValues.\n */\n private _insertWamPlugin(\n chain: EffectsChainController,\n target: EventTarget,\n wamModule: typeof import('@dawcore/wam'),\n plugin: import('@dawcore/wam').WamPluginInstance,\n meta: { url?: string; source?: { faust: string } }\n ): string {\n const node = plugin.audioNode;\n const label = plugin.descriptor.name;\n\n // The chain may have been torn down while the plugin was loading/compiling\n // (track removed, editor disconnected, adapter swapped). A late add would\n // wire the plugin into a severed graph and leak its worklet.\n if (chain.disposed) {\n plugin.destroy();\n throw new Error(\n PREFIX +\n 'addWamPlugin: the effects chain was disposed while \"' +\n (meta.url ?? label) +\n '\" was loading; the plugin was discarded.'\n );\n }\n\n let effectId: string;\n try {\n effectId = chain.add({\n kind: 'wam',\n type: 'wam',\n ...(meta.url !== undefined ? { url: meta.url } : {}),\n ...(meta.source !== undefined ? { source: meta.source } : {}),\n label,\n instance: {\n input: node,\n output: node,\n applyParams: (params) => {\n node.setParameterValues?.(toWamParameterMap(params))?.catch((err: unknown) => {\n console.warn(PREFIX + 'WAM setParameterValues failed: ' + String(err));\n });\n },\n dispose: () => {\n this._wamNodes.delete(node);\n plugin.destroy();\n },\n getState: () => plugin.getState(),\n getParameterInfo: () => plugin.getParameterInfo(),\n ...(plugin.createGui ? { createGui: () => plugin.createGui!() } : {}),\n ...(plugin.destroyGui\n ? { destroyGui: (gui: HTMLElement) => plugin.destroyGui!(gui) }\n : {}),\n },\n params: {},\n });\n } catch (err) {\n // Insertion failed — the chain never took ownership, so the live\n // worklet must be torn down here or it leaks.\n try {\n plugin.destroy();\n } catch (destroyErr) {\n console.warn(\n PREFIX + 'addWamPlugin: cleanup after failed insertion also failed: ' + String(destroyErr)\n );\n }\n throw err;\n }\n this._wamNodes.add(node);\n this._ensureTransportBridge(wamModule)?.notifyNodeAdded(node);\n const index = chain.entries.findIndex((e) => e.id === effectId);\n this._dispatch(target, 'daw-effect-add', {\n effectId,\n kind: 'wam',\n type: 'wam',\n ...(meta.url !== undefined ? { url: meta.url } : {}),\n ...(meta.source !== undefined ? { source: meta.source } : {}),\n params: {},\n index,\n });\n return effectId;\n }\n\n /**\n * Lazily create the wam-transport bridge so tempo-synced plugins lock to\n * the timeline. Skipped (not an error, one-time warn) when the adapter's\n * transport lacks the query/event surface — the bridge is an enhancement,\n * not a requirement for audio processing.\n */\n private _ensureTransportBridge(\n wamModule: typeof import('@dawcore/wam')\n ): { notifyNodeAdded(node: unknown): void; dispose(): void } | null {\n if (this._transportBridge) return this._transportBridge;\n if (typeof wamModule.createWamTransportBridge !== 'function') return null;\n const transport = this._getAdapter()?.transport as\n | (EffectsTransportLike & import('@dawcore/wam').TransportQueryLike)\n | undefined;\n if (\n !transport ||\n typeof transport.on !== 'function' ||\n typeof transport.getTempo !== 'function' ||\n typeof transport.tickToBar !== 'function' ||\n typeof transport.timeToTick !== 'function'\n ) {\n if (!this._transportBridgeWarned) {\n this._transportBridgeWarned = true;\n console.warn(\n '[waveform-playlist] wam-transport bridge skipped: the adapter transport does not ' +\n 'implement the query surface (on/getTempo/tickToBar/timeToTick), so WAM plugins ' +\n \"won't receive transport/tempo events. Use NativePlayoutAdapter for transport \" +\n 'sync — see issue #537.'\n );\n }\n return null;\n }\n this._transportBridge = wamModule.createWamTransportBridge(transport, () => [\n ...this._wamNodes,\n ]);\n return this._transportBridge;\n }\n\n /**\n * Replace a chain's contents with a persisted snapshot. Entries restore\n * sequentially so chain order survives async WAM loads. A WAM url that\n * fails to load becomes a bypassed passthrough placeholder at its saved\n * position — the restore continues, a daw-effect-error fires, and the\n * saved state is retained so a later snapshot/retry round-trips it.\n */\n private async _restoreChain(\n chain: EffectsChainController,\n target: EventTarget,\n entries: SerializedEffectEntry[]\n ): Promise<void> {\n // Last writer wins: a newer restore takes ownership of the chain and the\n // stale one aborts at its next checkpoint instead of interleaving entries.\n const token = Symbol('restore');\n this._restoreTokens.set(chain, token);\n const superseded = () => this._restoreTokens.get(chain) !== token;\n\n for (const existing of chain.entries) {\n this._runOp(chain, target, 'remove', existing.id);\n }\n for (const entry of entries) {\n if (superseded()) return;\n if (entry.kind === 'native') {\n try {\n // Restore is already async, so it can run the definition's\n // per-context setup itself (#657). A failure lands in the\n // placeholder path below like any other native restore failure.\n // Only await when there IS something to prepare: a chain of plain\n // natives must still restore synchronously within this call, as it\n // always has (callers read `effects` / add effects right after).\n const liveContext = this._requireWiring().audioContext;\n if (needsPrepare(entry.type, liveContext)) {\n await ensureEffectPrepared(entry.type, liveContext);\n if (superseded() || chain.disposed) return;\n }\n const id = this._addToChain(chain, target, entry.type, entry.params);\n if (entry.bypassed) {\n this._runOp(chain, target, 'setBypassed', id, true);\n }\n } catch (err) {\n // Same policy as failed WAM loads below: the old chain is already\n // destroyed at this point, so a throw here would strand a\n // half-built chain and lose every remaining entry. Placeholder +\n // error event + continue. (Reachable via an unregistered custom\n // type — the consumer saved state with registerEffect()'d types\n // that aren't re-registered on this page.)\n if (superseded() || chain.disposed) return;\n const message = err instanceof Error ? err.message : String(err);\n console.warn(\n PREFIX +\n 'setEffectsState: native effect \"' +\n entry.type +\n '\" failed to restore: ' +\n message\n );\n const effectId = this._addNativePlaceholder(chain, entry, message);\n this._dispatch(target, 'daw-effect-error', {\n effectId,\n type: entry.type,\n message,\n });\n }\n continue;\n }\n try {\n // Faust entries recompile from their persisted DSP source; url\n // entries load from their URL.\n const id =\n entry.faustDsp !== undefined\n ? await this._addFaustToChain(chain, target, entry.faustDsp, {\n name: entry.faustName,\n initialState: entry.state,\n })\n : await this._addWamToChain(chain, target, entry.url ?? '', entry.state);\n if (superseded()) {\n // A newer restore cleared the chain while this plugin loaded —\n // remove (and thereby destroy) the late arrival.\n this._runOp(chain, target, 'remove', id);\n return;\n }\n if (entry.bypassed) {\n this._runOp(chain, target, 'setBypassed', id, true);\n }\n } catch (err) {\n // chain.disposed guard: the chain can be torn down mid-restore (track\n // removed while a plugin loaded) — the placeholder add would itself\n // throw on the disposed chain, escaping setEffectsState with an error\n // about internal chain lifecycle instead of the plugin failure.\n if (superseded() || chain.disposed) return;\n const message = err instanceof Error ? err.message : String(err);\n const sourceLabel = entry.url ?? entry.faustName ?? 'Faust effect';\n console.warn(\n PREFIX + 'setEffectsState: plugin \"' + sourceLabel + '\" failed to restore: ' + message\n );\n const effectId = this._addWamPlaceholder(chain, entry, message);\n this._dispatch(target, 'daw-effect-error', {\n effectId,\n ...(entry.url !== undefined ? { url: entry.url } : {}),\n ...(entry.faustDsp !== undefined ? { source: { faust: entry.faustDsp } } : {}),\n message,\n });\n }\n }\n }\n\n /** A silent passthrough occupying a failed NATIVE entry's chain position.\n * Carries the saved params/bypassed so the snapshot round-trips (serialize\n * re-emits them with `placeholder: true`). */\n private _addNativePlaceholder(\n chain: EffectsChainController,\n entry: { type: string; params: Record<string, number>; bypassed: boolean },\n message: string\n ): string {\n const { audioContext } = this._requireWiring();\n const node = audioContext.createGain();\n const effectId = chain.add({\n kind: 'native',\n type: entry.type,\n label: entry.type,\n error: message,\n placeholder: { bypassed: entry.bypassed },\n instance: { input: node, output: node, applyParams: () => {} },\n params: { ...entry.params },\n });\n // Placeholders pass audio through, bypassed-style (no wet param).\n chain.setBypassed(effectId, true);\n return effectId;\n }\n\n /** A silent passthrough occupying the failed plugin's chain position. */\n private _addWamPlaceholder(\n chain: EffectsChainController,\n entry: {\n url?: string;\n faustDsp?: string;\n faustName?: string;\n bypassed: boolean;\n state?: unknown;\n },\n message: string\n ): string {\n const { audioContext } = this._requireWiring();\n const node = audioContext.createGain();\n const effectId = chain.add({\n kind: 'wam',\n type: 'wam',\n ...(entry.url !== undefined ? { url: entry.url } : {}),\n ...(entry.faustDsp !== undefined ? { source: { faust: entry.faustDsp } } : {}),\n label: entry.url ?? entry.faustName ?? 'Faust effect',\n error: message,\n placeholder: { state: entry.state, bypassed: entry.bypassed },\n instance: { input: node, output: node, applyParams: () => {} },\n params: {},\n });\n // Placeholders pass audio through, bypassed-style (no wet param).\n chain.setBypassed(effectId, true);\n return effectId;\n }\n\n private _runOp(\n chain: EffectsChainController | null,\n target: EventTarget,\n op: 'remove' | 'setParams' | 'setBypassed' | 'move',\n effectId: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n arg?: any\n ): void {\n const entries = chain?.entries ?? [];\n const fromIndex = entries.findIndex((e) => e.id === effectId);\n if (!chain || fromIndex === -1) {\n console.warn(PREFIX + 'effects.' + op + ': unknown effectId \"' + effectId + '\"');\n return;\n }\n if (entries[fromIndex].error !== undefined && (op === 'setParams' || op === 'setBypassed')) {\n // Error placeholders are inert passthroughs — silently \"succeeding\"\n // would mislead the consumer into thinking the edit took effect.\n console.warn(\n PREFIX +\n 'effects.' +\n op +\n ': effect \"' +\n effectId +\n '\" is a failed-plugin placeholder (' +\n entries[fromIndex].error +\n ') — edit ignored. Remove it or retry the restore.'\n );\n return;\n }\n switch (op) {\n case 'remove':\n this._destroyGui(effectId);\n chain.remove(effectId);\n this._dispatch(target, 'daw-effect-remove', { effectId });\n break;\n case 'setParams':\n chain.setParams(effectId, arg);\n this._dispatch(target, 'daw-effect-change', { effectId, params: { ...arg } });\n break;\n case 'setBypassed':\n chain.setBypassed(effectId, arg);\n this._dispatch(target, 'daw-effect-bypass', { effectId, bypassed: arg });\n break;\n case 'move': {\n // Report the index the chain ACTUALLY used — it clamps out-of-range\n // requests, and a consumer mirroring order from the event detail\n // would mis-sort (or crash indexing) on the raw request.\n const toIndex = chain.move(effectId, arg);\n this._dispatch(target, 'daw-effect-reorder', { effectId, fromIndex, toIndex });\n break;\n }\n }\n }\n\n private _dispatch(target: EventTarget, name: string, detail: Record<string, unknown>): void {\n target.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail }));\n }\n}\n\n/** Fail fast on malformed persisted data — external input, never trusted. */\nfunction validateSerializedEntries(entries: unknown): asserts entries is SerializedEffectEntry[] {\n if (!Array.isArray(entries)) {\n throw new Error(PREFIX + 'setEffectsState: expected an array of serialized effect entries');\n }\n entries.forEach((entry, i) => {\n const at = ' (entry ' + i + ')';\n if (entry === null || typeof entry !== 'object') {\n throw new Error(PREFIX + 'setEffectsState: entry must be an object' + at);\n }\n const e = entry as Record<string, unknown>;\n if (e.kind === 'native') {\n if (typeof e.type !== 'string' || e.type.length === 0) {\n throw new Error(PREFIX + 'setEffectsState: native entry requires a type string' + at);\n }\n if (e.params === null || typeof e.params !== 'object') {\n throw new Error(PREFIX + 'setEffectsState: native entry requires a params object' + at);\n }\n } else if (e.kind === 'wam') {\n const hasUrl = typeof e.url === 'string' && e.url.length > 0;\n const hasFaustDsp = typeof e.faustDsp === 'string' && e.faustDsp.trim().length > 0;\n if (!hasUrl && !hasFaustDsp) {\n throw new Error(\n PREFIX +\n 'setEffectsState: wam entry requires a url string or a faustDsp source string' +\n at\n );\n }\n if (e.faustName !== undefined && typeof e.faustName !== 'string') {\n throw new Error(PREFIX + 'setEffectsState: faustName must be a string when provided' + at);\n }\n } else {\n throw new Error(PREFIX + 'setEffectsState: unknown entry kind \"' + String(e.kind) + '\"' + at);\n }\n if (typeof e.bypassed !== 'boolean') {\n throw new Error(PREFIX + 'setEffectsState: entry requires a boolean bypassed flag' + at);\n }\n if (e.placeholder !== undefined && e.placeholder !== true) {\n // A malformed truthy value (e.g. \"false\", 1, {}) would restore as a\n // working live effect but be silently SKIPPED by exportAudio — an\n // export missing an effect the user hears, with zero warning.\n throw new Error(PREFIX + 'setEffectsState: placeholder must be true when present' + at);\n }\n });\n}\n\n/** WAM setParameterValues takes a map of {id, value, normalized} records. */\nfunction toWamParameterMap(\n params: Record<string, number>\n): Record<string, { id: string; value: number; normalized: boolean }> {\n const map: Record<string, { id: string; value: number; normalized: boolean }> = {};\n for (const [id, value] of Object.entries(params)) {\n map[id] = { id, value, normalized: false };\n }\n return map;\n}\n","/**\n * dawcore's built-in `native-*` effects. The registry itself lives in\n * `@waveform-playlist/core` (shared with the React effects hooks); importing\n * this module registers the built-ins there.\n */\nimport {\n getEffectDefinitions,\n registerEffect,\n unregisterEffect,\n type EffectParamDef,\n type NativeEffectDefinition,\n} from '@waveform-playlist/core';\n\nconst MAX_DELAY_SECONDS = 10;\n\n/** Test-only: restore the registry to just the built-ins. */\nexport function _resetEffectRegistryForTests(): void {\n for (const type of getEffectDefinitions().keys()) {\n unregisterEffect(type);\n }\n registerBuiltIns();\n}\n\nfunction singleNode(\n node: AudioNode,\n applyParams: (params: Record<string, number>) => void\n): { input: AudioNode; output: AudioNode; applyParams: (params: Record<string, number>) => void } {\n return { input: node, output: node, applyParams };\n}\n\ntype BiquadParam = 'frequency' | 'q' | 'gain';\n\nconst BIQUAD_PARAM_DEFS: Record<BiquadParam, EffectParamDef> = {\n frequency: { min: 20, max: 20000, step: 1, unit: 'Hz' },\n q: { min: 0.1, max: 20, step: 0.1 },\n gain: { min: -24, max: 24, step: 0.5, unit: 'dB' },\n};\n\n/**\n * Web Audio gives `Q` two meanings. For bandpass, notch and peaking it is\n * the usual linear quality factor. For LOWPASS and HIGHPASS it is the\n * resonance peak in DECIBELS at the cutoff (Q_linear = 10^(Q/20)): 0 dB is a\n * slight bump, about -3 dB is a flat Butterworth response, and a linear-style\n * 0.707 would actually be +0.7 dB of resonance.\n */\nconst RESONANCE_DB_PARAM_DEF: EffectParamDef = { min: -12, max: 24, step: 0.1, unit: 'dB' };\n/** Flat (Butterworth) response: 20·log10(1/√2). */\nconst BUTTERWORTH_RESONANCE_DB = -3;\n\ninterface BiquadFilterSpec {\n label: string;\n biquadType: BiquadFilterType;\n /** Only the params this biquad shape actually uses (the Web Audio spec\n * ignores Q on shelves and gain on everything but peaking/shelves) — a\n * generic parameter panel must not render dead sliders. */\n defaults: Partial<Record<BiquadParam, number>>;\n /** Per-type overrides of the shared param metadata. */\n paramDefs?: Partial<Record<BiquadParam, EffectParamDef>>;\n}\n\n/**\n * One registry type per biquad shape (#661). Effect params are numeric\n * (`Record<string, number>`), so the shape cannot be a param — sibling types\n * fit the model with no API change. `native-filter` keeps its original\n * (lowpass) meaning so persisted chains restore unchanged.\n */\nconst BIQUAD_FILTERS: Record<string, BiquadFilterSpec> = {\n // Unchanged since before #661 — including its q range, which predates the\n // dB reading above (q here is also resonance in dB; persisted chains rely\n // on these exact defaults and bounds).\n 'native-filter': {\n label: 'Lowpass Filter',\n biquadType: 'lowpass',\n defaults: { frequency: 1000, q: 1 },\n },\n 'native-highpass': {\n label: 'Highpass Filter',\n biquadType: 'highpass',\n defaults: { frequency: 80, q: BUTTERWORTH_RESONANCE_DB },\n paramDefs: { q: RESONANCE_DB_PARAM_DEF },\n },\n 'native-bandpass': {\n label: 'Bandpass Filter',\n biquadType: 'bandpass',\n defaults: { frequency: 1000, q: 1 },\n },\n 'native-notch': {\n label: 'Notch Filter',\n biquadType: 'notch',\n defaults: { frequency: 1000, q: 1 },\n },\n 'native-peaking': {\n label: 'Peaking EQ',\n biquadType: 'peaking',\n defaults: { frequency: 1000, q: 1, gain: 0 },\n },\n 'native-lowshelf': {\n label: 'Low Shelf',\n biquadType: 'lowshelf',\n defaults: { frequency: 200, gain: 0 },\n },\n 'native-highshelf': {\n label: 'High Shelf',\n biquadType: 'highshelf',\n defaults: { frequency: 4000, gain: 0 },\n },\n};\n\nfunction biquadDefinition(spec: BiquadFilterSpec): NativeEffectDefinition {\n const names = Object.keys(spec.defaults) as BiquadParam[];\n return {\n label: spec.label,\n category: 'filter',\n defaults: { ...spec.defaults } as Record<string, number>,\n params: Object.fromEntries(\n names.map((name) => [name, spec.paramDefs?.[name] ?? BIQUAD_PARAM_DEFS[name]])\n ),\n create: (ctx) => {\n const node = ctx.createBiquadFilter();\n node.type = spec.biquadType;\n return singleNode(node, (p) => {\n if (names.includes('frequency') && p.frequency !== undefined) {\n node.frequency.value = p.frequency;\n }\n if (names.includes('q') && p.q !== undefined) node.Q.value = p.q;\n if (names.includes('gain') && p.gain !== undefined) node.gain.value = p.gain;\n });\n },\n };\n}\n\n/**\n * Built-ins yield to whatever is already registered under their name: an app\n * may have registered its own `native-gain` through core before this module\n * loaded, and loading the module twice (HMR) must not warn about overwrites.\n */\nfunction registerBuiltIn(type: string, definition: NativeEffectDefinition): void {\n if (!getEffectDefinitions().has(type)) {\n // Marked as this library's catalogue, so other hosts of the shared\n // registry (the React effects hooks) do not list them as app effects.\n registerEffect(type, { ...definition, builtIn: true });\n }\n}\n\nfunction registerBuiltIns(): void {\n registerBuiltIn('native-gain', {\n label: 'Gain',\n category: 'dynamics',\n defaults: { gain: 1 },\n params: { gain: { min: 0, max: 2, step: 0.01 } },\n create: (ctx) => {\n const node = ctx.createGain();\n return singleNode(node, (p) => {\n if (p.gain !== undefined) node.gain.value = p.gain;\n });\n },\n });\n\n for (const [type, definition] of Object.entries(BIQUAD_FILTERS)) {\n registerBuiltIn(type, biquadDefinition(definition));\n }\n\n registerBuiltIn('native-compressor', {\n label: 'Compressor',\n category: 'dynamics',\n defaults: { threshold: -24, knee: 30, ratio: 12, attack: 0.003, release: 0.25 },\n params: {\n threshold: { min: -60, max: 0, step: 1, unit: 'dB' },\n knee: { min: 0, max: 40, step: 1, unit: 'dB' },\n ratio: { min: 1, max: 20, step: 0.5 },\n attack: { min: 0, max: 1, step: 0.001, unit: 's' },\n release: { min: 0, max: 1, step: 0.01, unit: 's' },\n },\n create: (ctx) => {\n const node = ctx.createDynamicsCompressor();\n return singleNode(node, (p) => {\n if (p.threshold !== undefined) node.threshold.value = p.threshold;\n if (p.knee !== undefined) node.knee.value = p.knee;\n if (p.ratio !== undefined) node.ratio.value = p.ratio;\n if (p.attack !== undefined) node.attack.value = p.attack;\n if (p.release !== undefined) node.release.value = p.release;\n });\n },\n });\n\n registerBuiltIn('native-stereo-panner', {\n label: 'Stereo Panner',\n category: 'spatial',\n defaults: { pan: 0 },\n params: { pan: { min: -1, max: 1, step: 0.01 } },\n create: (ctx) => {\n const node = ctx.createStereoPanner();\n return singleNode(node, (p) => {\n if (p.pan !== undefined) node.pan.value = p.pan;\n });\n },\n });\n\n registerBuiltIn('native-delay', {\n label: 'Delay',\n category: 'delay',\n defaults: { delayTime: 0.25, feedback: 0.4, wet: 0.35 },\n params: {\n delayTime: { min: 0, max: MAX_DELAY_SECONDS, step: 0.01, unit: 's' },\n feedback: { min: 0, max: 0.95, step: 0.01 },\n wet: { min: 0, max: 1, step: 0.01 },\n },\n wetParam: 'wet',\n create: (ctx) => {\n const input = ctx.createGain();\n const output = ctx.createGain();\n const delay = ctx.createDelay(MAX_DELAY_SECONDS);\n const feedback = ctx.createGain();\n const wet = ctx.createGain();\n const dry = ctx.createGain();\n\n input.connect(dry);\n dry.connect(output);\n input.connect(delay);\n delay.connect(feedback);\n feedback.connect(delay);\n delay.connect(wet);\n wet.connect(output);\n\n return {\n input,\n output,\n applyParams: (p) => {\n if (p.delayTime !== undefined) delay.delayTime.value = p.delayTime;\n if (p.feedback !== undefined) feedback.gain.value = p.feedback;\n if (p.wet !== undefined) {\n wet.gain.value = p.wet;\n dry.gain.value = 1 - p.wet;\n }\n },\n };\n },\n });\n}\n\nregisterBuiltIns();\n","import { createPanStage, trackPanLaw } from '@waveform-playlist/core';\nimport type { PanLaw } from '@waveform-playlist/core';\nimport {\n createEffectInstance,\n ensureEffectPrepared,\n getEffectDefinitions,\n} from '@waveform-playlist/core';\nimport '../effects/effect-registry'; // registers the native-* built-ins\nimport { loadWamModule, loadFaustModule } from '../effects/optional-modules';\nimport type { SerializedEffectEntry } from '../effects/types';\n\nconst PREFIX = '[waveform-playlist] ';\n\nexport interface ExportOptions {\n /** Default: the host's sample rate. */\n sampleRate?: number;\n /** Window start in seconds. Default: 0. */\n startTime?: number;\n /** Window length in seconds. Default: host duration minus startTime. */\n duration?: number;\n /** Default: 2 (stereo). */\n channels?: 1 | 2;\n}\n\ninterface ExportClip {\n startSample: number;\n durationSamples: number;\n offsetSamples: number;\n sampleRate: number;\n gain?: number;\n audioBuffer?: AudioBuffer;\n}\n\ninterface ExportTrack {\n id: string;\n volume: number;\n pan: number;\n /** The track's pan law (the arrangement's mixer value). `'auto'` or none: from its clips. */\n panLaw?: PanLaw;\n muted: boolean;\n soloed: boolean;\n clips: ExportClip[];\n}\n\n/** What the editor provides to the export pipeline. */\nexport interface ExportAudioHost {\n effectiveSampleRate: number;\n /** Natural session duration in seconds. */\n duration: number;\n tracks: ExportTrack[];\n /** Master output gain (engine setMasterVolume). Default 1. Without it the\n * export renders louder/quieter than what the user mixed against. */\n masterVolume?: number;\n getMasterEffectsState(): Promise<SerializedEffectEntry[]>;\n getTrackEffectsState(trackId: string): Promise<SerializedEffectEntry[]>;\n}\n\ninterface OfflineChain {\n input: AudioNode;\n output: AudioNode;\n dispose: () => void;\n}\n\n/**\n * Render the session offline through all effect chains (per-track + master).\n *\n * No Transport involved: clips are known upfront, so sources are scheduled\n * statically on an OfflineAudioContext. Effect chains rebuild from their\n * persisted form (#424) — natives via the registry (definitions take\n * BaseAudioContext for exactly this; a definition's async `prepare` hook is\n * awaited on the offline context first), WAM plugins re-instantiated on the\n * offline context with their saved state (worklets are context-bound, the\n * wam-studio cloneInto pattern). All offline plugin instances are destroyed\n * after rendering, success or failure.\n *\n * Parity note: clip fades are not rendered — the native ClipPlayer does not\n * apply them during playback either.\n */\nexport async function exportAudioImpl(\n host: ExportAudioHost,\n options: ExportOptions = {}\n): Promise<AudioBuffer> {\n const sampleRate = options.sampleRate ?? host.effectiveSampleRate;\n const startTime = options.startTime ?? 0;\n const duration = options.duration ?? Math.max(0, host.duration - startTime);\n const channels = options.channels ?? 2;\n if (!Number.isFinite(sampleRate) || sampleRate <= 0) {\n throw new Error(PREFIX + 'exportAudio: invalid sampleRate ' + String(sampleRate));\n }\n if (!Number.isFinite(duration) || duration <= 0) {\n throw new Error(PREFIX + 'exportAudio: nothing to render (duration ' + String(duration) + ')');\n }\n\n const ctx = new OfflineAudioContext({\n numberOfChannels: channels,\n length: Math.round(duration * sampleRate),\n sampleRate,\n });\n\n const cleanups: Array<() => void> = [];\n try {\n const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());\n cleanups.push(masterChain.dispose);\n // Master volume stage BEFORE the master chain — parity with live\n // playback, where MasterNode's gain feeds connectMasterOutput → chain.\n // Order matters for nonlinear master effects (compressor, distortion):\n // volume→chain and chain→volume compress differently.\n const masterVolume = ctx.createGain();\n masterVolume.gain.value = host.masterVolume ?? 1;\n masterVolume.connect(masterChain.input);\n masterChain.output.connect(ctx.destination);\n\n const anySoloed = host.tracks.some((t) => t.soloed);\n for (const track of host.tracks) {\n if (track.muted || (anySoloed && !track.soloed)) {\n continue;\n }\n const chain = await buildOfflineChain(ctx, await host.getTrackEffectsState(track.id));\n cleanups.push(chain.dispose);\n\n // Live track order (TrackNode, #660): clips → effects → volume → pan.\n // The chain is a PRE-FADER insert — it sees the clips' own level and\n // channel layout, so the fader and pan never change how hard a\n // compressor works. Order matters for every nonlinear effect.\n const volume = ctx.createGain();\n volume.gain.value = track.volume;\n // Same pan stage as live (#669): the law is the track's own (#684),\n // not whatever layout the effects chain outputs.\n const panStage = createPanStage(ctx, track.pan, trackPanLaw(track));\n cleanups.push(panStage.dispose);\n chain.output.connect(volume);\n volume.connect(panStage.input);\n panStage.output.connect(masterVolume);\n\n for (const clip of track.clips) {\n scheduleClip(ctx, clip, startTime, duration, chain.input);\n }\n }\n\n return await ctx.startRendering();\n } finally {\n for (const dispose of cleanups) {\n try {\n dispose();\n } catch (err) {\n console.warn(PREFIX + 'exportAudio: cleanup error: ' + String(err));\n }\n }\n }\n}\n\n/** Schedule one clip's source into the render window, clamping at both edges. */\nfunction scheduleClip(\n ctx: OfflineAudioContext,\n clip: ExportClip,\n windowStart: number,\n windowDuration: number,\n destination: AudioNode\n): void {\n if (!clip.audioBuffer || clip.durationSamples <= 0) {\n return;\n }\n const clipRate = clip.sampleRate;\n const clipStart = clip.startSample / clipRate;\n const clipDuration = clip.durationSamples / clipRate;\n let offset = clip.offsetSamples / clipRate;\n\n let when = clipStart - windowStart;\n let remaining = clipDuration;\n if (when < 0) {\n // Window begins mid-clip: start immediately, further into the file.\n offset += -when;\n remaining += when;\n when = 0;\n }\n remaining = Math.min(remaining, windowDuration - when);\n if (remaining <= 0) {\n return;\n }\n\n const source = ctx.createBufferSource();\n source.buffer = clip.audioBuffer;\n let out: AudioNode = source;\n if (clip.gain !== undefined && clip.gain !== 1) {\n const gainNode = ctx.createGain();\n gainNode.gain.value = clip.gain;\n out.connect(gainNode);\n out = gainNode;\n }\n out.connect(destination);\n source.start(when, offset, remaining);\n}\n\n/**\n * Rebuild a persisted effects chain on the offline context.\n * Bypass parity with live playback: wet-style entries are created with their\n * wet zeroed; disconnect-style entries (including bypassed WAM plugins and\n * placeholders) are skipped from the series entirely.\n */\nasync function buildOfflineChain(\n ctx: OfflineAudioContext,\n entries: SerializedEffectEntry[]\n): Promise<OfflineChain> {\n const input = ctx.createGain();\n const output = ctx.createGain();\n const cleanups: Array<() => void> = [];\n const dispose = (): void => {\n for (const cleanup of cleanups) {\n try {\n cleanup();\n } catch (err) {\n console.warn(PREFIX + 'exportAudio: chain cleanup error: ' + String(err));\n }\n }\n };\n let previous: AudioNode = input;\n\n try {\n await wireEntries();\n } catch (err) {\n // A failure partway through must not leak the plugin worklets already\n // created for this chain — the caller never gets a dispose handle for a\n // chain that threw.\n dispose();\n throw err;\n }\n\n previous.connect(output);\n return { input, output, dispose };\n\n async function wireEntries(): Promise<void> {\n for (const entry of entries) {\n // Failed-plugin placeholders (any kind) are silent passthroughs live —\n // skip them here too, regardless of their SAVED bypassed flag.\n // Instantiating would either fail the export (dead URL / unregistered\n // type) or render an effect absent from live playback. Warn: the only\n // other evidence the effect is missing is a daw-effect-error that\n // fired back at restore time.\n if (entry.placeholder) {\n console.warn(\n PREFIX +\n 'exportAudio: skipping failed-plugin placeholder \"' +\n (entry.kind === 'native' ? entry.type : (entry.url ?? 'Faust effect')) +\n '\"'\n );\n continue;\n }\n if (entry.kind === 'native') {\n // Disconnect-style bypass (no wet param): the effect is out of the\n // series, exactly as live — so do not prepare or create it. A\n // bypassed worklet effect whose module fails to load must not fail\n // an export it takes no part in. (Unknown types fall through to\n // createEffectInstance, which reports them.)\n const definition = getEffectDefinitions().get(entry.type);\n if (entry.bypassed && definition && !definition.wetParam) {\n continue;\n }\n // Async per-context setup (#657) — e.g. an AudioWorklet module must be\n // added to THIS offline context, which only the export ever holds.\n // Shared across chains: one run per type per export.\n await ensureEffectPrepared(entry.type, ctx);\n const created = createEffectInstance(entry.type, ctx, entry.params);\n if (entry.bypassed && created.wetParam) {\n created.instance.applyParams({ [created.wetParam]: 0 });\n }\n if (created.instance.dispose) {\n cleanups.push(created.instance.dispose);\n }\n previous.connect(created.instance.input);\n previous = created.instance.output;\n continue;\n }\n\n // kind 'wam'\n if (entry.bypassed) {\n continue; // disconnection bypass\n }\n const wamModule = await loadWamModule('exportAudio() with WAM effects');\n const { hostGroupId } = await wamModule.ensureWamHost(ctx);\n let plugin: import('@dawcore/wam').WamPluginInstance;\n if (entry.faustDsp !== undefined) {\n // Faust entries have no URL — recompile the persisted DSP source on\n // demand (worklets are context-bound, so the realtime instance can't\n // be reused; the compiled factory path mirrors setEffectsState).\n const faustModule = await loadFaustModule('exportAudio() with Faust effects');\n const compiled = await faustModule.compileFaustToWam(entry.faustDsp, {\n name: entry.faustName,\n });\n plugin = await wamModule.createWamInstanceFromFactory(\n compiled.factory as import('@dawcore/wam').WamFactory,\n ctx,\n hostGroupId,\n { initialState: entry.state, label: compiled.name }\n );\n } else {\n plugin = await wamModule.createWamInstance(entry.url ?? '', ctx, hostGroupId, {\n initialState: entry.state,\n });\n }\n cleanups.push(() => plugin.destroy());\n previous.connect(plugin.audioNode);\n previous = plugin.audioNode;\n }\n }\n}\n","/**\n * Load pre-computed waveform data from a .dat or .json file (BBC audiowaveform format).\n */\n\nimport WaveformData from 'waveform-data';\n\n/**\n * Fetch and parse a waveform data file (.dat binary or .json). An aborted\n * `signal` rejects with its reason (an `AbortError`), as `fetch()` does.\n */\nexport async function loadWaveformDataFromUrl(\n src: string,\n signal?: AbortSignal\n): Promise<WaveformData> {\n const response = await fetch(src, signal ? { signal } : undefined);\n\n if (!response.ok) {\n throw new Error('[dawcore] Failed to fetch peaks 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","import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\n// Line scrolling uses 16px per line (standard line height).\nconst LINE_HEIGHT_PX = 16;\n\n/**\n * Frozen-panes scroll sync. The editor's `.scroll-area` owns both scroll\n * axes; this controller keeps the ruler band (x) and controls column (y)\n * visually locked to it by applying translate3d transforms on EVERY scroll\n * event. (ViewportController's 100px threshold exists for chunk\n * virtualization and is too coarse for visual sync.)\n *\n * Also forwards wheel events from ALL elements matched by `wheelForwardSelector`\n * to the scroll container for both axes:\n * - Horizontal scrub (deltaX) — ruler band stays in sync when the user\n * scrolls the timeline left/right while hovering the ruler.\n * - Vertical scroll (deltaY) — controls column lets the user scroll track\n * rows while hovering the track controls.\n *\n * preventDefault fires only when at least one axis actually moved, so page\n * scrolling is unaffected for unconstrained editors and boundary scrolling\n * chains properly.\n */\nexport class ScrollSyncController implements ReactiveController {\n private _host: ReactiveControllerHost & HTMLElement;\n private _scrollContainer: HTMLElement | null = null;\n /** The scroll listener on `_scrollContainer`, aborted when it is replaced or detached. */\n private _scrollListener: AbortController | null = null;\n /** Each wheel target and the controller of its listener. */\n private _wheelTargets = new Map<HTMLElement, AbortController>();\n private _warnedX = false;\n private _warnedY = false;\n\n /** Selector (in host shadow DOM) for the scroll container. */\n scrollSelector = '';\n /** Selector for the element receiving translate3d(-scrollLeft, 0, 0). */\n xTargetSelector = '';\n /** Selector for the element receiving translate3d(0, -scrollTop, 0). */\n yTargetSelector = '';\n /**\n * Selector (or comma-separated selectors) for elements whose wheel events\n * forward to the scroll container. All matching elements receive listeners.\n */\n wheelForwardSelector = '';\n\n constructor(host: ReactiveControllerHost & HTMLElement) {\n this._host = host;\n host.addController(this);\n }\n\n hostConnected() {\n // Defer so the Shadow DOM renders before querying (same pattern as\n // ViewportController).\n requestAnimationFrame(() => {\n if (!this._host.isConnected) return;\n this._attach();\n if (!this._scrollContainer && this.scrollSelector) {\n console.warn(\n '[dawcore] ScrollSyncController: scroll container not found for \"' +\n this.scrollSelector +\n '\"'\n );\n }\n });\n }\n\n hostDisconnected() {\n this._detachAll();\n }\n\n /** Remove the scroll and every wheel listener. */\n private _detachAll() {\n this._scrollListener?.abort();\n this._scrollListener = null;\n this._scrollContainer = null;\n for (const listener of this._wheelTargets.values()) listener.abort();\n this._wheelTargets.clear();\n }\n\n /**\n * Re-attach and re-apply transforms from the current scroll position.\n * Called from the host's updated() so elements created by a re-render\n * (e.g. the ruler appearing when the first track loads) pick up the\n * current offset and listeners.\n */\n sync() {\n this._attach();\n }\n\n private _query(selector: string): HTMLElement | null {\n return selector ? (this._host.shadowRoot?.querySelector(selector) as HTMLElement | null) : null;\n }\n\n private _queryAll(selector: string): HTMLElement[] {\n if (!selector) return [];\n return Array.from(this._host.shadowRoot?.querySelectorAll(selector) ?? []) as HTMLElement[];\n }\n\n private _attach() {\n const container = this._query(this.scrollSelector);\n if (!container) {\n if (this._scrollContainer && !this._scrollContainer.isConnected) {\n console.warn(\n '[dawcore] ScrollSyncController: scroll container \"' +\n this.scrollSelector +\n '\" was removed from the DOM — detaching listeners until it reappears.'\n );\n this._detachAll();\n }\n return;\n }\n if (container !== this._scrollContainer) {\n this._scrollListener?.abort();\n this._scrollContainer = container;\n this._scrollListener = new AbortController();\n container.addEventListener('scroll', this._onScroll, {\n passive: true,\n signal: this._scrollListener.signal,\n });\n }\n\n // Diff the current set of matched wheel targets.\n const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));\n for (const [old, listener] of [...this._wheelTargets]) {\n if (!nextTargets.has(old)) {\n listener.abort();\n this._wheelTargets.delete(old);\n }\n }\n for (const next of nextTargets) {\n if (!this._wheelTargets.has(next)) {\n const listener = new AbortController();\n next.addEventListener('wheel', this._onWheel, { passive: false, signal: listener.signal });\n this._wheelTargets.set(next, listener);\n }\n }\n\n this._apply();\n }\n\n private _onScroll = () => {\n this._apply();\n };\n\n private _onWheel = (e: WheelEvent) => {\n const sc = this._scrollContainer;\n if (!sc) return;\n\n const scale =\n e.deltaMode === WheelEvent.DOM_DELTA_LINE\n ? LINE_HEIGHT_PX\n : e.deltaMode === WheelEvent.DOM_DELTA_PAGE\n ? sc.clientHeight // used for Y; X uses clientWidth below\n : 1;\n\n const scaleX = e.deltaMode === WheelEvent.DOM_DELTA_PAGE ? sc.clientWidth : scale;\n\n const beforeLeft = sc.scrollLeft;\n const beforeTop = sc.scrollTop;\n\n sc.scrollLeft += e.deltaX * scaleX;\n sc.scrollTop += e.deltaY * scale;\n\n if (sc.scrollLeft !== beforeLeft || sc.scrollTop !== beforeTop) {\n e.preventDefault();\n }\n };\n\n private _apply() {\n const sc = this._scrollContainer;\n if (!sc) return;\n // Re-query targets each time: Lit conditional templates create/replace\n // these elements between renders (e.g. the header row appears with the\n // first loaded track).\n const xTarget = this._query(this.xTargetSelector);\n if (xTarget) {\n xTarget.style.transform = `translate3d(${-sc.scrollLeft}px, 0, 0)`;\n this._warnedX = false;\n } else if (this.xTargetSelector && sc.scrollLeft !== 0 && !this._warnedX) {\n this._warnedX = true;\n console.warn(\n '[dawcore] ScrollSyncController: x target \"' +\n this.xTargetSelector +\n '\" not found while scrolled — the synced pane will appear frozen. Check the selector, or clear it if the target is intentionally not rendered.'\n );\n }\n const yTarget = this._query(this.yTargetSelector);\n if (yTarget) {\n yTarget.style.transform = `translate3d(0, ${-sc.scrollTop}px, 0)`;\n this._warnedY = false;\n } else if (this.yTargetSelector && sc.scrollTop !== 0 && !this._warnedY) {\n this._warnedY = true;\n console.warn(\n '[dawcore] ScrollSyncController: y target \"' +\n this.yTargetSelector +\n '\" not found while scrolled — the synced pane will appear frozen. Check the selector, or clear it if the target is intentionally not rendered.'\n );\n }\n }\n}\n","import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\nexport class AnimationController implements ReactiveController {\n private _rafId: number | null = null;\n private _callback: (() => void) | null = null;\n\n constructor(host: ReactiveControllerHost) {\n host.addController(this);\n }\n\n start(callback: () => void) {\n this.stop();\n this._callback = callback;\n const loop = () => {\n this._callback?.();\n // The callback may have called stop() (e.g. the editor's end-of-\n // timeline auto-stop fires from inside a frame). Rescheduling then\n // would leave a zombie loop burning frames with a null callback.\n if (this._callback !== null) {\n this._rafId = requestAnimationFrame(loop);\n }\n };\n this._rafId = requestAnimationFrame(loop);\n }\n\n stop() {\n if (this._rafId !== null) {\n cancelAnimationFrame(this._rafId);\n this._rafId = null;\n }\n this._callback = null;\n }\n\n hostConnected() {}\n\n hostDisconnected() {\n this.stop();\n }\n}\n","import type { ReactiveControllerHost } from 'lit';\nimport { AnimationController } from './animation-controller';\nimport type { DawTimeUpdateDetail } from '../events';\n\nexport interface PlayheadLike {\n setPosition(px: number): void;\n}\n\nexport interface PlaybackAnimationOptions {\n /** Convert playback seconds to a timeline pixel offset. */\n timeToPixels: (time: number) => number;\n /** Resolve the playhead element (re-queried per call — templates may recreate it). */\n getPlayhead: () => PlayheadLike | null;\n}\n\n/**\n * The single editor-owned playback animation loop (mirror of the React\n * `usePlaybackAnimation` pattern). Each frame reads the latency-compensated\n * playback time ONCE, positions the playhead, and dispatches `daw-timeupdate`\n * from the host element. External consumers hook into the same loop by\n * listening for `daw-timeupdate` — never add a second RAF loop for\n * playback-time concerns.\n *\n * `timeToPixels` and `getPlayhead` are injected once at construction — they\n * are stable per host, and threading them through every `start`/`stop` call\n * invited desync between the two call sites.\n *\n * HTMLMediaElement-adjacent: `stop()` dispatches one final event so idle\n * displays settle on the exact commanded position (media elements fire\n * `timeupdate` on pause and seek too). Pass `{ dispatch: false }` for\n * transitional stops (stop+play seeks) whose settle position must not leak\n * to consumers.\n */\nexport class PlaybackAnimationController {\n private _animation: AnimationController;\n private _host: ReactiveControllerHost & HTMLElement;\n private _options: PlaybackAnimationOptions;\n private _running = false;\n private _lastDispatchedTime: number | null = null;\n\n constructor(host: ReactiveControllerHost & HTMLElement, options: PlaybackAnimationOptions) {\n this._host = host;\n this._options = options;\n this._animation = new AnimationController(host);\n }\n\n start(getTime: () => number): void {\n this._running = true;\n this._animation.start(() => {\n const time = getTime();\n // getTime() (the editor's frame callback) can call this.stop() mid-\n // frame on auto-stop paths (end-of-timeline, bounded play(start, end)\n // annotation playback) — stop() already dispatched its own settle\n // daw-timeupdate synchronously before returning here. Skip this\n // frame's position/dispatch entirely so that settle event isn't\n // immediately followed by a stale trailing one (which would, e.g.,\n // re-set an annotation's \"playing\" highlight that daw-stop just\n // cleared). Manual stop/seek settle events are unaffected — they\n // dispatch from stop() itself, never from this wrapper.\n if (!this._running) return;\n this._options.getPlayhead()?.setPosition(this._options.timeToPixels(time));\n this._dispatchTimeUpdate(time);\n });\n }\n\n stop(finalTime: number, opts?: { dispatch?: boolean }): void {\n // The editor's stop path reaches here twice (the engine 'stop' handler\n // registered in _buildEngine AND editor.stop() both call _stopPlayhead).\n // Dedupe: dispatch only when the loop was actually running or the settled\n // time changed (seek-while-stopped must still fire its event).\n const wasRunning = this._running;\n this._running = false;\n this._animation.stop();\n this._options.getPlayhead()?.setPosition(this._options.timeToPixels(finalTime));\n // dispatch === false: transitional stop (seek-while-playing) — stop the\n // loop and position the playhead, but don't leak the settle time to\n // consumers; _lastDispatchedTime stays untouched so the dedupe logic\n // still reflects the last event consumers actually saw.\n if (opts?.dispatch === false) return;\n if (wasRunning || finalTime !== this._lastDispatchedTime) {\n this._dispatchTimeUpdate(finalTime);\n }\n }\n\n private _dispatchTimeUpdate(time: number): void {\n this._lastDispatchedTime = time;\n this._host.dispatchEvent(\n new CustomEvent<DawTimeUpdateDetail>('daw-timeupdate', {\n bubbles: true,\n composed: true,\n detail: { time },\n })\n );\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\n\n@customElement('daw-selection')\nexport class DawSelectionElement extends LitElement {\n @property({ type: Number, attribute: false }) startPx = 0;\n @property({ type: Number, attribute: false }) endPx = 0;\n\n static styles = css`\n :host {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n pointer-events: none;\n z-index: 5;\n }\n div {\n position: absolute;\n top: 0;\n bottom: 0;\n background: var(--daw-selection-color, rgba(99, 199, 95, 0.3));\n }\n `;\n\n render() {\n const left = Math.min(this.startPx, this.endPx);\n const width = Math.abs(this.endPx - this.startPx);\n if (width === 0) return html``;\n return html`<div style=\"left: ${left}px; width: ${width}px;\"></div>`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-selection': DawSelectionElement;\n }\n}\n","import { html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { DawTransportButton } from './daw-transport-button';\nimport { warnNoTargetOnce } from '../utils/transport-capability';\n\n@customElement('daw-record-button')\nexport class DawRecordButtonElement extends DawTransportButton {\n protected static override requiredTargetMethods: readonly string[] = [\n 'startRecording',\n 'stopRecording',\n ];\n\n @state() private _isRecording = false;\n private _targetRef: HTMLElement | null = null;\n /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */\n private _targetListeners: AbortController | null = null;\n private _onStart = () => {\n this._isRecording = true;\n };\n private _onComplete = () => {\n this._isRecording = false;\n };\n private _onError = () => {\n this._isRecording = false;\n };\n\n static override styles = [\n DawTransportButton.styles,\n css`\n button[data-recording] {\n color: #d08070;\n border-color: #d08070;\n background: rgba(208, 128, 112, 0.15);\n }\n `,\n ];\n\n connectedCallback() {\n super.connectedCallback();\n // Defer so <daw-transport for=\"...\"> and the target editor are resolved\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n this._ensureTargetListeners();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._cleanupListeners();\n }\n\n protected override updated() {\n // Re-resolve on every render (pointerenter triggers one via the base\n // class) — a target that upgrades/appears after the one-shot\n // connectedCallback rAF would otherwise never get the recording-state\n // listeners: the button starts recordings it can't reflect (#573).\n this._ensureTargetListeners();\n }\n\n private _ensureTargetListeners() {\n const target = this.target;\n if (target === this._targetRef) return;\n this._cleanupListeners();\n if (!target) return;\n this._targetRef = target;\n this._targetListeners = new AbortController();\n const { signal } = this._targetListeners;\n target.addEventListener('daw-recording-start', this._onStart, { signal });\n target.addEventListener('daw-recording-complete', this._onComplete, { signal });\n target.addEventListener('daw-recording-error', this._onError, { signal });\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetListeners?.abort();\n this._targetListeners = null;\n this._targetRef = null;\n }\n }\n\n render() {\n return html`\n <button\n part=\"button\"\n ?disabled=${!this.targetSupported}\n ?data-recording=${this._isRecording}\n @click=${this._onClick}\n >\n <slot>Record</slot>\n </button>\n `;\n }\n\n private _onClick() {\n // Start-only — stop is handled by the stop button\n if (this._isRecording) return;\n const target = this.target;\n // Stale-render race guard: the target can vanish between render and click.\n if (!target) {\n warnNoTargetOnce(this);\n return;\n }\n // Guarantee state listeners exist for any recording this button starts\n // (covers programmatic clicks that never trigger a re-render).\n this._ensureTargetListeners();\n target.startRecording(target.recordingStream);\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-record-button': DawRecordButtonElement;\n }\n}\n","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { handleKeyboardEvent } from '@waveform-playlist/core';\nimport type { KeyBinding, KeyboardShortcut } from '@waveform-playlist/core';\nimport type { DawEditorElement } from './daw-editor';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PlaybackShortcutMap {\n playPause?: KeyBinding;\n stop?: KeyBinding;\n rewindToStart?: KeyBinding;\n}\n\nexport interface SplittingShortcutMap {\n splitAtPlayhead?: KeyBinding;\n}\n\nexport interface UndoShortcutMap {\n undo?: KeyBinding;\n redo?: KeyBinding;\n}\n\n// ---------------------------------------------------------------------------\n// Element\n// ---------------------------------------------------------------------------\n\n/**\n * Render-less element that enables keyboard shortcuts for a parent <daw-editor>.\n * Place inside the editor element. Boolean attributes enable preset categories;\n * JS properties allow remapping and custom shortcuts.\n *\n * ```html\n * <daw-editor>\n * <daw-keyboard-shortcuts playback splitting undo></daw-keyboard-shortcuts>\n * </daw-editor>\n * ```\n */\n@customElement('daw-keyboard-shortcuts')\nexport class DawKeyboardShortcutsElement extends LitElement {\n // --- Preset attributes ---\n @property({ type: Boolean }) playback = false;\n @property({ type: Boolean }) splitting = false;\n @property({ type: Boolean }) undo = false;\n\n // --- JS properties for remapping ---\n // Accessors, not plain fields: assigning a remap after any keydown has\n // warmed _cachedShortcuts must invalidate it, or the documented remapping\n // API is silently ignored until an unrelated boolean attribute toggles.\n // (connectedCallback runs the standard upgrade-property dance so values\n // assigned BEFORE the element was defined don't shadow these accessors.)\n private _playbackShortcuts: PlaybackShortcutMap | null = null;\n get playbackShortcuts(): PlaybackShortcutMap | null {\n return this._playbackShortcuts;\n }\n set playbackShortcuts(value: PlaybackShortcutMap | null) {\n this._playbackShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n private _splittingShortcuts: SplittingShortcutMap | null = null;\n get splittingShortcuts(): SplittingShortcutMap | null {\n return this._splittingShortcuts;\n }\n set splittingShortcuts(value: SplittingShortcutMap | null) {\n this._splittingShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n private _undoShortcuts: UndoShortcutMap | null = null;\n get undoShortcuts(): UndoShortcutMap | null {\n return this._undoShortcuts;\n }\n set undoShortcuts(value: UndoShortcutMap | null) {\n this._undoShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n /** Additional custom shortcuts. */\n private _customShortcuts: KeyboardShortcut[] = [];\n get customShortcuts(): KeyboardShortcut[] {\n return this._customShortcuts;\n }\n set customShortcuts(value: KeyboardShortcut[]) {\n this._customShortcuts = value;\n this._cachedShortcuts = null;\n }\n\n private _editor: DawEditorElement | null = null;\n private _cachedShortcuts: KeyboardShortcut[] | null = null;\n\n /** All active shortcuts (read-only, cached). */\n get shortcuts(): KeyboardShortcut[] {\n if (!this._cachedShortcuts) {\n this._cachedShortcuts = this._buildShortcuts();\n }\n return this._cachedShortcuts;\n }\n\n /** Invalidate cached shortcuts when Lit properties change. */\n override updated(): void {\n this._cachedShortcuts = null;\n }\n\n // --- Lifecycle ---\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n override connectedCallback(): void {\n super.connectedCallback();\n // Upgrade-property dance: a remap assigned BEFORE this element was\n // defined created an own property that shadows the accessors above —\n // delete it and re-assign through the setter so cache invalidation works.\n for (const prop of [\n 'playbackShortcuts',\n 'splittingShortcuts',\n 'undoShortcuts',\n 'customShortcuts',\n ] as const) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete (this as Record<string, unknown>)[prop];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any)[prop] = value;\n }\n }\n this._editor = this.closest('daw-editor') as DawEditorElement | null;\n if (!this._editor) {\n console.warn(\n '[dawcore] <daw-keyboard-shortcuts> must be placed inside a <daw-editor>. ' +\n 'Preset shortcuts (playback, splitting, undo) will be inactive; only customShortcuts will fire.'\n );\n }\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('keydown', this._onKeyDown, { signal });\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n this._editor = null;\n }\n\n // No shadow DOM — render-less element\n override createRenderRoot(): this {\n return this;\n }\n\n // --- Shortcut building ---\n\n private _buildShortcuts(): KeyboardShortcut[] {\n const editor = this._editor;\n if (!editor) return this.customShortcuts;\n\n const result: KeyboardShortcut[] = [];\n\n if (this.playback) {\n const map = this.playbackShortcuts;\n // Explicit ctrlKey/metaKey: false prevents Cmd+Space (Spotlight on Mac)\n // and Ctrl+0 etc. from triggering playback shortcuts.\n result.push(\n this._makeShortcut(\n map?.playPause ?? { key: ' ', ctrlKey: false, metaKey: false },\n () => editor.togglePlayPause(),\n 'Play/Pause'\n ),\n this._makeShortcut(\n map?.stop ?? { key: 'Escape', ctrlKey: false, metaKey: false },\n () => editor.stop(),\n 'Stop'\n ),\n this._makeShortcut(\n map?.rewindToStart ?? { key: '0', ctrlKey: false, metaKey: false },\n () => editor.seekTo(0),\n 'Rewind to start'\n )\n );\n }\n\n if (this.splitting) {\n const map = this.splittingShortcuts;\n const binding = map?.splitAtPlayhead ?? {\n key: 's',\n ctrlKey: false,\n metaKey: false,\n altKey: false,\n };\n result.push(this._makeShortcut(binding, () => editor.splitAtPlayhead(), 'Split at playhead'));\n }\n\n if (this.undo) {\n const map = this.undoShortcuts;\n const undoBinding = map?.undo ?? { key: 'z' };\n const redoBinding = map?.redo ?? { key: 'z', shiftKey: true };\n\n // Undo: Ctrl+Z (Win/Linux) and Cmd+Z (Mac)\n // Use === undefined to distinguish \"not specified\" (auto-expand) from\n // \"explicitly false\" (user wants no modifier — respect their intent).\n if (undoBinding.ctrlKey === undefined && undoBinding.metaKey === undefined) {\n // Only set shiftKey: false when user didn't provide a value\n const undoShift = undoBinding.shiftKey === undefined ? { shiftKey: false } : {};\n result.push(\n this._makeShortcut(\n { ...undoBinding, ctrlKey: true, ...undoShift },\n () => editor.undo(),\n 'Undo'\n ),\n this._makeShortcut(\n { ...undoBinding, metaKey: true, ...undoShift },\n () => editor.undo(),\n 'Undo'\n )\n );\n } else {\n result.push(this._makeShortcut(undoBinding, () => editor.undo(), 'Undo'));\n }\n\n // Redo: Ctrl+Shift+Z (Win/Linux) and Cmd+Shift+Z (Mac)\n if (redoBinding.ctrlKey === undefined && redoBinding.metaKey === undefined) {\n const redoShift = redoBinding.shiftKey === undefined ? { shiftKey: true } : {};\n result.push(\n this._makeShortcut(\n { ...redoBinding, ctrlKey: true, ...redoShift },\n () => editor.redo(),\n 'Redo'\n ),\n this._makeShortcut(\n { ...redoBinding, metaKey: true, ...redoShift },\n () => editor.redo(),\n 'Redo'\n )\n );\n } else {\n result.push(this._makeShortcut(redoBinding, () => editor.redo(), 'Redo'));\n }\n }\n\n result.push(...this.customShortcuts);\n return result;\n }\n\n private _makeShortcut(\n binding: KeyBinding,\n action: () => void,\n description: string\n ): KeyboardShortcut {\n return {\n key: binding.key,\n ...(binding.ctrlKey !== undefined && { ctrlKey: binding.ctrlKey }),\n ...(binding.shiftKey !== undefined && { shiftKey: binding.shiftKey }),\n ...(binding.metaKey !== undefined && { metaKey: binding.metaKey }),\n ...(binding.altKey !== undefined && { altKey: binding.altKey }),\n action,\n description,\n };\n }\n\n // --- Event handler ---\n\n private _onKeyDown = (e: KeyboardEvent) => {\n const shortcuts = this.shortcuts;\n if (shortcuts.length === 0) return;\n try {\n handleKeyboardEvent(e, shortcuts, true);\n } catch (err) {\n console.warn('[dawcore] Keyboard shortcut failed (key=' + e.key + '): ' + String(err));\n const target = this._editor ?? this;\n target.dispatchEvent(\n new CustomEvent('daw-error', {\n bubbles: true,\n composed: true,\n detail: { operation: 'keyboard-shortcut', key: e.key, error: err },\n })\n );\n }\n };\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-keyboard-shortcuts': DawKeyboardShortcutsElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\n// The orchestrator's clip-relative sample math assumes chunk k starts at\n// clip pixel k * MAX_CANVAS_WIDTH — the constant must be the shared one,\n// not a local copy that can drift (#554 layout contract).\nimport { MAX_CANVAS_WIDTH, buildSpectrogramCanvasId } from '@waveform-playlist/core';\n\ninterface SpectrogramHost extends HTMLElement {\n _spectrogramRegisterCanvas?: (reg: {\n canvasId: string;\n canvas: OffscreenCanvas;\n clipId: string;\n trackId: string;\n channelIndex: number;\n chunkIndex: number;\n globalPixelOffset: number;\n widthPx: number;\n heightPx: number;\n }) => void;\n _spectrogramUnregisterCanvas?: (canvasId: string) => void;\n}\n\n@customElement('daw-spectrogram')\nexport class DawSpectrogramElement extends LitElement {\n @property({ attribute: false }) clipId = '';\n @property({ attribute: false }) trackId = '';\n @property({ type: Number, attribute: false }) channelIndex = 0;\n @property({ type: Number, attribute: false }) length = 0;\n @property({ type: Number, attribute: false }) waveHeight = 128;\n\n @property({ type: Number, attribute: false, noAccessor: true })\n get samplesPerPixel(): number {\n return this._samplesPerPixel;\n }\n set samplesPerPixel(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-spectrogram samplesPerPixel ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._samplesPerPixel;\n this._samplesPerPixel = value;\n this.requestUpdate('samplesPerPixel', old);\n }\n private _samplesPerPixel = 1024;\n\n @property({ type: Number, attribute: false, noAccessor: true })\n get sampleRate(): number {\n return this._sampleRate;\n }\n set sampleRate(value: number) {\n if (!Number.isFinite(value) || value <= 0) {\n console.warn('[dawcore] daw-spectrogram sampleRate ' + value + ' is invalid — ignored');\n return;\n }\n const old = this._sampleRate;\n this._sampleRate = value;\n this.requestUpdate('sampleRate', old);\n }\n private _sampleRate = 44100;\n\n @property({ type: Number, attribute: false }) clipOffsetSeconds = 0;\n @property({ type: Number, attribute: false }) visibleStart = -Infinity;\n @property({ type: Number, attribute: false }) visibleEnd = Infinity;\n @property({ type: Number, attribute: false }) originX = 0;\n\n static styles = css`\n :host {\n display: block;\n position: relative;\n background: var(--daw-spectrogram-background, #000);\n }\n canvas {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n pointer-events: none;\n }\n `;\n\n private _canvases: HTMLCanvasElement[] = [];\n private _registeredCanvasIds: string[] = [];\n private _warnedNoHost = false;\n\n /**\n * Walk up to the editor host. `closest('daw-editor')` does NOT cross\n * shadow boundaries — and this element lives inside the editor's shadow\n * DOM — so use getRootNode().host to step out.\n */\n private _findHostEditor(): SpectrogramHost | null {\n const root = this.getRootNode();\n const host = root instanceof ShadowRoot ? root.host : null;\n if (!host) return null;\n if (host.tagName === 'DAW-EDITOR') return host as SpectrogramHost;\n return host.closest('daw-editor') as SpectrogramHost | null;\n }\n\n willUpdate(changed: PropertyValues): void {\n const layoutChanged =\n changed.has('length') ||\n changed.has('waveHeight') ||\n changed.has('samplesPerPixel') ||\n changed.has('clipId') ||\n changed.has('channelIndex');\n if (layoutChanged) {\n this._rebuildChunks();\n }\n }\n\n private _rebuildChunks(): void {\n this._unregisterAllCanvases();\n this._canvases = [];\n\n if (this.length <= 0) return;\n\n const chunkCount = Math.ceil(this.length / MAX_CANVAS_WIDTH);\n for (let i = 0; i < chunkCount; i++) {\n const widthPx = Math.min(MAX_CANVAS_WIDTH, this.length - i * MAX_CANVAS_WIDTH);\n const canvas = document.createElement('canvas');\n canvas.style.left = i * MAX_CANVAS_WIDTH + 'px';\n canvas.style.width = widthPx + 'px';\n const dpr = window.devicePixelRatio || 1;\n canvas.width = widthPx * dpr;\n canvas.height = this.waveHeight * dpr;\n this._canvases.push(canvas);\n }\n }\n\n protected updated(_changed: PropertyValues): void {\n if (this._registeredCanvasIds.length === 0 && this._canvases.length > 0) {\n requestAnimationFrame(() => this._registerCanvases());\n }\n }\n\n private _registerCanvases(): void {\n const editor = this._findHostEditor();\n if (!editor || typeof editor._spectrogramRegisterCanvas !== 'function') {\n if (!this._warnedNoHost) {\n this._warnedNoHost = true;\n console.warn(\n '[dawcore] <daw-spectrogram> (clip ' +\n this.clipId +\n ') could not find host <daw-editor>. Canvases will not render. ' +\n 'Ensure the element is mounted inside a <daw-editor>.'\n );\n }\n return;\n }\n\n for (let i = 0; i < this._canvases.length; i++) {\n const canvas = this._canvases[i];\n const canvasId = buildSpectrogramCanvasId({\n clipId: this.clipId,\n channelIndex: this.channelIndex,\n chunkIndex: i,\n });\n let offscreen: OffscreenCanvas;\n try {\n offscreen = canvas.transferControlToOffscreen();\n } catch (err) {\n console.warn(\n '[dawcore] daw-spectrogram transferControlToOffscreen failed for ' +\n canvasId +\n ': ' +\n (err instanceof Error ? err.message : String(err))\n );\n continue;\n }\n editor._spectrogramRegisterCanvas({\n canvasId,\n canvas: offscreen,\n clipId: this.clipId,\n trackId: this.trackId,\n channelIndex: this.channelIndex,\n chunkIndex: i,\n globalPixelOffset: this.originX + i * MAX_CANVAS_WIDTH,\n widthPx: parseFloat(canvas.style.width),\n heightPx: this.waveHeight,\n });\n this._registeredCanvasIds.push(canvasId);\n }\n }\n\n private _unregisterAllCanvases(): void {\n const editor = this._findHostEditor();\n if (editor && typeof editor._spectrogramUnregisterCanvas === 'function') {\n for (const id of this._registeredCanvasIds) {\n editor._spectrogramUnregisterCanvas(id);\n }\n }\n this._registeredCanvasIds = [];\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this._unregisterAllCanvases();\n }\n\n render() {\n return html`${this._canvases.map((c) => c)}`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-spectrogram': DawSpectrogramElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport { resolveTransportTarget, warnNoTargetOnce } from '../utils/transport-capability';\nimport {\n formatDisplayTime,\n isTimeDisplayFormat,\n type TimeDisplayFormat,\n} from '../utils/time-display-format';\nimport type { DawEvent } from '../events';\n\n/**\n * Formatted playback time readout for <daw-transport>.\n *\n * Subscribes to bubbled `daw-timeupdate` / `daw-time-format-change` events at\n * the document level and filters by its transport target — works with any\n * target that dispatches them (<daw-editor> today, <daw-player> later) and\n * tolerates targets that upgrade after this element connects.\n *\n * Accessibility (spec): role=\"status\", aria-live=\"off\" — not announced every\n * frame; screen reader users query on demand.\n */\n@customElement('daw-time-display')\nexport class DawTimeDisplayElement extends LitElement {\n /** Null until the first successful target sync or daw-timeupdate. */\n @state() private _time: number | null = null;\n @state() private _format: TimeDisplayFormat = 'hh:mm:ss.sss';\n\n static styles = css`\n span {\n display: inline-block;\n font-family: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;\n font-variant-numeric: tabular-nums;\n color: var(--daw-controls-text, #e0d4c8);\n background: var(--daw-controls-background, #1a1a2e);\n border: 1px solid currentColor;\n padding: 4px 8px;\n }\n `;\n\n private get target(): HTMLElement | null {\n return resolveTransportTarget(this);\n }\n\n private _onTimeUpdate = (e: Event) => {\n if (e.target !== this.target) return;\n if (this._time === null) {\n // Late-target recovery: pick up the format we missed at connect time.\n const timeFormat = (e.target as HTMLElement & { timeFormat?: unknown }).timeFormat;\n if (isTimeDisplayFormat(timeFormat)) this._format = timeFormat;\n }\n this._time = (e as DawEvent<'daw-timeupdate'>).detail.time;\n };\n\n private _onFormatChange = (e: Event) => {\n if (e.target !== this.target) return;\n const detail = (e as DawEvent<'daw-time-format-change'>).detail;\n if (isTimeDisplayFormat(detail.format)) {\n this._format = detail.format;\n }\n };\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('daw-timeupdate', this._onTimeUpdate, { signal });\n document.addEventListener('daw-time-format-change', this._onFormatChange, { signal });\n // Defer the initial read until <daw-transport for> and the target have\n // upgraded (same pattern as the transport buttons).\n requestAnimationFrame(() => this._syncFromTarget());\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n }\n\n private _syncFromTarget() {\n if (!this.isConnected) return;\n const target = this.target;\n if (!target || typeof (target as { currentTime?: unknown }).currentTime !== 'number') {\n warnNoTargetOnce(\n this,\n ' The display recovers automatically once the target dispatches daw-timeupdate.'\n );\n return;\n }\n this._time = (target as unknown as { currentTime: number }).currentTime;\n const fmt = (target as { timeFormat?: unknown }).timeFormat;\n if (isTimeDisplayFormat(fmt)) {\n this._format = fmt;\n }\n }\n\n render() {\n const text = this._time === null ? '--:--:--' : formatDisplayTime(this._time, this._format);\n return html`<span role=\"status\" aria-label=\"Playback time\" aria-live=\"off\">${text}</span>`;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-time-display': DawTimeDisplayElement;\n }\n}\n","import { LitElement, html, css } from 'lit';\nimport { customElement, state } from 'lit/decorators.js';\nimport {\n resolveTransportTarget,\n targetSupports,\n targetUndetermined,\n warnNoTargetOnce,\n warnUnsupportedOnce,\n} from '../utils/transport-capability';\nimport {\n TIME_DISPLAY_FORMATS,\n isTimeDisplayFormat,\n type TimeDisplayFormat,\n} from '../utils/time-display-format';\nimport type { DawEvent } from '../events';\n\n/**\n * Time format select for <daw-transport>. Sets the format ON the target\n * (`target.setTimeFormat(...)`) — the target owns the state (native-form\n * style), and every display/input syncs via the bubbled\n * `daw-time-format-change` event. Renders disabled when the target doesn't\n * implement setTimeFormat (duck-typed capability detection, #474).\n */\n@customElement('daw-time-format')\nexport class DawTimeFormatElement extends LitElement {\n @state() private _format: TimeDisplayFormat = 'hh:mm:ss.sss';\n\n static styles = css`\n select {\n cursor: pointer;\n background: var(--daw-controls-background, #1a1a2e);\n color: var(--daw-controls-text, #e0d4c8);\n border: 1px solid currentColor;\n padding: 4px 8px;\n font: inherit;\n }\n select:disabled {\n opacity: 0.4;\n cursor: default;\n }\n `;\n\n private get target(): HTMLElement | null {\n return resolveTransportTarget(this);\n }\n\n /**\n * False when the target doesn't implement setTimeFormat. An undetermined\n * target (missing, or a not-yet-upgraded custom element) gets the benefit\n * of the doubt and stays enabled — interaction-time resolution warns if\n * it's still unusable.\n */\n private get _targetSupported(): boolean {\n const target = this.target;\n if (targetUndetermined(target)) return true;\n return targetSupports(target, ['setTimeFormat']);\n }\n\n private _onFormatChange = (e: Event) => {\n if (e.target !== this.target) return;\n const detail = (e as DawEvent<'daw-time-format-change'>).detail;\n if (isTimeDisplayFormat(detail.format)) {\n this._format = detail.format;\n }\n };\n\n private _onPointerEnter = () => {\n // A target that became resolvable since the last render should\n // re-evaluate before the click lands.\n this.requestUpdate();\n };\n\n private _onPointerDown = () => {\n const target = this.target;\n if (!target) {\n warnNoTargetOnce(this);\n return;\n }\n if (!this._targetSupported) {\n warnUnsupportedOnce(this, ['setTimeFormat']);\n }\n };\n\n /** The listeners of this connection, aborted in disconnectedCallback. */\n private _listeners: AbortController | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n this._listeners?.abort();\n this._listeners = new AbortController();\n const { signal } = this._listeners;\n document.addEventListener('daw-time-format-change', this._onFormatChange, { signal });\n this.addEventListener('pointerdown', this._onPointerDown, { signal });\n this.addEventListener('pointerenter', this._onPointerEnter, { signal });\n // Defer until the transport target has upgraded, then sync + re-render.\n requestAnimationFrame(() => {\n if (!this.isConnected) return;\n const target = this.target as (HTMLElement & { timeFormat?: unknown }) | null;\n if (target && isTimeDisplayFormat(target.timeFormat)) {\n this._format = target.timeFormat;\n }\n this.requestUpdate();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this._listeners?.abort();\n this._listeners = null;\n }\n\n protected updated() {\n // <option selected> attribute toggles stop working once the user has\n // picked an option (HTML selectedness dirtiness) — sync the IDL value\n // imperatively so programmatic format changes always reflect.\n const select = this.shadowRoot?.querySelector('select');\n if (select && select.value !== this._format) {\n select.value = this._format;\n }\n }\n\n private _onSelectChange(e: Event) {\n const value = (e.target as HTMLSelectElement).value as TimeDisplayFormat;\n const target = this.target as (HTMLElement & { setTimeFormat?: (f: string) => void }) | null;\n if (!target) {\n // Stale-render race guard: the target can vanish between render and change.\n warnNoTargetOnce(this);\n return;\n }\n target.setTimeFormat?.(value);\n }\n\n render() {\n return html`\n <select\n aria-label=\"Time format\"\n ?disabled=${!this._targetSupported}\n @change=${this._onSelectChange}\n >\n ${TIME_DISPLAY_FORMATS.map(\n (f) => html`<option value=${f} ?selected=${f === this._format}>${f}</option>`\n )}\n </select>\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-time-format': DawTimeFormatElement;\n }\n}\n","import { LitElement, html, css, type PropertyValues } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { repeat } from 'lit/directives/repeat.js';\nimport { MediaElementPlayout } from '@waveform-playlist/media-element-playout';\nimport { AnimationController } from '../controllers/animation-controller';\nimport type { DawPlayheadElement } from './daw-playhead';\nimport { loadWaveformDataFromUrl } from '../interactions/peaks-loader';\nimport { extractPeaks } from '../workers/waveformDataUtils';\nimport type { Peaks } from '@waveform-playlist/core';\n\n// Side-effect imports register the child custom elements used in the template.\nimport './daw-waveform';\nimport './daw-playhead';\nimport './daw-ruler';\n\nconst MIN_RATE = 0.25;\nconst MAX_RATE = 4.0;\n\n/**\n * `<daw-player>` — lightweight single-track HTMLMediaElement player.\n * Wraps a MediaElementPlayout engine for playback and composes\n * <daw-ruler>/<daw-waveform>/<daw-playhead> for visuals. No EditorEngine,\n * no adapter, no AudioContext. See docs/specs/2026-06-29-daw-player-core-design.md.\n */\n@customElement('daw-player')\nexport class DawPlayerElement extends LitElement {\n @property({ type: String }) src = '';\n @property({ type: String, attribute: 'peaks-src' }) peaksSrc = '';\n @property({ type: Number, attribute: 'wave-height' }) waveHeight = 128;\n @property({ type: Boolean }) timescale = false;\n @property({ type: Boolean }) mono = false;\n @property({ type: Number, attribute: 'bar-width' }) barWidth = 1;\n @property({ type: Number, attribute: 'bar-gap' }) barGap = 0;\n @property({ type: Boolean, attribute: 'rounded-bars' }) roundedBars = false;\n\n @property({ type: Number, attribute: 'playback-rate', noAccessor: true })\n get playbackRate(): number {\n return this._playbackRate;\n }\n set playbackRate(value: number) {\n const valid = Number.isFinite(value);\n if (!valid || value < MIN_RATE || value > MAX_RATE) {\n console.warn(\n '[dawcore] <daw-player> playback-rate ' +\n value +\n ' out of range ' +\n MIN_RATE +\n '–' +\n MAX_RATE +\n ' — clamping'\n );\n }\n const clamped = Math.max(MIN_RATE, Math.min(MAX_RATE, valid ? value : 1));\n const old = this._playbackRate;\n this._playbackRate = clamped;\n this.requestUpdate('playbackRate', old);\n }\n private _playbackRate = 1;\n\n private _engine: MediaElementPlayout = new MediaElementPlayout();\n /** Set by disconnectedCallback — a reconnect (DOM reparent, framework\n * re-render) must rebuild the engine + track or the player is dead. */\n private _engineDisposed = false;\n private _trackId: string | null = null;\n private _anim = new AnimationController(this);\n private _metadataLoaded = false;\n private _readyDispatched = false;\n /** True once peaks resolution is complete: succeeded, failed, or no peaks-src set. */\n private _peaksSettled = false;\n private _waveformData: import('waveform-data').default | null = null;\n @state() private _channelPeaks: Peaks[] = [];\n private _sampleRate = 48000;\n private _resizeObserver: ResizeObserver | null = null;\n\n static styles = css`\n /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */\n :host([hidden]) {\n display: none;\n }\n :host {\n display: block;\n position: relative;\n background: var(--daw-background, #1a1a2e);\n }\n .waveform-area {\n position: relative;\n width: 100%;\n overflow: hidden;\n }\n `;\n\n connectedCallback(): void {\n super.connectedCallback();\n let rebuilt = false;\n if (this._engineDisposed) {\n // A removed player must not keep audio alive, so disconnect disposes\n // the engine — but reparenting (appendChild of a connected element)\n // disconnects and reconnects synchronously, and updated() only reloads\n // on a src CHANGE. Rebuild here or the player never plays again.\n const volume = this._engine.masterVolume;\n this._engine = new MediaElementPlayout();\n this._engine.setMasterVolume(volume);\n this._engineDisposed = false;\n this._trackId = null;\n rebuilt = true;\n }\n this._engine.on('loadedmetadata', this._onLoadedMetadata);\n this._engine.on('play', this._onPlay);\n this._engine.on('pause', this._onPause);\n this._engine.on('ended', this._onEnded);\n this._engine.on('error', this._onError);\n this._resizeObserver = new ResizeObserver(() => this._renderWaveform());\n // Observe after first render so .waveform-area exists.\n requestAnimationFrame(() => {\n const area = this.shadowRoot?.querySelector('.waveform-area');\n if (area) this._resizeObserver?.observe(area);\n });\n // Peaks that had not arrived when it was disconnected (the fetch was\n // aborted, #848): fetch them again.\n if (rebuilt && this.peaksSrc && !this._peaksSettled) void this._loadPeaks();\n if (rebuilt && this.src) {\n this._loadSource();\n // The fresh engine is at 0 but the playhead kept its imperatively-set\n // px from before the reparent — snap it back so they agree. NOTE:\n // _loadSource re-arms daw-ready, so consumers see a second daw-ready\n // after a reparent (it IS a new load cycle; position/metadata reset).\n this._playhead?.setPosition(0);\n }\n }\n\n render() {\n const width = this._timelineWidth;\n const channels = this._channelPeaks.length;\n const channelHeight = channels > 0 ? this.waveHeight / channels : this.waveHeight;\n return html`\n ${this.timescale\n ? html`<daw-ruler\n .samplesPerPixel=${this._channelSpp(width)}\n .sampleRate=${this._sampleRate}\n .duration=${this._engine.duration}\n .totalWidth=${width}\n ></daw-ruler>`\n : null}\n <div\n class=\"waveform-area\"\n style=\"height:${this.waveHeight}px\"\n @pointerdown=${this._onPointerDown}\n >\n ${repeat(\n this._channelPeaks,\n (_p, i) => i,\n (peaks) =>\n html`<daw-waveform\n .peaks=${peaks}\n .length=${width}\n .waveHeight=${channelHeight}\n .barWidth=${this.barWidth}\n .barGap=${this.barGap}\n .roundedBars=${this.roundedBars}\n ></daw-waveform>`\n )}\n <daw-playhead></daw-playhead>\n </div>\n `;\n }\n\n protected updated(changed: PropertyValues): void {\n if (changed.has('src')) this._loadSource();\n if (changed.has('playbackRate')) this._engine.setPlaybackRate(this._playbackRate);\n if (changed.has('peaksSrc')) this._loadPeaks();\n // Only `mono` changes the derived peaks; `wave-height` only affects display\n // height, which render() reads directly (recomputing peaks for it is wasteful\n // and, on first update, sets @state mid-cycle → a Lit change-in-update warning).\n if (changed.has('mono')) this._renderWaveform();\n }\n\n /** The peaks fetch in flight: a newer peaks-src or a disconnect aborts it (#848, D7). */\n private _peaksFetch: AbortController | null = null;\n\n private async _loadPeaks(): Promise<void> {\n this._peaksFetch?.abort();\n this._peaksFetch = null;\n this._waveformData = null;\n this._readyDispatched = false; // re-arm ready for the new source\n this._peaksSettled = false; // new load in progress; wait for outcome before firing daw-ready\n if (!this.peaksSrc) {\n // No peaks-src — peaks are settled immediately (scrubber-only is a valid ready state).\n this._peaksSettled = true;\n this._renderWaveform();\n this._maybeDispatchReady();\n return;\n }\n const requested = this.peaksSrc;\n const fetching = new AbortController();\n this._peaksFetch = fetching;\n try {\n const wd = await loadWaveformDataFromUrl(requested, fetching.signal);\n if (this._peaksFetch === fetching) this._peaksFetch = null;\n if (this.peaksSrc !== requested) return; // stale — a newer peaks-src won (don't settle)\n this._waveformData = wd;\n this._sampleRate = wd.sample_rate;\n this._peaksSettled = true;\n this._renderWaveform();\n this._maybeDispatchReady();\n } catch (err) {\n // Aborted (a newer peaks-src, a disconnect): that one settles nothing.\n if (fetching.signal.aborted) return;\n // Same stale guard as the success path: a superseded load's late\n // rejection must not settle readiness (daw-ready would fire while the\n // NEWER peaks-src is still in flight) or clobber its waveform.\n if (this.peaksSrc !== requested) return;\n console.warn('[dawcore] <daw-player> failed to load peaks-src: ' + String(err));\n // A failed waveform must not permanently block daw-ready — the player IS ready to play.\n this._peaksSettled = true;\n this._renderWaveform(); // scrubber-only fallback\n this._maybeDispatchReady();\n }\n }\n\n /** Recompute fit-to-width peaks from the loaded WaveformData. No-op without data. */\n private _renderWaveform(): void {\n const wd = this._waveformData;\n const width = this._timelineWidth;\n if (!wd || width <= 0) {\n // Avoid churning @state with a fresh empty array when already empty —\n // a redundant reassignment during updated() schedules a wasted re-render.\n if (this._channelPeaks.length > 0) this._channelPeaks = [];\n return;\n }\n // Resample so the peak count ≈ the host width (fit-to-width).\n const totalSamples = wd.length * wd.scale;\n const samplesPerPixel = Math.max(wd.scale, Math.ceil(totalSamples / width));\n const peakData = extractPeaks(wd, samplesPerPixel, this.mono);\n this._channelPeaks = peakData.data;\n }\n\n /**\n * Samples-per-pixel used by the ruler so its time labels span the full width.\n * This is intentionally a separate time-based SPP (duration × sampleRate / width)\n * for the ruler labels — equivalent to the waveform SPP when the WaveformData spans\n * the full audio duration; may differ for pre-trimmed peaks.\n */\n private _channelSpp(width: number): number {\n const d = this._engine.duration;\n if (d <= 0 || width <= 0) return 1;\n return Math.max(1, Math.ceil((d * this._sampleRate) / width));\n }\n\n private _loadSource(): void {\n if (!this.src) return;\n // Re-arm the daw-ready gate so a new audio source fires a fresh event.\n // _peaksSettled is intentionally NOT touched here — for a src-only swap the\n // existing peaks remain valid; _loadPeaks resets it when peaks-src changes.\n this._metadataLoaded = false;\n this._readyDispatched = false;\n const track = this._engine.setSource({ source: this.src });\n this._trackId = track.id;\n this._engine.setPlaybackRate(this._playbackRate);\n }\n\n // --- Transport methods ---\n play(): void {\n // resume() keeps the current position (pause→play, paused seek→play);\n // play() with no offset would reset to 0. After stop() the element's\n // currentTime is already 0, so play-after-stop still starts at the top.\n this._engine.resume();\n }\n pause(): void {\n this._engine.pause();\n }\n stop(): void {\n this._engine.stop();\n this._anim.stop();\n this._updatePlayhead();\n this._dispatch('daw-stop');\n }\n seekTo(time: number): void {\n this._engine.seekTo(time);\n if (!this._engine.isPlaying) {\n // The rAF loop only runs while playing — without this, the playhead\n // and daw-timeupdate consumers (<daw-time-display>) stay stale until\n // the next play.\n this._updatePlayhead();\n this._dispatch('daw-timeupdate', { time: this._engine.getCurrentTime() });\n }\n }\n setPlaybackRate(rate: number): void {\n this.playbackRate = rate; // setter clamps + requestUpdate triggers engine forward\n }\n setVolume(volume: number): void {\n this._engine.setMasterVolume(volume);\n }\n\n // --- Properties ---\n get isPlaying(): boolean {\n return this._engine.isPlaying;\n }\n get duration(): number {\n return this._engine.duration;\n }\n get currentTime(): number {\n return this._engine.getCurrentTime();\n }\n set currentTime(time: number) {\n // Route through seekTo so paused assignments update the playhead and\n // dispatch daw-timeupdate — the property API must not be staler than\n // the method API.\n this.seekTo(time);\n }\n get volume(): number {\n return this._engine.masterVolume;\n }\n set volume(value: number) {\n this._engine.setMasterVolume(value);\n }\n get audioElement(): HTMLAudioElement | null {\n return this._trackId ? (this._engine.getTrack(this._trackId)?.element ?? null) : null;\n }\n\n private _onPointerDown = (e: PointerEvent): void => {\n const area = e.currentTarget as HTMLElement;\n const width = area.clientWidth;\n const d = this._engine.duration;\n // _engine.duration coerces NaN→0 upstream (MediaElementTrack.duration is\n // `audioElement.duration || _peaks?.duration || 0`), so `d <= 0` also\n // covers the pre-metadata/NaN case — no separate NaN check needed.\n if (width <= 0 || d <= 0) return;\n const ratio = Math.max(0, Math.min(1, e.offsetX / width));\n this.seekTo(ratio * d); // seekTo updates the playhead when paused; rAF covers playing\n };\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this._anim.stop();\n this._resizeObserver?.disconnect();\n this._resizeObserver = null;\n this._engine.off('loadedmetadata', this._onLoadedMetadata);\n this._engine.off('play', this._onPlay);\n this._engine.off('pause', this._onPause);\n this._engine.off('ended', this._onEnded);\n this._engine.off('error', this._onError);\n this._engine.dispose();\n this._engineDisposed = true;\n // The peaks fetch in flight is aborted; a reconnect fetches again.\n this._peaksFetch?.abort();\n this._peaksFetch = null;\n }\n\n // --- Private event handlers (arrow fields for stable identity) ---\n\n private _dispatch<T>(name: string, detail?: T): void {\n this.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail }));\n }\n\n private _onLoadedMetadata = (): void => {\n this._metadataLoaded = true;\n // duration (and the ruler SPP derived from it) is a render input read\n // straight off the engine — without this, a render that happened before\n // metadata (peaks usually resolve first) leaves the ruler frozen at 0:00.\n this.requestUpdate();\n this._maybeDispatchReady();\n };\n\n private _onPlay = (): void => {\n this._dispatch('daw-play');\n this._anim.start(this._frame);\n };\n\n private _onPause = (): void => {\n this._anim.stop();\n this._updatePlayhead();\n this._dispatch('daw-pause');\n };\n\n private _onEnded = (): void => {\n this._anim.stop();\n this._updatePlayhead(); // snap playhead to end rather than leaving it ≤1 frame short\n this._dispatch('daw-ended');\n };\n\n private _onError = (err: MediaError | null): void => {\n console.warn('[dawcore] <daw-player> failed to load src: ' + (err?.message ?? 'unknown'));\n this._dispatch('daw-error', { operation: 'load', error: err });\n };\n\n /** rAF tick while playing: positions the playhead and emits daw-timeupdate. */\n private _frame = (): void => {\n this._updatePlayhead();\n this._dispatch('daw-timeupdate', { time: this._engine.getCurrentTime() });\n };\n\n private _maybeDispatchReady(): void {\n if (this._readyDispatched) return;\n if (this._metadataLoaded && this._peaksSettled) {\n this._readyDispatched = true;\n this._dispatch('daw-ready');\n }\n }\n\n private get _playhead(): DawPlayheadElement | null {\n return this.shadowRoot?.querySelector('daw-playhead') ?? null;\n }\n\n private _updatePlayhead(): void {\n const d = this._engine.duration;\n if (d <= 0) return;\n const px = (this._engine.getCurrentTime() / d) * this._timelineWidth;\n this._playhead?.setPosition(px);\n }\n\n private get _timelineWidth(): number {\n return this.shadowRoot?.querySelector<HTMLElement>('.waveform-area')?.clientWidth ?? 0;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'daw-player': DawPlayerElement;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qCAAC,kBAAiB,gCAA+B,iBAAgB,gCAA+B,sBAAqB,sCAAqC,gBAAe,8BAA6B,2BAA0B,2CAA0C,6BAA4B,4CAA2C,+BAA8B,8CAA6C,8BAA6B,6CAA4C;;;ACAre,iBAA2B;AAC3B,wBAAwC;AAKxC,SAAS,YAAY,OAAwB;AAC3C,SAAO,OAAO,SAAS,KAAK,KAAK,OAAO,UAAU,KAAK,KAAK,SAAS;AACvE;AAQO,IAAM,uBAAN,cAAmC,sBAAW;AAAA,EAA9C;AAAA;AAeL,SAAQ,SAAS;AAgBjB,SAAQ,OAAO;AAyBf,SAAQ,aAA4B;AAqBpC,SAAQ,WAA0B;AAOlC,SAAQ,kBAAkB;AAE1B,SAAiB,eAAe,gBAAgB,OAAO,WAAW;AA+ClE,SAAQ,eAAe;AAAA;AAAA,EAlIvB,IAAI,QAAgB;AAClB,WAAO,KAAK;AAAA,EACd;AAAA,EACA,IAAI,MAAM,OAAe;AACvB,QAAI,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG;AACxC,cAAQ,KAAK,oCAAoC,OAAO,KAAK,IAAI,4BAAuB;AACxF;AAAA,IACF;AACA,UAAM,MAAM,KAAK;AACjB,SAAK,SAAS;AACd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AHzC,iBAG2C;AACzB;AAAA,MAA5B,8BAAS,EAAE,MAAM,QAAQ,CAAC;AAAA,GAJhB,iBAIkB;AACA;AAAA,MAA5B,8BAAS,EAAE,MAAM,QAAQ,CAAC;AAAA,GALhB,iBAKkB;AACuB;AAAA,MAAnD,8BAAS,EAAE,MAAM,QAAQ,WAAW,YAAY,CAAC;AAAA,GANvC,iBAMyC;AACF;AAAA,MAAjD,8BAAS,EAAE,MAAM,QAAQ,WAAW,UAAU,CAAC;AAAA,GAPrC,iBAOuC;AACM;AAAA,MAAvD,8BAAS,EAAE,MAAM,SAAS,WAAW,eAAe,CAAC;AAAA,GAR3C,iBAQ6C;AAGpD;AAAA,MADH,8BAAS,EAAE,MAAM,QAAQ,WAAW,iBAAiB,YAAY,KAAK,CAAC;AAAA,GAV7D,iBAWP;AAkCa;AAAA,MAAhB,2BAAM;AAAA,GA7CI,iBA6CM;AA7CN,mBAAN;AAAA,MADN,mCAAc,YAAY;AAAA,GACd;","names":["import_lit","import_decorators","updated","import_lit","import_decorators","import_core","import_lit","import_decorators","state","import_lit","import_decorators","import_core","state","import_lit","import_decorators","import_lit","import_decorators","MAX_CANVAS_WIDTH","LAYOUT_PROPS","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_core","idCounter","WaveformData","bits","numChannels","import_lit","import_decorators","import_core","MAX_CANVAS_WIDTH","import_engine","import_lit","import_decorators","import_core","import_lit","import_decorators","import_core","MAX_CANVAS_WIDTH","import_lit","import_core","import_lit","left","width","import_core","state","LIBRARY_DEFAULTS","LIBRARY_DEFAULT_COLOR_MAP","import_core","signal","import_core","import_core","updated","import_core","state","import_core","import_core","import_core","import_engine","import_core","state","import_core","import_core","PREFIX","element","import_core","PREFIX","import_waveform_data","WaveformData","peaksSrc","updatedClip","id","state","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_core","import_lit","import_decorators","import_core","import_lit","import_decorators","import_lit","import_decorators","import_lit","import_decorators","import_repeat"]}