@dawcore/components 0.0.39-next.3 → 0.0.39-next.4

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/elements/daw-track.ts","../src/types.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/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/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 KeyBinding,\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} 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 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.2\",\"@dawcore/transport\":\"@dawcore/transport@^0.0.16-next.2\",\"@dawcore/wam\":\"@dawcore/wam@^0.0.5-next.0\",\"@waveform-playlist/core\":\"@waveform-playlist/core@^13.0.0-next.2\",\"@waveform-playlist/engine\":\"@waveform-playlist/engine@^14.0.0-next.1\",\"@waveform-playlist/worklets\":\"@waveform-playlist/worklets@^13.0.1-next.0\",\"@waveform-playlist/playout\":\"@waveform-playlist/playout@^13.0.0-next.2\"}","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 // 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 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 document.addEventListener('keydown', this._onKeyDownCapture, true); // capture phase\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 document.removeEventListener('keydown', this._onKeyDownCapture, true);\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/** m:ss.mmm for annotation timestamps (finer than the ruler's m:ss). */\nfunction formatAnnotationTime(seconds: number): string {\n const whole = Math.floor(seconds);\n const ms = Math.round((seconds - whole) * 1000);\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 :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 connectedCallback() {\n super.connectedCallback();\n document.addEventListener('daw-annotation-select', this._onSelect as EventListener);\n document.addEventListener('daw-timeupdate', this._onTimeUpdate as EventListener);\n document.addEventListener('daw-stop', this._onStop as EventListener);\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n document.removeEventListener('daw-annotation-select', this._onSelect as EventListener);\n document.removeEventListener('daw-timeupdate', this._onTimeUpdate as EventListener);\n document.removeEventListener('daw-stop', this._onStop as EventListener);\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';\n\n@customElement('daw-clip')\nexport class DawClipElement extends LitElement {\n @property() src = '';\n @property({ attribute: 'peaks-src' }) peaksSrc = '';\n /**\n * Timeline position in seconds. JS property only — NOT reflected to the\n * `start` attribute (Lit's `reflect` defaults to false). Tests that need\n * to assert clip position must read this property directly; reading\n * `el.getAttribute('start')` returns `null` regardless of correctness.\n */\n @property({ type: Number }) start = 0;\n @property({ type: Number }) duration = 0;\n @property({ type: Number }) offset = 0;\n @property({ type: Number }) gain = 1;\n @property() name = '';\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 }) midiNotes: MidiNoteData[] | null = null;\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._midiChannel;\n }\n set midiChannel(value: number | null) {\n const old = this._midiChannel;\n if (value === null) {\n this._midiChannel = null;\n this.requestUpdate('midiChannel', old);\n return;\n }\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15) {\n console.warn('[dawcore] daw-clip midi-channel ' + value + ' is out of range 0-15 — ignored');\n return;\n }\n this._midiChannel = value;\n this.requestUpdate('midiChannel', old);\n }\n private _midiChannel: number | null = null;\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._midiProgram;\n }\n set midiProgram(value: number | null) {\n const old = this._midiProgram;\n if (value === null) {\n this._midiProgram = null;\n this.requestUpdate('midiProgram', old);\n return;\n }\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127) {\n console.warn('[dawcore] daw-clip midi-program ' + value + ' is out of range 0-127 — ignored');\n return;\n }\n this._midiProgram = value;\n this.requestUpdate('midiProgram', old);\n }\n private _midiProgram: number | null = null;\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 connectedCallback() {\n super.connectedCallback();\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 editor\n // reads <daw-clip> children synchronously via _readTrackDescriptor, so\n // this event is the canonical late-append signal.\n // _onClipConnected skips this event during the parent track's initial load\n // (parent not yet in _engineTracks) and runs an incremental load otherwise.\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","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { RenderMode, SpectrogramConfig, TrackKind } from '@waveform-playlist/core';\nimport type { EffectState as TrackEffectState, SerializedEffectEntry } from '../effects/types';\nimport { normalizeRenderMode } from '../types';\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 @property() name = '';\n @property({ type: Number }) volume = 1;\n @property({ type: Number }) pan = 0;\n @property({ type: Boolean }) muted = false;\n @property({ type: Boolean }) soloed = false;\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 connects:\n * the editor reads it when it loads the track.\n */\n @property({ reflect: true, noAccessor: true })\n get kind(): TrackKind {\n return this._kind;\n }\n set kind(value: TrackKind) {\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 connectedCallback() {\n super.connectedCallback();\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 const trackProps = [\n 'volume',\n 'pan',\n 'muted',\n 'soloed',\n 'src',\n 'name',\n 'kind',\n 'renderMode',\n 'spectrogramConfig',\n ];\n const hasTrackChange = trackProps.some((p) => changed.has(p as keyof this));\n\n if (hasTrackChange) {\n this.dispatchEvent(\n new CustomEvent('daw-track-update', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId },\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 RenderMode,\n SpectrogramConfig,\n TrackKind,\n} from '@waveform-playlist/core';\n\n// Re-export RenderMode from core as TrackRenderMode for backward compatibility\n// during the migration; consumers should prefer RenderMode directly.\nexport type { RenderMode } from '@waveform-playlist/core';\nexport type TrackRenderMode = RenderMode;\n\nexport interface TrackDescriptor {\n name: string;\n src: string;\n volume: number;\n pan: number;\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/** 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. Engine `clip.id` is aligned with this id in `_loadTrack`\n * and `_loadAndAppendClip` so DOM and engine reference 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; the engine generates its own id at\n * clip-creation time.\n *\n * `clipId` is that engine clip id when the editor knows it at descriptor\n * creation — currently recorded takes (#659). Pass it to\n * `editor.updateClip()` / `removeClip()` to address the clip.\n */\nexport interface DropClipDescriptor extends BaseClipDescriptor {\n kind: 'drop';\n clipId?: string;\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 * 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 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","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 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 target.addEventListener('daw-recording-start', this._onRecStart);\n target.addEventListener('daw-recording-complete', this._onRecEnd);\n target.addEventListener('daw-recording-error', this._onRecEnd);\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetRef.removeEventListener('daw-recording-start', this._onRecStart);\n this._targetRef.removeEventListener('daw-recording-complete', this._onRecEnd);\n this._targetRef.removeEventListener('daw-recording-error', this._onRecEnd);\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 connectedCallback() {\n super.connectedCallback();\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);\n // A target that became resolvable since the last render should\n // re-evaluate before the click lands.\n this.addEventListener('pointerenter', this._onCapabilityPointerEnter);\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.removeEventListener('pointerdown', this._onCapabilityPointerDown);\n this.removeEventListener('pointerenter', this._onCapabilityPointerEnter);\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 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 target.addEventListener('daw-recording-start', this._onRecStart);\n target.addEventListener('daw-recording-complete', this._onRecEnd);\n target.addEventListener('daw-recording-error', this._onRecEnd);\n target.addEventListener('daw-recording-pause', this._onRecPause);\n target.addEventListener('daw-recording-resume', this._onRecResume);\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetRef.removeEventListener('daw-recording-start', this._onRecStart);\n this._targetRef.removeEventListener('daw-recording-complete', this._onRecEnd);\n this._targetRef.removeEventListener('daw-recording-error', this._onRecEnd);\n this._targetRef.removeEventListener('daw-recording-pause', this._onRecPause);\n this._targetRef.removeEventListener('daw-recording-resume', this._onRecResume);\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 type {\n AudioClip,\n ClipTrack,\n FadeType,\n MidiNoteData,\n Peaks,\n PeakData,\n SnapTo,\n MeterEntry,\n SpectrogramConfig,\n ColorMapValue,\n} from '@waveform-playlist/core';\nimport type {\n TrackDescriptor,\n TrackWithId,\n ClipDescriptor,\n DomClipDescriptor,\n TrackConfig,\n ClipConfig,\n} from '../types';\nimport { isDomClip, normalizeRenderMode, trackDescriptorRenderMode } from '../types';\nimport {\n createClip,\n createClipFromSeconds,\n createTrack,\n clipPixelWidth,\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 type { PlaylistEngine, PlayoutAdapter } from '@waveform-playlist/engine';\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 DawTrackErrorDetail,\n DawTrackReorderDetail,\n DawTrackReorderGrabDetail,\n DawClipIdDetail,\n DawClipErrorDetail,\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 { 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// 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/** Thrown by _loadTrack when a load is cancelled (track removed / editor\n * disconnected mid-load) rather than failed. Surfaced through daw-track-error\n * with `detail.reason` set so consumers can filter intentional cancellations\n * from real load failures; the event still fires so addTrack()/loadMidi()\n * awaiters settle. */\nclass TrackLoadCancelledError extends Error {\n constructor(\n message: string,\n readonly reason: 'removed' | 'disconnected'\n ) {\n super(message);\n this.name = 'TrackLoadCancelledError';\n }\n}\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 const descriptor = this._tracks.get(trackId);\n if (descriptor?.renderMode !== '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 /** Sample rate — reads from adapter's AudioContext when available, otherwise falls back to 48000. */\n get sampleRate(): number {\n return this._resolvedSampleRate ?? this._externalAdapter?.audioContext.sampleRate ?? 48000;\n }\n /** Resolved sample rate — falls back to sampleRate property until first audio decode. */\n _resolvedSampleRate: number | null = null;\n @state() _tracks: Map<string, TrackDescriptor> = new Map();\n @state() _engineTracks: Map<string, ClipTrack> = 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 // A fresh adapter re-arms engine building after a disconnect consumed\n // the previous one (see _adapterConsumedByDispose).\n this._adapterConsumedByDispose = false;\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 }\n get adapter(): PlayoutAdapter | null {\n return this._externalAdapter;\n }\n private _externalAdapter: PlayoutAdapter | null = null;\n /** True after a disconnect disposed the consumer's adapter via the engine\n * — rebuild attempts fail loudly until a fresh adapter is set. */\n private _adapterConsumedByDispose = false;\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._engineTracks.values()],\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: PlaylistEngine | null = null;\n private _warnedMissingTicksToSeconds = false;\n private _warnedMissingSecondsToTicks = false;\n private _enginePromise: Promise<PlaylistEngine> | null = null;\n _audioCache = new Map<string, Promise<AudioBuffer>>();\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 /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`\n * membership: the peaks-first path inserts a render-only PREVIEW track\n * into _engineTracks mid-load, so `has()` alone cannot answer \"is this\n * track still loading?\". */\n private _loadingTracks = new Set<string>();\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 track = this._engineTracks.get(trackId);\n if (!track) return false;\n const clip = track.clips.find((c) => c.id === clipId);\n return clip?.midiNotes != null;\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 :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._resolvedSampleRate ?? this.sampleRate;\n }\n resolveAudioContextSampleRate(rate: number) {\n if (!this._resolvedSampleRate) this._resolvedSampleRate = rate;\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 get tracks(): TrackWithId[] {\n return [...this._tracks.entries()].map(([trackId, descriptor]) => ({\n trackId,\n ...descriptor,\n }));\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 this.addEventListener('daw-track-connected', this._onTrackConnected as EventListener);\n this.addEventListener('daw-track-update', this._onTrackUpdate as EventListener);\n this.addEventListener('daw-track-control', this._onTrackControl as EventListener);\n this.addEventListener('daw-track-remove', this._onTrackRemoveRequest as EventListener);\n this.addEventListener('daw-clip-connected', this._onClipConnected as EventListener);\n this.addEventListener('daw-clip-update', this._onClipUpdate as EventListener);\n this.addEventListener(\n 'daw-annotation-track-connected',\n this._onAnnotationTrackConnected as EventListener\n );\n this.addEventListener('daw-annotation-select', this._onAnnotationSelect as EventListener);\n this.addEventListener('daw-track-reorder', this._onTrackReorder as EventListener);\n this.addEventListener('daw-track-reorder-grab', this._onTrackReorderGrab as EventListener);\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 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 }\n }\n let orderMayHaveChanged = addedTrackIds.size > 0;\n for (const [trackId] of removedTracks) {\n if (addedTrackIds.has(trackId)) {\n orderMayHaveChanged = true; // move, not removal\n continue;\n }\n this._onTrackRemoved(trackId);\n }\n for (const clip of removedClips) {\n // A clip that moved with its track (or was re-slotted) is still connected.\n if (clip.isConnected) continue;\n this._onClipRemovedFromDom(clip);\n }\n if (orderMayHaveChanged) this._syncEngineOrderToDom();\n });\n this._childObserver.observe(this, { childList: true, subtree: true });\n }\n disconnectedCallback() {\n super.disconnectedCallback();\n this._effectsManager?.disposeAll();\n this._effectsManager = null;\n this.removeEventListener('daw-track-connected', this._onTrackConnected as EventListener);\n this.removeEventListener('daw-track-update', this._onTrackUpdate as EventListener);\n this.removeEventListener('daw-track-control', this._onTrackControl as EventListener);\n this.removeEventListener('daw-track-remove', this._onTrackRemoveRequest as EventListener);\n this.removeEventListener('daw-clip-connected', this._onClipConnected as EventListener);\n this.removeEventListener('daw-clip-update', this._onClipUpdate as EventListener);\n this.removeEventListener(\n 'daw-annotation-track-connected',\n this._onAnnotationTrackConnected as EventListener\n );\n this.removeEventListener('daw-annotation-select', this._onAnnotationSelect as EventListener);\n this.removeEventListener('daw-track-reorder', this._onTrackReorder as EventListener);\n this.removeEventListener('daw-track-reorder-grab', this._onTrackReorderGrab as EventListener);\n this._trackReorderDrag.cancel();\n this._childObserver?.disconnect();\n this._childObserver = null;\n this._trackElements.clear();\n this._audioCache.clear();\n this._peaksCache.clear();\n this._clipBuffers.clear();\n this._clipOffsets.clear();\n this._peakPipeline.terminate();\n this._minSamplesPerPixel = 0;\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 a reconnect\n // would decode successfully and wire tracks into a dead transport graph\n // — waveforms render, play() runs, no audio. Refuse to rebuild on it;\n // the adapter setter clears the flag when a fresh one arrives.\n if (hadEngine) {\n this._adapterConsumedByDispose = true;\n }\n // Symmetric teardown: the caches above are gone and the engine (and the\n // consumer's adapter through it) disposed — retaining the render state\n // would make a reconnected editor show ghost waveforms that can never\n // play. Declarative AND programmatic (addTrack) tracks are element-backed\n // and re-register on reconnect (failing LOUDLY via the disposed-adapter\n // guard in _buildEngine until a fresh adapter is set); file-dropped\n // element-less content does not survive a reparent.\n this._tracks = new Map();\n this._engineTracks = new Map();\n this._peaksData = new Map();\n this._loadingTracks.clear();\n this._recomputeDuration();\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 // Custom elements fire disconnectedCallback+connectedCallback on a pure\n // DOM MOVE (e.g. insertBefore during a consumer reorder), not just on a\n // genuine removal — no moveBefore() is used anywhere in this codebase.\n // daw-track.ts's connectedCallback re-dispatches a deferred\n // daw-track-connected for the SAME trackId in that case. If the track is\n // already registered (loading or fully loaded), this is a reconnect from\n // a move, not a first-time (or post-teardown) registration: refresh the\n // element mapping and bail out WITHOUT re-reading the descriptor or\n // reloading. Re-reading would revert live daw-track-control mixer edits\n // (they mutate the _tracks descriptor at runtime, not the element's\n // attributes); reloading would re-fetch — for a file-dropped track whose\n // blob: URL was already revoked after its first load (Task 6), that\n // fetch is against a dead URL and spuriously fires daw-track-error.\n // Genuine re-registration after the EDITOR itself is reparented still\n // works: the editor's disconnectedCallback clears _tracks entirely, so\n // this guard is a no-op then and a full reload happens as before.\n if (this._tracks.has(trackId)) {\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n return;\n }\n const descriptor = this._readTrackDescriptor(trackEl as DawTrackElement);\n this._tracks = new Map(this._tracks).set(trackId, descriptor);\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n this._loadTrack(trackId, descriptor);\n };\n private _onTrackRemoved(trackId: string) {\n // Captured before the cleanup below mutates _tracks — gates the outbound\n // event so it only fires for a track that was actually registered.\n const existed = this._tracks.has(trackId);\n this._trackElements.delete(trackId);\n this._effectsManager?.disposeTrackChain(trackId);\n // Clean up per-clip data before removing the track (need clip IDs from engine tracks)\n const removedTrack = this._engineTracks.get(trackId);\n if (removedTrack) {\n const nextPeaks = new Map(this._peaksData);\n for (const clip of removedTrack.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 nextTracks = new Map(this._tracks);\n nextTracks.delete(trackId);\n this._tracks = nextTracks;\n const nextEngine = new Map(this._engineTracks);\n nextEngine.delete(trackId);\n this._engineTracks = nextEngine;\n this._recomputeDuration();\n if (this._engine) {\n // Incremental removal preserves playback (no playout rebuild)\n this._engine.removeTrack(trackId);\n }\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 && nextEngine.size === 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 // _tracks is updated so handlers reading editor.tracks see the removal.\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) => {\n const trackId = e.detail?.trackId as string;\n if (!trackId) return;\n const trackEl = (e.target as HTMLElement).closest('daw-track') as DawTrackElement | null;\n if (!trackEl) return;\n const oldDescriptor = this._tracks.get(trackId);\n let descriptor = this._readTrackDescriptor(trackEl);\n if (oldDescriptor && oldDescriptor.kind !== descriptor.kind) {\n // The clips already loaded are of the old kind (#756).\n console.warn(\n '[dawcore] <daw-track> \"' +\n descriptor.name +\n '\": kind cannot change after the track has loaded (still \"' +\n oldDescriptor.kind +\n '\"). Remove the track and add one of the other kind.'\n );\n descriptor = {\n ...descriptor,\n kind: oldDescriptor.kind,\n renderMode: trackDescriptorRenderMode(oldDescriptor.kind, trackEl.renderMode),\n };\n // Put the element back, so it says what the editor holds and the next\n // unrelated update (a volume change) does not warn again. The update\n // this assignment dispatches finds the kinds equal. In a microtask: we\n // are inside the element's own updated(), where Lit's dev build warns\n // about a property change.\n const keptKind = oldDescriptor.kind;\n queueMicrotask(() => {\n trackEl.kind = keptKind;\n });\n }\n this._tracks = new Map(this._tracks).set(trackId, descriptor);\n if (this._engine) {\n if (oldDescriptor?.volume !== descriptor.volume)\n this._engine.setTrackVolume(trackId, descriptor.volume);\n if (oldDescriptor?.pan !== descriptor.pan) this._engine.setTrackPan(trackId, descriptor.pan);\n if (oldDescriptor?.muted !== descriptor.muted)\n this._engine.setTrackMute(trackId, descriptor.muted);\n if (oldDescriptor?.soloed !== descriptor.soloed)\n this._engine.setTrackSolo(trackId, descriptor.soloed);\n }\n if (oldDescriptor?.src !== descriptor.src) {\n this._loadTrack(trackId, descriptor);\n }\n // Track switched into spectrogram mode — push existing clip audio into the controller.\n if (descriptor.renderMode === 'spectrogram' && oldDescriptor?.renderMode !== 'spectrogram') {\n const engineTrack = this._engineTracks.get(trackId);\n if (engineTrack) {\n for (const clip of engineTrack.clips) {\n this._maybeRegisterSpectrogramClipAudio(trackId, clip);\n }\n }\n }\n // Track switched OUT of spectrogram mode — drop clip audio.\n if (descriptor.renderMode !== 'spectrogram' && oldDescriptor?.renderMode === 'spectrogram') {\n const engineTrack = this._engineTracks.get(trackId);\n if (engineTrack && this._spectrogramController) {\n for (const clip of engineTrack.clips) {\n this._spectrogramController.unregisterClipAudio(clip.id);\n }\n }\n this._disposeSpectrogramControllerIfEmpty();\n }\n if (descriptor.spectrogramConfig !== oldDescriptor?.spectrogramConfig) {\n this._spectrogramController?.setTrackConfig(trackId, descriptor.spectrogramConfig ?? null);\n }\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._tracks.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 /** Reconcile `_tracks` descriptors with the engine's track list.\n *\n * ADD: engine.undo() restores removed tracks in ENGINE state only —\n * without a synthesized descriptor the track plays and renders but shows\n * \"Untitled\" controls and is missing from `editor.tracks`.\n * PRUNE (the symmetric half): redo removes the track from engine state\n * again — without pruning, the synthesized descriptor is a permanent\n * ghost that even removeTrack() can't clean (no element, no engine\n * entry). Never prunes tracks that are mid-load or element-backed —\n * their descriptors legitimately precede their engine entries. */\n _reconcileDescriptorsWithEngineTracks(tracks: readonly ClipTrack[]): void {\n const engineIds = new Set(tracks.map((t) => t.id));\n let next: Map<string, TrackDescriptor> | null = null;\n for (const track of tracks) {\n if (this._tracks.has(track.id)) continue;\n next ??= new Map(this._tracks);\n next.set(track.id, {\n name: track.name ?? '',\n src: '',\n volume: track.volume ?? 1,\n pan: track.pan ?? 0,\n muted: track.muted ?? false,\n soloed: track.soloed ?? false,\n kind: trackKind(track),\n renderMode: trackDescriptorRenderMode(trackKind(track), 'waveform'),\n clips: [],\n });\n }\n for (const trackId of this._tracks.keys()) {\n if (\n engineIds.has(trackId) ||\n this._loadingTracks.has(trackId) ||\n this._trackElements.has(trackId)\n ) {\n continue;\n }\n next ??= new Map(this._tracks);\n next.delete(trackId);\n }\n // Element-less clips that carry their engine id (recorded takes, #659)\n // have no <daw-clip> to re-read them, and the engine changes them on its\n // own: undo removes a take, a split replaces it with two new ids, a\n // punch-in carves it away, a drag moves or trims it. Follow the engine —\n // a descriptor whose id is gone would otherwise be a ghost that even\n // removeClip() cannot reach.\n for (const track of tracks) {\n const desc = (next ?? this._tracks).get(track.id);\n if (!desc || !desc.clips.some((c) => !isDomClip(c) && c.clipId !== undefined)) continue;\n const reconciled = this._reconcileIdentifiedDropClips(desc.clips, track);\n if (reconciled === desc.clips) continue;\n next ??= new Map(this._tracks);\n next.set(track.id, { ...desc, clips: reconciled });\n }\n if (next) {\n this._tracks = next;\n }\n }\n /** Prune id-bearing drop descriptors the engine no longer has, and refresh\n * the rest from their engine clip. Returns the SAME array when nothing\n * changed, so an unchanged track never triggers a re-render. */\n private _reconcileIdentifiedDropClips(\n clips: ClipDescriptor[],\n track: ClipTrack\n ): ClipDescriptor[] {\n const engineClips = new Map(track.clips.map((c) => [c.id, c]));\n let changed = false;\n const result: ClipDescriptor[] = [];\n for (const desc of clips) {\n if (isDomClip(desc) || desc.clipId === undefined) {\n result.push(desc);\n continue;\n }\n const clip = engineClips.get(desc.clipId);\n if (!clip) {\n changed = true;\n continue;\n }\n const sr = clip.sampleRate ?? this.effectiveSampleRate;\n const start = clip.startSample / sr;\n const duration = clip.durationSamples / sr;\n const offset = clip.offsetSamples / sr;\n const gain = clip.gain ?? desc.gain;\n const name = clip.name ?? desc.name;\n if (\n desc.start === start &&\n desc.duration === duration &&\n desc.offset === offset &&\n desc.gain === gain &&\n desc.name === name\n ) {\n result.push(desc);\n continue;\n }\n changed = true;\n result.push({ ...desc, start, duration, offset, gain, name });\n }\n return changed ? result : clips;\n }\n private static _CONTROL_PROPS = new Set(['volume', 'pan', 'muted', 'soloed']);\n private _onTrackControl = (e: CustomEvent) => {\n const { trackId, prop, value } = 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 const oldDescriptor = this._tracks.get(trackId);\n if (oldDescriptor) {\n const descriptor = { ...oldDescriptor, [prop]: value };\n this._tracks = new Map(this._tracks).set(trackId, descriptor);\n // Forward to engine with validated values\n if (this._engine) {\n if (prop === 'volume')\n this._engine.setTrackVolume(trackId, Math.max(0, Math.min(1, Number(value))));\n if (prop === 'pan')\n this._engine.setTrackPan(trackId, Math.max(-1, Math.min(1, Number(value))));\n if (prop === 'muted') this._engine.setTrackMute(trackId, Boolean(value));\n if (prop === 'soloed') this._engine.setTrackSolo(trackId, Boolean(value));\n }\n }\n // Don't sync back to <daw-track> DOM element — avoids daw-track-update loop.\n // _tracks descriptor map is the source of truth for 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 // Skip during initial track load — daw-track-connected reads all <daw-clip>\n // children synchronously via _readTrackDescriptor. Late-append clips trigger\n // an incremental load below.\n // \"Still loading\" = a _loadTrack in flight OR no engine track yet.\n // _engineTracks membership alone is NOT sufficient: the peaks-first path\n // inserts a render-only preview track mid-load — appending to it would\n // resolve the addClip() promise and then silently discard the clip when\n // the final commit overwrites the preview.\n if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {\n // _tracks is populated in _onTrackConnected before _loadTrack runs, so\n // having a descriptor without a loaded engine track means the parent is\n // still loading. _readTrackDescriptor already captured each existing\n // <daw-clip> child's id into descriptor.clips — those deferred\n // daw-clip-connected events are redundant and silent skip is correct.\n // Only a clipId that wasn't in the pre-load capture is a true\n // late-append; a missing descriptor means the parent was removed.\n // A missing descriptor is NOT an error: the clip's deferred connect\n // event can fire before the parent track's own deferred connect\n // registers the descriptor — _readTrackDescriptor will capture this\n // clip moments later. Silent skip.\n const desc = this._tracks.get(trackId);\n if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {\n const message =\n 'daw-clip-connected fired while parent track \"' +\n trackId +\n '\" is still loading — the clip will not be loaded. ' +\n 'Wait for daw-track-ready before appending more <daw-clip> children, ' +\n 'or use editor.addClip(trackId, config) after the track finishes loading.';\n console.warn('[dawcore] ' + message);\n // Settle the addClip() promise: _readTrackDescriptor snapshotted the\n // clip list at connect time, so nothing will ever load this clip —\n // without an error event the returned promise hangs forever.\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clipEl.clipId, error: new Error(message) },\n })\n );\n }\n return;\n }\n // Reconnect from a DOM move (custom elements fire disconnectedCallback+\n // connectedCallback on insertBefore, same as the track-level case in\n // _onTrackConnected) — or any other duplicate deferred daw-clip-connected\n // for a clip already registered on this FULLY LOADED track. Unlike the\n // still-loading branch above, _readTrackDescriptor cannot have filtered\n // this one out (that only runs once, before the track finished loading),\n // so this check is the only guard against _loadAndAppendClip inserting a\n // second engine clip with the same id. Reuses the exact same isDomClip\n // membership check as the still-loading branch.\n const loadedDesc = this._tracks.get(trackId);\n if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {\n return;\n }\n const clipDesc: ClipDescriptor = {\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 this._loadAndAppendClip(trackId, clipDesc);\n };\n private _onClipUpdate = (e: CustomEvent) => {\n const clipEl = e.target as DawClipElement;\n if (!(clipEl instanceof HTMLElement) || clipEl.tagName !== 'DAW-CLIP') return;\n const detail = e.detail as { trackId: string; clipId: string };\n if (!detail.trackId) {\n // <daw-clip> mounted outside a <daw-track> — developer error.\n console.warn(\n '[dawcore] daw-clip-update fired from a <daw-clip> not nested in a <daw-track> — ignored'\n );\n return;\n }\n this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);\n };\n private _onClipRemovedFromDom(clipEl: DawClipElement) {\n const clipId = clipEl.clipId;\n for (const [trackId, t] of this._engineTracks.entries()) {\n if (t.clips.some((c) => c.id === clipId)) {\n this._removeClipFromTrack(trackId, clipId);\n return;\n }\n }\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 private async _loadAndAppendClip(trackId: string, clipDesc: DomClipDescriptor) {\n if (!clipDesc.src) return; // Late-append of MIDI clips is not yet supported by _loadAndAppendClip — only _loadTrack handles the no-src MIDI branch on initial load.\n // Late-append always comes via _onClipConnected, which only fires for\n // <daw-clip> elements — so clipId is always known. We use it for the\n // error dispatch so the consumer's addClip Promise rejects with a usable\n // identifier even if _finalizeAudioClip throws before clip.id is set.\n const clipId = clipDesc.clipId;\n // Track which clip id has been inserted into per-clip caches so the catch\n // block can roll back partial state on any error past the cache writes.\n let insertedClipId: string | null = null;\n try {\n const trackDesc = this._tracks.get(trackId);\n const kindError = trackDesc\n ? this._clipKindError(trackDesc.name, trackDesc.kind, false, clipDesc.name || clipDesc.src)\n : null;\n if (kindError) throw kindError;\n // Concurrent fetches: peaks (if provided) + audio decode.\n const waveformDataPromise = clipDesc.peaksSrc\n ? this._resolvePeaks(clipDesc.peaksSrc)\n : Promise.resolve(null);\n const audioPromise = this._fetchAndDecode(clipDesc.src);\n const [waveformData, audioBuffer] = await Promise.all([waveformDataPromise, audioPromise]);\n this._resolvedSampleRate = audioBuffer.sampleRate;\n\n const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, waveformData);\n insertedClipId = clip.id;\n\n const t = this._engineTracks.get(trackId);\n if (!t) {\n // Track was removed during load — purge clip state\n this._purgeClipCaches(clip.id);\n return;\n }\n const updatedTrack: ClipTrack = { ...t, clips: [...t.clips, clip] };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n\n const desc = this._tracks.get(trackId);\n if (desc) {\n this._tracks = new Map(this._tracks).set(trackId, {\n ...desc,\n clips: [...desc.clips, clipDesc],\n });\n }\n this._commitTrackChange(trackId, updatedTrack);\n this._maybeRegisterSpectrogramClipAudio(trackId, clip);\n\n this.dispatchEvent(\n new CustomEvent<DawClipIdDetail>('daw-clip-ready', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clip.id },\n })\n );\n } catch (err) {\n // Always warn — even when disconnected — so the failure isn't silent.\n console.warn('[dawcore] _loadAndAppendClip failed: ' + String(err));\n // Roll back partial cache state so a retry isn't poisoned by stale entries.\n if (insertedClipId) this._purgeClipCaches(insertedClipId);\n // Detached elements can't bubble events, but the listener registered on\n // `this` via addClip will still fire — dispatch directly so the addClip\n // promise rejects instead of orphaning.\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: insertedClipId ?? clipId, error: err },\n })\n );\n }\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 * Shared between `_loadTrack` (peaks-first preview path) and\n * `_loadAndAppendClip` (incremental late-append).\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 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 /**\n * Construct an AudioClip from a decoded buffer (and optional WaveformData),\n * align its id with the source `<daw-clip>.clipId` when present, populate\n * `_clipBuffers` / `_clipOffsets`, generate peaks via the worker pipeline,\n * and populate `_peaksData`. Returns the finished AudioClip.\n *\n * Shared between `_loadTrack`'s standard path and `_loadAndAppendClip`.\n * Not used by `_loadTrack`'s peaks-first preview path because that path\n * uses sync `extractPeaks` and inserts a preview track BEFORE audio decode.\n */\n private async _finalizeAudioClip(\n clipDesc: ClipDescriptor,\n audioBuffer: AudioBuffer,\n waveformData: import('waveform-data').default | null\n ): Promise<AudioClip> {\n let clip: AudioClip;\n if (waveformData) {\n const wdRate = waveformData.sample_rate;\n clip = createClip({\n audioBuffer,\n waveformData,\n startSample: Math.round(clipDesc.start * wdRate),\n durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),\n offsetSamples: Math.round(clipDesc.offset * wdRate),\n gain: clipDesc.gain,\n name: clipDesc.name,\n sampleRate: wdRate,\n sourceDurationSamples: Math.ceil(waveformData.duration * wdRate),\n });\n this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);\n } else {\n clip = createClipFromSeconds({\n audioBuffer,\n startTime: clipDesc.start,\n duration: clipDesc.duration || audioBuffer.duration,\n offset: clipDesc.offset,\n gain: clipDesc.gain,\n name: clipDesc.name,\n sampleRate: audioBuffer.sampleRate,\n sourceDuration: audioBuffer.duration,\n });\n }\n if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;\n\n this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);\n this._clipOffsets.set(clip.id, {\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n });\n // generatePeaks can fail (worker crash, CSP, OOM). Purge the cache entries\n // we just inserted so the caller's catch path doesn't leak. The caller may\n // also call _purgeClipCaches in its own error handler — _purgeClipCaches\n // is idempotent.\n let peakData: PeakData;\n try {\n peakData = await this._peakPipeline.generatePeaks(\n audioBuffer,\n this._renderSpp,\n this.mono,\n clip.offsetSamples,\n clip.durationSamples\n );\n } catch (err) {\n this._purgeClipCaches(clip.id);\n throw err;\n }\n this._peaksData = new Map(this._peaksData).set(clip.id, peakData);\n // Raise the zoom-floor only after generatePeaks succeeds — without this,\n // a generatePeaks failure would strand _minSamplesPerPixel at a value\n // backed by no actual peaks (CLAUDE.md `samplesPerPixel` Zoom Floor rule).\n // Worker-generated peaks count too (cached at the pipeline base scale):\n // extractPeaks clamps to the cached scale, so a floor that ignores them\n // lets the zoom go finer than the peaks can render — squeezed waveforms.\n const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);\n this._raiseZoomFloor(cachedScale);\n return clip;\n }\n /**\n * Filter MIDI notes to only those with finite, in-range fields. Logs a\n * warning for each dropped note. Used by _buildMidiClip and the\n * _applyClipUpdate MIDI branch to prevent NaN propagation through the\n * timeline.\n */\n private _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 * A clip descriptor is treated as MIDI when it has no audio src.\n * Includes placeholder MIDI clips (no notes, no duration yet — registered\n * with a 1s default span; notes upgrade via _applyClipUpdate). Warns when\n * a clip ambiguously has both src and midiNotes — the audio path runs\n * and notes would be silently ignored.\n */\n private _isMidiDescriptor(clipDesc: ClipDescriptor): boolean {\n if (clipDesc.src) {\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 * Build an engine clip from a MIDI clip descriptor. Always returns a clip\n * — empty notes / no declared duration get a 1-second placeholder span so\n * the clip is reachable via `engine.updateTrack` once notes arrive.\n */\n private _buildMidiClip(clipDesc: ClipDescriptor): AudioClip {\n const sr = this.effectiveSampleRate;\n const notes = this._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(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);\n const requestedDurationSamples =\n clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;\n\n const clip = createClip({\n startSample: Math.round(clipDesc.start * sr),\n durationSamples: requestedDurationSamples,\n offsetSamples: Math.round(clipDesc.offset * sr),\n sampleRate: sr,\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 (isDomClip(clipDesc)) clip.id = clipDesc.clipId;\n return clip;\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 * Recompute duration and forward an updated track to the engine. Single\n * source of truth for the incremental-vs-full-rebuild policy used by every\n * clip-level mutation (addClip, updateClip, removeClip, _applyClipUpdate).\n * Use the engine's incremental updateTrack when available; otherwise fall\n * back to full setTracks (legacy adapters).\n */\n private _commitTrackChange(trackId: string, updatedTrack: ClipTrack) {\n this._recomputeDuration();\n if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);\n else if (this._engine)\n this._engine.setTracks(this._getOrderedTracks().map(([, track]) => track));\n }\n private _applyClipUpdate(trackId: string, clipId: string, clipEl: DawClipElement) {\n const t = this._engineTracks.get(trackId);\n if (!t) {\n console.warn('[dawcore] _applyClipUpdate: no engine track for id \"' + trackId + '\"');\n return;\n }\n const idx = t.clips.findIndex((c) => c.id === clipId);\n if (idx === -1) {\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 = t.clips[idx];\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 = this._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 const notes = this._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 const updatedClips = [...t.clips];\n updatedClips[idx] = updatedClip;\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n // Drop any audio caches in case this clip was previously loaded as audio.\n this._purgeClipCaches(clipId);\n this._commitTrackChange(trackId, updatedTrack);\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 const updatedClips = [...t.clips];\n updatedClips[idx] = updatedClip;\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\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._commitTrackChange(trackId, updatedTrack);\n }\n private _removeClipFromTrack(trackId: string, clipId: string) {\n const t = this._engineTracks.get(trackId);\n if (!t) {\n console.warn('[dawcore] _removeClipFromTrack: no engine track for id \"' + trackId + '\"');\n return;\n }\n const updatedClips = t.clips.filter((c) => c.id !== clipId);\n if (updatedClips.length === t.clips.length) {\n console.warn(\n '[dawcore] _removeClipFromTrack: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n\n const nextBuffers = new Map(this._clipBuffers);\n nextBuffers.delete(clipId);\n this._clipBuffers = nextBuffers;\n this._clipOffsets.delete(clipId);\n const nextPeaks = new Map(this._peaksData);\n nextPeaks.delete(clipId);\n this._peaksData = nextPeaks;\n\n const desc = this._tracks.get(trackId);\n if (desc) {\n this._tracks = new Map(this._tracks).set(trackId, {\n ...desc,\n // Descriptors without an id (file drops, the <daw-track src>\n // shorthand) are kept — their identity is the descriptor itself.\n clips: desc.clips.filter((c) => c.clipId !== clipId),\n });\n }\n this._commitTrackChange(trackId, updatedTrack);\n }\n private _readTrackDescriptor(trackEl: DawTrackElement): TrackDescriptor {\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) {\n clips.push({\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 }\n return {\n name: trackEl.name || 'Untitled',\n src: trackEl.src,\n volume: trackEl.volume,\n pan: trackEl.pan,\n muted: trackEl.muted,\n soloed: trackEl.soloed,\n kind: trackEl.kind,\n renderMode: trackDescriptorRenderMode(trackEl.kind, trackEl.renderMode),\n clips,\n };\n }\n /**\n * The error for a clip whose kind is not its track's (#756), or null. A clip\n * with no `src` is a MIDI clip (see _isMidiDescriptor).\n */\n private _clipKindError(\n trackName: string,\n kind: TrackDescriptor['kind'],\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 // --- Audio Loading ---\n private async _loadTrack(trackId: string, descriptor: TrackDescriptor) {\n // \"Still loading\" must be knowable independently of _engineTracks — the\n // peaks-first path inserts a PREVIEW track there mid-load, which would\n // otherwise make _onClipConnected treat a load-in-progress track as\n // fully loaded (late-appended clips silently discarded on final commit).\n this._loadingTracks.add(trackId);\n // Snapshot for the cancellation bail: this load's floor raises may\n // re-clamp (coarsen) the live zoom; a cancelled load restores it.\n const sppAtLoadStart = this._samplesPerPixel;\n try {\n const clips = [];\n // MIDI clips refused because the track is an audio track: they have no\n // src, so the \"all clips failed\" count below would not see them.\n let refusedMidiClips = 0;\n for (const clipDesc of descriptor.clips) {\n const clipIsMidi = this._isMidiDescriptor(clipDesc);\n const kindError = this._clipKindError(\n descriptor.name,\n descriptor.kind,\n clipIsMidi,\n clipDesc.name || clipDesc.src || (isDomClip(clipDesc) ? clipDesc.clipId : '')\n );\n if (kindError) {\n // Not added: a wrong-kind clip must never reach the engine, which\n // throws on a track that holds both kinds.\n console.warn('[dawcore] _loadTrack: ' + kindError.message);\n if (this.isConnected) {\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n clipId: isDomClip(clipDesc) ? clipDesc.clipId : '',\n error: kindError,\n },\n })\n );\n }\n if (clipIsMidi) refusedMidiClips++;\n continue;\n }\n if (clipIsMidi) {\n // MIDI clip path: no fetch, no peaks, register the clip directly.\n // Always registers (even with no notes / no duration) so late note\n // arrivals via daw-clip-update — handled in _applyClipUpdate\n // — can find the clip in _engineTracks.\n clips.push(this._buildMidiClip(clipDesc));\n continue;\n }\n // Per-clip try/catch: a single bad clip dispatches daw-clip-error and\n // skips to the next clip rather than aborting the whole track. Without\n // this, clip N's failure leaks earlier clips' cache writes from this\n // loop because the outer catch never reaches engine.setTracks().\n try {\n // Start both fetches concurrently — await peaks first to render preview before audio decode\n const waveformDataPromise = clipDesc.peaksSrc\n ? this._resolvePeaks(clipDesc.peaksSrc)\n : Promise.resolve(null);\n const audioPromise = this._fetchAndDecode(clipDesc.src);\n\n // --- Peaks-first path: render waveform before audio decode completes ---\n // _resolvePeaks returns null on fetch failure or sample-rate mismatch\n // (warns in either case); the standard path below handles the null case.\n const waveformData = await waveformDataPromise;\n if (waveformData) {\n // Create clip with integer samples to avoid float round-trip drift\n // (CLAUDE.md pattern #40: prefer createClip when samples known)\n const wdRate = waveformData.sample_rate;\n const clip = createClip({\n waveformData,\n startSample: Math.round(clipDesc.start * wdRate),\n durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),\n offsetSamples: Math.round(clipDesc.offset * wdRate),\n gain: clipDesc.gain,\n name: clipDesc.name,\n sampleRate: wdRate,\n sourceDurationSamples: Math.ceil(waveformData.duration * wdRate),\n });\n // Align engine clip.id with the source <daw-clip>.clipId (if any) so\n // DOM and engine refer to the same clip — required for editor.removeClip\n // and editor.updateClip lookups.\n if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;\n const effectiveScale = Math.max(this._renderSpp, waveformData.scale);\n const peakData = extractPeaks(\n waveformData,\n effectiveScale,\n this.mono,\n clip.offsetSamples,\n clip.durationSamples\n );\n this._clipOffsets.set(clip.id, {\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n });\n this._peaksData = new Map(this._peaksData).set(clip.id, peakData);\n this._raiseZoomFloor(waveformData.scale);\n\n // Render preview track immediately with peaks (render-only until audio\n // completes and engine.setTracks() runs at end of _loadTrack).\n // Skip when the track was removed while the .dat was fetching —\n // inserting would visibly resurrect the removed track for the\n // whole audio decode (the commit-time re-check only catches it\n // at the end).\n if (this._tracks.has(trackId)) {\n const previewTrack = createTrack({\n name: descriptor.name,\n kind: descriptor.kind,\n clips: [clip],\n volume: descriptor.volume,\n pan: descriptor.pan,\n muted: descriptor.muted,\n soloed: descriptor.soloed,\n });\n previewTrack.id = trackId;\n this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);\n this._recomputeDuration();\n }\n\n // Wait for audio decode — clean up preview state if it fails\n let audioBuffer: AudioBuffer;\n try {\n audioBuffer = await audioPromise;\n } catch (audioErr) {\n // Remove ghost preview so the user doesn't see a waveform with no audio\n const nextPeaks = new Map(this._peaksData);\n nextPeaks.delete(clip.id);\n this._peaksData = nextPeaks;\n this._clipOffsets.delete(clip.id);\n const nextEngine = new Map(this._engineTracks);\n nextEngine.delete(trackId);\n this._engineTracks = nextEngine;\n this._recomputeZoomFloor();\n this._recomputeDuration();\n throw audioErr; // Propagate to outer catch for daw-track-error event\n }\n this._resolvedSampleRate = audioBuffer.sampleRate;\n // Backfill audioBuffer immutably: new clip replaces the preview clip\n const updatedClip = { ...clip, audioBuffer };\n this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);\n this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);\n clips.push(updatedClip);\n continue;\n }\n\n // --- Standard path: decode audio first, then generate peaks ---\n // Reached only when the peaks-first branch above didn't kick in\n // (no peaksSrc, fetch failure, or sample-rate mismatch). waveformData\n // is always null here.\n const audioBuffer = await audioPromise;\n this._resolvedSampleRate = audioBuffer.sampleRate;\n const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, null);\n clips.push(clip);\n } catch (clipErr) {\n // _finalizeAudioClip and the peaks-first audio-decode catch already\n // purged their own per-clip caches before throwing here. Dispatch\n // daw-clip-error so consumers can correlate the failure to a clip.\n console.warn(\n '[dawcore] _loadTrack: clip \"' + clipDesc.src + '\" failed: ' + String(clipErr)\n );\n if (this.isConnected) {\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n clipId: isDomClip(clipDesc) ? clipDesc.clipId : '',\n error: clipErr,\n },\n })\n );\n }\n }\n }\n // Track removed while its clips were loading (removeTrack / element\n // removal during fetch/decode), or the editor itself was detached —\n // committing now would resurrect the track in the engine/UI, and on a\n // detached editor _ensureEngine() would build a fresh engine + adapter\n // graph that nothing ever disposes (disconnectedCallback already ran).\n // Undo this load's own writes (clip caches, a peaks-first preview\n // insert, the zoom floor it raised) and settle any addTrack() awaiter\n // via the outer catch's daw-track-error.\n const trackWasRemoved = !this._tracks.has(trackId);\n if (trackWasRemoved || !this.isConnected) {\n for (const clip of clips) {\n this._purgeClipCaches(clip.id);\n }\n if (this._engineTracks.has(trackId)) {\n const nextEngine = new Map(this._engineTracks);\n nextEngine.delete(trackId);\n this._engineTracks = nextEngine;\n this._recomputeDuration();\n }\n this._recomputeZoomFloor();\n // Undo the coarsening this load's own floor re-clamp forced on the\n // live zoom — the load that required it no longer exists. Restore\n // only when the recomputed floor allows it.\n if (\n this._samplesPerPixel !== sppAtLoadStart &&\n sppAtLoadStart >= this._minSamplesPerPixel\n ) {\n this.samplesPerPixel = sppAtLoadStart;\n }\n throw new TrackLoadCancelledError(\n trackWasRemoved\n ? 'track \"' + trackId + '\" was removed while loading'\n : 'editor was disconnected while track \"' + trackId + '\" was loading',\n trackWasRemoved ? 'removed' : 'disconnected'\n );\n }\n const track = createTrack({\n name: descriptor.name,\n kind: descriptor.kind,\n clips,\n volume: descriptor.volume,\n pan: descriptor.pan,\n muted: descriptor.muted,\n soloed: descriptor.soloed,\n });\n // If clips were requested but ALL failed to load, surface as a track-level\n // error so addTrack({clips: [...]}) rejects appropriately. Per-clip\n // daw-clip-error events have already fired for each individual failure.\n const requestedClips = descriptor.clips.filter((c) => c.src).length + refusedMidiClips;\n if (requestedClips > 0 && clips.length === 0) {\n throw new Error(\n 'all ' + requestedClips + ' clip(s) failed to load — see prior daw-clip-error events'\n );\n }\n // Align track.id with the editor's trackId so engine.setTrackSolo/Mute/etc. find it\n track.id = trackId;\n this._engineTracks = new Map(this._engineTracks).set(trackId, track);\n this._recomputeDuration();\n // Now that descriptor is recorded and clips have ids, push audio into\n // the spectrogram controller (no-op unless renderMode === 'spectrogram').\n for (const c of clips) {\n this._maybeRegisterSpectrogramClipAudio(trackId, c);\n }\n const engine = await this._ensureEngine();\n engine.setTracks(this._getOrderedTracks().map(([, track]) => track));\n this.dispatchEvent(\n new CustomEvent<DawTrackIdDetail>('daw-track-ready', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n } catch (err) {\n const cancelled = err instanceof TrackLoadCancelledError;\n // A cancellation is a normal user action (removal / teardown), not a\n // failure — don't log it as one.\n console.warn(\n cancelled\n ? '[dawcore] Track load cancelled: ' + (err as Error).message\n : '[dawcore] Failed to load track \"' + trackId + '\": ' + String(err)\n );\n // Dispatch even when detached: a bubbling event can't reach ancestors\n // (CLAUDE.md pattern #36), but the _awaitId listeners registered on\n // `this` for addTrack()/loadMidi() still fire on a detached element —\n // skipping the dispatch leaves those promises unsettled forever\n // (mirrors _loadAndAppendClip's error path). Cancellations carry\n // detail.reason so consumer error UIs can filter them.\n this.dispatchEvent(\n new CustomEvent<DawTrackErrorDetail>('daw-track-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n error: err,\n ...(cancelled ? { reason: (err as TrackLoadCancelledError).reason } : {}),\n },\n })\n );\n } finally {\n this._loadingTracks.delete(trackId);\n }\n }\n async _fetchAndDecode(src: string): Promise<AudioBuffer> {\n if (this._audioCache.has(src)) {\n return this._audioCache.get(src)!;\n }\n const promise = (async () => {\n const response = await fetch(src);\n if (!response.ok) {\n throw new Error(\n 'Failed to fetch audio \"' + src + '\": ' + response.status + ' ' + response.statusText\n );\n }\n const arrayBuffer = await response.arrayBuffer();\n return this.audioContext.decodeAudioData(arrayBuffer);\n })();\n this._audioCache.set(src, promise);\n try {\n return await promise;\n } catch (err) {\n this._audioCache.delete(src);\n throw err;\n }\n }\n private _fetchPeaks(src: string): Promise<import('waveform-data').default> {\n const cached = this._peaksCache.get(src);\n if (cached) return cached;\n const promise = loadWaveformDataFromUrl(src).catch((err) => {\n this._peaksCache.delete(src);\n throw err;\n });\n this._peaksCache.set(src, promise);\n return promise;\n }\n _recomputeDuration() {\n let maxSample = 0;\n for (const track of this._engineTracks.values()) {\n for (const clip of track.clips) {\n const endSample = clip.startSample + clip.durationSamples;\n if (endSample > maxSample) maxSample = endSample;\n }\n }\n this._duration = maxSample / this.effectiveSampleRate;\n }\n // --- Engine ---\n _ensureEngine(): Promise<PlaylistEngine> {\n if (this._engine) return Promise.resolve(this._engine);\n if (this._enginePromise) return this._enginePromise;\n this._enginePromise = this._buildEngine().catch((err) => {\n this._enginePromise = null;\n throw err;\n });\n return this._enginePromise;\n }\n private async _buildEngine() {\n if (!this._externalAdapter) {\n throw new Error(noAdapterError());\n }\n if (this._adapterConsumedByDispose) {\n // The previous disconnect disposed this adapter through the engine.\n // Some adapters (NativePlayoutAdapter) leave the AudioContext open, so\n // building on it would decode fine but wire tracks into a dead\n // transport graph — waveforms without audio. Fail loudly instead.\n throw new Error(\n '[dawcore] editor.adapter was disposed by a previous disconnect — ' +\n 'set a fresh PlayoutAdapter after reparenting <daw-editor>.'\n );\n }\n\n const { PlaylistEngine } = await import('@waveform-playlist/engine');\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 PlaylistEngine({\n adapter,\n sampleRate: this.effectiveSampleRate,\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 let lastTracksVersion = -1;\n let lastMixerVersion = -1;\n engine.on('statechange', (engineState) => {\n this._isPlaying = engineState.isPlaying;\n this._duration = engineState.duration;\n this._selectedTrackId = engineState.selectedTrackId;\n const structuralChange = engineState.tracksVersion !== lastTracksVersion;\n // Per-track mixer edits (volume/mute/solo/pan) bump mixerVersion, NOT\n // tracksVersion (#501). Refresh the _engineTracks cache on either so the\n // next setTracks rebuild keeps live mixer state — 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 !== lastMixerVersion;\n if (structuralChange || mixerChange) {\n lastTracksVersion = engineState.tracksVersion;\n lastMixerVersion = engineState.mixerVersion;\n const nextTracks = new Map<string, ClipTrack>();\n for (const track of engineState.tracks) {\n nextTracks.set(track.id, track);\n }\n this._engineTracks = nextTracks;\n // Undo can resurrect a track whose editor descriptor was purged at\n // removal — synthesize one so the track shows real name/controls\n // and appears in editor.tracks (the effects chain does not survive;\n // it was disposed at removal).\n this._reconcileDescriptorsWithEngineTracks(engineState.tracks);\n }\n // Sync clip positions when tracks change structurally (moveClip, trimClip,\n // splitClip, setTracks, addTrack, removeTrack).\n if (structuralChange) {\n // Engine-initiated order changes (undo/redo of a reorder) move the\n // DOM to match; guarded so the observer's own DOM→engine sync (which\n // emits intermediate statechanges mid-transaction) can't bounce\n // half-applied orders back into the DOM (#612).\n if (!this._inOrderSync) {\n this._syncDomToEngineOrder(engineState.tracks);\n }\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 syncPeaksForChangedClips(this, audioTracks);\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 engine.on('pause', () => {\n this._currentTime = engine.getCurrentTime();\n });\n engine.on('stop', () => {\n // Fires synchronously from PlaylistEngine.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\n this._engine = engine;\n return engine;\n }\n private _disposeEngine() {\n if (this._engine) {\n this._engine.dispose();\n this._engine = null;\n }\n this._enginePromise = null;\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(files: FileList | File[]): Promise<LoadFilesResult> {\n return loadFilesImpl(this, files);\n }\n /**\n * Imperatively load a `.mid` file (URL or File) and create N `<daw-track>`\n * elements — one per note-bearing MIDI track. On any per-track failure,\n * every `<daw-track>` appended during the call is removed (both successful\n * and failed) so the editor returns to its pre-call state.\n *\n * `options.signal` is forwarded to `fetch()` only for URL sources; aborting\n * after parsing does not cancel in-flight `addTrack` calls.\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<PlaylistEngine> {\n return this._ensureEngine();\n }\n /**\n * Wait for either `readyEvent` or `errorEvent` to fire on this editor for\n * the entity matching `matchesId`. Listeners are wired synchronously, then\n * `setup` is called (typical: appendChild). Resolves with `resolveValue`\n * on ready; rejects with a normalized Error on error. Used by addTrack and\n * addClip to share their Promise-with-listener-cleanup machinery.\n */\n private _awaitId<T>(\n readyEvent: string,\n errorEvent: string,\n matchesId: (detail: { trackId?: string; clipId?: string }) => boolean,\n resolveValue: T,\n setup: () => void\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onReady = (e: Event) => {\n if (!matchesId((e as CustomEvent).detail)) return;\n cleanup();\n resolve(resolveValue);\n };\n const onError = (e: Event) => {\n const detail = (e as CustomEvent).detail as { error?: unknown };\n if (!matchesId((e as CustomEvent).detail)) return;\n cleanup();\n const err = detail.error;\n reject(err instanceof Error ? err : new Error(String(err)));\n };\n const cleanup = () => {\n this.removeEventListener(readyEvent, onReady);\n this.removeEventListener(errorEvent, onError);\n };\n this.addEventListener(readyEvent, onReady);\n this.addEventListener(errorEvent, onError);\n setup();\n });\n }\n /**\n * Append a `<daw-track>` element built from `config` and resolve once the\n * track finishes loading (or reject on `daw-track-error`). Goes through\n * the same `_loadTrack` pipeline as declarative tracks, so descriptors,\n * peaks, and clip buffers are populated correctly.\n */\n addTrack(config: TrackConfig = {}): Promise<DawTrackElement> {\n const trackEl = document.createElement('daw-track') as DawTrackElement;\n if (config.name !== undefined) trackEl.setAttribute('name', config.name);\n if (config.volume !== undefined) trackEl.volume = config.volume;\n if (config.pan !== undefined) trackEl.pan = config.pan;\n if (config.muted) trackEl.setAttribute('muted', '');\n if (config.soloed) trackEl.setAttribute('soloed', '');\n\n // kind: explicit > 'midi' from the midi shorthand > default 'audio'. A\n // MIDI track is drawn as a piano roll whatever render-mode says.\n const kind = config.kind ?? (config.midi ? 'midi' : undefined);\n if (kind !== undefined) trackEl.setAttribute('kind', kind);\n if (config.renderMode !== undefined) trackEl.setAttribute('render-mode', config.renderMode);\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 for (const clipConfig of clipConfigs) {\n trackEl.appendChild(this._buildClipElement(clipConfig));\n }\n\n return this._awaitId(\n 'daw-track-ready',\n 'daw-track-error',\n (d) => d.trackId === trackEl.trackId,\n trackEl,\n () => this.appendChild(trackEl)\n );\n }\n /**\n * Remove a track by id. Equivalent to `trackElement.remove()` —\n * the editor's MutationObserver handles engine and cache cleanup.\n * No-op if no matching track exists.\n */\n removeTrack(trackId: string): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n trackEl.remove();\n } else if (this._engineTracks.has(trackId)) {\n // File-dropped tracks have no DOM element; clean up engine state directly.\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 new position in the vertical order (0-based index among\n * `<daw-track>` elements). Element-backed tracks move their DOM element —\n * the MutationObserver syncs the engine (single write path). Element-less\n * tracks (undo-resurrected) reorder the engine directly.\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 const el = this._trackElements.get(trackId);\n if (el) {\n const els = [...this.querySelectorAll('daw-track')] as DawTrackElement[];\n const from = els.indexOf(el);\n if (from === -1) return;\n const clamped = Math.max(0, Math.min(toIndex, els.length - 1));\n if (from === clamped) return;\n const anchor = els[clamped];\n if (clamped > from) anchor.after(el);\n else anchor.before(el);\n } else if (this._engineTracks.has(trackId)) {\n this._engine!.reorderTrack(trackId, toIndex);\n this.requestUpdate();\n } else {\n console.warn('[dawcore] reorderTrack: no track found for id \"' + trackId + '\"');\n }\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 * Update reflected attributes on a track. For DOM-element tracks the changes\n * are written to the `<daw-track>` element (which fires `daw-track-update`);\n * for tracks without a DOM element (file drops) the descriptor and engine\n * state are updated in place.\n */\n updateTrack(trackId: string, partial: Partial<TrackConfig>): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n // Mutating reflected props triggers daw-track-update which propagates\n // to engine via _onTrackUpdate.\n if (partial.name !== undefined) trackEl.setAttribute('name', partial.name);\n if (partial.volume !== undefined) trackEl.volume = partial.volume;\n if (partial.pan !== undefined) trackEl.pan = partial.pan;\n if (partial.muted !== undefined) {\n if (partial.muted) trackEl.setAttribute('muted', '');\n else trackEl.removeAttribute('muted');\n }\n if (partial.soloed !== undefined) {\n if (partial.soloed) trackEl.setAttribute('soloed', '');\n else trackEl.removeAttribute('soloed');\n }\n if (partial.renderMode !== undefined) trackEl.setAttribute('render-mode', partial.renderMode);\n return;\n }\n // No DOM element — apply directly to descriptor + engine.\n const oldDesc = this._tracks.get(trackId);\n if (!oldDesc) return;\n let normalizedRenderMode =\n partial.renderMode === undefined ? undefined : normalizeRenderMode(partial.renderMode);\n if (normalizedRenderMode === 'both') {\n console.warn(\n '[dawcore] render-mode=\"both\" is not yet supported; falling back to \\'spectrogram\\''\n );\n normalizedRenderMode = 'spectrogram';\n }\n const newDesc: TrackDescriptor = {\n ...oldDesc,\n ...(partial.name !== undefined && { name: partial.name }),\n ...(partial.volume !== undefined && { volume: partial.volume }),\n ...(partial.pan !== undefined && { pan: partial.pan }),\n ...(partial.muted !== undefined && { muted: partial.muted }),\n ...(partial.soloed !== undefined && { soloed: partial.soloed }),\n ...(normalizedRenderMode !== undefined && {\n renderMode: trackDescriptorRenderMode(oldDesc.kind, normalizedRenderMode),\n }),\n };\n this._tracks = new Map(this._tracks).set(trackId, newDesc);\n if (this._engine) {\n if (partial.volume !== undefined) this._engine.setTrackVolume(trackId, partial.volume);\n if (partial.pan !== undefined) this._engine.setTrackPan(trackId, partial.pan);\n if (partial.muted !== undefined) this._engine.setTrackMute(trackId, partial.muted);\n if (partial.soloed !== undefined) this._engine.setTrackSolo(trackId, partial.soloed);\n }\n }\n /**\n * Append a clip to an existing track. Builds a `<daw-clip>` from `config`\n * and appends it to the track's DOM element when one exists; resolves with\n * the new clip's id once the audio decode + peak generation finish.\n */\n addClip(trackId: string, config: ClipConfig): Promise<string> {\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 trackEl = this._trackElements.get(trackId);\n if (!trackEl) {\n return Promise.reject(\n new Error(\n 'addClip: no <daw-track> element for trackId \"' +\n trackId +\n '\" — addClip currently requires a DOM-backed track. Use editor.addTrack(config) first.'\n )\n );\n }\n const clipEl = this._buildClipElement(config);\n return this._awaitId(\n 'daw-clip-ready',\n 'daw-clip-error',\n (d) => d.clipId === clipEl.clipId,\n clipEl.clipId,\n () => trackEl.appendChild(clipEl)\n );\n }\n /**\n * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when\n * present (MutationObserver handles cleanup); otherwise updates engine\n * state directly. No-op if no matching clip exists.\n */\n removeClip(trackId: string, clipId: string): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n const clipEl = [...trackEl.querySelectorAll('daw-clip')].find(\n (c) => (c as DawClipElement).clipId === clipId\n ) as DawClipElement | undefined;\n if (clipEl) {\n clipEl.remove();\n return;\n }\n }\n if (this._engineTracks.has(trackId)) {\n this._removeClipFromTrack(trackId, clipId);\n return;\n }\n console.warn(\n '[dawcore] removeClip: no track found for id \"' + trackId + '\" (clipId \"' + clipId + '\")'\n );\n }\n /**\n * Update a clip's position (start/duration/offset) or properties (gain/name).\n * For DOM-element clips, writes properties on the `<daw-clip>` element which\n * fires `daw-clip-update`; otherwise applies directly via `_applyClipUpdate`.\n *\n * Re-decoding (changing `src`) is not supported via this method — remove and\n * re-add the clip instead.\n *\n * Note: `fadeIn` / `fadeOut` / `fadeType` on the partial are written to the\n * `<daw-clip>` element (so they round-trip in the descriptor), but engine-side\n * fade application from `<daw-clip>` properties is not yet implemented — see\n * the broader fade-engine integration tracked separately.\n */\n updateClip(trackId: string, clipId: string, partial: Partial<ClipConfig>): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n const clipEl = [...trackEl.querySelectorAll('daw-clip')].find(\n (c) => (c as DawClipElement).clipId === clipId\n ) as DawClipElement | undefined;\n if (clipEl) {\n if (partial.start !== undefined) clipEl.start = partial.start;\n if (partial.duration !== undefined) clipEl.duration = partial.duration;\n if (partial.offset !== undefined) clipEl.offset = partial.offset;\n if (partial.gain !== undefined) clipEl.gain = partial.gain;\n if (partial.name !== undefined) clipEl.setAttribute('name', partial.name);\n if (partial.fadeIn !== undefined) clipEl.fadeIn = partial.fadeIn;\n if (partial.fadeOut !== undefined) clipEl.fadeOut = partial.fadeOut;\n if (partial.fadeType !== undefined) clipEl.setAttribute('fade-type', partial.fadeType);\n return;\n }\n }\n // No DOM element — apply changes directly.\n const t = this._engineTracks.get(trackId);\n if (!t) {\n console.warn('[dawcore] updateClip: no track found for id \"' + trackId + '\"');\n return;\n }\n const idx = t.clips.findIndex((c) => c.id === clipId);\n if (idx === -1) {\n console.warn(\n '[dawcore] updateClip: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n const oldClip = t.clips[idx];\n const sr = oldClip.sampleRate ?? this.effectiveSampleRate;\n const updatedClip = {\n ...oldClip,\n ...(partial.start !== undefined && { startSample: Math.round(partial.start * sr) }),\n ...(partial.duration !== undefined &&\n partial.duration > 0 && { durationSamples: Math.round(partial.duration * sr) }),\n ...(partial.offset !== undefined && { offsetSamples: Math.round(partial.offset * sr) }),\n ...(partial.gain !== undefined && { gain: partial.gain }),\n ...(partial.name !== undefined && { name: partial.name }),\n };\n const updatedClips = [...t.clips];\n updatedClips[idx] = updatedClip;\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n // Keep editor.tracks truthful for element-less clips that carry their\n // engine id (recorded takes, #659) — no <daw-clip> element re-reads them.\n const desc = this._tracks.get(trackId);\n if (desc?.clips.some((c) => c.clipId === clipId)) {\n this._tracks = new Map(this._tracks).set(trackId, {\n ...desc,\n clips: desc.clips.map((c) =>\n c.clipId === clipId\n ? {\n ...c,\n start: updatedClip.startSample / sr,\n duration: updatedClip.durationSamples / sr,\n offset: updatedClip.offsetSamples / sr,\n ...(partial.gain !== undefined && { gain: partial.gain }),\n ...(partial.name !== undefined && { name: partial.name }),\n }\n : c\n ),\n });\n }\n this._commitTrackChange(trackId, updatedTrack);\n }\n private _buildClipElement(config: ClipConfig): DawClipElement {\n const clipEl = document.createElement('daw-clip') as DawClipElement;\n if (config.src !== undefined) clipEl.setAttribute('src', config.src);\n if (config.peaksSrc !== undefined) clipEl.setAttribute('peaks-src', config.peaksSrc);\n if (config.start !== undefined) clipEl.start = config.start;\n if (config.duration !== undefined) clipEl.duration = config.duration;\n if (config.offset !== undefined) clipEl.offset = config.offset;\n if (config.gain !== undefined) clipEl.gain = config.gain;\n if (config.name !== undefined) clipEl.setAttribute('name', config.name);\n if (config.fadeIn !== undefined) clipEl.fadeIn = config.fadeIn;\n if (config.fadeOut !== undefined) clipEl.fadeOut = config.fadeOut;\n if (config.fadeType !== undefined) clipEl.setAttribute('fade-type', config.fadeType);\n if (config.midiNotes !== undefined) clipEl.midiNotes = config.midiNotes;\n if (config.midiChannel !== undefined)\n clipEl.setAttribute('midi-channel', String(config.midiChannel));\n if (config.midiProgram !== undefined)\n clipEl.setAttribute('midi-program', String(config.midiProgram));\n return clipEl;\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() (PlaylistEngine 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 /** Undo the last structural edit. */\n undo(): void {\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. */\n redo(): void {\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 ? this._tracks.get(targetId) : undefined;\n if (targetId && target?.kind === '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 /** Guards the statechange handler's engine→DOM sync (Task: reorder #612)\n * while the observer is pushing DOM order INTO the engine — the intermediate\n * statechange emissions during the transaction would otherwise bounce\n * half-applied orders back into the DOM. */\n _inOrderSync = false;\n\n /**\n * DOM → engine: make the engine's track order match the light-DOM\n * `<daw-track>` order. Single write path for reorders — editor-initiated\n * (buttons/drag move the element) and consumer-initiated (insertBefore)\n * mutations both land here via the MutationObserver. Element-less tracks\n * (undo-resurrected) keep their engine positions (stable sort).\n * Write-only-on-change: a no-op when orders already match, so the\n * engine→DOM direction (statechange handler) converges in one pass.\n */\n _syncEngineOrderToDom(): void {\n const engine = this._engine;\n if (!engine) return;\n const domOrder: string[] = [...this.querySelectorAll('daw-track')].map(\n (el) => (el as DawTrackElement).trackId\n );\n const engineIds: string[] = engine.getState().tracks.map((t) => t.id);\n const target = [...engineIds].sort((a, b) => {\n const ai = domOrder.indexOf(a);\n const bi = domOrder.indexOf(b);\n if (ai === -1 || bi === -1) return 0; // element-less: keep relative position\n return ai - bi;\n });\n if (target.every((id, i) => id === engineIds[i])) return;\n this._inOrderSync = true;\n try {\n engine.beginTransaction(); // one undo step for the whole permutation\n const current = [...engineIds];\n for (let i = 0; i < target.length; i++) {\n if (current[i] === target[i]) continue;\n engine.reorderTrack(target[i], i);\n const from = current.indexOf(target[i]);\n current.splice(from, 1);\n current.splice(i, 0, target[i]);\n }\n engine.commitTransaction();\n } finally {\n this._inOrderSync = false;\n }\n this.requestUpdate();\n }\n\n /**\n * Engine → DOM: after an engine-initiated order change (undo/redo), move\n * `<daw-track>` elements to match engine order. The resulting mutations fire\n * the observer's _syncEngineOrderToDom, which finds the orders equal and\n * no-ops — converges in one pass (write-only-on-change).\n */\n _syncDomToEngineOrder(tracks: readonly ClipTrack[]): void {\n const els = [...this.querySelectorAll('daw-track')] as DawTrackElement[];\n if (els.length < 2) return;\n const byId = new Map<string, DawTrackElement>(els.map((el) => [el.trackId, el]));\n const desired = tracks\n .map((t) => byId.get(t.id))\n .filter((el): el is DawTrackElement => el != null);\n if (desired.length < 2) return;\n // Permute engine-known elements into engine order. Elements the engine\n // hasn't seen yet (tracks still loading — the engine holds only the\n // loaded subset during startup) are never moved, so they keep their\n // relative order among themselves (their absolute index can still shift\n // when engine-known neighbors move around them); anchoring desired[0] at\n // els[0] instead would promote the loaded subset to the top and reorder\n // tracks by decode-completion order (#625).\n const desiredSet = new Set(desired);\n const slots = els.filter((el) => desiredSet.has(el));\n if (desired.every((el, i) => el === slots[i])) return;\n for (let i = 0; i < desired.length; i++) {\n if (slots[i] === desired[i]) continue;\n // desired[i] currently sits at a later slot (earlier ones are settled);\n // insert it directly before the element occupying slot i.\n slots[i].before(desired[i]);\n const from = slots.indexOf(desired[i]);\n slots.splice(from, 1);\n slots.splice(i, 0, desired[i]);\n }\n }\n\n private _getOrderedTracks(): Array<[string, ClipTrack]> {\n const domOrder: string[] = [...this.querySelectorAll('daw-track')].map(\n (el) => (el as DawTrackElement).trackId\n );\n return [...this._engineTracks.entries()].sort((a, b) => {\n const ai = domOrder.indexOf(a[0]);\n const bi = domOrder.indexOf(b[0]);\n // Both not in DOM (e.g. file drops): preserve Map insertion order\n if (ai === -1 && bi === -1) return 0;\n // Only one not in DOM: sort it after DOM tracks\n if (ai === -1) return 1;\n if (bi === -1) return -1;\n return ai - bi;\n });\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]) => {\n const descriptor = this._tracks.get(trackId);\n const firstPeaks = track.clips\n .map((c) => this._peaksData.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 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 ${orderedTracks.map(\n (t, i) => html`\n <daw-track-controls\n style=\"height: ${t.trackHeight}px;\"\n .trackId=${t.trackId}\n .trackName=${t.descriptor?.name ?? 'Untitled'}\n .volume=${t.descriptor?.volume ?? 1}\n .pan=${t.descriptor?.pan ?? 0}\n .muted=${t.descriptor?.muted ?? false}\n .soloed=${t.descriptor?.soloed ?? false}\n .reorderable=${this.trackReordering}\n .trackIndex=${i}\n .trackCount=${orderedTracks.length}\n ></daw-track-controls>\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 ${orderedTracks.map((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 = this._peaksData.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(MIN_RENDER_STEP, Math.ceil(this.ticksPerPixel));\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(startSec + clip.durationSamples / sr);\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 ${this._renderRecordingPreview(t.trackId, channelHeight)}\n </div>\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 const pixPerSec = sampleRate / samplesPerPixel;\n\n // Iterate with integer counter (milliseconds) to avoid float precision drift.\n // Compute pixel position from counter each iteration instead of accumulating.\n for (let counter = 0; ; counter += smallStep) {\n const pix = Math.floor((counter / 1000) * pixPerSec);\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 type { DawTrackReorderDetail, DawTrackReorderGrabDetail } 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 @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 static styles = css`\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 protected firstUpdated(): void {\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);\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);\n };\n\n private _onMuteClick = () => {\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 private _dispatchControl(prop: string, value: number | boolean) {\n if (!this.trackId) return;\n this.dispatchEvent(\n new CustomEvent('daw-track-control', {\n bubbles: true,\n composed: true,\n detail: { trackId: this.trackId, prop, value },\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 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 .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\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._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._resizeObserver?.disconnect();\n this._resizeObserver = null;\n this._scrollContainer = null;\n }\n\n private _attachScrollContainer(container: HTMLElement) {\n this._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._resizeObserver?.disconnect();\n this._scrollContainer = container;\n container.addEventListener('scroll', this._onScroll, { passive: true });\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 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 resolvedTarget.addEventListener('pointerdown', this._onGesture, {\n once: true,\n capture: true,\n });\n resolvedTarget.addEventListener('keydown', this._onGesture, {\n once: true,\n capture: true,\n });\n });\n }\n\n hostDisconnected() {\n this._removeListeners();\n this._attached = false;\n }\n\n private _onGesture = (e: Event) => {\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 // Remove the other listener (the fired one was auto-removed by { once: true })\n const otherType = e.type === 'pointerdown' ? 'keydown' : 'pointerdown';\n this._target?.removeEventListener(otherType, this._onGesture, {\n capture: true,\n });\n this._target = null;\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._target.removeEventListener('pointerdown', this._onGesture, {\n capture: true,\n });\n this._target.removeEventListener('keydown', this._onGesture, {\n capture: true,\n });\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 /** Pre-session mute state of the armed track — restored when the session\n * ends. null = mute never engaged (no engine on the host). */\n armedPrevMuted: boolean | null;\n readonly wasOverdub: boolean;\n /** Stored so it can be removed on stop/cleanup — not just when stream ends. */\n readonly _onTrackEnded: (() => void) | null;\n readonly _audioTrack: MediaStreamTrack | null;\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' | '_onTrackEnded' | '_audioTrack' | '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 resolveAudioContextSampleRate(rate: number): void;\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 armed-track transient\n * mute (punch-in replaces the overlapped content, so the recorded-over\n * track's existing material must not play under the take). Optional —\n * hosts without an engine skip the mute. */\n _engine?: {\n setTrackMute(trackId: string, muted: boolean): void;\n getState(): { tracks: ReadonlyArray<{ id: string; muted: boolean }> };\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 /** 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 // Resolve editor sample rate from AudioContext before computing startSample\n this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);\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 armedPrevMuted: null,\n wasOverdub: options.overdub ?? false,\n _onTrackEnded: onTrackEnded,\n _audioTrack: audioTrack,\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 audioTrack.addEventListener('ended', onTrackEnded);\n }\n\n // Transiently mute the armed track for the session — punch-in replaces\n // whatever the take overlaps (#579), so the doomed material must not\n // play under the overdub. Engine-level only: the editor's _tracks\n // descriptors (the UI mute control) are untouched. Restored by\n // _restoreArmedTrackMute on every session-teardown path. Must engage\n // BEFORE the overdub host.play() below so the track never blips.\n // (Parity with the React provider's setRecordingActive.)\n const engine = this._host._engine;\n if (engine) {\n session.armedPrevMuted =\n engine.getState().tracks.find((t) => t.id === trackId)?.muted ?? false;\n engine.setTrackMute(trackId, true);\n }\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 // armed-track transient mute engaged. 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._restoreArmedTrackMute(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 if (session._audioTrack && session._onTrackEnded) {\n session._audioTrack.removeEventListener('ended', session._onTrackEnded);\n }\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): restore the armed-track\n * mute, drop the session, and notify via daw-recording-error so record\n * buttons reset 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._restoreArmedTrackMute(session);\n this._sessions.delete(id);\n this._host.requestUpdate();\n this._dispatchRecordingError(id, new Error(errorMessage));\n }\n\n /** Restore the armed track's pre-session mute state (idempotent — safe to\n * call from both the finalize path and _cleanupSession). */\n private _restoreArmedTrackMute(session: RecordingSession) {\n if (session.armedPrevMuted === null) return;\n this._host._engine?.setTrackMute(session.trackId, session.armedPrevMuted);\n session.armedPrevMuted = null;\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._restoreArmedTrackMute(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 hostConnected(): void {\n this._host.addEventListener('daw-annotation-update', this._onDataChange);\n this._host.addEventListener('daw-annotation-select', this._onDataChange);\n this._host.addEventListener('daw-annotation-connected', this._onDataChange);\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);\n this._host.addEventListener('daw-stop', this._onStop);\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._host.removeEventListener('daw-annotation-update', this._onDataChange);\n this._host.removeEventListener('daw-annotation-select', this._onDataChange);\n this._host.removeEventListener('daw-annotation-connected', this._onDataChange);\n this._host.removeEventListener('daw-timeupdate', this._onTimeUpdate as EventListener);\n this._host.removeEventListener('daw-stop', this._onStop);\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 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 const detach = (pe: PointerEvent) => {\n this._timeline?.removeEventListener('pointermove', onMove);\n this._timeline?.removeEventListener('pointerup', onUp);\n this._timeline?.removeEventListener('pointercancel', onCancel);\n try {\n this._timeline?.releasePointerCapture(pe.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);\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);\n };\n this._timeline.addEventListener('pointermove', onMove);\n this._timeline.addEventListener('pointerup', onUp);\n this._timeline.addEventListener('pointercancel', onCancel);\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 this._timeline.addEventListener('pointermove', this._onPointerMove);\n this._timeline.addEventListener('pointerup', this._onPointerUp);\n this._timeline.addEventListener('pointercancel', this._onPointerCancel);\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._timeline.removeEventListener('pointermove', this._onPointerMove);\n this._timeline.removeEventListener('pointerup', this._onPointerUp);\n this._timeline.removeEventListener('pointercancel', this._onPointerCancel);\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 { SnapTo, MeterEntry } from '@waveform-playlist/core';\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 moveClip(trackId: string, clipId: string, deltaSamples: number, skipAdapter?: boolean): number;\n trimClip(\n trackId: string,\n clipId: string,\n boundary: 'left' | 'right',\n deltaSamples: number,\n skipAdapter?: boolean\n ): void;\n updateTrack(trackId: string): void;\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 /** Begin a transaction — groups mutations into one undo step. */\n beginTransaction(): void;\n /** Commit the transaction — pushes one undo step for all grouped mutations. */\n commitTransaction(): void;\n /** Abort the transaction — restores pre-transaction state without pushing to undo. */\n abortTransaction(): void;\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 * Move: sends incremental deltas per-frame with skipAdapter=true (engine shifts\n * startSample additively without touching audio adapter). Adapter synced once\n * via updateTrack() at drag end.\n * Trim: updates clip container CSS imperatively during drag for visual feedback,\n * then applies cumulative delta to engine once at drag end.\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\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 /** Returns true if a drag interaction is currently in progress. */\n get isActive(): boolean {\n return this._mode !== null;\n }\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 // Snapshot clip start position for snap calculations\n const engine = this._host.engine;\n if (engine) {\n const bounds = engine.getClipBounds(trackId, clipId);\n if (bounds) {\n this._originalStartSample = bounds.startSample;\n }\n }\n\n // Group all drag mutations into one undo step\n if (engine) {\n engine.beginTransaction();\n } else {\n console.warn(\n '[dawcore] beginDrag: engine unavailable, drag mutations will not be grouped for undo'\n );\n }\n\n // For trim: snapshot the clip container's current position/width\n if (mode === 'trim-left' || mode === 'trim-right') {\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 trim visual feedback: ' + clipId);\n }\n // Snapshot clip audio bounds for peak re-extraction during drag\n const engine = this._host.engine;\n if (engine) {\n const bounds = engine.getClipBounds(trackId, clipId);\n if (bounds) {\n this._originalOffsetSamples = bounds.offsetSamples;\n this._originalDurationSamples = bounds.durationSamples;\n }\n }\n }\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 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: compute total snapped delta from original position, then derive\n // the incremental from what's already been applied to the engine.\n // Anchor = clip start position (move shifts the whole clip)\n const totalSnappedDelta = this._snapDeltaToSamples(totalDeltaPx, this._originalStartSample);\n const incrementalDeltaSamples = totalSnappedDelta - this._cumulativeDeltaSamples;\n if (incrementalDeltaSamples !== 0) {\n // Track constrained delta (not raw) so undo transactions are accurate\n const applied = engine.moveClip(this._trackId, this._clipId, incrementalDeltaSamples, true);\n this._cumulativeDeltaSamples += applied;\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 // Convert sample delta to pixels — use tick space in beats mode\n // to avoid quantization drift from the sample round-trip.\n let deltaPx: number;\n if (this._host.scaleMode === 'beats') {\n const h = this._host;\n const anchorSec = anchor / h.effectiveSampleRate;\n const anchorTick = h._secondsToTicks(anchorSec);\n const newSec = anchorSec + deltaSamples / h.effectiveSampleRate;\n const newTick = h._secondsToTicks(newSec);\n deltaPx = Math.round((newTick - anchorTick) / h.ticksPerPixel);\n } else {\n deltaPx = Math.round(deltaSamples / this._host.renderSamplesPerPixel);\n }\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 trim drag didn't produce a delta\n this._restoreTrimVisual();\n return;\n }\n\n const engine = this._host.engine;\n\n if (this._mode === 'move') {\n // Sync adapter once on drop (skipped during drag for performance)\n if (engine) {\n engine.updateTrack(this._trackId);\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: this._cumulativeDeltaSamples,\n },\n })\n );\n } else {\n console.warn(\n '[dawcore] engine unavailable at move drop — audio may be out of sync for track ' +\n this._trackId\n );\n }\n } else {\n // Restore visual before engine applies — Lit will re-render with correct values\n this._restoreTrimVisual();\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 // Commit transaction if mutations occurred, abort if click/no-op.\n // Abort does NOT push to undo stack or clear redo stack.\n if (this._isDragging && this._cumulativeDeltaSamples !== 0) {\n this._host.engine?.commitTransaction();\n } else {\n this._host.engine?.abortTransaction();\n }\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 engine transaction stays open\n * (every later edit becomes un-undoable until some drag commits), and the\n * per-frame skipAdapter moveClip mutations are never synced or rolled back\n * (waveform and audio permanently disagree). */\n onPointerCancel(_e: PointerEvent): void {\n if (this._mode === null) return;\n try {\n // Undo the trim CSS preview; move mutations are rolled back by\n // abortTransaction below (restores the pre-drag snapshot and rebuilds\n // the adapter when mutations occurred).\n this._restoreTrimVisual();\n } finally {\n this._host.engine?.abortTransaction();\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 trim visual preview. Peaks matter: the drag wrote re-extracted peak\n * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and\n * a cancelled/zero-delta trim makes no engine mutation — so no statechange\n * re-render will ever repair them. */\n private _restoreTrimVisual(): 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 }\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 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 this._drag = {\n track,\n captureEl,\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 captureEl.addEventListener('pointermove', this._onPointerMove as EventListener);\n captureEl.addEventListener('pointerup', this._onPointerUp as EventListener);\n captureEl.addEventListener('pointercancel', this._onPointerCancel as EventListener);\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 // Restore the drag-start snapshot — a cancelled drag must not commit.\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.captureEl.removeEventListener('pointermove', this._onPointerMove as EventListener);\n drag.captureEl.removeEventListener('pointerup', this._onPointerUp as EventListener);\n drag.captureEl.removeEventListener('pointercancel', this._onPointerCancel as EventListener);\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\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\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 — lane DOM order\n // never changes, so the editor's MutationObserver order-sync never fires.\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 gripEl.addEventListener('pointermove', this._onPointerMove);\n gripEl.addEventListener('pointerup', this._onPointerUp);\n gripEl.addEventListener('pointercancel', this._onPointerCancel);\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 grip.removeEventListener('pointermove', this._onPointerMove);\n grip.removeEventListener('pointerup', this._onPointerUp);\n grip.removeEventListener('pointercancel', this._onPointerCancel);\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/** Parse a formatted time string back to seconds. Lenient: returns 0 for empty/unparseable input; does not validate segment ranges. */\nexport function parseDisplayTime(value: string, format: TimeDisplayFormat): number {\n if (!value) return 0;\n let seconds = 0;\n if (format === 'seconds') {\n seconds = parseFloat(value) || 0;\n } else {\n const parts = value.split(':');\n if (parts.length !== 3) return 0;\n const h = parseInt(parts[0], 10) || 0;\n const m = parseInt(parts[1], 10) || 0;\n const s = parseFloat(parts[2]) || 0;\n seconds = h * 3600 + m * 60 + s;\n }\n return Math.max(0, seconds);\n}\n","/**\n * File loading: routes dropped files through the same element pipeline as\n * editor.addTrack() — each file becomes a real `<daw-track><daw-clip>` in the\n * editor's light DOM, \"as a fresh page load would have\" (#612). The existing\n * daw-track-connected → _loadTrack pipeline does the fetch/decode.\n */\n\nimport type { DawTrackElement } from '../elements/daw-track';\nimport type { DawFilesLoadErrorDetail, LoadFilesResult } from '../events';\nimport type { TrackConfig } from '../types';\n\nexport interface FileLoaderHost {\n readonly isConnected: boolean;\n _audioCache: Map<string, Promise<AudioBuffer>>;\n addTrack(config: TrackConfig): Promise<DawTrackElement>;\n dispatchEvent(event: Event): boolean;\n}\n\nexport async function loadFiles(\n host: FileLoaderHost,\n files: FileList | File[]\n): Promise<LoadFilesResult> {\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 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 // 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\n const blobUrl = URL.createObjectURL(file);\n const name = file.name.replace(/\\.\\w+$/, '');\n try {\n // Sequential on purpose: preserves drop order as DOM/track order.\n const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });\n loaded.push(trackEl.trackId);\n // daw-track-ready was dispatched by the load pipeline — don't re-dispatch.\n } catch (err) {\n console.warn('[dawcore] Failed to load file: ' + file.name + ' — ' + String(err));\n dispatchLoadError(file, err);\n } finally {\n // The decode is complete either way; the blob URL and its cache entry\n // (keyed by a URL that will never be fetched again) are dead weight.\n URL.revokeObjectURL(blobUrl);\n host._audioCache.delete(blobUrl);\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` + `querySelectorAll`) — `<daw-editor>`\n * satisfies it without any new public surface.\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 { TrackConfig } from '../types';\nimport type { DawTrackElement } from '../elements/daw-track';\nimport { installCommand } from '../utils/install-command';\n\nexport type { MidiLoadOptions, MidiLoadResult };\n\n/**\n * Minimal host surface needed by `loadMidiImpl`. `<daw-editor>` satisfies this\n * structurally. `querySelectorAll` is needed for cleanup-on-failure so the\n * loader can identify `<daw-track>` elements appended during this call (both\n * those whose `addTrack` resolved and those that rejected after `_loadTrack`\n * fired `daw-track-error` — the latter aren't in the `addTrack` resolution\n * value, so we need DOM observation to find them).\n */\nexport interface MidiLoaderHost {\n addTrack(config: TrackConfig): Promise<DawTrackElement>;\n querySelectorAll(selector: string): NodeListOf<Element>;\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 creates N `<daw-track>` elements,\n * one per note-bearing MIDI track. On any per-track failure, every\n * `<daw-track>` appended during this call is removed so the editor returns\n * to its pre-call state (cleanup-on-failure — covers both `addTrack`\n * successes and the elements that `addTrack` left in the DOM before its\n * promise rejected).\n *\n * AbortSignal is forwarded to the fetch phase only. Aborting after parsing\n * does not cancel in-flight `addTrack` calls (documented limitation).\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 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, options.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\n // (3) Snapshot existing tracks so cleanup can identify the ones we appended.\n const childrenBefore = new Set<Element>(host.querySelectorAll('daw-track'));\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 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 )\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: DawTrackElement[] = [];\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 ALL tracks appended during this call (both\n // succeeded and the ones addTrack left in the DOM before rejecting), 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 const appendedTracks = Array.from(host.querySelectorAll('daw-track')).filter(\n (el) => !childrenBefore.has(el)\n );\n for (const el of appendedTracks) {\n try {\n el.remove();\n } catch (cleanupErr) {\n console.warn('[dawcore] loadMidi cleanup failed for a track: ' + String(cleanupErr));\n }\n }\n // Let MutationObserver microtasks flush so engine state is consistent\n // before rethrow.\n await Promise.resolve();\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.map((el) => el.trackId),\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 { ClipTrack, PeakData } from '@waveform-playlist/core';\nimport { carveClipRange, createClip } from '@waveform-playlist/core';\nimport type { PeakPipeline } from '../workers/peakPipeline';\nimport type { DawErrorDetail, DawRecordingClipAddDetail } from '../events';\nimport type { TrackDescriptor, ClipDescriptor } from '../types';\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 _tracks: Map<string, TrackDescriptor>;\n _engineTracks: Map<string, ClipTrack>;\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 _engine: {\n setTracks(tracks: readonly ClipTrack[]): void;\n updateTrack?(trackId: string, track: ClipTrack): void;\n } | null;\n _recomputeDuration(): void;\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 const t = host._engineTracks.get(trackId);\n if (!t) {\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 // Same floor policy as _finalizeAudioClip: 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 host._engineTracks = new Map(host._engineTracks).set(trackId, {\n ...t,\n // Punch-in replace (#579): the recorded clip owns [startSample,\n // startSample + durSamples) — carve overlapped content out of the\n // existing clips before inserting (parity with the React provider).\n clips: [...carveClipRange(t.clips, startSample, startSample + durSamples), clip],\n });\n // Keep _tracks in sync so public API and track controls reflect the clip\n const desc = host._tracks.get(trackId);\n if (desc) {\n const sr = host.effectiveSampleRate;\n const clipDesc: ClipDescriptor = {\n kind: 'drop',\n // The take has no <daw-clip> element — the engine id is the only\n // handle updateClip()/removeClip() can address it by (#659).\n clipId: clip.id,\n src: '',\n peaksSrc: '',\n start: startSample / sr,\n duration: durSamples / sr,\n offset: 0,\n gain: 1,\n name: clipName ?? 'Recording',\n fadeIn: 0,\n fadeOut: 0,\n fadeType: 'linear',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n };\n host._tracks = new Map(host._tracks).set(trackId, {\n ...desc,\n clips: [...desc.clips, clipDesc],\n });\n }\n host._recomputeDuration();\n const updatedTrack = host._engineTracks.get(trackId);\n if (host._engine?.updateTrack && updatedTrack) {\n host._engine.updateTrack(trackId, updatedTrack);\n } else {\n host._engine?.setTracks([...host._engineTracks.values()]);\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 if (!clip) return false;\n\n // MIDI clip splitting requires note slicing — not implemented yet.\n if (clip.midiNotes != null) return false;\n\n return true;\n}\n\n/** Core split logic — finds clip at position, calls engine, diffs state for new IDs. */\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 // Engine replaces the original clip with two halves; both get new IDs\n const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));\n if (newClips.length !== 2) {\n if (newClips.length > 0) {\n console.warn(\n '[dawcore] splitAtPlayhead: expected 2 new clips after split but got ' + newClips.length\n );\n }\n return false;\n }\n\n // Sort by startSample: lower = left, higher = right\n const sorted = [...newClips].sort((a, b) => a.startSample - b.startSample);\n const leftClipId = sorted[0].id;\n const rightClipId = sorted[1].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}\n\n/**\n * Regenerate peaks for clips that are new or whose offset/duration changed.\n * Handles split (new clip IDs) 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 })\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., the original clip after a split is replaced by two new clips)\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","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, trackChannelCount } 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 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 comes from the clips' channel\n // count, not from whatever layout the effects chain outputs.\n const panStage = createPanStage(ctx, track.pan, trackChannelCount(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).\n */\nexport async function loadWaveformDataFromUrl(src: string): Promise<WaveformData> {\n const response = await fetch(src);\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 private _wheelTargets: Set<HTMLElement> = new Set();\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._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._scrollContainer = null;\n for (const target of this._wheelTargets) {\n target.removeEventListener('wheel', this._onWheel);\n }\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._scrollContainer.removeEventListener('scroll', this._onScroll);\n this._scrollContainer = null;\n for (const t of this._wheelTargets) t.removeEventListener('wheel', this._onWheel);\n this._wheelTargets.clear();\n }\n return;\n }\n if (container !== this._scrollContainer) {\n this._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._scrollContainer = container;\n container.addEventListener('scroll', this._onScroll, { passive: true });\n }\n\n // Diff the current set of matched wheel targets.\n const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));\n for (const old of this._wheelTargets) {\n if (!nextTargets.has(old)) {\n old.removeEventListener('wheel', this._onWheel);\n this._wheelTargets.delete(old);\n }\n }\n for (const next of nextTargets) {\n if (!this._wheelTargets.has(next)) {\n next.addEventListener('wheel', this._onWheel, { passive: false });\n this._wheelTargets.add(next);\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 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 target.addEventListener('daw-recording-start', this._onStart);\n target.addEventListener('daw-recording-complete', this._onComplete);\n target.addEventListener('daw-recording-error', this._onError);\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetRef.removeEventListener('daw-recording-start', this._onStart);\n this._targetRef.removeEventListener('daw-recording-complete', this._onComplete);\n this._targetRef.removeEventListener('daw-recording-error', this._onError);\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 { KeyboardShortcut } from '@waveform-playlist/core';\nimport type { DawEditorElement } from './daw-editor';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Key binding for remapping — derived from KeyboardShortcut to stay in sync. */\nexport type KeyBinding = Pick<\n KeyboardShortcut,\n 'key' | 'ctrlKey' | 'shiftKey' | 'metaKey' | 'altKey'\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 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 document.addEventListener('keydown', this._onKeyDown);\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n document.removeEventListener('keydown', this._onKeyDown);\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 connectedCallback() {\n super.connectedCallback();\n document.addEventListener('daw-timeupdate', this._onTimeUpdate);\n document.addEventListener('daw-time-format-change', this._onFormatChange);\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 document.removeEventListener('daw-timeupdate', this._onTimeUpdate);\n document.removeEventListener('daw-time-format-change', this._onFormatChange);\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 connectedCallback() {\n super.connectedCallback();\n document.addEventListener('daw-time-format-change', this._onFormatChange);\n this.addEventListener('pointerdown', this._onPointerDown);\n this.addEventListener('pointerenter', this._onPointerEnter);\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 document.removeEventListener('daw-time-format-change', this._onFormatChange);\n this.removeEventListener('pointerdown', this._onPointerDown);\n this.removeEventListener('pointerenter', this._onPointerEnter);\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 PlaylistEngine,\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 :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 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 private async _loadPeaks(): Promise<void> {\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 try {\n const wd = await loadWaveformDataFromUrl(requested);\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 // 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 }\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,+BAA8B,sBAAqB,qCAAoC,gBAAe,8BAA6B,2BAA0B,0CAAyC,6BAA4B,4CAA2C,+BAA8B,8CAA6C,8BAA6B,4CAA2C;;;ACAje,iBAA2B;AAC3B,wBAAwC;AAKxC,SAAS,YAAY,OAAwB;AAC3C,SAAO,OAAO,SAAS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c,YAAY;AAAA,GACd;","names":["import_lit","import_decorators","updated","import_lit","import_decorators","import_core","import_lit","import_decorators","import_lit","import_decorators","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_lit","import_decorators","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","import_core","engine","import_core","updated","import_core","state","state","import_core","import_core","PREFIX","element","import_core","PREFIX","import_waveform_data","WaveformData","updatedClip","updatedClips","updatedTrack","clip","audioBuffer","track","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"]}
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/elements/daw-track.ts","../src/types.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/utils/track-mix.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/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/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 KeyBinding,\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} 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.3\",\"@dawcore/transport\":\"@dawcore/transport@^0.0.16-next.3\",\"@dawcore/wam\":\"@dawcore/wam@^0.0.5-next.0\",\"@waveform-playlist/core\":\"@waveform-playlist/core@^13.0.0-next.3\",\"@waveform-playlist/engine\":\"@waveform-playlist/engine@^14.0.0-next.2\",\"@waveform-playlist/worklets\":\"@waveform-playlist/worklets@^13.0.1-next.0\",\"@waveform-playlist/playout\":\"@waveform-playlist/playout@^13.0.0-next.3\"}","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 // 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 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 document.addEventListener('keydown', this._onKeyDownCapture, true); // capture phase\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 document.removeEventListener('keydown', this._onKeyDownCapture, true);\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/** m:ss.mmm for annotation timestamps (finer than the ruler's m:ss). */\nfunction formatAnnotationTime(seconds: number): string {\n const whole = Math.floor(seconds);\n const ms = Math.round((seconds - whole) * 1000);\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 :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 connectedCallback() {\n super.connectedCallback();\n document.addEventListener('daw-annotation-select', this._onSelect as EventListener);\n document.addEventListener('daw-timeupdate', this._onTimeUpdate as EventListener);\n document.addEventListener('daw-stop', this._onStop as EventListener);\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n document.removeEventListener('daw-annotation-select', this._onSelect as EventListener);\n document.removeEventListener('daw-timeupdate', this._onTimeUpdate as EventListener);\n document.removeEventListener('daw-stop', this._onStop as EventListener);\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';\n\n@customElement('daw-clip')\nexport class DawClipElement extends LitElement {\n @property() src = '';\n @property({ attribute: 'peaks-src' }) peaksSrc = '';\n /**\n * Timeline position in seconds. JS property only — NOT reflected to the\n * `start` attribute (Lit's `reflect` defaults to false). Tests that need\n * to assert clip position must read this property directly; reading\n * `el.getAttribute('start')` returns `null` regardless of correctness.\n */\n @property({ type: Number }) start = 0;\n @property({ type: Number }) duration = 0;\n @property({ type: Number }) offset = 0;\n @property({ type: Number }) gain = 1;\n @property() name = '';\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 }) midiNotes: MidiNoteData[] | null = null;\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._midiChannel;\n }\n set midiChannel(value: number | null) {\n const old = this._midiChannel;\n if (value === null) {\n this._midiChannel = null;\n this.requestUpdate('midiChannel', old);\n return;\n }\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15) {\n console.warn('[dawcore] daw-clip midi-channel ' + value + ' is out of range 0-15 — ignored');\n return;\n }\n this._midiChannel = value;\n this.requestUpdate('midiChannel', old);\n }\n private _midiChannel: number | null = null;\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._midiProgram;\n }\n set midiProgram(value: number | null) {\n const old = this._midiProgram;\n if (value === null) {\n this._midiProgram = null;\n this.requestUpdate('midiProgram', old);\n return;\n }\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127) {\n console.warn('[dawcore] daw-clip midi-program ' + value + ' is out of range 0-127 — ignored');\n return;\n }\n this._midiProgram = value;\n this.requestUpdate('midiProgram', old);\n }\n private _midiProgram: number | null = null;\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 connectedCallback() {\n super.connectedCallback();\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 editor\n // reads <daw-clip> children synchronously via _readTrackDescriptor, so\n // this event is the canonical late-append signal.\n // _onClipConnected skips this event during the parent track's initial load\n // (parent not yet in _engineTracks) and runs an incremental load otherwise.\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","import { LitElement } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport type { PropertyValues } from 'lit';\nimport type { 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';\n\n/** The properties whose change the editor hears about (`daw-track-update`). */\nconst TRACK_PROPS: readonly string[] = [\n 'volume',\n 'pan',\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 @property() name = '';\n @property({ type: Number }) volume = 1;\n @property({ type: Number }) pan = 0;\n @property({ type: Boolean }) muted = false;\n @property({ type: Boolean }) soloed = false;\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 connects:\n * the editor reads it when it loads the track.\n */\n @property({ reflect: true, noAccessor: true })\n get kind(): TrackKind {\n return this._kind;\n }\n set kind(value: TrackKind) {\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 connectedCallback() {\n super.connectedCallback();\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 sends a mixer property\n // only when it is one of them, so an unrelated change (a rename after an\n // Undo) never writes the element's older volume back.\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 RenderMode,\n SpectrogramConfig,\n TrackKind,\n} from '@waveform-playlist/core';\n\n// Re-export RenderMode from core as TrackRenderMode for backward compatibility\n// during the migration; consumers should prefer RenderMode directly.\nexport type { RenderMode } from '@waveform-playlist/core';\nexport type TrackRenderMode = RenderMode;\n\nexport interface TrackDescriptor {\n name: string;\n src: string;\n volume: number;\n pan: number;\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';\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 four fields in from it.\n */\nexport type StoredTrackDescriptor = Omit<TrackDescriptor, TrackMixFields>;\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. Engine `clip.id` is aligned with this id in `_loadTrack`\n * and `_loadAndAppendClip` so DOM and engine reference 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; the engine generates its own id at\n * clip-creation time.\n *\n * `clipId` is that engine clip id when the editor knows it at descriptor\n * creation — currently recorded takes (#659). Pass it to\n * `editor.updateClip()` / `removeClip()` to address the clip.\n */\nexport interface DropClipDescriptor extends BaseClipDescriptor {\n kind: 'drop';\n clipId?: string;\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 * 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 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","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 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 target.addEventListener('daw-recording-start', this._onRecStart);\n target.addEventListener('daw-recording-complete', this._onRecEnd);\n target.addEventListener('daw-recording-error', this._onRecEnd);\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetRef.removeEventListener('daw-recording-start', this._onRecStart);\n this._targetRef.removeEventListener('daw-recording-complete', this._onRecEnd);\n this._targetRef.removeEventListener('daw-recording-error', this._onRecEnd);\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 connectedCallback() {\n super.connectedCallback();\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);\n // A target that became resolvable since the last render should\n // re-evaluate before the click lands.\n this.addEventListener('pointerenter', this._onCapabilityPointerEnter);\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.removeEventListener('pointerdown', this._onCapabilityPointerDown);\n this.removeEventListener('pointerenter', this._onCapabilityPointerEnter);\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 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 target.addEventListener('daw-recording-start', this._onRecStart);\n target.addEventListener('daw-recording-complete', this._onRecEnd);\n target.addEventListener('daw-recording-error', this._onRecEnd);\n target.addEventListener('daw-recording-pause', this._onRecPause);\n target.addEventListener('daw-recording-resume', this._onRecResume);\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetRef.removeEventListener('daw-recording-start', this._onRecStart);\n this._targetRef.removeEventListener('daw-recording-complete', this._onRecEnd);\n this._targetRef.removeEventListener('daw-recording-error', this._onRecEnd);\n this._targetRef.removeEventListener('daw-recording-pause', this._onRecPause);\n this._targetRef.removeEventListener('daw-recording-resume', this._onRecResume);\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 type {\n AudioClip,\n ClipTrack,\n FadeType,\n MidiNoteData,\n Peaks,\n PeakData,\n SnapTo,\n MeterEntry,\n SpectrogramConfig,\n ColorMapValue,\n} from '@waveform-playlist/core';\nimport type {\n StoredTrackDescriptor,\n TrackDescriptor,\n TrackWithId,\n ClipDescriptor,\n DomClipDescriptor,\n TrackConfig,\n ClipConfig,\n} from '../types';\nimport { isDomClip, normalizeRenderMode, trackDescriptorRenderMode } from '../types';\nimport {\n createClip,\n createClipFromSeconds,\n createMixerGesture,\n createTrack,\n clipPixelWidth,\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 type {\n MixerChangeOptions,\n PlaylistEngine,\n PlayoutAdapter,\n TrackMixerValues,\n} from '@waveform-playlist/engine';\nimport {\n DEFAULT_TRACK_MIX,\n clampNumber,\n mixOfElement,\n pickMix,\n mixOfTrack,\n withMix,\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 DawClipIdDetail,\n DawClipErrorDetail,\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 { 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// 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/** Thrown by _loadTrack when a load is cancelled (track removed / editor\n * disconnected mid-load) rather than failed. Surfaced through daw-track-error\n * with `detail.reason` set so consumers can filter intentional cancellations\n * from real load failures; the event still fires so addTrack()/loadMidi()\n * awaiters settle. */\nclass TrackLoadCancelledError extends Error {\n constructor(\n message: string,\n readonly reason: 'removed' | 'disconnected'\n ) {\n super(message);\n this.name = 'TrackLoadCancelledError';\n }\n}\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 const descriptor = this._tracks.get(trackId);\n if (descriptor?.renderMode !== '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 /** Sample rate — reads from adapter's AudioContext when available, otherwise falls back to 48000. */\n get sampleRate(): number {\n return this._resolvedSampleRate ?? this._externalAdapter?.audioContext.sampleRate ?? 48000;\n }\n /** Resolved sample rate — falls back to sampleRate property until first audio decode. */\n _resolvedSampleRate: number | null = null;\n /** Per-track descriptors, without the mix: the arrangement owns that (#843). */\n @state() _tracks: Map<string, StoredTrackDescriptor> = new Map();\n /**\n * The mix of a track the engine does not hold yet: what it will enter the\n * arrangement with (from the `<daw-track>` element or the `addTrack` config,\n * changed by a control or `updateTrack` while it loads). Deleted once\n * `engine.getState().tracks` holds the id; read only through `_mixOf`.\n */\n @state() _seedMix: Map<string, TrackMixerValues> = new Map();\n @state() _engineTracks: Map<string, ClipTrack> = 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 // A fresh adapter re-arms engine building after a disconnect consumed\n // the previous one (see _adapterConsumedByDispose).\n this._adapterConsumedByDispose = false;\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 }\n get adapter(): PlayoutAdapter | null {\n return this._externalAdapter;\n }\n private _externalAdapter: PlayoutAdapter | null = null;\n /** True after a disconnect disposed the consumer's adapter via the engine\n * — rebuild attempts fail loudly until a fresh adapter is set. */\n private _adapterConsumedByDispose = false;\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._engineTracks.values()],\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: PlaylistEngine | null = null;\n private _warnedMissingTicksToSeconds = false;\n private _warnedMissingSecondsToTicks = false;\n private _enginePromise: Promise<PlaylistEngine> | null = null;\n _audioCache = new Map<string, Promise<AudioBuffer>>();\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 /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`\n * membership: the peaks-first path inserts a render-only PREVIEW track\n * into _engineTracks mid-load, so `has()` alone cannot answer \"is this\n * track still loading?\". */\n private _loadingTracks = new Set<string>();\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 track = this._engineTracks.get(trackId);\n if (!track) return false;\n const clip = track.clips.find((c) => c.id === clipId);\n return clip?.midiNotes != null;\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 :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._resolvedSampleRate ?? this.sampleRate;\n }\n resolveAudioContextSampleRate(rate: number) {\n if (!this._resolvedSampleRate) this._resolvedSampleRate = rate;\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 get tracks(): TrackWithId[] {\n return [...this._tracks.entries()].map(([trackId, descriptor]) => ({\n trackId,\n ...descriptor,\n ...this._mixOf(trackId),\n }));\n }\n /**\n * A track's mix, from its one owner: the arrangement (through\n * `_engineTracks`, which follows `mixerVersion`) for a track the engine\n * holds, the seed for one still on its way in (#843).\n */\n _mixOf(trackId: string): TrackMixerValues {\n const seed = this._seedMix.get(trackId);\n if (seed) return seed;\n const track = this._engineTracks.get(trackId);\n return track ? mixOfTrack(track) : DEFAULT_TRACK_MIX;\n }\n /** Replace a track's seed (a new Map: `_seedMix` is reactive state). */\n private _setSeedMix(trackId: string, mix: TrackMixerValues): void {\n this._seedMix = new Map(this._seedMix).set(trackId, mix);\n }\n private _deleteSeedMix(trackIds: Iterable<string>): void {\n let next: Map<string, TrackMixerValues> | null = null;\n for (const id of trackIds) {\n if (!this._seedMix.has(id)) continue;\n next ??= new Map(this._seedMix);\n next.delete(id);\n }\n if (next) this._seedMix = next;\n }\n /**\n * Change one mixer field of a track: the seed while the track is loading\n * (not an undo step, nothing sent), else the engine's setter with\n * `options` (an undo step; changes with one `gesture` id are one step).\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 seed = this._seedMix.get(trackId);\n if (seed) {\n if (seed[field] !== value) this._setSeedMix(trackId, { ...seed, [field]: value });\n return;\n }\n if (!this._engine) return;\n if (field === 'volume') this._engine.setTrackVolume(trackId, value as number, options);\n else if (field === 'pan') this._engine.setTrackPan(trackId, value as number, options);\n else if (field === 'muted') this._engine.setTrackMute(trackId, value as boolean, options);\n else this._engine.setTrackSolo(trackId, value as boolean, options);\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(trackId: string, mix: Partial<TrackMixerValues>): void {\n const options: MixerChangeOptions = { gesture: createMixerGesture().id };\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 }\n /** The ordered tracks for `engine.setTracks`, a loading track with its seed. */\n private _tracksForEngine(): ClipTrack[] {\n return this._getOrderedTracks().map(([trackId, track]) => {\n const seed = this._seedMix.get(trackId);\n return seed ? withMix(track, seed) : track;\n });\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 this.addEventListener('daw-track-connected', this._onTrackConnected as EventListener);\n this.addEventListener('daw-track-update', this._onTrackUpdate as EventListener);\n this.addEventListener('daw-track-control', this._onTrackControl as EventListener);\n this.addEventListener('daw-track-remove', this._onTrackRemoveRequest as EventListener);\n this.addEventListener('daw-clip-connected', this._onClipConnected as EventListener);\n this.addEventListener('daw-clip-update', this._onClipUpdate as EventListener);\n this.addEventListener(\n 'daw-annotation-track-connected',\n this._onAnnotationTrackConnected as EventListener\n );\n this.addEventListener('daw-annotation-select', this._onAnnotationSelect as EventListener);\n this.addEventListener('daw-track-reorder', this._onTrackReorder as EventListener);\n this.addEventListener('daw-track-reorder-grab', this._onTrackReorderGrab as EventListener);\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 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 }\n }\n let orderMayHaveChanged = addedTrackIds.size > 0;\n for (const [trackId] of removedTracks) {\n if (addedTrackIds.has(trackId)) {\n orderMayHaveChanged = true; // move, not removal\n continue;\n }\n this._onTrackRemoved(trackId);\n }\n for (const clip of removedClips) {\n // A clip that moved with its track (or was re-slotted) is still connected.\n if (clip.isConnected) continue;\n this._onClipRemovedFromDom(clip);\n }\n if (orderMayHaveChanged) this._syncEngineOrderToDom();\n });\n this._childObserver.observe(this, { childList: true, subtree: true });\n }\n disconnectedCallback() {\n super.disconnectedCallback();\n this._effectsManager?.disposeAll();\n this._effectsManager = null;\n this.removeEventListener('daw-track-connected', this._onTrackConnected as EventListener);\n this.removeEventListener('daw-track-update', this._onTrackUpdate as EventListener);\n this.removeEventListener('daw-track-control', this._onTrackControl as EventListener);\n this.removeEventListener('daw-track-remove', this._onTrackRemoveRequest as EventListener);\n this.removeEventListener('daw-clip-connected', this._onClipConnected as EventListener);\n this.removeEventListener('daw-clip-update', this._onClipUpdate as EventListener);\n this.removeEventListener(\n 'daw-annotation-track-connected',\n this._onAnnotationTrackConnected as EventListener\n );\n this.removeEventListener('daw-annotation-select', this._onAnnotationSelect as EventListener);\n this.removeEventListener('daw-track-reorder', this._onTrackReorder as EventListener);\n this.removeEventListener('daw-track-reorder-grab', this._onTrackReorderGrab as EventListener);\n this._trackReorderDrag.cancel();\n this._childObserver?.disconnect();\n this._childObserver = null;\n this._trackElements.clear();\n this._audioCache.clear();\n this._peaksCache.clear();\n this._clipBuffers.clear();\n this._clipOffsets.clear();\n this._peakPipeline.terminate();\n this._minSamplesPerPixel = 0;\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 a reconnect\n // would decode successfully and wire tracks into a dead transport graph\n // — waveforms render, play() runs, no audio. Refuse to rebuild on it;\n // the adapter setter clears the flag when a fresh one arrives.\n if (hadEngine) {\n this._adapterConsumedByDispose = true;\n }\n // Symmetric teardown: the caches above are gone and the engine (and the\n // consumer's adapter through it) disposed — retaining the render state\n // would make a reconnected editor show ghost waveforms that can never\n // play. Declarative AND programmatic (addTrack) tracks are element-backed\n // and re-register on reconnect (failing LOUDLY via the disposed-adapter\n // guard in _buildEngine until a fresh adapter is set); file-dropped\n // element-less content does not survive a reparent.\n this._tracks = new Map();\n this._seedMix = new Map();\n this._engineTracks = new Map();\n this._peaksData = new Map();\n this._loadingTracks.clear();\n this._recomputeDuration();\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 // Custom elements fire disconnectedCallback+connectedCallback on a pure\n // DOM MOVE (e.g. insertBefore during a consumer reorder), not just on a\n // genuine removal — no moveBefore() is used anywhere in this codebase.\n // daw-track.ts's connectedCallback re-dispatches a deferred\n // daw-track-connected for the SAME trackId in that case. If the track is\n // already registered (loading or fully loaded), this is a reconnect from\n // a move, not a first-time (or post-teardown) registration: refresh the\n // element mapping and bail out WITHOUT re-reading the descriptor or\n // reloading. Re-reading would revert live daw-track-control mixer edits\n // of a loading track (they change its seed, not the element's\n // attributes); reloading would re-fetch — for a file-dropped track whose\n // blob: URL was already revoked after its first load (Task 6), that\n // fetch is against a dead URL and spuriously fires daw-track-error.\n // Genuine re-registration after the EDITOR itself is reparented still\n // works: the editor's disconnectedCallback clears _tracks entirely, so\n // this guard is a no-op then and a full reload happens as before.\n if (this._tracks.has(trackId)) {\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n return;\n }\n const descriptor = this._readTrackDescriptor(trackEl as DawTrackElement);\n this._tracks = new Map(this._tracks).set(trackId, descriptor);\n // The values it enters the arrangement with; not an undo step (#843).\n this._setSeedMix(trackId, mixOfElement(trackEl as DawTrackElement));\n this._trackElements.set(trackId, trackEl as DawTrackElement);\n this._loadTrack(trackId, descriptor);\n };\n private _onTrackRemoved(trackId: string) {\n // Captured before the cleanup below mutates _tracks — gates the outbound\n // event so it only fires for a track that was actually registered.\n const existed = this._tracks.has(trackId);\n this._trackElements.delete(trackId);\n this._effectsManager?.disposeTrackChain(trackId);\n // Clean up per-clip data before removing the track (need clip IDs from engine tracks)\n const removedTrack = this._engineTracks.get(trackId);\n if (removedTrack) {\n const nextPeaks = new Map(this._peaksData);\n for (const clip of removedTrack.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 nextTracks = new Map(this._tracks);\n nextTracks.delete(trackId);\n this._tracks = nextTracks;\n this._deleteSeedMix([trackId]);\n const nextEngine = new Map(this._engineTracks);\n nextEngine.delete(trackId);\n this._engineTracks = nextEngine;\n this._recomputeDuration();\n if (this._engine) {\n // Incremental removal preserves playback (no playout rebuild)\n this._engine.removeTrack(trackId);\n }\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 && nextEngine.size === 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 // _tracks is updated so handlers reading editor.tracks see the removal.\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 const oldDescriptor = this._tracks.get(trackId);\n let descriptor = this._readTrackDescriptor(trackEl);\n if (oldDescriptor && oldDescriptor.kind !== descriptor.kind) {\n // The clips already loaded are of the old kind (#756).\n console.warn(\n '[dawcore] <daw-track> \"' +\n descriptor.name +\n '\": kind cannot change after the track has loaded (still \"' +\n oldDescriptor.kind +\n '\"). Remove the track and add one of the other kind.'\n );\n descriptor = {\n ...descriptor,\n kind: oldDescriptor.kind,\n renderMode: trackDescriptorRenderMode(oldDescriptor.kind, trackEl.renderMode),\n };\n // Put the element back, so it says what the editor holds and the next\n // unrelated update (a volume change) does not warn again. The update\n // this assignment dispatches finds the kinds equal. In a microtask: we\n // are inside the element's own updated(), where Lit's dev build warns\n // about a property change.\n const keptKind = oldDescriptor.kind;\n queueMicrotask(() => {\n trackEl.kind = keptKind;\n });\n }\n this._tracks = new Map(this._tracks).set(trackId, descriptor);\n // Only the mixer properties this update changed (#843), as one undo step:\n // a rename after an Undo must not send the element's older volume back.\n // The seed while loading, else the engine setters.\n const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];\n this._writeMixFields(trackId, pickMix(mixOfElement(trackEl), changed));\n if (oldDescriptor?.src !== descriptor.src) {\n this._loadTrack(trackId, descriptor);\n }\n // Track switched into spectrogram mode — push existing clip audio into the controller.\n if (descriptor.renderMode === 'spectrogram' && oldDescriptor?.renderMode !== 'spectrogram') {\n const engineTrack = this._engineTracks.get(trackId);\n if (engineTrack) {\n for (const clip of engineTrack.clips) {\n this._maybeRegisterSpectrogramClipAudio(trackId, clip);\n }\n }\n }\n // Track switched OUT of spectrogram mode — drop clip audio.\n if (descriptor.renderMode !== 'spectrogram' && oldDescriptor?.renderMode === 'spectrogram') {\n const engineTrack = this._engineTracks.get(trackId);\n if (engineTrack && this._spectrogramController) {\n for (const clip of engineTrack.clips) {\n this._spectrogramController.unregisterClipAudio(clip.id);\n }\n }\n this._disposeSpectrogramControllerIfEmpty();\n }\n if (descriptor.spectrogramConfig !== oldDescriptor?.spectrogramConfig) {\n this._spectrogramController?.setTrackConfig(trackId, descriptor.spectrogramConfig ?? null);\n }\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._tracks.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 /** Reconcile `_tracks` descriptors with the engine's track list.\n *\n * ADD: engine.undo() restores removed tracks in ENGINE state only —\n * without a synthesized descriptor the track plays and renders but shows\n * \"Untitled\" controls and is missing from `editor.tracks`.\n * PRUNE (the symmetric half): redo removes the track from engine state\n * again — without pruning, the synthesized descriptor is a permanent\n * ghost that even removeTrack() can't clean (no element, no engine\n * entry). Never prunes tracks that are mid-load or element-backed —\n * their descriptors legitimately precede their engine entries. */\n _reconcileDescriptorsWithEngineTracks(tracks: readonly ClipTrack[]): void {\n const engineIds = new Set(tracks.map((t) => t.id));\n let next: Map<string, StoredTrackDescriptor> | null = null;\n for (const track of tracks) {\n if (this._tracks.has(track.id)) continue;\n next ??= new Map(this._tracks);\n // No mix of its own: it is read from the engine track (#843).\n next.set(track.id, {\n name: track.name ?? '',\n src: '',\n kind: trackKind(track),\n renderMode: trackDescriptorRenderMode(trackKind(track), 'waveform'),\n clips: [],\n });\n }\n for (const trackId of this._tracks.keys()) {\n if (\n engineIds.has(trackId) ||\n this._loadingTracks.has(trackId) ||\n this._trackElements.has(trackId)\n ) {\n continue;\n }\n next ??= new Map(this._tracks);\n next.delete(trackId);\n }\n // Element-less clips that carry their engine id (recorded takes, #659)\n // have no <daw-clip> to re-read them, and the engine changes them on its\n // own: undo removes a take, a split replaces it with two new ids, a\n // punch-in carves it away, a drag moves or trims it. Follow the engine —\n // a descriptor whose id is gone would otherwise be a ghost that even\n // removeClip() cannot reach.\n for (const track of tracks) {\n const desc = (next ?? this._tracks).get(track.id);\n if (!desc || !desc.clips.some((c) => !isDomClip(c) && c.clipId !== undefined)) continue;\n const reconciled = this._reconcileIdentifiedDropClips(desc.clips, track);\n if (reconciled === desc.clips) continue;\n next ??= new Map(this._tracks);\n next.set(track.id, { ...desc, clips: reconciled });\n }\n if (next) {\n this._tracks = next;\n }\n }\n /** Prune id-bearing drop descriptors the engine no longer has, and refresh\n * the rest from their engine clip. Returns the SAME array when nothing\n * changed, so an unchanged track never triggers a re-render. */\n private _reconcileIdentifiedDropClips(\n clips: ClipDescriptor[],\n track: ClipTrack\n ): ClipDescriptor[] {\n const engineClips = new Map(track.clips.map((c) => [c.id, c]));\n let changed = false;\n const result: ClipDescriptor[] = [];\n for (const desc of clips) {\n if (isDomClip(desc) || desc.clipId === undefined) {\n result.push(desc);\n continue;\n }\n const clip = engineClips.get(desc.clipId);\n if (!clip) {\n changed = true;\n continue;\n }\n const sr = clip.sampleRate ?? this.effectiveSampleRate;\n const start = clip.startSample / sr;\n const duration = clip.durationSamples / sr;\n const offset = clip.offsetSamples / sr;\n const gain = clip.gain ?? desc.gain;\n const name = clip.name ?? desc.name;\n if (\n desc.start === start &&\n desc.duration === duration &&\n desc.offset === offset &&\n desc.gain === gain &&\n desc.name === name\n ) {\n result.push(desc);\n continue;\n }\n changed = true;\n result.push({ ...desc, start, duration, offset, gain, name });\n }\n return changed ? result : clips;\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._tracks.has(trackId)) {\n // Validated values: to the seed while loading, else to the engine. A\n // slider's gesture id makes its drag one undo step (#843); a control\n // 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 (or a loading track's seed) 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 // Skip during initial track load — daw-track-connected reads all <daw-clip>\n // children synchronously via _readTrackDescriptor. Late-append clips trigger\n // an incremental load below.\n // \"Still loading\" = a _loadTrack in flight OR no engine track yet.\n // _engineTracks membership alone is NOT sufficient: the peaks-first path\n // inserts a render-only preview track mid-load — appending to it would\n // resolve the addClip() promise and then silently discard the clip when\n // the final commit overwrites the preview.\n if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {\n // _tracks is populated in _onTrackConnected before _loadTrack runs, so\n // having a descriptor without a loaded engine track means the parent is\n // still loading. _readTrackDescriptor already captured each existing\n // <daw-clip> child's id into descriptor.clips — those deferred\n // daw-clip-connected events are redundant and silent skip is correct.\n // Only a clipId that wasn't in the pre-load capture is a true\n // late-append; a missing descriptor means the parent was removed.\n // A missing descriptor is NOT an error: the clip's deferred connect\n // event can fire before the parent track's own deferred connect\n // registers the descriptor — _readTrackDescriptor will capture this\n // clip moments later. Silent skip.\n const desc = this._tracks.get(trackId);\n if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {\n const message =\n 'daw-clip-connected fired while parent track \"' +\n trackId +\n '\" is still loading — the clip will not be loaded. ' +\n 'Wait for daw-track-ready before appending more <daw-clip> children, ' +\n 'or use editor.addClip(trackId, config) after the track finishes loading.';\n console.warn('[dawcore] ' + message);\n // Settle the addClip() promise: _readTrackDescriptor snapshotted the\n // clip list at connect time, so nothing will ever load this clip —\n // without an error event the returned promise hangs forever.\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clipEl.clipId, error: new Error(message) },\n })\n );\n }\n return;\n }\n // Reconnect from a DOM move (custom elements fire disconnectedCallback+\n // connectedCallback on insertBefore, same as the track-level case in\n // _onTrackConnected) — or any other duplicate deferred daw-clip-connected\n // for a clip already registered on this FULLY LOADED track. Unlike the\n // still-loading branch above, _readTrackDescriptor cannot have filtered\n // this one out (that only runs once, before the track finished loading),\n // so this check is the only guard against _loadAndAppendClip inserting a\n // second engine clip with the same id. Reuses the exact same isDomClip\n // membership check as the still-loading branch.\n const loadedDesc = this._tracks.get(trackId);\n if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {\n return;\n }\n const clipDesc: ClipDescriptor = {\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 this._loadAndAppendClip(trackId, clipDesc);\n };\n private _onClipUpdate = (e: CustomEvent) => {\n const clipEl = e.target as DawClipElement;\n if (!(clipEl instanceof HTMLElement) || clipEl.tagName !== 'DAW-CLIP') return;\n const detail = e.detail as { trackId: string; clipId: string };\n if (!detail.trackId) {\n // <daw-clip> mounted outside a <daw-track> — developer error.\n console.warn(\n '[dawcore] daw-clip-update fired from a <daw-clip> not nested in a <daw-track> — ignored'\n );\n return;\n }\n this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);\n };\n private _onClipRemovedFromDom(clipEl: DawClipElement) {\n const clipId = clipEl.clipId;\n for (const [trackId, t] of this._engineTracks.entries()) {\n if (t.clips.some((c) => c.id === clipId)) {\n this._removeClipFromTrack(trackId, clipId);\n return;\n }\n }\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 private async _loadAndAppendClip(trackId: string, clipDesc: DomClipDescriptor) {\n if (!clipDesc.src) return; // Late-append of MIDI clips is not yet supported by _loadAndAppendClip — only _loadTrack handles the no-src MIDI branch on initial load.\n // Late-append always comes via _onClipConnected, which only fires for\n // <daw-clip> elements — so clipId is always known. We use it for the\n // error dispatch so the consumer's addClip Promise rejects with a usable\n // identifier even if _finalizeAudioClip throws before clip.id is set.\n const clipId = clipDesc.clipId;\n // Track which clip id has been inserted into per-clip caches so the catch\n // block can roll back partial state on any error past the cache writes.\n let insertedClipId: string | null = null;\n try {\n const trackDesc = this._tracks.get(trackId);\n const kindError = trackDesc\n ? this._clipKindError(trackDesc.name, trackDesc.kind, false, clipDesc.name || clipDesc.src)\n : null;\n if (kindError) throw kindError;\n // Concurrent fetches: peaks (if provided) + audio decode.\n const waveformDataPromise = clipDesc.peaksSrc\n ? this._resolvePeaks(clipDesc.peaksSrc)\n : Promise.resolve(null);\n const audioPromise = this._fetchAndDecode(clipDesc.src);\n const [waveformData, audioBuffer] = await Promise.all([waveformDataPromise, audioPromise]);\n this._resolvedSampleRate = audioBuffer.sampleRate;\n\n const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, waveformData);\n insertedClipId = clip.id;\n\n const t = this._engineTracks.get(trackId);\n if (!t) {\n // Track was removed during load — purge clip state\n this._purgeClipCaches(clip.id);\n return;\n }\n const updatedTrack: ClipTrack = { ...t, clips: [...t.clips, clip] };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n\n const desc = this._tracks.get(trackId);\n if (desc) {\n this._tracks = new Map(this._tracks).set(trackId, {\n ...desc,\n clips: [...desc.clips, clipDesc],\n });\n }\n this._commitTrackChange(trackId, updatedTrack);\n this._maybeRegisterSpectrogramClipAudio(trackId, clip);\n\n this.dispatchEvent(\n new CustomEvent<DawClipIdDetail>('daw-clip-ready', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: clip.id },\n })\n );\n } catch (err) {\n // Always warn — even when disconnected — so the failure isn't silent.\n console.warn('[dawcore] _loadAndAppendClip failed: ' + String(err));\n // Roll back partial cache state so a retry isn't poisoned by stale entries.\n if (insertedClipId) this._purgeClipCaches(insertedClipId);\n // Detached elements can't bubble events, but the listener registered on\n // `this` via addClip will still fire — dispatch directly so the addClip\n // promise rejects instead of orphaning.\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: { trackId, clipId: insertedClipId ?? clipId, error: err },\n })\n );\n }\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 * Shared between `_loadTrack` (peaks-first preview path) and\n * `_loadAndAppendClip` (incremental late-append).\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 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 /**\n * Construct an AudioClip from a decoded buffer (and optional WaveformData),\n * align its id with the source `<daw-clip>.clipId` when present, populate\n * `_clipBuffers` / `_clipOffsets`, generate peaks via the worker pipeline,\n * and populate `_peaksData`. Returns the finished AudioClip.\n *\n * Shared between `_loadTrack`'s standard path and `_loadAndAppendClip`.\n * Not used by `_loadTrack`'s peaks-first preview path because that path\n * uses sync `extractPeaks` and inserts a preview track BEFORE audio decode.\n */\n private async _finalizeAudioClip(\n clipDesc: ClipDescriptor,\n audioBuffer: AudioBuffer,\n waveformData: import('waveform-data').default | null\n ): Promise<AudioClip> {\n let clip: AudioClip;\n if (waveformData) {\n const wdRate = waveformData.sample_rate;\n clip = createClip({\n audioBuffer,\n waveformData,\n startSample: Math.round(clipDesc.start * wdRate),\n durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),\n offsetSamples: Math.round(clipDesc.offset * wdRate),\n gain: clipDesc.gain,\n name: clipDesc.name,\n sampleRate: wdRate,\n sourceDurationSamples: Math.ceil(waveformData.duration * wdRate),\n });\n this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);\n } else {\n clip = createClipFromSeconds({\n audioBuffer,\n startTime: clipDesc.start,\n duration: clipDesc.duration || audioBuffer.duration,\n offset: clipDesc.offset,\n gain: clipDesc.gain,\n name: clipDesc.name,\n sampleRate: audioBuffer.sampleRate,\n sourceDuration: audioBuffer.duration,\n });\n }\n if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;\n\n this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);\n this._clipOffsets.set(clip.id, {\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n });\n // generatePeaks can fail (worker crash, CSP, OOM). Purge the cache entries\n // we just inserted so the caller's catch path doesn't leak. The caller may\n // also call _purgeClipCaches in its own error handler — _purgeClipCaches\n // is idempotent.\n let peakData: PeakData;\n try {\n peakData = await this._peakPipeline.generatePeaks(\n audioBuffer,\n this._renderSpp,\n this.mono,\n clip.offsetSamples,\n clip.durationSamples\n );\n } catch (err) {\n this._purgeClipCaches(clip.id);\n throw err;\n }\n this._peaksData = new Map(this._peaksData).set(clip.id, peakData);\n // Raise the zoom-floor only after generatePeaks succeeds — without this,\n // a generatePeaks failure would strand _minSamplesPerPixel at a value\n // backed by no actual peaks (CLAUDE.md `samplesPerPixel` Zoom Floor rule).\n // Worker-generated peaks count too (cached at the pipeline base scale):\n // extractPeaks clamps to the cached scale, so a floor that ignores them\n // lets the zoom go finer than the peaks can render — squeezed waveforms.\n const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);\n this._raiseZoomFloor(cachedScale);\n return clip;\n }\n /**\n * Filter MIDI notes to only those with finite, in-range fields. Logs a\n * warning for each dropped note. Used by _buildMidiClip and the\n * _applyClipUpdate MIDI branch to prevent NaN propagation through the\n * timeline.\n */\n private _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 * A clip descriptor is treated as MIDI when it has no audio src.\n * Includes placeholder MIDI clips (no notes, no duration yet — registered\n * with a 1s default span; notes upgrade via _applyClipUpdate). Warns when\n * a clip ambiguously has both src and midiNotes — the audio path runs\n * and notes would be silently ignored.\n */\n private _isMidiDescriptor(clipDesc: ClipDescriptor): boolean {\n if (clipDesc.src) {\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 * Build an engine clip from a MIDI clip descriptor. Always returns a clip\n * — empty notes / no declared duration get a 1-second placeholder span so\n * the clip is reachable via `engine.updateTrack` once notes arrive.\n */\n private _buildMidiClip(clipDesc: ClipDescriptor): AudioClip {\n const sr = this.effectiveSampleRate;\n const notes = this._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(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);\n const requestedDurationSamples =\n clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;\n\n const clip = createClip({\n startSample: Math.round(clipDesc.start * sr),\n durationSamples: requestedDurationSamples,\n offsetSamples: Math.round(clipDesc.offset * sr),\n sampleRate: sr,\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 (isDomClip(clipDesc)) clip.id = clipDesc.clipId;\n return clip;\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 * Recompute duration and forward an updated track to the engine. Single\n * source of truth for the incremental-vs-full-rebuild policy used by every\n * clip-level mutation (addClip, updateClip, removeClip, _applyClipUpdate).\n * Use the engine's incremental updateTrack when available; otherwise fall\n * back to full setTracks (legacy adapters).\n */\n private _commitTrackChange(trackId: string, updatedTrack: ClipTrack) {\n this._recomputeDuration();\n if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);\n else if (this._engine) this._engine.setTracks(this._tracksForEngine());\n }\n private _applyClipUpdate(trackId: string, clipId: string, clipEl: DawClipElement) {\n const t = this._engineTracks.get(trackId);\n if (!t) {\n console.warn('[dawcore] _applyClipUpdate: no engine track for id \"' + trackId + '\"');\n return;\n }\n const idx = t.clips.findIndex((c) => c.id === clipId);\n if (idx === -1) {\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 = t.clips[idx];\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 = this._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 const notes = this._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 const updatedClips = [...t.clips];\n updatedClips[idx] = updatedClip;\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n // Drop any audio caches in case this clip was previously loaded as audio.\n this._purgeClipCaches(clipId);\n this._commitTrackChange(trackId, updatedTrack);\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 const updatedClips = [...t.clips];\n updatedClips[idx] = updatedClip;\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\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._commitTrackChange(trackId, updatedTrack);\n }\n private _removeClipFromTrack(trackId: string, clipId: string) {\n const t = this._engineTracks.get(trackId);\n if (!t) {\n console.warn('[dawcore] _removeClipFromTrack: no engine track for id \"' + trackId + '\"');\n return;\n }\n const updatedClips = t.clips.filter((c) => c.id !== clipId);\n if (updatedClips.length === t.clips.length) {\n console.warn(\n '[dawcore] _removeClipFromTrack: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n\n const nextBuffers = new Map(this._clipBuffers);\n nextBuffers.delete(clipId);\n this._clipBuffers = nextBuffers;\n this._clipOffsets.delete(clipId);\n const nextPeaks = new Map(this._peaksData);\n nextPeaks.delete(clipId);\n this._peaksData = nextPeaks;\n\n const desc = this._tracks.get(trackId);\n if (desc) {\n this._tracks = new Map(this._tracks).set(trackId, {\n ...desc,\n // Descriptors without an id (file drops, the <daw-track src>\n // shorthand) are kept — their identity is the descriptor itself.\n clips: desc.clips.filter((c) => c.clipId !== clipId),\n });\n }\n this._commitTrackChange(trackId, updatedTrack);\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) {\n clips.push({\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 }\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 /**\n * The error for a clip whose kind is not its track's (#756), or null. A clip\n * with no `src` is a MIDI clip (see _isMidiDescriptor).\n */\n private _clipKindError(\n trackName: string,\n kind: TrackDescriptor['kind'],\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 // --- Audio Loading ---\n private async _loadTrack(trackId: string, descriptor: StoredTrackDescriptor) {\n // \"Still loading\" must be knowable independently of _engineTracks — the\n // peaks-first path inserts a PREVIEW track there mid-load, which would\n // otherwise make _onClipConnected treat a load-in-progress track as\n // fully loaded (late-appended clips silently discarded on final commit).\n this._loadingTracks.add(trackId);\n // Snapshot for the cancellation bail: this load's floor raises may\n // re-clamp (coarsen) the live zoom; a cancelled load restores it.\n const sppAtLoadStart = this._samplesPerPixel;\n try {\n const clips = [];\n // MIDI clips refused because the track is an audio track: they have no\n // src, so the \"all clips failed\" count below would not see them.\n let refusedMidiClips = 0;\n for (const clipDesc of descriptor.clips) {\n const clipIsMidi = this._isMidiDescriptor(clipDesc);\n const kindError = this._clipKindError(\n descriptor.name,\n descriptor.kind,\n clipIsMidi,\n clipDesc.name || clipDesc.src || (isDomClip(clipDesc) ? clipDesc.clipId : '')\n );\n if (kindError) {\n // Not added: a wrong-kind clip must never reach the engine, which\n // throws on a track that holds both kinds.\n console.warn('[dawcore] _loadTrack: ' + kindError.message);\n if (this.isConnected) {\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n clipId: isDomClip(clipDesc) ? clipDesc.clipId : '',\n error: kindError,\n },\n })\n );\n }\n if (clipIsMidi) refusedMidiClips++;\n continue;\n }\n if (clipIsMidi) {\n // MIDI clip path: no fetch, no peaks, register the clip directly.\n // Always registers (even with no notes / no duration) so late note\n // arrivals via daw-clip-update — handled in _applyClipUpdate\n // — can find the clip in _engineTracks.\n clips.push(this._buildMidiClip(clipDesc));\n continue;\n }\n // Per-clip try/catch: a single bad clip dispatches daw-clip-error and\n // skips to the next clip rather than aborting the whole track. Without\n // this, clip N's failure leaks earlier clips' cache writes from this\n // loop because the outer catch never reaches engine.setTracks().\n try {\n // Start both fetches concurrently — await peaks first to render preview before audio decode\n const waveformDataPromise = clipDesc.peaksSrc\n ? this._resolvePeaks(clipDesc.peaksSrc)\n : Promise.resolve(null);\n const audioPromise = this._fetchAndDecode(clipDesc.src);\n\n // --- Peaks-first path: render waveform before audio decode completes ---\n // _resolvePeaks returns null on fetch failure or sample-rate mismatch\n // (warns in either case); the standard path below handles the null case.\n const waveformData = await waveformDataPromise;\n if (waveformData) {\n // Create clip with integer samples to avoid float round-trip drift\n // (CLAUDE.md pattern #40: prefer createClip when samples known)\n const wdRate = waveformData.sample_rate;\n const clip = createClip({\n waveformData,\n startSample: Math.round(clipDesc.start * wdRate),\n durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),\n offsetSamples: Math.round(clipDesc.offset * wdRate),\n gain: clipDesc.gain,\n name: clipDesc.name,\n sampleRate: wdRate,\n sourceDurationSamples: Math.ceil(waveformData.duration * wdRate),\n });\n // Align engine clip.id with the source <daw-clip>.clipId (if any) so\n // DOM and engine refer to the same clip — required for editor.removeClip\n // and editor.updateClip lookups.\n if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;\n const effectiveScale = Math.max(this._renderSpp, waveformData.scale);\n const peakData = extractPeaks(\n waveformData,\n effectiveScale,\n this.mono,\n clip.offsetSamples,\n clip.durationSamples\n );\n this._clipOffsets.set(clip.id, {\n offsetSamples: clip.offsetSamples,\n durationSamples: clip.durationSamples,\n });\n this._peaksData = new Map(this._peaksData).set(clip.id, peakData);\n this._raiseZoomFloor(waveformData.scale);\n\n // Render preview track immediately with peaks (render-only until audio\n // completes and engine.setTracks() runs at end of _loadTrack).\n // Skip when the track was removed while the .dat was fetching —\n // inserting would visibly resurrect the removed track for the\n // whole audio decode (the commit-time re-check only catches it\n // at the end).\n if (this._tracks.has(trackId)) {\n const previewTrack = createTrack({\n name: descriptor.name,\n kind: descriptor.kind,\n clips: [clip],\n ...this._mixOf(trackId),\n });\n previewTrack.id = trackId;\n this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);\n this._recomputeDuration();\n }\n\n // Wait for audio decode — clean up preview state if it fails\n let audioBuffer: AudioBuffer;\n try {\n audioBuffer = await audioPromise;\n } catch (audioErr) {\n // Remove ghost preview so the user doesn't see a waveform with no audio\n const nextPeaks = new Map(this._peaksData);\n nextPeaks.delete(clip.id);\n this._peaksData = nextPeaks;\n this._clipOffsets.delete(clip.id);\n const nextEngine = new Map(this._engineTracks);\n nextEngine.delete(trackId);\n this._engineTracks = nextEngine;\n this._recomputeZoomFloor();\n this._recomputeDuration();\n throw audioErr; // Propagate to outer catch for daw-track-error event\n }\n this._resolvedSampleRate = audioBuffer.sampleRate;\n // Backfill audioBuffer immutably: new clip replaces the preview clip\n const updatedClip = { ...clip, audioBuffer };\n this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);\n this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);\n clips.push(updatedClip);\n continue;\n }\n\n // --- Standard path: decode audio first, then generate peaks ---\n // Reached only when the peaks-first branch above didn't kick in\n // (no peaksSrc, fetch failure, or sample-rate mismatch). waveformData\n // is always null here.\n const audioBuffer = await audioPromise;\n this._resolvedSampleRate = audioBuffer.sampleRate;\n const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, null);\n clips.push(clip);\n } catch (clipErr) {\n // _finalizeAudioClip and the peaks-first audio-decode catch already\n // purged their own per-clip caches before throwing here. Dispatch\n // daw-clip-error so consumers can correlate the failure to a clip.\n console.warn(\n '[dawcore] _loadTrack: clip \"' + clipDesc.src + '\" failed: ' + String(clipErr)\n );\n if (this.isConnected) {\n this.dispatchEvent(\n new CustomEvent<DawClipErrorDetail>('daw-clip-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n clipId: isDomClip(clipDesc) ? clipDesc.clipId : '',\n error: clipErr,\n },\n })\n );\n }\n }\n }\n // Track removed while its clips were loading (removeTrack / element\n // removal during fetch/decode), or the editor itself was detached —\n // committing now would resurrect the track in the engine/UI, and on a\n // detached editor _ensureEngine() would build a fresh engine + adapter\n // graph that nothing ever disposes (disconnectedCallback already ran).\n // Undo this load's own writes (clip caches, a peaks-first preview\n // insert, the zoom floor it raised) and settle any addTrack() awaiter\n // via the outer catch's daw-track-error.\n const trackWasRemoved = !this._tracks.has(trackId);\n if (trackWasRemoved || !this.isConnected) {\n for (const clip of clips) {\n this._purgeClipCaches(clip.id);\n }\n if (this._engineTracks.has(trackId)) {\n const nextEngine = new Map(this._engineTracks);\n nextEngine.delete(trackId);\n this._engineTracks = nextEngine;\n this._recomputeDuration();\n }\n this._recomputeZoomFloor();\n // Undo the coarsening this load's own floor re-clamp forced on the\n // live zoom — the load that required it no longer exists. Restore\n // only when the recomputed floor allows it.\n if (\n this._samplesPerPixel !== sppAtLoadStart &&\n sppAtLoadStart >= this._minSamplesPerPixel\n ) {\n this.samplesPerPixel = sppAtLoadStart;\n }\n throw new TrackLoadCancelledError(\n trackWasRemoved\n ? 'track \"' + trackId + '\" was removed while loading'\n : 'editor was disconnected while track \"' + trackId + '\" was loading',\n trackWasRemoved ? 'removed' : 'disconnected'\n );\n }\n // The seed while it loads; the arrangement's mix when the engine holds\n // it already (a src change reloads a loaded track).\n const track = createTrack({\n name: descriptor.name,\n kind: descriptor.kind,\n clips,\n ...this._mixOf(trackId),\n });\n // If clips were requested but ALL failed to load, surface as a track-level\n // error so addTrack({clips: [...]}) rejects appropriately. Per-clip\n // daw-clip-error events have already fired for each individual failure.\n const requestedClips = descriptor.clips.filter((c) => c.src).length + refusedMidiClips;\n if (requestedClips > 0 && clips.length === 0) {\n throw new Error(\n 'all ' + requestedClips + ' clip(s) failed to load — see prior daw-clip-error events'\n );\n }\n // Align track.id with the editor's trackId so engine.setTrackSolo/Mute/etc. find it\n track.id = trackId;\n this._engineTracks = new Map(this._engineTracks).set(trackId, track);\n this._recomputeDuration();\n // Now that descriptor is recorded and clips have ids, push audio into\n // the spectrogram controller (no-op unless renderMode === 'spectrogram').\n for (const c of clips) {\n this._maybeRegisterSpectrogramClipAudio(trackId, c);\n }\n const engine = await this._ensureEngine();\n // A control moved during the await is in the seed, not in `track`.\n engine.setTracks(this._tracksForEngine());\n this.dispatchEvent(\n new CustomEvent<DawTrackIdDetail>('daw-track-ready', {\n bubbles: true,\n composed: true,\n detail: { trackId },\n })\n );\n } catch (err) {\n const cancelled = err instanceof TrackLoadCancelledError;\n // A cancellation is a normal user action (removal / teardown), not a\n // failure — don't log it as one.\n console.warn(\n cancelled\n ? '[dawcore] Track load cancelled: ' + (err as Error).message\n : '[dawcore] Failed to load track \"' + trackId + '\": ' + String(err)\n );\n // Dispatch even when detached: a bubbling event can't reach ancestors\n // (CLAUDE.md pattern #36), but the _awaitId listeners registered on\n // `this` for addTrack()/loadMidi() still fire on a detached element —\n // skipping the dispatch leaves those promises unsettled forever\n // (mirrors _loadAndAppendClip's error path). Cancellations carry\n // detail.reason so consumer error UIs can filter them.\n this.dispatchEvent(\n new CustomEvent<DawTrackErrorDetail>('daw-track-error', {\n bubbles: true,\n composed: true,\n detail: {\n trackId,\n error: err,\n ...(cancelled ? { reason: (err as TrackLoadCancelledError).reason } : {}),\n },\n })\n );\n } finally {\n this._loadingTracks.delete(trackId);\n }\n }\n async _fetchAndDecode(src: string): Promise<AudioBuffer> {\n if (this._audioCache.has(src)) {\n return this._audioCache.get(src)!;\n }\n const promise = (async () => {\n const response = await fetch(src);\n if (!response.ok) {\n throw new Error(\n 'Failed to fetch audio \"' + src + '\": ' + response.status + ' ' + response.statusText\n );\n }\n const arrayBuffer = await response.arrayBuffer();\n return this.audioContext.decodeAudioData(arrayBuffer);\n })();\n this._audioCache.set(src, promise);\n try {\n return await promise;\n } catch (err) {\n this._audioCache.delete(src);\n throw err;\n }\n }\n private _fetchPeaks(src: string): Promise<import('waveform-data').default> {\n const cached = this._peaksCache.get(src);\n if (cached) return cached;\n const promise = loadWaveformDataFromUrl(src).catch((err) => {\n this._peaksCache.delete(src);\n throw err;\n });\n this._peaksCache.set(src, promise);\n return promise;\n }\n _recomputeDuration() {\n let maxSample = 0;\n for (const track of this._engineTracks.values()) {\n for (const clip of track.clips) {\n const endSample = clip.startSample + clip.durationSamples;\n if (endSample > maxSample) maxSample = endSample;\n }\n }\n this._duration = maxSample / this.effectiveSampleRate;\n }\n // --- Engine ---\n _ensureEngine(): Promise<PlaylistEngine> {\n if (this._engine) return Promise.resolve(this._engine);\n if (this._enginePromise) return this._enginePromise;\n this._enginePromise = this._buildEngine().catch((err) => {\n this._enginePromise = null;\n throw err;\n });\n return this._enginePromise;\n }\n private async _buildEngine() {\n if (!this._externalAdapter) {\n throw new Error(noAdapterError());\n }\n if (this._adapterConsumedByDispose) {\n // The previous disconnect disposed this adapter through the engine.\n // Some adapters (NativePlayoutAdapter) leave the AudioContext open, so\n // building on it would decode fine but wire tracks into a dead\n // transport graph — waveforms without audio. Fail loudly instead.\n throw new Error(\n '[dawcore] editor.adapter was disposed by a previous disconnect — ' +\n 'set a fresh PlayoutAdapter after reparenting <daw-editor>.'\n );\n }\n\n const { PlaylistEngine } = await import('@waveform-playlist/engine');\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 PlaylistEngine({\n adapter,\n sampleRate: this.effectiveSampleRate,\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 let lastTracksVersion = -1;\n let lastMixerVersion = -1;\n engine.on('statechange', (engineState) => {\n this._isPlaying = engineState.isPlaying;\n this._duration = engineState.duration;\n this._selectedTrackId = engineState.selectedTrackId;\n const structuralChange = engineState.tracksVersion !== lastTracksVersion;\n // Per-track mixer edits (volume/mute/solo/pan) bump mixerVersion, NOT\n // tracksVersion (#501). Refresh the _engineTracks cache on either so the\n // next setTracks rebuild keeps live mixer state — 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 !== lastMixerVersion;\n if (structuralChange || mixerChange) {\n lastTracksVersion = engineState.tracksVersion;\n lastMixerVersion = engineState.mixerVersion;\n const nextTracks = new Map<string, ClipTrack>();\n for (const track of engineState.tracks) {\n nextTracks.set(track.id, track);\n }\n this._engineTracks = nextTracks;\n // The arrangement holds these now: their seeds are not read again.\n this._deleteSeedMix(nextTracks.keys());\n // Undo can resurrect a track whose editor descriptor was purged at\n // removal — synthesize one so the track shows real name/controls\n // and appears in editor.tracks (the effects chain does not survive;\n // it was disposed at removal).\n this._reconcileDescriptorsWithEngineTracks(engineState.tracks);\n }\n // Sync clip positions when tracks change structurally (moveClip, trimClip,\n // splitClip, setTracks, addTrack, removeTrack).\n if (structuralChange) {\n // Engine-initiated order changes (undo/redo of a reorder) move the\n // DOM to match; guarded so the observer's own DOM→engine sync (which\n // emits intermediate statechanges mid-transaction) can't bounce\n // half-applied orders back into the DOM (#612).\n if (!this._inOrderSync) {\n this._syncDomToEngineOrder(engineState.tracks);\n }\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 syncPeaksForChangedClips(this, audioTracks);\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 engine.on('pause', () => {\n this._currentTime = engine.getCurrentTime();\n });\n engine.on('stop', () => {\n // Fires synchronously from PlaylistEngine.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\n this._engine = engine;\n return engine;\n }\n private _disposeEngine() {\n if (this._engine) {\n this._engine.dispose();\n this._engine = null;\n }\n this._enginePromise = null;\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(files: FileList | File[]): Promise<LoadFilesResult> {\n return loadFilesImpl(this, files);\n }\n /**\n * Imperatively load a `.mid` file (URL or File) and create N `<daw-track>`\n * elements — one per note-bearing MIDI track. On any per-track failure,\n * every `<daw-track>` appended during the call is removed (both successful\n * and failed) so the editor returns to its pre-call state.\n *\n * `options.signal` is forwarded to `fetch()` only for URL sources; aborting\n * after parsing does not cancel in-flight `addTrack` calls.\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<PlaylistEngine> {\n return this._ensureEngine();\n }\n /**\n * Wait for either `readyEvent` or `errorEvent` to fire on this editor for\n * the entity matching `matchesId`. Listeners are wired synchronously, then\n * `setup` is called (typical: appendChild). Resolves with `resolveValue`\n * on ready; rejects with a normalized Error on error. Used by addTrack and\n * addClip to share their Promise-with-listener-cleanup machinery.\n */\n private _awaitId<T>(\n readyEvent: string,\n errorEvent: string,\n matchesId: (detail: { trackId?: string; clipId?: string }) => boolean,\n resolveValue: T,\n setup: () => void\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onReady = (e: Event) => {\n if (!matchesId((e as CustomEvent).detail)) return;\n cleanup();\n resolve(resolveValue);\n };\n const onError = (e: Event) => {\n const detail = (e as CustomEvent).detail as { error?: unknown };\n if (!matchesId((e as CustomEvent).detail)) return;\n cleanup();\n const err = detail.error;\n reject(err instanceof Error ? err : new Error(String(err)));\n };\n const cleanup = () => {\n this.removeEventListener(readyEvent, onReady);\n this.removeEventListener(errorEvent, onError);\n };\n this.addEventListener(readyEvent, onReady);\n this.addEventListener(errorEvent, onError);\n setup();\n });\n }\n /**\n * Append a `<daw-track>` element built from `config` and resolve once the\n * track finishes loading (or reject on `daw-track-error`). Goes through\n * the same `_loadTrack` pipeline as declarative tracks, so descriptors,\n * peaks, and clip buffers are populated correctly.\n */\n addTrack(config: TrackConfig = {}): Promise<DawTrackElement> {\n const trackEl = document.createElement('daw-track') as DawTrackElement;\n if (config.name !== undefined) trackEl.setAttribute('name', config.name);\n if (config.volume !== undefined) trackEl.volume = config.volume;\n if (config.pan !== undefined) trackEl.pan = config.pan;\n if (config.muted) trackEl.setAttribute('muted', '');\n if (config.soloed) trackEl.setAttribute('soloed', '');\n\n // kind: explicit > 'midi' from the midi shorthand > default 'audio'. A\n // MIDI track is drawn as a piano roll whatever render-mode says.\n const kind = config.kind ?? (config.midi ? 'midi' : undefined);\n if (kind !== undefined) trackEl.setAttribute('kind', kind);\n if (config.renderMode !== undefined) trackEl.setAttribute('render-mode', config.renderMode);\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 for (const clipConfig of clipConfigs) {\n trackEl.appendChild(this._buildClipElement(clipConfig));\n }\n\n return this._awaitId(\n 'daw-track-ready',\n 'daw-track-error',\n (d) => d.trackId === trackEl.trackId,\n trackEl,\n () => this.appendChild(trackEl)\n );\n }\n /**\n * Remove a track by id. Equivalent to `trackElement.remove()` —\n * the editor's MutationObserver handles engine and cache cleanup.\n * No-op if no matching track exists.\n */\n removeTrack(trackId: string): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n trackEl.remove();\n } else if (this._engineTracks.has(trackId)) {\n // File-dropped tracks have no DOM element; clean up engine state directly.\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 new position in the vertical order (0-based index among\n * `<daw-track>` elements). Element-backed tracks move their DOM element —\n * the MutationObserver syncs the engine (single write path). Element-less\n * tracks (undo-resurrected) reorder the engine directly.\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 const el = this._trackElements.get(trackId);\n if (el) {\n const els = [...this.querySelectorAll('daw-track')] as DawTrackElement[];\n const from = els.indexOf(el);\n if (from === -1) return;\n const clamped = Math.max(0, Math.min(toIndex, els.length - 1));\n if (from === clamped) return;\n const anchor = els[clamped];\n if (clamped > from) anchor.after(el);\n else anchor.before(el);\n } else if (this._engineTracks.has(trackId)) {\n this._engine!.reorderTrack(trackId, toIndex);\n this.requestUpdate();\n } else {\n console.warn('[dawcore] reorderTrack: no track found for id \"' + trackId + '\"');\n }\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 * Update reflected attributes on a track. The mixer fields go to their\n * owner as one undo step (#843): the engine, or while the track is loading\n * the values it will enter with (not a step). For DOM-element tracks the\n * changes are also written to the `<daw-track>` element; for tracks\n * without a DOM element (file drops) the descriptor is updated in place.\n */\n updateTrack(trackId: string, partial: Partial<TrackConfig>): void {\n const mix: Partial<TrackMixerValues> = {\n volume: partial.volume,\n pan: partial.pan,\n muted: partial.muted,\n soloed: partial.soloed,\n };\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n // Written directly as well: an element that already holds a value (the\n // one an Undo took back) fires no update for it. The update the\n // element does fire sends the same values, which changes nothing.\n this._writeMixFields(trackId, mix);\n if (partial.name !== undefined) trackEl.setAttribute('name', partial.name);\n if (partial.volume !== undefined) trackEl.volume = partial.volume;\n if (partial.pan !== undefined) trackEl.pan = partial.pan;\n if (partial.muted !== undefined) {\n if (partial.muted) trackEl.setAttribute('muted', '');\n else trackEl.removeAttribute('muted');\n }\n if (partial.soloed !== undefined) {\n if (partial.soloed) trackEl.setAttribute('soloed', '');\n else trackEl.removeAttribute('soloed');\n }\n if (partial.renderMode !== undefined) trackEl.setAttribute('render-mode', partial.renderMode);\n return;\n }\n // No DOM element — apply directly to descriptor + engine.\n const oldDesc = this._tracks.get(trackId);\n if (!oldDesc) return;\n let normalizedRenderMode =\n partial.renderMode === undefined ? undefined : normalizeRenderMode(partial.renderMode);\n if (normalizedRenderMode === 'both') {\n console.warn(\n '[dawcore] render-mode=\"both\" is not yet supported; falling back to \\'spectrogram\\''\n );\n normalizedRenderMode = 'spectrogram';\n }\n const newDesc: StoredTrackDescriptor = {\n ...oldDesc,\n ...(partial.name !== undefined && { name: partial.name }),\n ...(normalizedRenderMode !== undefined && {\n renderMode: trackDescriptorRenderMode(oldDesc.kind, normalizedRenderMode),\n }),\n };\n this._tracks = new Map(this._tracks).set(trackId, newDesc);\n this._writeMixFields(trackId, mix);\n }\n /**\n * Append a clip to an existing track. Builds a `<daw-clip>` from `config`\n * and appends it to the track's DOM element when one exists; resolves with\n * the new clip's id once the audio decode + peak generation finish.\n */\n addClip(trackId: string, config: ClipConfig): Promise<string> {\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 trackEl = this._trackElements.get(trackId);\n if (!trackEl) {\n return Promise.reject(\n new Error(\n 'addClip: no <daw-track> element for trackId \"' +\n trackId +\n '\" — addClip currently requires a DOM-backed track. Use editor.addTrack(config) first.'\n )\n );\n }\n const clipEl = this._buildClipElement(config);\n return this._awaitId(\n 'daw-clip-ready',\n 'daw-clip-error',\n (d) => d.clipId === clipEl.clipId,\n clipEl.clipId,\n () => trackEl.appendChild(clipEl)\n );\n }\n /**\n * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when\n * present (MutationObserver handles cleanup); otherwise updates engine\n * state directly. No-op if no matching clip exists.\n */\n removeClip(trackId: string, clipId: string): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n const clipEl = [...trackEl.querySelectorAll('daw-clip')].find(\n (c) => (c as DawClipElement).clipId === clipId\n ) as DawClipElement | undefined;\n if (clipEl) {\n clipEl.remove();\n return;\n }\n }\n if (this._engineTracks.has(trackId)) {\n this._removeClipFromTrack(trackId, clipId);\n return;\n }\n console.warn(\n '[dawcore] removeClip: no track found for id \"' + trackId + '\" (clipId \"' + clipId + '\")'\n );\n }\n /**\n * Update a clip's position (start/duration/offset) or properties (gain/name).\n * For DOM-element clips, writes properties on the `<daw-clip>` element which\n * fires `daw-clip-update`; otherwise applies directly via `_applyClipUpdate`.\n *\n * Re-decoding (changing `src`) is not supported via this method — remove and\n * re-add the clip instead.\n *\n * Note: `fadeIn` / `fadeOut` / `fadeType` on the partial are written to the\n * `<daw-clip>` element (so they round-trip in the descriptor), but engine-side\n * fade application from `<daw-clip>` properties is not yet implemented — see\n * the broader fade-engine integration tracked separately.\n */\n updateClip(trackId: string, clipId: string, partial: Partial<ClipConfig>): void {\n const trackEl = this._trackElements.get(trackId);\n if (trackEl) {\n const clipEl = [...trackEl.querySelectorAll('daw-clip')].find(\n (c) => (c as DawClipElement).clipId === clipId\n ) as DawClipElement | undefined;\n if (clipEl) {\n if (partial.start !== undefined) clipEl.start = partial.start;\n if (partial.duration !== undefined) clipEl.duration = partial.duration;\n if (partial.offset !== undefined) clipEl.offset = partial.offset;\n if (partial.gain !== undefined) clipEl.gain = partial.gain;\n if (partial.name !== undefined) clipEl.setAttribute('name', partial.name);\n if (partial.fadeIn !== undefined) clipEl.fadeIn = partial.fadeIn;\n if (partial.fadeOut !== undefined) clipEl.fadeOut = partial.fadeOut;\n if (partial.fadeType !== undefined) clipEl.setAttribute('fade-type', partial.fadeType);\n return;\n }\n }\n // No DOM element — apply changes directly.\n const t = this._engineTracks.get(trackId);\n if (!t) {\n console.warn('[dawcore] updateClip: no track found for id \"' + trackId + '\"');\n return;\n }\n const idx = t.clips.findIndex((c) => c.id === clipId);\n if (idx === -1) {\n console.warn(\n '[dawcore] updateClip: clip \"' + clipId + '\" not found in track \"' + trackId + '\"'\n );\n return;\n }\n const oldClip = t.clips[idx];\n const sr = oldClip.sampleRate ?? this.effectiveSampleRate;\n const updatedClip = {\n ...oldClip,\n ...(partial.start !== undefined && { startSample: Math.round(partial.start * sr) }),\n ...(partial.duration !== undefined &&\n partial.duration > 0 && { durationSamples: Math.round(partial.duration * sr) }),\n ...(partial.offset !== undefined && { offsetSamples: Math.round(partial.offset * sr) }),\n ...(partial.gain !== undefined && { gain: partial.gain }),\n ...(partial.name !== undefined && { name: partial.name }),\n };\n const updatedClips = [...t.clips];\n updatedClips[idx] = updatedClip;\n const updatedTrack: ClipTrack = { ...t, clips: updatedClips };\n this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);\n // Keep editor.tracks truthful for element-less clips that carry their\n // engine id (recorded takes, #659) — no <daw-clip> element re-reads them.\n const desc = this._tracks.get(trackId);\n if (desc?.clips.some((c) => c.clipId === clipId)) {\n this._tracks = new Map(this._tracks).set(trackId, {\n ...desc,\n clips: desc.clips.map((c) =>\n c.clipId === clipId\n ? {\n ...c,\n start: updatedClip.startSample / sr,\n duration: updatedClip.durationSamples / sr,\n offset: updatedClip.offsetSamples / sr,\n ...(partial.gain !== undefined && { gain: partial.gain }),\n ...(partial.name !== undefined && { name: partial.name }),\n }\n : c\n ),\n });\n }\n this._commitTrackChange(trackId, updatedTrack);\n }\n private _buildClipElement(config: ClipConfig): DawClipElement {\n const clipEl = document.createElement('daw-clip') as DawClipElement;\n if (config.src !== undefined) clipEl.setAttribute('src', config.src);\n if (config.peaksSrc !== undefined) clipEl.setAttribute('peaks-src', config.peaksSrc);\n if (config.start !== undefined) clipEl.start = config.start;\n if (config.duration !== undefined) clipEl.duration = config.duration;\n if (config.offset !== undefined) clipEl.offset = config.offset;\n if (config.gain !== undefined) clipEl.gain = config.gain;\n if (config.name !== undefined) clipEl.setAttribute('name', config.name);\n if (config.fadeIn !== undefined) clipEl.fadeIn = config.fadeIn;\n if (config.fadeOut !== undefined) clipEl.fadeOut = config.fadeOut;\n if (config.fadeType !== undefined) clipEl.setAttribute('fade-type', config.fadeType);\n if (config.midiNotes !== undefined) clipEl.midiNotes = config.midiNotes;\n if (config.midiChannel !== undefined)\n clipEl.setAttribute('midi-channel', String(config.midiChannel));\n if (config.midiProgram !== undefined)\n clipEl.setAttribute('midi-program', String(config.midiProgram));\n return clipEl;\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() (PlaylistEngine 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 /** Undo the last structural edit. */\n undo(): void {\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. */\n redo(): void {\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 ? this._tracks.get(targetId) : undefined;\n if (targetId && target?.kind === '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 /** Guards the statechange handler's engine→DOM sync (Task: reorder #612)\n * while the observer is pushing DOM order INTO the engine — the intermediate\n * statechange emissions during the transaction would otherwise bounce\n * half-applied orders back into the DOM. */\n _inOrderSync = false;\n\n /**\n * DOM → engine: make the engine's track order match the light-DOM\n * `<daw-track>` order. Single write path for reorders — editor-initiated\n * (buttons/drag move the element) and consumer-initiated (insertBefore)\n * mutations both land here via the MutationObserver. Element-less tracks\n * (undo-resurrected) keep their engine positions (stable sort).\n * Write-only-on-change: a no-op when orders already match, so the\n * engine→DOM direction (statechange handler) converges in one pass.\n */\n _syncEngineOrderToDom(): void {\n const engine = this._engine;\n if (!engine) return;\n const domOrder: string[] = [...this.querySelectorAll('daw-track')].map(\n (el) => (el as DawTrackElement).trackId\n );\n const engineIds: string[] = engine.getState().tracks.map((t) => t.id);\n const target = [...engineIds].sort((a, b) => {\n const ai = domOrder.indexOf(a);\n const bi = domOrder.indexOf(b);\n if (ai === -1 || bi === -1) return 0; // element-less: keep relative position\n return ai - bi;\n });\n if (target.every((id, i) => id === engineIds[i])) return;\n this._inOrderSync = true;\n try {\n engine.beginTransaction(); // one undo step for the whole permutation\n const current = [...engineIds];\n for (let i = 0; i < target.length; i++) {\n if (current[i] === target[i]) continue;\n engine.reorderTrack(target[i], i);\n const from = current.indexOf(target[i]);\n current.splice(from, 1);\n current.splice(i, 0, target[i]);\n }\n engine.commitTransaction();\n } finally {\n this._inOrderSync = false;\n }\n this.requestUpdate();\n }\n\n /**\n * Engine → DOM: after an engine-initiated order change (undo/redo), move\n * `<daw-track>` elements to match engine order. The resulting mutations fire\n * the observer's _syncEngineOrderToDom, which finds the orders equal and\n * no-ops — converges in one pass (write-only-on-change).\n */\n _syncDomToEngineOrder(tracks: readonly ClipTrack[]): void {\n const els = [...this.querySelectorAll('daw-track')] as DawTrackElement[];\n if (els.length < 2) return;\n const byId = new Map<string, DawTrackElement>(els.map((el) => [el.trackId, el]));\n const desired = tracks\n .map((t) => byId.get(t.id))\n .filter((el): el is DawTrackElement => el != null);\n if (desired.length < 2) return;\n // Permute engine-known elements into engine order. Elements the engine\n // hasn't seen yet (tracks still loading — the engine holds only the\n // loaded subset during startup) are never moved, so they keep their\n // relative order among themselves (their absolute index can still shift\n // when engine-known neighbors move around them); anchoring desired[0] at\n // els[0] instead would promote the loaded subset to the top and reorder\n // tracks by decode-completion order (#625).\n const desiredSet = new Set(desired);\n const slots = els.filter((el) => desiredSet.has(el));\n if (desired.every((el, i) => el === slots[i])) return;\n for (let i = 0; i < desired.length; i++) {\n if (slots[i] === desired[i]) continue;\n // desired[i] currently sits at a later slot (earlier ones are settled);\n // insert it directly before the element occupying slot i.\n slots[i].before(desired[i]);\n const from = slots.indexOf(desired[i]);\n slots.splice(from, 1);\n slots.splice(i, 0, desired[i]);\n }\n }\n\n private _getOrderedTracks(): Array<[string, ClipTrack]> {\n const domOrder: string[] = [...this.querySelectorAll('daw-track')].map(\n (el) => (el as DawTrackElement).trackId\n );\n return [...this._engineTracks.entries()].sort((a, b) => {\n const ai = domOrder.indexOf(a[0]);\n const bi = domOrder.indexOf(b[0]);\n // Both not in DOM (e.g. file drops): preserve Map insertion order\n if (ai === -1 && bi === -1) return 0;\n // Only one not in DOM: sort it after DOM tracks\n if (ai === -1) return 1;\n if (bi === -1) return -1;\n return ai - bi;\n });\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]) => {\n const descriptor = this._tracks.get(trackId);\n const firstPeaks = track.clips\n .map((c) => this._peaksData.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 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 ${orderedTracks.map((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 </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 ${orderedTracks.map((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 = this._peaksData.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(MIN_RENDER_STEP, Math.ceil(this.ticksPerPixel));\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(startSec + clip.durationSamples / sr);\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 ${this._renderRecordingPreview(t.trackId, channelHeight)}\n </div>\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 const pixPerSec = sampleRate / samplesPerPixel;\n\n // Iterate with integer counter (milliseconds) to avoid float precision drift.\n // Compute pixel position from counter each iteration instead of accumulating.\n for (let counter = 0; ; counter += smallStep) {\n const pix = Math.floor((counter / 1000) * pixPerSec);\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","/**\n * A track's mix (volume, pan, 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 type { ClipTrack } 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});\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 { volume: track.volume, pan: track.pan, muted: track.muted, soloed: track.soloed };\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 { volume: el.volume, pan: el.pan, muted: el.muted, soloed: el.soloed };\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 };\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 { 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 :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 .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\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._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._resizeObserver?.disconnect();\n this._resizeObserver = null;\n this._scrollContainer = null;\n }\n\n private _attachScrollContainer(container: HTMLElement) {\n this._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._resizeObserver?.disconnect();\n this._scrollContainer = container;\n container.addEventListener('scroll', this._onScroll, { passive: true });\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 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 resolvedTarget.addEventListener('pointerdown', this._onGesture, {\n once: true,\n capture: true,\n });\n resolvedTarget.addEventListener('keydown', this._onGesture, {\n once: true,\n capture: true,\n });\n });\n }\n\n hostDisconnected() {\n this._removeListeners();\n this._attached = false;\n }\n\n private _onGesture = (e: Event) => {\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 // Remove the other listener (the fired one was auto-removed by { once: true })\n const otherType = e.type === 'pointerdown' ? 'keydown' : 'pointerdown';\n this._target?.removeEventListener(otherType, this._onGesture, {\n capture: true,\n });\n this._target = null;\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._target.removeEventListener('pointerdown', this._onGesture, {\n capture: true,\n });\n this._target.removeEventListener('keydown', this._onGesture, {\n capture: true,\n });\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 /** Stored so it can be removed on stop/cleanup — not just when stream ends. */\n readonly _onTrackEnded: (() => void) | null;\n readonly _audioTrack: MediaStreamTrack | null;\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' | '_onTrackEnded' | '_audioTrack' | '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 resolveAudioContextSampleRate(rate: number): void;\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 /** 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 // Resolve editor sample rate from AudioContext before computing startSample\n this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);\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 _onTrackEnded: onTrackEnded,\n _audioTrack: audioTrack,\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 audioTrack.addEventListener('ended', onTrackEnded);\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 if (session._audioTrack && session._onTrackEnded) {\n session._audioTrack.removeEventListener('ended', session._onTrackEnded);\n }\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 hostConnected(): void {\n this._host.addEventListener('daw-annotation-update', this._onDataChange);\n this._host.addEventListener('daw-annotation-select', this._onDataChange);\n this._host.addEventListener('daw-annotation-connected', this._onDataChange);\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);\n this._host.addEventListener('daw-stop', this._onStop);\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._host.removeEventListener('daw-annotation-update', this._onDataChange);\n this._host.removeEventListener('daw-annotation-select', this._onDataChange);\n this._host.removeEventListener('daw-annotation-connected', this._onDataChange);\n this._host.removeEventListener('daw-timeupdate', this._onTimeUpdate as EventListener);\n this._host.removeEventListener('daw-stop', this._onStop);\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 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 const detach = (pe: PointerEvent) => {\n this._timeline?.removeEventListener('pointermove', onMove);\n this._timeline?.removeEventListener('pointerup', onUp);\n this._timeline?.removeEventListener('pointercancel', onCancel);\n try {\n this._timeline?.releasePointerCapture(pe.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);\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);\n };\n this._timeline.addEventListener('pointermove', onMove);\n this._timeline.addEventListener('pointerup', onUp);\n this._timeline.addEventListener('pointercancel', onCancel);\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 this._timeline.addEventListener('pointermove', this._onPointerMove);\n this._timeline.addEventListener('pointerup', this._onPointerUp);\n this._timeline.addEventListener('pointercancel', this._onPointerCancel);\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._timeline.removeEventListener('pointermove', this._onPointerMove);\n this._timeline.removeEventListener('pointerup', this._onPointerUp);\n this._timeline.removeEventListener('pointercancel', this._onPointerCancel);\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 { SnapTo, MeterEntry } from '@waveform-playlist/core';\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 moveClip(trackId: string, clipId: string, deltaSamples: number, skipAdapter?: boolean): number;\n trimClip(\n trackId: string,\n clipId: string,\n boundary: 'left' | 'right',\n deltaSamples: number,\n skipAdapter?: boolean\n ): void;\n updateTrack(trackId: string): void;\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 /** Begin a transaction — groups mutations into one undo step. */\n beginTransaction(): void;\n /** Commit the transaction — pushes one undo step for all grouped mutations. */\n commitTransaction(): void;\n /** Abort the transaction — restores pre-transaction state without pushing to undo. */\n abortTransaction(): void;\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 * Move: sends incremental deltas per-frame with skipAdapter=true (engine shifts\n * startSample additively without touching audio adapter). Adapter synced once\n * via updateTrack() at drag end.\n * Trim: updates clip container CSS imperatively during drag for visual feedback,\n * then applies cumulative delta to engine once at drag end.\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\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 /** Returns true if a drag interaction is currently in progress. */\n get isActive(): boolean {\n return this._mode !== null;\n }\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 // Snapshot clip start position for snap calculations\n const engine = this._host.engine;\n if (engine) {\n const bounds = engine.getClipBounds(trackId, clipId);\n if (bounds) {\n this._originalStartSample = bounds.startSample;\n }\n }\n\n // Group all drag mutations into one undo step\n if (engine) {\n engine.beginTransaction();\n } else {\n console.warn(\n '[dawcore] beginDrag: engine unavailable, drag mutations will not be grouped for undo'\n );\n }\n\n // For trim: snapshot the clip container's current position/width\n if (mode === 'trim-left' || mode === 'trim-right') {\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 trim visual feedback: ' + clipId);\n }\n // Snapshot clip audio bounds for peak re-extraction during drag\n const engine = this._host.engine;\n if (engine) {\n const bounds = engine.getClipBounds(trackId, clipId);\n if (bounds) {\n this._originalOffsetSamples = bounds.offsetSamples;\n this._originalDurationSamples = bounds.durationSamples;\n }\n }\n }\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 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: compute total snapped delta from original position, then derive\n // the incremental from what's already been applied to the engine.\n // Anchor = clip start position (move shifts the whole clip)\n const totalSnappedDelta = this._snapDeltaToSamples(totalDeltaPx, this._originalStartSample);\n const incrementalDeltaSamples = totalSnappedDelta - this._cumulativeDeltaSamples;\n if (incrementalDeltaSamples !== 0) {\n // Track constrained delta (not raw) so undo transactions are accurate\n const applied = engine.moveClip(this._trackId, this._clipId, incrementalDeltaSamples, true);\n this._cumulativeDeltaSamples += applied;\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 // Convert sample delta to pixels — use tick space in beats mode\n // to avoid quantization drift from the sample round-trip.\n let deltaPx: number;\n if (this._host.scaleMode === 'beats') {\n const h = this._host;\n const anchorSec = anchor / h.effectiveSampleRate;\n const anchorTick = h._secondsToTicks(anchorSec);\n const newSec = anchorSec + deltaSamples / h.effectiveSampleRate;\n const newTick = h._secondsToTicks(newSec);\n deltaPx = Math.round((newTick - anchorTick) / h.ticksPerPixel);\n } else {\n deltaPx = Math.round(deltaSamples / this._host.renderSamplesPerPixel);\n }\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 trim drag didn't produce a delta\n this._restoreTrimVisual();\n return;\n }\n\n const engine = this._host.engine;\n\n if (this._mode === 'move') {\n // Sync adapter once on drop (skipped during drag for performance)\n if (engine) {\n engine.updateTrack(this._trackId);\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: this._cumulativeDeltaSamples,\n },\n })\n );\n } else {\n console.warn(\n '[dawcore] engine unavailable at move drop — audio may be out of sync for track ' +\n this._trackId\n );\n }\n } else {\n // Restore visual before engine applies — Lit will re-render with correct values\n this._restoreTrimVisual();\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 // Commit transaction if mutations occurred, abort if click/no-op.\n // Abort does NOT push to undo stack or clear redo stack.\n if (this._isDragging && this._cumulativeDeltaSamples !== 0) {\n this._host.engine?.commitTransaction();\n } else {\n this._host.engine?.abortTransaction();\n }\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 engine transaction stays open\n * (every later edit becomes un-undoable until some drag commits), and the\n * per-frame skipAdapter moveClip mutations are never synced or rolled back\n * (waveform and audio permanently disagree). */\n onPointerCancel(_e: PointerEvent): void {\n if (this._mode === null) return;\n try {\n // Undo the trim CSS preview; move mutations are rolled back by\n // abortTransaction below (restores the pre-drag snapshot and rebuilds\n // the adapter when mutations occurred).\n this._restoreTrimVisual();\n } finally {\n this._host.engine?.abortTransaction();\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 trim visual preview. Peaks matter: the drag wrote re-extracted peak\n * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and\n * a cancelled/zero-delta trim makes no engine mutation — so no statechange\n * re-render will ever repair them. */\n private _restoreTrimVisual(): 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 }\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 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 this._drag = {\n track,\n captureEl,\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 captureEl.addEventListener('pointermove', this._onPointerMove as EventListener);\n captureEl.addEventListener('pointerup', this._onPointerUp as EventListener);\n captureEl.addEventListener('pointercancel', this._onPointerCancel as EventListener);\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 // Restore the drag-start snapshot — a cancelled drag must not commit.\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.captureEl.removeEventListener('pointermove', this._onPointerMove as EventListener);\n drag.captureEl.removeEventListener('pointerup', this._onPointerUp as EventListener);\n drag.captureEl.removeEventListener('pointercancel', this._onPointerCancel as EventListener);\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\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\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 — lane DOM order\n // never changes, so the editor's MutationObserver order-sync never fires.\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 gripEl.addEventListener('pointermove', this._onPointerMove);\n gripEl.addEventListener('pointerup', this._onPointerUp);\n gripEl.addEventListener('pointercancel', this._onPointerCancel);\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 grip.removeEventListener('pointermove', this._onPointerMove);\n grip.removeEventListener('pointerup', this._onPointerUp);\n grip.removeEventListener('pointercancel', this._onPointerCancel);\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/** Parse a formatted time string back to seconds. Lenient: returns 0 for empty/unparseable input; does not validate segment ranges. */\nexport function parseDisplayTime(value: string, format: TimeDisplayFormat): number {\n if (!value) return 0;\n let seconds = 0;\n if (format === 'seconds') {\n seconds = parseFloat(value) || 0;\n } else {\n const parts = value.split(':');\n if (parts.length !== 3) return 0;\n const h = parseInt(parts[0], 10) || 0;\n const m = parseInt(parts[1], 10) || 0;\n const s = parseFloat(parts[2]) || 0;\n seconds = h * 3600 + m * 60 + s;\n }\n return Math.max(0, seconds);\n}\n","/**\n * File loading: routes dropped files through the same element pipeline as\n * editor.addTrack() — each file becomes a real `<daw-track><daw-clip>` in the\n * editor's light DOM, \"as a fresh page load would have\" (#612). The existing\n * daw-track-connected → _loadTrack pipeline does the fetch/decode.\n */\n\nimport type { DawTrackElement } from '../elements/daw-track';\nimport type { DawFilesLoadErrorDetail, LoadFilesResult } from '../events';\nimport type { TrackConfig } from '../types';\n\nexport interface FileLoaderHost {\n readonly isConnected: boolean;\n _audioCache: Map<string, Promise<AudioBuffer>>;\n addTrack(config: TrackConfig): Promise<DawTrackElement>;\n dispatchEvent(event: Event): boolean;\n}\n\nexport async function loadFiles(\n host: FileLoaderHost,\n files: FileList | File[]\n): Promise<LoadFilesResult> {\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 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 // 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\n const blobUrl = URL.createObjectURL(file);\n const name = file.name.replace(/\\.\\w+$/, '');\n try {\n // Sequential on purpose: preserves drop order as DOM/track order.\n const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });\n loaded.push(trackEl.trackId);\n // daw-track-ready was dispatched by the load pipeline — don't re-dispatch.\n } catch (err) {\n console.warn('[dawcore] Failed to load file: ' + file.name + ' — ' + String(err));\n dispatchLoadError(file, err);\n } finally {\n // The decode is complete either way; the blob URL and its cache entry\n // (keyed by a URL that will never be fetched again) are dead weight.\n URL.revokeObjectURL(blobUrl);\n host._audioCache.delete(blobUrl);\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` + `querySelectorAll`) — `<daw-editor>`\n * satisfies it without any new public surface.\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 { TrackConfig } from '../types';\nimport type { DawTrackElement } from '../elements/daw-track';\nimport { installCommand } from '../utils/install-command';\n\nexport type { MidiLoadOptions, MidiLoadResult };\n\n/**\n * Minimal host surface needed by `loadMidiImpl`. `<daw-editor>` satisfies this\n * structurally. `querySelectorAll` is needed for cleanup-on-failure so the\n * loader can identify `<daw-track>` elements appended during this call (both\n * those whose `addTrack` resolved and those that rejected after `_loadTrack`\n * fired `daw-track-error` — the latter aren't in the `addTrack` resolution\n * value, so we need DOM observation to find them).\n */\nexport interface MidiLoaderHost {\n addTrack(config: TrackConfig): Promise<DawTrackElement>;\n querySelectorAll(selector: string): NodeListOf<Element>;\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 creates N `<daw-track>` elements,\n * one per note-bearing MIDI track. On any per-track failure, every\n * `<daw-track>` appended during this call is removed so the editor returns\n * to its pre-call state (cleanup-on-failure — covers both `addTrack`\n * successes and the elements that `addTrack` left in the DOM before its\n * promise rejected).\n *\n * AbortSignal is forwarded to the fetch phase only. Aborting after parsing\n * does not cancel in-flight `addTrack` calls (documented limitation).\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 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, options.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\n // (3) Snapshot existing tracks so cleanup can identify the ones we appended.\n const childrenBefore = new Set<Element>(host.querySelectorAll('daw-track'));\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 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 )\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: DawTrackElement[] = [];\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 ALL tracks appended during this call (both\n // succeeded and the ones addTrack left in the DOM before rejecting), 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 const appendedTracks = Array.from(host.querySelectorAll('daw-track')).filter(\n (el) => !childrenBefore.has(el)\n );\n for (const el of appendedTracks) {\n try {\n el.remove();\n } catch (cleanupErr) {\n console.warn('[dawcore] loadMidi cleanup failed for a track: ' + String(cleanupErr));\n }\n }\n // Let MutationObserver microtasks flush so engine state is consistent\n // before rethrow.\n await Promise.resolve();\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.map((el) => el.trackId),\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 { ClipTrack, PeakData } from '@waveform-playlist/core';\nimport { carveClipRange, createClip } from '@waveform-playlist/core';\nimport type { PeakPipeline } from '../workers/peakPipeline';\nimport type { DawErrorDetail, DawRecordingClipAddDetail } from '../events';\nimport type { StoredTrackDescriptor, ClipDescriptor } from '../types';\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 _tracks: Map<string, StoredTrackDescriptor>;\n _engineTracks: Map<string, ClipTrack>;\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 _engine: {\n setTracks(tracks: readonly ClipTrack[]): void;\n updateTrack?(trackId: string, track: ClipTrack): void;\n } | null;\n _recomputeDuration(): void;\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 const t = host._engineTracks.get(trackId);\n if (!t) {\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 // Same floor policy as _finalizeAudioClip: 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 host._engineTracks = new Map(host._engineTracks).set(trackId, {\n ...t,\n // Punch-in replace (#579): the recorded clip owns [startSample,\n // startSample + durSamples) — carve overlapped content out of the\n // existing clips before inserting (parity with the React provider).\n clips: [...carveClipRange(t.clips, startSample, startSample + durSamples), clip],\n });\n // Keep _tracks in sync so public API and track controls reflect the clip\n const desc = host._tracks.get(trackId);\n if (desc) {\n const sr = host.effectiveSampleRate;\n const clipDesc: ClipDescriptor = {\n kind: 'drop',\n // The take has no <daw-clip> element — the engine id is the only\n // handle updateClip()/removeClip() can address it by (#659).\n clipId: clip.id,\n src: '',\n peaksSrc: '',\n start: startSample / sr,\n duration: durSamples / sr,\n offset: 0,\n gain: 1,\n name: clipName ?? 'Recording',\n fadeIn: 0,\n fadeOut: 0,\n fadeType: 'linear',\n midiNotes: null,\n midiChannel: null,\n midiProgram: null,\n };\n host._tracks = new Map(host._tracks).set(trackId, {\n ...desc,\n clips: [...desc.clips, clipDesc],\n });\n }\n host._recomputeDuration();\n const updatedTrack = host._engineTracks.get(trackId);\n if (host._engine?.updateTrack && updatedTrack) {\n host._engine.updateTrack(trackId, updatedTrack);\n } else {\n host._engine?.setTracks([...host._engineTracks.values()]);\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 if (!clip) return false;\n\n // MIDI clip splitting requires note slicing — not implemented yet.\n if (clip.midiNotes != null) return false;\n\n return true;\n}\n\n/** Core split logic — finds clip at position, calls engine, diffs state for new IDs. */\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 // Engine replaces the original clip with two halves; both get new IDs\n const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));\n if (newClips.length !== 2) {\n if (newClips.length > 0) {\n console.warn(\n '[dawcore] splitAtPlayhead: expected 2 new clips after split but got ' + newClips.length\n );\n }\n return false;\n }\n\n // Sort by startSample: lower = left, higher = right\n const sorted = [...newClips].sort((a, b) => a.startSample - b.startSample);\n const leftClipId = sorted[0].id;\n const rightClipId = sorted[1].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}\n\n/**\n * Regenerate peaks for clips that are new or whose offset/duration changed.\n * Handles split (new clip IDs) 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 })\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., the original clip after a split is replaced by two new clips)\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","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, trackChannelCount } 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 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 comes from the clips' channel\n // count, not from whatever layout the effects chain outputs.\n const panStage = createPanStage(ctx, track.pan, trackChannelCount(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).\n */\nexport async function loadWaveformDataFromUrl(src: string): Promise<WaveformData> {\n const response = await fetch(src);\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 private _wheelTargets: Set<HTMLElement> = new Set();\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._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._scrollContainer = null;\n for (const target of this._wheelTargets) {\n target.removeEventListener('wheel', this._onWheel);\n }\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._scrollContainer.removeEventListener('scroll', this._onScroll);\n this._scrollContainer = null;\n for (const t of this._wheelTargets) t.removeEventListener('wheel', this._onWheel);\n this._wheelTargets.clear();\n }\n return;\n }\n if (container !== this._scrollContainer) {\n this._scrollContainer?.removeEventListener('scroll', this._onScroll);\n this._scrollContainer = container;\n container.addEventListener('scroll', this._onScroll, { passive: true });\n }\n\n // Diff the current set of matched wheel targets.\n const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));\n for (const old of this._wheelTargets) {\n if (!nextTargets.has(old)) {\n old.removeEventListener('wheel', this._onWheel);\n this._wheelTargets.delete(old);\n }\n }\n for (const next of nextTargets) {\n if (!this._wheelTargets.has(next)) {\n next.addEventListener('wheel', this._onWheel, { passive: false });\n this._wheelTargets.add(next);\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 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 target.addEventListener('daw-recording-start', this._onStart);\n target.addEventListener('daw-recording-complete', this._onComplete);\n target.addEventListener('daw-recording-error', this._onError);\n }\n\n private _cleanupListeners() {\n if (this._targetRef) {\n this._targetRef.removeEventListener('daw-recording-start', this._onStart);\n this._targetRef.removeEventListener('daw-recording-complete', this._onComplete);\n this._targetRef.removeEventListener('daw-recording-error', this._onError);\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 { KeyboardShortcut } from '@waveform-playlist/core';\nimport type { DawEditorElement } from './daw-editor';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Key binding for remapping — derived from KeyboardShortcut to stay in sync. */\nexport type KeyBinding = Pick<\n KeyboardShortcut,\n 'key' | 'ctrlKey' | 'shiftKey' | 'metaKey' | 'altKey'\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 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 document.addEventListener('keydown', this._onKeyDown);\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n document.removeEventListener('keydown', this._onKeyDown);\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 connectedCallback() {\n super.connectedCallback();\n document.addEventListener('daw-timeupdate', this._onTimeUpdate);\n document.addEventListener('daw-time-format-change', this._onFormatChange);\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 document.removeEventListener('daw-timeupdate', this._onTimeUpdate);\n document.removeEventListener('daw-time-format-change', this._onFormatChange);\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 connectedCallback() {\n super.connectedCallback();\n document.addEventListener('daw-time-format-change', this._onFormatChange);\n this.addEventListener('pointerdown', this._onPointerDown);\n this.addEventListener('pointerenter', this._onPointerEnter);\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 document.removeEventListener('daw-time-format-change', this._onFormatChange);\n this.removeEventListener('pointerdown', this._onPointerDown);\n this.removeEventListener('pointerenter', this._onPointerEnter);\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 PlaylistEngine,\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 :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 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 private async _loadPeaks(): Promise<void> {\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 try {\n const wd = await loadWaveformDataFromUrl(requested);\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 // 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 }\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,+BAA8B,sBAAqB,qCAAoC,gBAAe,8BAA6B,2BAA0B,0CAAyC,6BAA4B,4CAA2C,+BAA8B,8CAA6C,8BAA6B,4CAA2C;;;ACAje,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,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AAI,IAAK,KAAK;AACtD,SAAK,WAAW,YAAY,EAAE;AAAA,EAChC;AAAA,EAEA,IAAY,iBAAyB;AACnC,WAAO,KAAK,YAAY,cAA2B,gBAAgB,GAAG,eAAe;AAAA,EACvF;AACF;AAhXa,iBAiDJ,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAhDY;AAAA,MAA3B,8BAAS,EAAE,MAAM,OAAO,CAAC;AAAA,GADf,iBACiB;AACwB;AAAA,MAAnD,8BAAS,EAAE,MAAM,QAAQ,WAAW,YAAY,CAAC;AAAA,GAFvC,iBAEyC;AACE;AAAA,MAArD,8BAAS,EAAE,MAAM,QAAQ,WAAW,cAAc,CAAC;AAAA,GAHzC,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","import_lit","import_decorators","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_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","import_core","engine","import_core","updated","import_core","state","state","import_core","import_core","PREFIX","element","import_core","PREFIX","import_waveform_data","WaveformData","updatedClip","updatedClips","updatedTrack","clip","audioBuffer","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"]}