@dawcore/components 0.0.23 → 0.0.25

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.mjs CHANGED
@@ -201,6 +201,68 @@ var DawTrackElement = class extends LitElement2 {
201
201
  createRenderRoot() {
202
202
  return this;
203
203
  }
204
+ // --- Effects API (delegates to the owning <daw-editor>) ---
205
+ addEffect(type, params) {
206
+ return this._effectsEditor()._trackAddEffect(this.trackId, this, type, params);
207
+ }
208
+ /** Load a WAM plugin (via the optional @dawcore/wam peer) into this track's chain. */
209
+ addWamPlugin(url, initialState) {
210
+ return this._effectsEditor()._trackAddWamPlugin(this.trackId, this, url, initialState);
211
+ }
212
+ /**
213
+ * Compile Faust DSP source in the browser (via the optional @dawcore/faust
214
+ * peer) and add the resulting WAM to this track's chain. Compile errors
215
+ * keep their Faust line/column diagnostics and leave the chain untouched.
216
+ */
217
+ addFaustEffect(dspCode, options) {
218
+ return this._effectsEditor()._trackAddFaustEffect(this.trackId, this, dspCode, options);
219
+ }
220
+ /** Snapshot this track's chain in its persisted form (see dawcore README). */
221
+ getEffectsState() {
222
+ const editor = this.closest("daw-editor");
223
+ return editor?._trackGetEffectsState(this.trackId) ?? Promise.resolve([]);
224
+ }
225
+ /** Replace this track's chain with a persisted snapshot. */
226
+ setEffectsState(entries) {
227
+ return this._effectsEditor()._trackSetEffectsState(this.trackId, this, entries);
228
+ }
229
+ /**
230
+ * Open (lazily creating) the GUI for one of this track's effects into a
231
+ * consumer-provided container. Closing hides without interrupting audio;
232
+ * the element is cached for reopen. See <daw-editor>.openEffectGui.
233
+ */
234
+ openEffectGui(effectId, container) {
235
+ return this._effectsEditor()._trackOpenEffectGui(this.trackId, this, effectId, container);
236
+ }
237
+ /** Hide an effect's GUI (cached for reopen — never destroys). */
238
+ closeEffectGui(effectId) {
239
+ this._effectsEditor()._trackCloseEffectGui(this.trackId, effectId);
240
+ }
241
+ removeEffect(effectId) {
242
+ this._effectsEditor()._trackEffectOp(this.trackId, this, "remove", effectId);
243
+ }
244
+ setEffectParams(effectId, params) {
245
+ this._effectsEditor()._trackEffectOp(this.trackId, this, "setParams", effectId, params);
246
+ }
247
+ setEffectBypassed(effectId, bypassed) {
248
+ this._effectsEditor()._trackEffectOp(this.trackId, this, "setBypassed", effectId, bypassed);
249
+ }
250
+ moveEffect(effectId, newIndex) {
251
+ this._effectsEditor()._trackEffectOp(this.trackId, this, "move", effectId, newIndex);
252
+ }
253
+ get effects() {
254
+ const editor = this.closest("daw-editor");
255
+ return editor?._trackEffects(this.trackId) ?? [];
256
+ }
257
+ _effectsEditor() {
258
+ const editor = this.closest("daw-editor");
259
+ if (!editor) {
260
+ throw new Error(
261
+ "[waveform-playlist] <daw-track> effects API requires the track to be inside a <daw-editor>"
262
+ );
263
+ }
264
+ return editor;
265
+ }
204
266
  connectedCallback() {
205
267
  super.connectedCallback();
206
268
  setTimeout(() => {
@@ -836,42 +898,9 @@ DawPianoRollElement = __decorateClass([
836
898
  // src/elements/daw-playhead.ts
837
899
  import { LitElement as LitElement5, html as html3, css as css3 } from "lit";
838
900
  import { customElement as customElement5 } from "lit/decorators.js";
839
-
840
- // src/controllers/animation-controller.ts
841
- var AnimationController = class {
842
- constructor(host) {
843
- this._rafId = null;
844
- this._callback = null;
845
- host.addController(this);
846
- }
847
- start(callback) {
848
- this.stop();
849
- this._callback = callback;
850
- const loop = () => {
851
- this._callback?.();
852
- this._rafId = requestAnimationFrame(loop);
853
- };
854
- this._rafId = requestAnimationFrame(loop);
855
- }
856
- stop() {
857
- if (this._rafId !== null) {
858
- cancelAnimationFrame(this._rafId);
859
- this._rafId = null;
860
- }
861
- this._callback = null;
862
- }
863
- hostConnected() {
864
- }
865
- hostDisconnected() {
866
- this.stop();
867
- }
868
- };
869
-
870
- // src/elements/daw-playhead.ts
871
901
  var DawPlayheadElement = class extends LitElement5 {
872
902
  constructor() {
873
903
  super(...arguments);
874
- this._animation = new AnimationController(this);
875
904
  this._line = null;
876
905
  }
877
906
  render() {
@@ -880,52 +909,10 @@ var DawPlayheadElement = class extends LitElement5 {
880
909
  firstUpdated() {
881
910
  this._line = this.shadowRoot.querySelector("div");
882
911
  }
883
- startAnimation(getTime, sampleRate, samplesPerPixel) {
884
- this._animation.start(() => {
885
- const time = getTime();
886
- const px = time * sampleRate / samplesPerPixel;
887
- if (this._line) {
888
- this._line.style.transform = `translate3d(${px}px, 0, 0)`;
889
- }
890
- });
891
- }
892
- stopAnimation(time, sampleRate, samplesPerPixel) {
893
- this._animation.stop();
894
- const px = time * sampleRate / samplesPerPixel;
895
- if (this._line) {
896
- this._line.style.transform = `translate3d(${px}px, 0, 0)`;
897
- }
898
- }
899
- startBeatsAnimation(getTime, bpm, ppqn, ticksPerPixel) {
900
- const ticksPerSecond = bpm * ppqn / 60;
901
- this._animation.start(() => {
902
- const time = getTime();
903
- const px = time * ticksPerSecond / ticksPerPixel;
904
- if (this._line) {
905
- this._line.style.transform = `translate3d(${px}px, 0, 0)`;
906
- }
907
- });
908
- }
909
- stopBeatsAnimation(time, bpm, ppqn, ticksPerPixel) {
910
- this._animation.stop();
911
- const px = time * bpm * ppqn / (60 * ticksPerPixel);
912
- if (this._line) {
913
- this._line.style.transform = `translate3d(${px}px, 0, 0)`;
914
- }
915
- }
916
- startBeatsAnimationWithMap(getTime, secondsToTicks, ticksPerPixel) {
917
- this._animation.start(() => {
918
- const time = getTime();
919
- const tick = secondsToTicks(time);
920
- const px = tick / ticksPerPixel;
921
- if (this._line) {
922
- this._line.style.transform = `translate3d(${px}px, 0, 0)`;
923
- }
924
- });
925
- }
926
- stopBeatsAnimationWithMap(time, secondsToTicks, ticksPerPixel) {
927
- this._animation.stop();
928
- const px = secondsToTicks(time) / ticksPerPixel;
912
+ /** Position the playhead line at an absolute pixel offset on the timeline.
913
+ * The editor's PlaybackAnimationController drives this each frame — the
914
+ * playhead owns no animation loop or time math of its own. */
915
+ setPosition(px) {
929
916
  if (this._line) {
930
917
  this._line.style.transform = `translate3d(${px}px, 0, 0)`;
931
918
  }
@@ -983,12 +970,102 @@ import { customElement as customElement7, state } from "lit/decorators.js";
983
970
 
984
971
  // src/elements/daw-transport-button.ts
985
972
  import { LitElement as LitElement7, css as css4 } from "lit";
973
+
974
+ // src/utils/transport-capability.ts
975
+ function resolveTransportTarget(el) {
976
+ const transport = el.closest("daw-transport");
977
+ return transport?.target ?? null;
978
+ }
979
+ function targetSupports(target, methods) {
980
+ if (!target) return false;
981
+ return methods.every((m) => typeof target[m] === "function");
982
+ }
983
+ function targetUndetermined(target) {
984
+ if (!target) return true;
985
+ const name = target.localName;
986
+ return name.includes("-") && customElements.get(name) === void 0;
987
+ }
988
+ var warned = /* @__PURE__ */ new WeakMap();
989
+ function warnOnce(element, message) {
990
+ let messages = warned.get(element);
991
+ if (!messages) {
992
+ messages = /* @__PURE__ */ new Set();
993
+ warned.set(element, messages);
994
+ }
995
+ if (messages.has(message)) return;
996
+ messages.add(message);
997
+ console.warn(message);
998
+ }
999
+ function warnNoTargetOnce(element, suffix) {
1000
+ warnOnce(
1001
+ element,
1002
+ `[dawcore] <${element.tagName.toLowerCase()}> has no target. Check <daw-transport for="..."> references a valid element id.` + (suffix ?? "")
1003
+ );
1004
+ }
1005
+ function warnUnsupportedOnce(element, methods) {
1006
+ warnOnce(
1007
+ element,
1008
+ `[dawcore] <${element.tagName.toLowerCase()}> is disabled: its transport target does not implement ${methods.join(", ")}. See the transport compatibility table in the docs for which controls work with which targets.`
1009
+ );
1010
+ }
1011
+
1012
+ // src/elements/daw-transport-button.ts
986
1013
  var DawTransportButton = class extends LitElement7 {
1014
+ constructor() {
1015
+ super(...arguments);
1016
+ this._onCapabilityPointerEnter = () => {
1017
+ this.requestUpdate();
1018
+ };
1019
+ this._onCapabilityPointerDown = () => {
1020
+ const target = this.target;
1021
+ if (!target) {
1022
+ if (this._requiredMethods.length > 0) {
1023
+ warnNoTargetOnce(this);
1024
+ }
1025
+ return;
1026
+ }
1027
+ if (!this.targetSupported) {
1028
+ warnUnsupportedOnce(this, this._requiredMethods);
1029
+ }
1030
+ };
1031
+ }
987
1032
  get target() {
988
- const transport = this.closest("daw-transport");
989
- return transport?.target ?? null;
1033
+ return resolveTransportTarget(this);
1034
+ }
1035
+ get _requiredMethods() {
1036
+ return this.constructor.requiredTargetMethods;
1037
+ }
1038
+ /**
1039
+ * False when this control declares requirements its target doesn't meet.
1040
+ * An undetermined target (missing, or a not-yet-upgraded custom element)
1041
+ * gets the benefit of the doubt and stays enabled — click-time resolution
1042
+ * warns if it's still unusable.
1043
+ */
1044
+ get targetSupported() {
1045
+ const required = this._requiredMethods;
1046
+ if (required.length === 0) return true;
1047
+ const target = this.target;
1048
+ if (targetUndetermined(target)) return true;
1049
+ return targetSupports(target, required);
1050
+ }
1051
+ connectedCallback() {
1052
+ super.connectedCallback();
1053
+ this.addEventListener("pointerdown", this._onCapabilityPointerDown);
1054
+ this.addEventListener("pointerenter", this._onCapabilityPointerEnter);
1055
+ requestAnimationFrame(() => {
1056
+ if (!this.isConnected) return;
1057
+ this.requestUpdate();
1058
+ });
1059
+ }
1060
+ disconnectedCallback() {
1061
+ super.disconnectedCallback();
1062
+ this.removeEventListener("pointerdown", this._onCapabilityPointerDown);
1063
+ this.removeEventListener("pointerenter", this._onCapabilityPointerEnter);
990
1064
  }
991
1065
  };
1066
+ /** Methods the transport target must implement for this control to be
1067
+ * enabled. Empty = works with any target. */
1068
+ DawTransportButton.requiredTargetMethods = [];
992
1069
  DawTransportButton.styles = css4`
993
1070
  button {
994
1071
  cursor: pointer;
@@ -1386,7 +1463,7 @@ function createPeaksWorker() {
1386
1463
  }
1387
1464
  const pending = /* @__PURE__ */ new Map();
1388
1465
  let terminated = false;
1389
- let idCounter = 0;
1466
+ let idCounter2 = 0;
1390
1467
  worker.onmessage = (e) => {
1391
1468
  const msg = e.data;
1392
1469
  const entry = pending.get(msg.id);
@@ -1419,7 +1496,7 @@ function createPeaksWorker() {
1419
1496
  return {
1420
1497
  generate(params) {
1421
1498
  if (terminated) return Promise.reject(new Error("Worker terminated"));
1422
- const messageId = String(++idCounter);
1499
+ const messageId = String(++idCounter2);
1423
1500
  return new Promise((resolve, reject) => {
1424
1501
  pending.set(messageId, { resolve, reject });
1425
1502
  worker.postMessage(
@@ -3054,8 +3131,8 @@ var SpectrogramController = class {
3054
3131
  unregisterCanvas(canvasId) {
3055
3132
  this.orchestrator?.unregisterCanvas(canvasId);
3056
3133
  }
3057
- setViewport(state5) {
3058
- this.orchestrator?.setViewport(state5);
3134
+ setViewport(state7) {
3135
+ this.orchestrator?.setViewport(state7);
3059
3136
  }
3060
3137
  dispose() {
3061
3138
  if (this.orchestrator) {
@@ -3294,7 +3371,12 @@ var PointerHandler = class {
3294
3371
  if (h._engine) {
3295
3372
  h._engine.setSelection(0, 0);
3296
3373
  if (wasPlaying) {
3297
- h._engine.stop();
3374
+ h._inSeekTransition = true;
3375
+ try {
3376
+ h._engine.stop();
3377
+ } finally {
3378
+ h._inSeekTransition = false;
3379
+ }
3298
3380
  h._engine.play(time);
3299
3381
  h._startPlayhead();
3300
3382
  } else {
@@ -3635,6 +3717,57 @@ var ClipPointerHandler = class {
3635
3717
  }
3636
3718
  };
3637
3719
 
3720
+ // src/utils/time-display-format.ts
3721
+ var TIME_DISPLAY_FORMATS = [
3722
+ "hh:mm:ss.sss",
3723
+ "hh:mm:ss",
3724
+ "seconds"
3725
+ ];
3726
+ function isTimeDisplayFormat(value) {
3727
+ return TIME_DISPLAY_FORMATS.includes(value);
3728
+ }
3729
+ function clockFormat(totalSeconds, decimals) {
3730
+ const hours = Math.floor(totalSeconds / 3600);
3731
+ const minutes = Math.floor(totalSeconds / 60) % 60;
3732
+ const secsRem = totalSeconds % 60;
3733
+ let secs;
3734
+ if (decimals === 0) {
3735
+ secs = String(Math.min(Math.floor(secsRem + 1e-6), 59)).padStart(2, "0");
3736
+ } else {
3737
+ const factor = 10 ** decimals;
3738
+ const truncated = Math.min(Math.floor(secsRem * factor + 1e-6), 60 * factor - 1);
3739
+ secs = (truncated / factor).toFixed(decimals).padStart(decimals + 3, "0");
3740
+ }
3741
+ return String(hours).padStart(2, "0") + ":" + String(minutes).padStart(2, "0") + ":" + secs;
3742
+ }
3743
+ function formatDisplayTime(seconds, format) {
3744
+ const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;
3745
+ switch (format) {
3746
+ case "seconds":
3747
+ return safe.toFixed(3);
3748
+ case "hh:mm:ss":
3749
+ return clockFormat(safe, 0);
3750
+ case "hh:mm:ss.sss":
3751
+ default:
3752
+ return clockFormat(safe, 3);
3753
+ }
3754
+ }
3755
+ function parseDisplayTime(value, format) {
3756
+ if (!value) return 0;
3757
+ let seconds = 0;
3758
+ if (format === "seconds") {
3759
+ seconds = parseFloat(value) || 0;
3760
+ } else {
3761
+ const parts = value.split(":");
3762
+ if (parts.length !== 3) return 0;
3763
+ const h = parseInt(parts[0], 10) || 0;
3764
+ const m = parseInt(parts[1], 10) || 0;
3765
+ const s = parseFloat(parts[2]) || 0;
3766
+ seconds = h * 3600 + m * 60 + s;
3767
+ }
3768
+ return Math.max(0, seconds);
3769
+ }
3770
+
3638
3771
  // src/interactions/file-loader.ts
3639
3772
  import { createClip, createTrack } from "@waveform-playlist/core";
3640
3773
  async function loadFiles(host, files) {
@@ -3953,9 +4086,9 @@ function splitAtPlayhead(host) {
3953
4086
  function canSplitAtTime(host, time) {
3954
4087
  const { engine } = host;
3955
4088
  if (!engine) return false;
3956
- const state5 = engine.getState();
3957
- if (!state5.selectedTrackId) return false;
3958
- const track = state5.tracks.find((t) => t.id === state5.selectedTrackId);
4089
+ const state7 = engine.getState();
4090
+ if (!state7.selectedTrackId) return false;
4091
+ const track = state7.tracks.find((t) => t.id === state7.selectedTrackId);
3959
4092
  if (!track) return false;
3960
4093
  const atSample = Math.round(time * host.effectiveSampleRate);
3961
4094
  const clip = findClipAtSample(track.clips, atSample);
@@ -4096,125 +4229,1207 @@ function findAudioBufferForClip(host, clip, track) {
4096
4229
  return null;
4097
4230
  }
4098
4231
 
4099
- // src/interactions/peaks-loader.ts
4100
- import WaveformData2 from "waveform-data";
4101
- async function loadWaveformDataFromUrl(src) {
4102
- const response = await fetch(src);
4103
- if (!response.ok) {
4104
- throw new Error("[dawcore] Failed to fetch peaks data: " + response.statusText);
4232
+ // src/effects/effects-chain-controller.ts
4233
+ var idCounter = 0;
4234
+ var EffectsChainController = class {
4235
+ constructor(audioContext) {
4236
+ this._entries = [];
4237
+ this._disposed = false;
4238
+ this._input = audioContext.createGain();
4239
+ this._output = audioContext.createGain();
4240
+ this._input.connect(this._output);
4241
+ }
4242
+ /** Connect the upstream source (track mute node, master gain) into this. */
4243
+ get input() {
4244
+ return this._input;
4245
+ }
4246
+ /** Route this onward (to the master bus / destination). */
4247
+ get output() {
4248
+ return this._output;
4249
+ }
4250
+ get entries() {
4251
+ return this._entries.map((entry) => ({
4252
+ id: entry.id,
4253
+ kind: entry.kind,
4254
+ type: entry.type,
4255
+ params: { ...entry.params },
4256
+ bypassed: entry.bypassed,
4257
+ ...entry.url !== void 0 ? { url: entry.url } : {},
4258
+ ...entry.source !== void 0 ? { source: { ...entry.source } } : {},
4259
+ ...entry.label !== void 0 ? { label: entry.label } : {},
4260
+ ...entry.error !== void 0 ? { error: entry.error } : {}
4261
+ }));
4262
+ }
4263
+ /** Snapshot the chain in its persisted form. WAM entries are asked for
4264
+ * their live state; placeholders re-emit the state they were saved with. */
4265
+ serialize() {
4266
+ return Promise.all(
4267
+ this._entries.map(async (entry) => {
4268
+ if (entry.kind === "wam") {
4269
+ const sourceFields = entry.source?.faust !== void 0 ? {
4270
+ faustDsp: entry.source.faust,
4271
+ ...entry.label !== void 0 ? { faustName: entry.label } : {}
4272
+ } : { url: entry.url ?? "" };
4273
+ if (entry.placeholder) {
4274
+ return {
4275
+ kind: "wam",
4276
+ ...sourceFields,
4277
+ bypassed: entry.placeholder.bypassed,
4278
+ ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {}
4279
+ };
4280
+ }
4281
+ let state7;
4282
+ try {
4283
+ state7 = await entry.instance.getState?.();
4284
+ } catch (err) {
4285
+ console.warn(
4286
+ '[waveform-playlist] serialize: plugin "' + (entry.url ?? entry.label ?? entry.type) + '" getState failed: ' + String(err)
4287
+ );
4288
+ }
4289
+ return {
4290
+ kind: "wam",
4291
+ ...sourceFields,
4292
+ bypassed: entry.bypassed,
4293
+ ...state7 !== void 0 ? { state: state7 } : {}
4294
+ };
4295
+ }
4296
+ return {
4297
+ kind: "native",
4298
+ type: entry.type,
4299
+ params: { ...entry.params },
4300
+ bypassed: entry.bypassed
4301
+ };
4302
+ })
4303
+ );
4105
4304
  }
4106
- const { pathname } = new URL(src, globalThis.location?.href ?? "http://localhost");
4107
- const isBinary = pathname.toLowerCase().endsWith(".dat");
4108
- if (isBinary) {
4109
- const arrayBuffer = await response.arrayBuffer();
4110
- return WaveformData2.create(arrayBuffer);
4111
- } else {
4112
- const json = await response.json();
4113
- return WaveformData2.create(json);
4305
+ get disposed() {
4306
+ return this._disposed;
4114
4307
  }
4115
- }
4116
-
4117
- // src/controllers/scroll-sync-controller.ts
4118
- var LINE_HEIGHT_PX = 16;
4119
- var ScrollSyncController = class {
4120
- constructor(host) {
4121
- this._scrollContainer = null;
4122
- this._wheelTargets = /* @__PURE__ */ new Set();
4123
- this._warnedX = false;
4124
- this._warnedY = false;
4125
- /** Selector (in host shadow DOM) for the scroll container. */
4126
- this.scrollSelector = "";
4127
- /** Selector for the element receiving translate3d(-scrollLeft, 0, 0). */
4128
- this.xTargetSelector = "";
4129
- /** Selector for the element receiving translate3d(0, -scrollTop, 0). */
4130
- this.yTargetSelector = "";
4131
- /**
4132
- * Selector (or comma-separated selectors) for elements whose wheel events
4133
- * forward to the scroll container. All matching elements receive listeners.
4134
- */
4135
- this.wheelForwardSelector = "";
4136
- this._onScroll = () => {
4137
- this._apply();
4138
- };
4139
- this._onWheel = (e) => {
4140
- const sc = this._scrollContainer;
4141
- if (!sc) return;
4142
- const scale = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? LINE_HEIGHT_PX : e.deltaMode === WheelEvent.DOM_DELTA_PAGE ? sc.clientHeight : 1;
4143
- const scaleX = e.deltaMode === WheelEvent.DOM_DELTA_PAGE ? sc.clientWidth : scale;
4144
- const beforeLeft = sc.scrollLeft;
4145
- const beforeTop = sc.scrollTop;
4146
- sc.scrollLeft += e.deltaX * scaleX;
4147
- sc.scrollTop += e.deltaY * scale;
4148
- if (sc.scrollLeft !== beforeLeft || sc.scrollTop !== beforeTop) {
4149
- e.preventDefault();
4150
- }
4151
- };
4152
- this._host = host;
4153
- host.addController(this);
4308
+ /** Internal (manager-facing): the live entry — including its instance —
4309
+ * for GUI wiring. Returns undefined (no warning) when the id is unknown. */
4310
+ getEntry(effectId) {
4311
+ return this._entries.find((e) => e.id === effectId);
4154
4312
  }
4155
- hostConnected() {
4156
- requestAnimationFrame(() => {
4157
- if (!this._host.isConnected) return;
4158
- this._attach();
4159
- if (!this._scrollContainer && this.scrollSelector) {
4160
- console.warn(
4161
- '[dawcore] ScrollSyncController: scroll container not found for "' + this.scrollSelector + '"'
4162
- );
4313
+ add(item, index) {
4314
+ if (this._disposed) {
4315
+ throw new Error(
4316
+ "[waveform-playlist] EffectsChainController.add: chain is disposed \u2014 entries cannot be added"
4317
+ );
4318
+ }
4319
+ const id = "effect-" + ++idCounter;
4320
+ const entry = { ...item, params: { ...item.params }, id, bypassed: false };
4321
+ const at = index === void 0 ? this._entries.length : Math.max(0, Math.min(index, this._entries.length));
4322
+ this._entries = [...this._entries.slice(0, at), entry, ...this._entries.slice(at)];
4323
+ this._rebuild();
4324
+ return id;
4325
+ }
4326
+ remove(effectId) {
4327
+ const entry = this._find("remove", effectId);
4328
+ if (!entry) return;
4329
+ this._entries = this._entries.filter((e) => e.id !== effectId);
4330
+ entry.instance.output.disconnect();
4331
+ entry.instance.dispose?.();
4332
+ this._rebuild();
4333
+ }
4334
+ move(effectId, newIndex) {
4335
+ const entry = this._find("move", effectId);
4336
+ if (!entry) return;
4337
+ const without = this._entries.filter((e) => e.id !== effectId);
4338
+ const at = Math.max(0, Math.min(newIndex, without.length));
4339
+ this._entries = [...without.slice(0, at), entry, ...without.slice(at)];
4340
+ this._rebuild();
4341
+ }
4342
+ setParams(effectId, params) {
4343
+ const entry = this._find("setParams", effectId);
4344
+ if (!entry) return;
4345
+ entry.params = { ...entry.params, ...params };
4346
+ if (entry.bypassed && entry.wetParam && entry.wetParam in params) {
4347
+ const { [entry.wetParam]: _stored, ...rest } = params;
4348
+ if (Object.keys(rest).length > 0) {
4349
+ entry.instance.applyParams(rest);
4163
4350
  }
4164
- });
4165
- }
4166
- hostDisconnected() {
4167
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
4168
- this._scrollContainer = null;
4169
- for (const target of this._wheelTargets) {
4170
- target.removeEventListener("wheel", this._onWheel);
4351
+ return;
4171
4352
  }
4172
- this._wheelTargets.clear();
4173
- }
4174
- /**
4175
- * Re-attach and re-apply transforms from the current scroll position.
4176
- * Called from the host's updated() so elements created by a re-render
4177
- * (e.g. the ruler appearing when the first track loads) pick up the
4178
- * current offset and listeners.
4179
- */
4180
- sync() {
4181
- this._attach();
4353
+ entry.instance.applyParams(params);
4182
4354
  }
4183
- _query(selector) {
4184
- return selector ? this._host.shadowRoot?.querySelector(selector) : null;
4355
+ setBypassed(effectId, bypassed) {
4356
+ const entry = this._find("setBypassed", effectId);
4357
+ if (!entry || entry.bypassed === bypassed) return;
4358
+ entry.bypassed = bypassed;
4359
+ if (entry.wetParam) {
4360
+ const wet = bypassed ? 0 : entry.params[entry.wetParam] ?? 0;
4361
+ entry.instance.applyParams({ [entry.wetParam]: wet });
4362
+ return;
4363
+ }
4364
+ this._rebuild();
4185
4365
  }
4186
- _queryAll(selector) {
4187
- if (!selector) return [];
4188
- return Array.from(this._host.shadowRoot?.querySelectorAll(selector) ?? []);
4366
+ dispose() {
4367
+ if (this._disposed) return;
4368
+ this._disposed = true;
4369
+ this._severOwnEdges();
4370
+ for (const entry of this._entries) {
4371
+ entry.instance.dispose?.();
4372
+ }
4373
+ this._entries = [];
4374
+ try {
4375
+ this._output.disconnect();
4376
+ } catch {
4377
+ }
4189
4378
  }
4190
- _attach() {
4191
- const container = this._query(this.scrollSelector);
4192
- if (!container) {
4193
- if (this._scrollContainer && !this._scrollContainer.isConnected) {
4194
- console.warn(
4195
- '[dawcore] ScrollSyncController: scroll container "' + this.scrollSelector + '" was removed from the DOM \u2014 detaching listeners until it reappears.'
4196
- );
4197
- this._scrollContainer.removeEventListener("scroll", this._onScroll);
4198
- this._scrollContainer = null;
4199
- for (const t of this._wheelTargets) t.removeEventListener("wheel", this._onWheel);
4200
- this._wheelTargets.clear();
4201
- }
4202
- return;
4379
+ _find(op, effectId) {
4380
+ const entry = this._entries.find((e) => e.id === effectId);
4381
+ if (!entry) {
4382
+ console.warn(
4383
+ "[waveform-playlist] EffectsChainController." + op + ': unknown effectId "' + effectId + '"'
4384
+ );
4203
4385
  }
4204
- if (container !== this._scrollContainer) {
4205
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
4206
- this._scrollContainer = container;
4207
- container.addEventListener("scroll", this._onScroll, { passive: true });
4386
+ return entry;
4387
+ }
4388
+ /** Sever only this chain's outgoing edges — never the consumer's. */
4389
+ _severOwnEdges() {
4390
+ this._input.disconnect();
4391
+ for (const entry of this._entries) {
4392
+ entry.instance.output.disconnect();
4208
4393
  }
4209
- const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));
4210
- for (const old of this._wheelTargets) {
4211
- if (!nextTargets.has(old)) {
4212
- old.removeEventListener("wheel", this._onWheel);
4213
- this._wheelTargets.delete(old);
4394
+ }
4395
+ _rebuild() {
4396
+ this._severOwnEdges();
4397
+ let previous = this._input;
4398
+ for (const entry of this._entries) {
4399
+ if (entry.bypassed && !entry.wetParam) {
4400
+ continue;
4214
4401
  }
4402
+ previous.connect(entry.instance.input);
4403
+ previous = entry.instance.output;
4215
4404
  }
4216
- for (const next of nextTargets) {
4217
- if (!this._wheelTargets.has(next)) {
4405
+ previous.connect(this._output);
4406
+ }
4407
+ };
4408
+
4409
+ // src/effects/optional-modules.ts
4410
+ var PREFIX = "[waveform-playlist] ";
4411
+ async function loadOptionalModule(importer, packageName, feature) {
4412
+ try {
4413
+ return await importer();
4414
+ } catch (originalErr) {
4415
+ console.warn(PREFIX + packageName + " dynamic import failed: " + String(originalErr));
4416
+ throw new Error(
4417
+ PREFIX + packageName + " is required for " + feature + ". Install with: npm install " + packageName + " (import failed: " + String(originalErr) + ")"
4418
+ );
4419
+ }
4420
+ }
4421
+ function loadWamModule(feature) {
4422
+ return loadOptionalModule(() => import("@dawcore/wam"), "@dawcore/wam", feature);
4423
+ }
4424
+ function loadFaustModule(feature) {
4425
+ return loadOptionalModule(() => import("@dawcore/faust"), "@dawcore/faust", feature);
4426
+ }
4427
+
4428
+ // src/effects/effect-registry.ts
4429
+ var MAX_DELAY_SECONDS = 10;
4430
+ var registry = /* @__PURE__ */ new Map();
4431
+ function registerEffect(type, definition) {
4432
+ if (registry.has(type)) {
4433
+ console.warn(
4434
+ '[waveform-playlist] registerEffect: overwriting existing effect type "' + type + '"'
4435
+ );
4436
+ }
4437
+ registry.set(type, definition);
4438
+ }
4439
+ function getEffectDefinitions() {
4440
+ return new Map(registry);
4441
+ }
4442
+ function createEffectInstance(type, audioContext, params = {}) {
4443
+ const definition = registry.get(type);
4444
+ if (!definition) {
4445
+ throw new Error(
4446
+ '[waveform-playlist] createEffectInstance: unknown effect type "' + type + '". Available types: ' + [...registry.keys()].join(", ")
4447
+ );
4448
+ }
4449
+ const merged = { ...definition.defaults, ...params };
4450
+ const instance = definition.create(audioContext, merged);
4451
+ instance.applyParams(merged);
4452
+ return { instance, params: merged, wetParam: definition.wetParam };
4453
+ }
4454
+ function singleNode(node, applyParams) {
4455
+ return { input: node, output: node, applyParams };
4456
+ }
4457
+ function registerBuiltIns() {
4458
+ registry.set("native-gain", {
4459
+ label: "Gain",
4460
+ category: "dynamics",
4461
+ defaults: { gain: 1 },
4462
+ params: { gain: { min: 0, max: 2, step: 0.01 } },
4463
+ create: (ctx) => {
4464
+ const node = ctx.createGain();
4465
+ return singleNode(node, (p) => {
4466
+ if (p.gain !== void 0) node.gain.value = p.gain;
4467
+ });
4468
+ }
4469
+ });
4470
+ registry.set("native-filter", {
4471
+ label: "Lowpass Filter",
4472
+ category: "filter",
4473
+ defaults: { frequency: 1e3, q: 1 },
4474
+ params: {
4475
+ frequency: { min: 20, max: 2e4, step: 1, unit: "Hz" },
4476
+ q: { min: 0.1, max: 20, step: 0.1 }
4477
+ },
4478
+ create: (ctx) => {
4479
+ const node = ctx.createBiquadFilter();
4480
+ node.type = "lowpass";
4481
+ return singleNode(node, (p) => {
4482
+ if (p.frequency !== void 0) node.frequency.value = p.frequency;
4483
+ if (p.q !== void 0) node.Q.value = p.q;
4484
+ });
4485
+ }
4486
+ });
4487
+ registry.set("native-compressor", {
4488
+ label: "Compressor",
4489
+ category: "dynamics",
4490
+ defaults: { threshold: -24, knee: 30, ratio: 12, attack: 3e-3, release: 0.25 },
4491
+ params: {
4492
+ threshold: { min: -60, max: 0, step: 1, unit: "dB" },
4493
+ knee: { min: 0, max: 40, step: 1, unit: "dB" },
4494
+ ratio: { min: 1, max: 20, step: 0.5 },
4495
+ attack: { min: 0, max: 1, step: 1e-3, unit: "s" },
4496
+ release: { min: 0, max: 1, step: 0.01, unit: "s" }
4497
+ },
4498
+ create: (ctx) => {
4499
+ const node = ctx.createDynamicsCompressor();
4500
+ return singleNode(node, (p) => {
4501
+ if (p.threshold !== void 0) node.threshold.value = p.threshold;
4502
+ if (p.knee !== void 0) node.knee.value = p.knee;
4503
+ if (p.ratio !== void 0) node.ratio.value = p.ratio;
4504
+ if (p.attack !== void 0) node.attack.value = p.attack;
4505
+ if (p.release !== void 0) node.release.value = p.release;
4506
+ });
4507
+ }
4508
+ });
4509
+ registry.set("native-stereo-panner", {
4510
+ label: "Stereo Panner",
4511
+ category: "spatial",
4512
+ defaults: { pan: 0 },
4513
+ params: { pan: { min: -1, max: 1, step: 0.01 } },
4514
+ create: (ctx) => {
4515
+ const node = ctx.createStereoPanner();
4516
+ return singleNode(node, (p) => {
4517
+ if (p.pan !== void 0) node.pan.value = p.pan;
4518
+ });
4519
+ }
4520
+ });
4521
+ registry.set("native-delay", {
4522
+ label: "Delay",
4523
+ category: "delay",
4524
+ defaults: { delayTime: 0.25, feedback: 0.4, wet: 0.35 },
4525
+ params: {
4526
+ delayTime: { min: 0, max: MAX_DELAY_SECONDS, step: 0.01, unit: "s" },
4527
+ feedback: { min: 0, max: 0.95, step: 0.01 },
4528
+ wet: { min: 0, max: 1, step: 0.01 }
4529
+ },
4530
+ wetParam: "wet",
4531
+ create: (ctx) => {
4532
+ const input = ctx.createGain();
4533
+ const output = ctx.createGain();
4534
+ const delay = ctx.createDelay(MAX_DELAY_SECONDS);
4535
+ const feedback = ctx.createGain();
4536
+ const wet = ctx.createGain();
4537
+ const dry = ctx.createGain();
4538
+ input.connect(dry);
4539
+ dry.connect(output);
4540
+ input.connect(delay);
4541
+ delay.connect(feedback);
4542
+ feedback.connect(delay);
4543
+ delay.connect(wet);
4544
+ wet.connect(output);
4545
+ return {
4546
+ input,
4547
+ output,
4548
+ applyParams: (p) => {
4549
+ if (p.delayTime !== void 0) delay.delayTime.value = p.delayTime;
4550
+ if (p.feedback !== void 0) feedback.gain.value = p.feedback;
4551
+ if (p.wet !== void 0) {
4552
+ wet.gain.value = p.wet;
4553
+ dry.gain.value = 1 - p.wet;
4554
+ }
4555
+ }
4556
+ };
4557
+ }
4558
+ });
4559
+ }
4560
+ registerBuiltIns();
4561
+
4562
+ // src/effects/effects-manager.ts
4563
+ var PREFIX2 = "[waveform-playlist] ";
4564
+ function makeGuiRecord(element, destroyImpl) {
4565
+ let destroyed = false;
4566
+ return {
4567
+ element,
4568
+ destroy: () => {
4569
+ if (destroyed) return;
4570
+ destroyed = true;
4571
+ destroyImpl();
4572
+ }
4573
+ };
4574
+ }
4575
+ var EffectsManager = class {
4576
+ constructor(getAdapter, masterEventTarget) {
4577
+ this._masterChain = null;
4578
+ this._trackChains = /* @__PURE__ */ new Map();
4579
+ /** Per-chain restore ownership — a newer setEffectsState supersedes a stale in-flight one. */
4580
+ this._restoreTokens = /* @__PURE__ */ new WeakMap();
4581
+ /** Cached GUI elements by effectId — close hides, only removal destroys. */
4582
+ this._guis = /* @__PURE__ */ new Map();
4583
+ /** In-flight GUI creation by effectId — concurrent opens share one build. */
4584
+ this._guiPending = /* @__PURE__ */ new Map();
4585
+ /** Live WAM plugin nodes across all chains, fed to the wam-transport bridge. */
4586
+ this._wamNodes = /* @__PURE__ */ new Set();
4587
+ this._transportBridge = null;
4588
+ this._getAdapter = getAdapter;
4589
+ this._masterTarget = masterEventTarget;
4590
+ }
4591
+ // --- Master chain ---
4592
+ addMasterEffect(type, params) {
4593
+ const chain = this._ensureMasterChain();
4594
+ return this._addToChain(chain, this._masterTarget, type, params);
4595
+ }
4596
+ masterEffects() {
4597
+ return this._masterChain?.entries ?? [];
4598
+ }
4599
+ masterOp(op, effectId, arg) {
4600
+ this._runOp(this._masterChain, this._masterTarget, op, effectId, arg);
4601
+ }
4602
+ addMasterWamPlugin(url, initialState) {
4603
+ const chain = this._ensureMasterChain();
4604
+ return this._addWamToChain(chain, this._masterTarget, url, initialState);
4605
+ }
4606
+ addMasterFaustEffect(dspCode, options) {
4607
+ const chain = this._ensureMasterChain();
4608
+ return this._addFaustToChain(chain, this._masterTarget, dspCode, { name: options?.name });
4609
+ }
4610
+ getMasterEffectsState() {
4611
+ return this._masterChain?.serialize() ?? Promise.resolve([]);
4612
+ }
4613
+ async setMasterEffectsState(entries) {
4614
+ validateSerializedEntries(entries);
4615
+ await this._restoreChain(this._ensureMasterChain(), this._masterTarget, entries);
4616
+ }
4617
+ // --- Track chains ---
4618
+ addTrackEffect(trackId, target, type, params) {
4619
+ const chain = this._ensureTrackChain(trackId);
4620
+ return this._addToChain(chain, target, type, params);
4621
+ }
4622
+ addTrackWamPlugin(trackId, target, url, initialState) {
4623
+ const chain = this._ensureTrackChain(trackId);
4624
+ return this._addWamToChain(chain, target, url, initialState);
4625
+ }
4626
+ addTrackFaustEffect(trackId, target, dspCode, options) {
4627
+ const chain = this._ensureTrackChain(trackId);
4628
+ return this._addFaustToChain(chain, target, dspCode, { name: options?.name });
4629
+ }
4630
+ trackEffects(trackId) {
4631
+ return this._trackChains.get(trackId)?.entries ?? [];
4632
+ }
4633
+ getTrackEffectsState(trackId) {
4634
+ return this._trackChains.get(trackId)?.serialize() ?? Promise.resolve([]);
4635
+ }
4636
+ async setTrackEffectsState(trackId, target, entries) {
4637
+ validateSerializedEntries(entries);
4638
+ await this._restoreChain(this._ensureTrackChain(trackId), target, entries);
4639
+ }
4640
+ trackOp(trackId, target, op, effectId, arg) {
4641
+ this._runOp(this._trackChains.get(trackId) ?? null, target, op, effectId, arg);
4642
+ }
4643
+ // --- Effect GUIs ---
4644
+ /** Open (lazily creating) the GUI for a master-chain effect. */
4645
+ openMasterEffectGui(effectId, container) {
4646
+ return this._openGui(this._masterChain, this._masterTarget, effectId, container);
4647
+ }
4648
+ /** Open (lazily creating) the GUI for a track-chain effect. */
4649
+ openTrackEffectGui(trackId, target, effectId, container) {
4650
+ return this._openGui(this._trackChains.get(trackId) ?? null, target, effectId, container);
4651
+ }
4652
+ /** Hide an open GUI. The element stays cached so reopen is instant —
4653
+ * audio processing is never interrupted. */
4654
+ closeEffectGui(effectId) {
4655
+ const record = this._guis.get(effectId);
4656
+ if (!record) {
4657
+ console.warn(PREFIX2 + 'closeEffectGui: no open GUI for effectId "' + effectId + '"');
4658
+ return;
4659
+ }
4660
+ record.element.remove();
4661
+ }
4662
+ // --- Lifecycle ---
4663
+ /** Transport setTracks rebuilds TrackNodes, severing chain hookups — re-wire. */
4664
+ rewireTrackChains() {
4665
+ const transport = this._getAdapter()?.transport;
4666
+ if (!transport) return;
4667
+ for (const [trackId, chain] of this._trackChains) {
4668
+ transport.connectTrackOutput(trackId, chain.input);
4669
+ chain.output.connect(transport.masterOutputNode);
4670
+ }
4671
+ }
4672
+ disposeTrackChain(trackId) {
4673
+ const chain = this._trackChains.get(trackId);
4674
+ if (!chain) return;
4675
+ this._trackChains.delete(trackId);
4676
+ for (const entry of chain.entries) {
4677
+ this._destroyGui(entry.id);
4678
+ }
4679
+ try {
4680
+ this._getAdapter()?.transport?.disconnectTrackOutput(trackId);
4681
+ } catch (err) {
4682
+ console.warn(PREFIX2 + "EffectsManager: error disconnecting track output: " + String(err));
4683
+ }
4684
+ chain.dispose();
4685
+ }
4686
+ disposeAll() {
4687
+ this._transportBridge?.dispose();
4688
+ this._transportBridge = null;
4689
+ this._wamNodes.clear();
4690
+ for (const trackId of [...this._trackChains.keys()]) {
4691
+ this.disposeTrackChain(trackId);
4692
+ }
4693
+ if (this._masterChain) {
4694
+ for (const entry of this._masterChain.entries) {
4695
+ this._destroyGui(entry.id);
4696
+ }
4697
+ try {
4698
+ this._getAdapter()?.transport?.disconnectMasterOutput();
4699
+ } catch (err) {
4700
+ console.warn(PREFIX2 + "EffectsManager: error disconnecting master output: " + String(err));
4701
+ }
4702
+ this._masterChain.dispose();
4703
+ this._masterChain = null;
4704
+ }
4705
+ }
4706
+ // --- Private ---
4707
+ _requireWiring() {
4708
+ const adapter = this._getAdapter();
4709
+ if (!adapter) {
4710
+ throw new Error(
4711
+ PREFIX2 + "effects require an adapter \u2014 set editor.adapter before adding effects."
4712
+ );
4713
+ }
4714
+ const { audioContext, transport } = adapter;
4715
+ if (!audioContext || !transport || typeof transport.connectTrackOutput !== "function") {
4716
+ throw new Error(
4717
+ PREFIX2 + "the current adapter does not expose effects hooks (transport.connectTrackOutput / connectMasterOutput)."
4718
+ );
4719
+ }
4720
+ return { audioContext, transport };
4721
+ }
4722
+ /** Dynamic-import the optional @dawcore/wam peer with an actionable error. */
4723
+ _loadWamModule(feature) {
4724
+ return loadWamModule(feature);
4725
+ }
4726
+ /** Dynamic-import the optional @dawcore/faust peer with an actionable error. */
4727
+ _loadFaustModule(feature) {
4728
+ return loadFaustModule(feature);
4729
+ }
4730
+ async _openGui(chain, target, effectId, container) {
4731
+ if (!container || typeof container.appendChild !== "function") {
4732
+ throw new Error(PREFIX2 + "openEffectGui: container must be a DOM element");
4733
+ }
4734
+ const entry = chain?.getEntry(effectId);
4735
+ if (!chain || !entry) {
4736
+ throw new Error(PREFIX2 + 'openEffectGui: unknown effectId "' + effectId + '"');
4737
+ }
4738
+ if (entry.error !== void 0) {
4739
+ throw new Error(
4740
+ PREFIX2 + 'openEffectGui: effect "' + effectId + '" is a failed-plugin placeholder (' + entry.error + ") \u2014 no GUI is available. Remove it or retry the restore."
4741
+ );
4742
+ }
4743
+ const cached = this._guis.get(effectId);
4744
+ if (cached) {
4745
+ container.appendChild(cached.element);
4746
+ return cached.element;
4747
+ }
4748
+ let pending = this._guiPending.get(effectId);
4749
+ if (!pending) {
4750
+ pending = this._createGuiRecord(chain, target, entry, effectId).finally(() => {
4751
+ this._guiPending.delete(effectId);
4752
+ });
4753
+ this._guiPending.set(effectId, pending);
4754
+ }
4755
+ const record = await pending;
4756
+ if (chain.disposed || !chain.getEntry(effectId)) {
4757
+ this._guis.delete(effectId);
4758
+ record.element.remove();
4759
+ try {
4760
+ record.destroy();
4761
+ } catch (err) {
4762
+ console.warn(
4763
+ PREFIX2 + 'openEffectGui: destroying a late GUI for "' + effectId + '" failed: ' + String(err)
4764
+ );
4765
+ }
4766
+ throw new Error(
4767
+ PREFIX2 + 'openEffectGui: effect "' + effectId + '" was removed while its GUI was loading; the GUI was discarded.'
4768
+ );
4769
+ }
4770
+ this._guis.set(effectId, record);
4771
+ container.appendChild(record.element);
4772
+ return record.element;
4773
+ }
4774
+ /** Build a GUI record: the plugin's own GUI when available, otherwise the
4775
+ * generic parameter panel from @dawcore/wam. */
4776
+ async _createGuiRecord(chain, target, entry, effectId) {
4777
+ const { instance } = entry;
4778
+ if (typeof instance.createGui === "function") {
4779
+ try {
4780
+ const element2 = await instance.createGui();
4781
+ return makeGuiRecord(element2, () => instance.destroyGui?.(element2));
4782
+ } catch (err) {
4783
+ console.warn(
4784
+ PREFIX2 + 'openEffectGui: plugin createGui failed for "' + effectId + '" \u2014 falling back to the generic parameter panel: ' + String(err)
4785
+ );
4786
+ }
4787
+ }
4788
+ const element = await this._createFallbackPanel(chain, target, entry, effectId);
4789
+ return makeGuiRecord(element, () => {
4790
+ });
4791
+ }
4792
+ /** The generic parameter panel — one code path for "no custom GUI":
4793
+ * native entries render from the registry's params metadata, WAM entries
4794
+ * from getParameterInfo(). Edits route through the regular setParams op so
4795
+ * they hit the audio (applyParams → setParameterValues for WAM) AND
4796
+ * dispatch daw-effect-change like any other parameter edit. */
4797
+ async _createFallbackPanel(chain, target, entry, effectId) {
4798
+ const wamModule = await this._loadWamModule("openEffectGui() parameter panels");
4799
+ const onChange = (paramId, value) => {
4800
+ this._runOp(chain, target, "setParams", effectId, { [paramId]: value });
4801
+ };
4802
+ if (entry.kind === "native") {
4803
+ const definition = getEffectDefinitions().get(entry.type);
4804
+ if (!definition) {
4805
+ throw new Error(
4806
+ PREFIX2 + 'openEffectGui: no registry definition for effect type "' + entry.type + '"'
4807
+ );
4808
+ }
4809
+ const params = Object.entries(definition.params).map(([id, def]) => ({
4810
+ id,
4811
+ min: def.min,
4812
+ max: def.max,
4813
+ ...def.step !== void 0 ? { step: def.step } : {},
4814
+ ...def.unit !== void 0 ? { unit: def.unit } : {},
4815
+ value: entry.params[id] ?? definition.defaults[id]
4816
+ }));
4817
+ return wamModule.createParameterPanel(params, onChange);
4818
+ }
4819
+ if (typeof entry.instance.getParameterInfo !== "function") {
4820
+ throw new Error(
4821
+ PREFIX2 + 'openEffectGui: effect "' + effectId + '" has no GUI and exposes no parameter info \u2014 nothing to render.'
4822
+ );
4823
+ }
4824
+ return wamModule.createWamParameterPanel(
4825
+ { getParameterInfo: () => entry.instance.getParameterInfo() },
4826
+ { onParamChange: onChange }
4827
+ );
4828
+ }
4829
+ /** Detach + destroy a cached GUI. Called only from removal paths — close
4830
+ * never destroys. Safe when no GUI was ever opened. */
4831
+ _destroyGui(effectId) {
4832
+ const record = this._guis.get(effectId);
4833
+ if (!record) return;
4834
+ this._guis.delete(effectId);
4835
+ record.element.remove();
4836
+ try {
4837
+ record.destroy();
4838
+ } catch (err) {
4839
+ console.warn(PREFIX2 + 'destroyGui failed for effect "' + effectId + '": ' + String(err));
4840
+ }
4841
+ }
4842
+ _ensureMasterChain() {
4843
+ if (this._masterChain) return this._masterChain;
4844
+ const { audioContext, transport } = this._requireWiring();
4845
+ const chain = new EffectsChainController(audioContext);
4846
+ transport.connectMasterOutput(chain.input);
4847
+ chain.output.connect(audioContext.destination);
4848
+ this._masterChain = chain;
4849
+ return chain;
4850
+ }
4851
+ _ensureTrackChain(trackId) {
4852
+ const existing = this._trackChains.get(trackId);
4853
+ if (existing) return existing;
4854
+ const { audioContext, transport } = this._requireWiring();
4855
+ const chain = new EffectsChainController(audioContext);
4856
+ transport.connectTrackOutput(trackId, chain.input);
4857
+ chain.output.connect(transport.masterOutputNode);
4858
+ this._trackChains.set(trackId, chain);
4859
+ return chain;
4860
+ }
4861
+ _addToChain(chain, target, type, params) {
4862
+ const audioContext = this._requireWiring().audioContext;
4863
+ const created = createEffectInstance(type, audioContext, params);
4864
+ const effectId = chain.add({
4865
+ kind: "native",
4866
+ type,
4867
+ instance: created.instance,
4868
+ params: created.params,
4869
+ wetParam: created.wetParam
4870
+ });
4871
+ const index = chain.entries.findIndex((e) => e.id === effectId);
4872
+ this._dispatch(target, "daw-effect-add", {
4873
+ effectId,
4874
+ kind: "native",
4875
+ type,
4876
+ params: { ...created.params },
4877
+ index
4878
+ });
4879
+ return effectId;
4880
+ }
4881
+ /**
4882
+ * Load a WAM plugin (via the optional @dawcore/wam peer dep) and add it to
4883
+ * a chain as a kind:'wam' entry. WAM entries participate in every chain
4884
+ * operation with no special-casing: remove destroys the plugin (via the
4885
+ * entry's dispose), bypass uses disconnection semantics (no wet param),
4886
+ * and setParams maps onto the plugin's setParameterValues.
4887
+ */
4888
+ async _addWamToChain(chain, target, url, initialState) {
4889
+ const { audioContext } = this._requireWiring();
4890
+ const wamModule = await this._loadWamModule("addWamPlugin()");
4891
+ const { hostGroupId } = await wamModule.ensureWamHost(audioContext);
4892
+ const plugin = await wamModule.createWamInstance(url, audioContext, hostGroupId, {
4893
+ initialState
4894
+ });
4895
+ return this._insertWamPlugin(chain, target, wamModule, plugin, { url });
4896
+ }
4897
+ /**
4898
+ * Compile Faust DSP source in the browser (via the optional @dawcore/faust
4899
+ * peer) and add the resulting WAM to a chain. Compilation happens BEFORE
4900
+ * any chain work, so a Faust error (with its line/column diagnostics intact)
4901
+ * leaves the chain untouched. The entry lands as kind:'wam' with a
4902
+ * `source: { faust }` marker so persistence recompiles instead of fetching.
4903
+ */
4904
+ async _addFaustToChain(chain, target, dspCode, opts) {
4905
+ if (typeof dspCode !== "string" || dspCode.trim().length === 0) {
4906
+ throw new Error(PREFIX2 + "addFaustEffect: dspCode must be a non-empty string");
4907
+ }
4908
+ this._requireWiring();
4909
+ const faustModule = await this._loadFaustModule("addFaustEffect()");
4910
+ const compiled = await faustModule.compileFaustToWam(dspCode, { name: opts.name });
4911
+ const { audioContext } = this._requireWiring();
4912
+ const wamModule = await this._loadWamModule("addFaustEffect()");
4913
+ const { hostGroupId } = await wamModule.ensureWamHost(audioContext);
4914
+ const plugin = await wamModule.createWamInstanceFromFactory(
4915
+ compiled.factory,
4916
+ audioContext,
4917
+ hostGroupId,
4918
+ { initialState: opts.initialState, label: compiled.name }
4919
+ );
4920
+ return this._insertWamPlugin(chain, target, wamModule, plugin, {
4921
+ source: { faust: compiled.dspCode }
4922
+ });
4923
+ }
4924
+ /**
4925
+ * Wire a live WAM plugin instance into a chain as a kind:'wam' entry —
4926
+ * shared by the url path (addWamPlugin) and the Faust path (addFaustEffect).
4927
+ * WAM entries participate in every chain operation with no special-casing:
4928
+ * remove destroys the plugin (via the entry's dispose), bypass uses
4929
+ * disconnection semantics (no wet param), and setParams maps onto the
4930
+ * plugin's setParameterValues.
4931
+ */
4932
+ _insertWamPlugin(chain, target, wamModule, plugin, meta) {
4933
+ const node = plugin.audioNode;
4934
+ const label = plugin.descriptor.name;
4935
+ if (chain.disposed) {
4936
+ plugin.destroy();
4937
+ throw new Error(
4938
+ PREFIX2 + 'addWamPlugin: the effects chain was disposed while "' + (meta.url ?? label) + '" was loading; the plugin was discarded.'
4939
+ );
4940
+ }
4941
+ let effectId;
4942
+ try {
4943
+ effectId = chain.add({
4944
+ kind: "wam",
4945
+ type: "wam",
4946
+ ...meta.url !== void 0 ? { url: meta.url } : {},
4947
+ ...meta.source !== void 0 ? { source: meta.source } : {},
4948
+ label,
4949
+ instance: {
4950
+ input: node,
4951
+ output: node,
4952
+ applyParams: (params) => {
4953
+ node.setParameterValues?.(toWamParameterMap(params))?.catch((err) => {
4954
+ console.warn(PREFIX2 + "WAM setParameterValues failed: " + String(err));
4955
+ });
4956
+ },
4957
+ dispose: () => {
4958
+ this._wamNodes.delete(node);
4959
+ plugin.destroy();
4960
+ },
4961
+ getState: () => plugin.getState(),
4962
+ getParameterInfo: () => plugin.getParameterInfo(),
4963
+ ...plugin.createGui ? { createGui: () => plugin.createGui() } : {},
4964
+ ...plugin.destroyGui ? { destroyGui: (gui) => plugin.destroyGui(gui) } : {}
4965
+ },
4966
+ params: {}
4967
+ });
4968
+ } catch (err) {
4969
+ try {
4970
+ plugin.destroy();
4971
+ } catch (destroyErr) {
4972
+ console.warn(
4973
+ PREFIX2 + "addWamPlugin: cleanup after failed insertion also failed: " + String(destroyErr)
4974
+ );
4975
+ }
4976
+ throw err;
4977
+ }
4978
+ this._wamNodes.add(node);
4979
+ this._ensureTransportBridge(wamModule)?.notifyNodeAdded(node);
4980
+ const index = chain.entries.findIndex((e) => e.id === effectId);
4981
+ this._dispatch(target, "daw-effect-add", {
4982
+ effectId,
4983
+ kind: "wam",
4984
+ type: "wam",
4985
+ ...meta.url !== void 0 ? { url: meta.url } : {},
4986
+ ...meta.source !== void 0 ? { source: meta.source } : {},
4987
+ params: {},
4988
+ index
4989
+ });
4990
+ return effectId;
4991
+ }
4992
+ /**
4993
+ * Lazily create the wam-transport bridge so tempo-synced plugins lock to
4994
+ * the timeline. Skipped (not an error) when the adapter's transport lacks
4995
+ * the query/event surface — the bridge is an enhancement, not a
4996
+ * requirement for audio processing.
4997
+ */
4998
+ _ensureTransportBridge(wamModule) {
4999
+ if (this._transportBridge) return this._transportBridge;
5000
+ if (typeof wamModule.createWamTransportBridge !== "function") return null;
5001
+ const transport = this._getAdapter()?.transport;
5002
+ if (!transport || typeof transport.on !== "function" || typeof transport.getTempo !== "function" || typeof transport.tickToBar !== "function" || typeof transport.timeToTick !== "function") {
5003
+ return null;
5004
+ }
5005
+ this._transportBridge = wamModule.createWamTransportBridge(transport, () => [
5006
+ ...this._wamNodes
5007
+ ]);
5008
+ return this._transportBridge;
5009
+ }
5010
+ /**
5011
+ * Replace a chain's contents with a persisted snapshot. Entries restore
5012
+ * sequentially so chain order survives async WAM loads. A WAM url that
5013
+ * fails to load becomes a bypassed passthrough placeholder at its saved
5014
+ * position — the restore continues, a daw-effect-error fires, and the
5015
+ * saved state is retained so a later snapshot/retry round-trips it.
5016
+ */
5017
+ async _restoreChain(chain, target, entries) {
5018
+ const token = /* @__PURE__ */ Symbol("restore");
5019
+ this._restoreTokens.set(chain, token);
5020
+ const superseded = () => this._restoreTokens.get(chain) !== token;
5021
+ for (const existing of chain.entries) {
5022
+ this._runOp(chain, target, "remove", existing.id);
5023
+ }
5024
+ for (const entry of entries) {
5025
+ if (superseded()) return;
5026
+ if (entry.kind === "native") {
5027
+ const id = this._addToChain(chain, target, entry.type, entry.params);
5028
+ if (entry.bypassed) {
5029
+ this._runOp(chain, target, "setBypassed", id, true);
5030
+ }
5031
+ continue;
5032
+ }
5033
+ try {
5034
+ const id = entry.faustDsp !== void 0 ? await this._addFaustToChain(chain, target, entry.faustDsp, {
5035
+ name: entry.faustName,
5036
+ initialState: entry.state
5037
+ }) : await this._addWamToChain(chain, target, entry.url ?? "", entry.state);
5038
+ if (superseded()) {
5039
+ this._runOp(chain, target, "remove", id);
5040
+ return;
5041
+ }
5042
+ if (entry.bypassed) {
5043
+ this._runOp(chain, target, "setBypassed", id, true);
5044
+ }
5045
+ } catch (err) {
5046
+ if (superseded()) return;
5047
+ const message = err instanceof Error ? err.message : String(err);
5048
+ const sourceLabel = entry.url ?? entry.faustName ?? "Faust effect";
5049
+ console.warn(
5050
+ PREFIX2 + 'setEffectsState: plugin "' + sourceLabel + '" failed to restore: ' + message
5051
+ );
5052
+ const effectId = this._addWamPlaceholder(chain, entry, message);
5053
+ this._dispatch(target, "daw-effect-error", {
5054
+ effectId,
5055
+ ...entry.url !== void 0 ? { url: entry.url } : {},
5056
+ ...entry.faustDsp !== void 0 ? { source: { faust: entry.faustDsp } } : {},
5057
+ message
5058
+ });
5059
+ }
5060
+ }
5061
+ }
5062
+ /** A silent passthrough occupying the failed plugin's chain position. */
5063
+ _addWamPlaceholder(chain, entry, message) {
5064
+ const { audioContext } = this._requireWiring();
5065
+ const node = audioContext.createGain();
5066
+ const effectId = chain.add({
5067
+ kind: "wam",
5068
+ type: "wam",
5069
+ ...entry.url !== void 0 ? { url: entry.url } : {},
5070
+ ...entry.faustDsp !== void 0 ? { source: { faust: entry.faustDsp } } : {},
5071
+ label: entry.url ?? entry.faustName ?? "Faust effect",
5072
+ error: message,
5073
+ placeholder: { state: entry.state, bypassed: entry.bypassed },
5074
+ instance: { input: node, output: node, applyParams: () => {
5075
+ } },
5076
+ params: {}
5077
+ });
5078
+ chain.setBypassed(effectId, true);
5079
+ return effectId;
5080
+ }
5081
+ _runOp(chain, target, op, effectId, arg) {
5082
+ const entries = chain?.entries ?? [];
5083
+ const fromIndex = entries.findIndex((e) => e.id === effectId);
5084
+ if (!chain || fromIndex === -1) {
5085
+ console.warn(PREFIX2 + "effects." + op + ': unknown effectId "' + effectId + '"');
5086
+ return;
5087
+ }
5088
+ if (entries[fromIndex].error !== void 0 && (op === "setParams" || op === "setBypassed")) {
5089
+ console.warn(
5090
+ PREFIX2 + "effects." + op + ': effect "' + effectId + '" is a failed-plugin placeholder (' + entries[fromIndex].error + ") \u2014 edit ignored. Remove it or retry the restore."
5091
+ );
5092
+ return;
5093
+ }
5094
+ switch (op) {
5095
+ case "remove":
5096
+ this._destroyGui(effectId);
5097
+ chain.remove(effectId);
5098
+ this._dispatch(target, "daw-effect-remove", { effectId });
5099
+ break;
5100
+ case "setParams":
5101
+ chain.setParams(effectId, arg);
5102
+ this._dispatch(target, "daw-effect-change", { effectId, params: { ...arg } });
5103
+ break;
5104
+ case "setBypassed":
5105
+ chain.setBypassed(effectId, arg);
5106
+ this._dispatch(target, "daw-effect-bypass", { effectId, bypassed: arg });
5107
+ break;
5108
+ case "move":
5109
+ chain.move(effectId, arg);
5110
+ this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex: arg });
5111
+ break;
5112
+ }
5113
+ }
5114
+ _dispatch(target, name, detail) {
5115
+ target.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail }));
5116
+ }
5117
+ };
5118
+ function validateSerializedEntries(entries) {
5119
+ if (!Array.isArray(entries)) {
5120
+ throw new Error(PREFIX2 + "setEffectsState: expected an array of serialized effect entries");
5121
+ }
5122
+ entries.forEach((entry, i) => {
5123
+ const at = " (entry " + i + ")";
5124
+ if (entry === null || typeof entry !== "object") {
5125
+ throw new Error(PREFIX2 + "setEffectsState: entry must be an object" + at);
5126
+ }
5127
+ const e = entry;
5128
+ if (e.kind === "native") {
5129
+ if (typeof e.type !== "string" || e.type.length === 0) {
5130
+ throw new Error(PREFIX2 + "setEffectsState: native entry requires a type string" + at);
5131
+ }
5132
+ if (e.params === null || typeof e.params !== "object") {
5133
+ throw new Error(PREFIX2 + "setEffectsState: native entry requires a params object" + at);
5134
+ }
5135
+ } else if (e.kind === "wam") {
5136
+ const hasUrl = typeof e.url === "string" && e.url.length > 0;
5137
+ const hasFaustDsp = typeof e.faustDsp === "string" && e.faustDsp.trim().length > 0;
5138
+ if (!hasUrl && !hasFaustDsp) {
5139
+ throw new Error(
5140
+ PREFIX2 + "setEffectsState: wam entry requires a url string or a faustDsp source string" + at
5141
+ );
5142
+ }
5143
+ if (e.faustName !== void 0 && typeof e.faustName !== "string") {
5144
+ throw new Error(PREFIX2 + "setEffectsState: faustName must be a string when provided" + at);
5145
+ }
5146
+ } else {
5147
+ throw new Error(PREFIX2 + 'setEffectsState: unknown entry kind "' + String(e.kind) + '"' + at);
5148
+ }
5149
+ if (typeof e.bypassed !== "boolean") {
5150
+ throw new Error(PREFIX2 + "setEffectsState: entry requires a boolean bypassed flag" + at);
5151
+ }
5152
+ });
5153
+ }
5154
+ function toWamParameterMap(params) {
5155
+ const map = {};
5156
+ for (const [id, value] of Object.entries(params)) {
5157
+ map[id] = { id, value, normalized: false };
5158
+ }
5159
+ return map;
5160
+ }
5161
+
5162
+ // src/interactions/export-audio.ts
5163
+ var PREFIX3 = "[waveform-playlist] ";
5164
+ async function exportAudioImpl(host, options = {}) {
5165
+ const sampleRate = options.sampleRate ?? host.effectiveSampleRate;
5166
+ const startTime = options.startTime ?? 0;
5167
+ const duration = options.duration ?? Math.max(0, host.duration - startTime);
5168
+ const channels = options.channels ?? 2;
5169
+ if (!Number.isFinite(sampleRate) || sampleRate <= 0) {
5170
+ throw new Error(PREFIX3 + "exportAudio: invalid sampleRate " + String(sampleRate));
5171
+ }
5172
+ if (!Number.isFinite(duration) || duration <= 0) {
5173
+ throw new Error(PREFIX3 + "exportAudio: nothing to render (duration " + String(duration) + ")");
5174
+ }
5175
+ const ctx = new OfflineAudioContext({
5176
+ numberOfChannels: channels,
5177
+ length: Math.round(duration * sampleRate),
5178
+ sampleRate
5179
+ });
5180
+ const cleanups = [];
5181
+ try {
5182
+ const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());
5183
+ cleanups.push(masterChain.dispose);
5184
+ masterChain.output.connect(ctx.destination);
5185
+ const anySoloed = host.tracks.some((t) => t.soloed);
5186
+ for (const track of host.tracks) {
5187
+ if (track.muted || anySoloed && !track.soloed) {
5188
+ continue;
5189
+ }
5190
+ const chain = await buildOfflineChain(ctx, await host.getTrackEffectsState(track.id));
5191
+ cleanups.push(chain.dispose);
5192
+ const volume = ctx.createGain();
5193
+ volume.gain.value = track.volume;
5194
+ const panner = ctx.createStereoPanner();
5195
+ panner.pan.value = track.pan;
5196
+ volume.connect(panner);
5197
+ panner.connect(chain.input);
5198
+ chain.output.connect(masterChain.input);
5199
+ for (const clip of track.clips) {
5200
+ scheduleClip(ctx, clip, startTime, duration, volume);
5201
+ }
5202
+ }
5203
+ return await ctx.startRendering();
5204
+ } finally {
5205
+ for (const dispose of cleanups) {
5206
+ try {
5207
+ dispose();
5208
+ } catch (err) {
5209
+ console.warn(PREFIX3 + "exportAudio: cleanup error: " + String(err));
5210
+ }
5211
+ }
5212
+ }
5213
+ }
5214
+ function scheduleClip(ctx, clip, windowStart, windowDuration, destination) {
5215
+ if (!clip.audioBuffer || clip.durationSamples <= 0) {
5216
+ return;
5217
+ }
5218
+ const clipRate = clip.sampleRate;
5219
+ const clipStart = clip.startSample / clipRate;
5220
+ const clipDuration = clip.durationSamples / clipRate;
5221
+ let offset = clip.offsetSamples / clipRate;
5222
+ let when = clipStart - windowStart;
5223
+ let remaining = clipDuration;
5224
+ if (when < 0) {
5225
+ offset += -when;
5226
+ remaining += when;
5227
+ when = 0;
5228
+ }
5229
+ remaining = Math.min(remaining, windowDuration - when);
5230
+ if (remaining <= 0) {
5231
+ return;
5232
+ }
5233
+ const source = ctx.createBufferSource();
5234
+ source.buffer = clip.audioBuffer;
5235
+ let out = source;
5236
+ if (clip.gain !== void 0 && clip.gain !== 1) {
5237
+ const gainNode = ctx.createGain();
5238
+ gainNode.gain.value = clip.gain;
5239
+ out.connect(gainNode);
5240
+ out = gainNode;
5241
+ }
5242
+ out.connect(destination);
5243
+ source.start(when, offset, remaining);
5244
+ }
5245
+ async function buildOfflineChain(ctx, entries) {
5246
+ const input = ctx.createGain();
5247
+ const output = ctx.createGain();
5248
+ const cleanups = [];
5249
+ const dispose = () => {
5250
+ for (const cleanup of cleanups) {
5251
+ try {
5252
+ cleanup();
5253
+ } catch (err) {
5254
+ console.warn(PREFIX3 + "exportAudio: chain cleanup error: " + String(err));
5255
+ }
5256
+ }
5257
+ };
5258
+ let previous = input;
5259
+ try {
5260
+ await wireEntries();
5261
+ } catch (err) {
5262
+ dispose();
5263
+ throw err;
5264
+ }
5265
+ previous.connect(output);
5266
+ return { input, output, dispose };
5267
+ async function wireEntries() {
5268
+ for (const entry of entries) {
5269
+ if (entry.kind === "native") {
5270
+ const created = createEffectInstance(entry.type, ctx, entry.params);
5271
+ if (entry.bypassed) {
5272
+ if (!created.wetParam) {
5273
+ created.instance.dispose?.();
5274
+ continue;
5275
+ }
5276
+ created.instance.applyParams({ [created.wetParam]: 0 });
5277
+ }
5278
+ if (created.instance.dispose) {
5279
+ cleanups.push(created.instance.dispose);
5280
+ }
5281
+ previous.connect(created.instance.input);
5282
+ previous = created.instance.output;
5283
+ continue;
5284
+ }
5285
+ if (entry.bypassed) {
5286
+ continue;
5287
+ }
5288
+ const wamModule = await loadWamModule("exportAudio() with WAM effects");
5289
+ const { hostGroupId } = await wamModule.ensureWamHost(ctx);
5290
+ let plugin;
5291
+ if (entry.faustDsp !== void 0) {
5292
+ const faustModule = await loadFaustModule("exportAudio() with Faust effects");
5293
+ const compiled = await faustModule.compileFaustToWam(entry.faustDsp, {
5294
+ name: entry.faustName
5295
+ });
5296
+ plugin = await wamModule.createWamInstanceFromFactory(
5297
+ compiled.factory,
5298
+ ctx,
5299
+ hostGroupId,
5300
+ { initialState: entry.state, label: compiled.name }
5301
+ );
5302
+ } else {
5303
+ plugin = await wamModule.createWamInstance(entry.url ?? "", ctx, hostGroupId, {
5304
+ initialState: entry.state
5305
+ });
5306
+ }
5307
+ cleanups.push(() => plugin.destroy());
5308
+ previous.connect(plugin.audioNode);
5309
+ previous = plugin.audioNode;
5310
+ }
5311
+ }
5312
+ }
5313
+
5314
+ // src/interactions/peaks-loader.ts
5315
+ import WaveformData2 from "waveform-data";
5316
+ async function loadWaveformDataFromUrl(src) {
5317
+ const response = await fetch(src);
5318
+ if (!response.ok) {
5319
+ throw new Error("[dawcore] Failed to fetch peaks data: " + response.statusText);
5320
+ }
5321
+ const { pathname } = new URL(src, globalThis.location?.href ?? "http://localhost");
5322
+ const isBinary = pathname.toLowerCase().endsWith(".dat");
5323
+ if (isBinary) {
5324
+ const arrayBuffer = await response.arrayBuffer();
5325
+ return WaveformData2.create(arrayBuffer);
5326
+ } else {
5327
+ const json = await response.json();
5328
+ return WaveformData2.create(json);
5329
+ }
5330
+ }
5331
+
5332
+ // src/controllers/scroll-sync-controller.ts
5333
+ var LINE_HEIGHT_PX = 16;
5334
+ var ScrollSyncController = class {
5335
+ constructor(host) {
5336
+ this._scrollContainer = null;
5337
+ this._wheelTargets = /* @__PURE__ */ new Set();
5338
+ this._warnedX = false;
5339
+ this._warnedY = false;
5340
+ /** Selector (in host shadow DOM) for the scroll container. */
5341
+ this.scrollSelector = "";
5342
+ /** Selector for the element receiving translate3d(-scrollLeft, 0, 0). */
5343
+ this.xTargetSelector = "";
5344
+ /** Selector for the element receiving translate3d(0, -scrollTop, 0). */
5345
+ this.yTargetSelector = "";
5346
+ /**
5347
+ * Selector (or comma-separated selectors) for elements whose wheel events
5348
+ * forward to the scroll container. All matching elements receive listeners.
5349
+ */
5350
+ this.wheelForwardSelector = "";
5351
+ this._onScroll = () => {
5352
+ this._apply();
5353
+ };
5354
+ this._onWheel = (e) => {
5355
+ const sc = this._scrollContainer;
5356
+ if (!sc) return;
5357
+ const scale = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? LINE_HEIGHT_PX : e.deltaMode === WheelEvent.DOM_DELTA_PAGE ? sc.clientHeight : 1;
5358
+ const scaleX = e.deltaMode === WheelEvent.DOM_DELTA_PAGE ? sc.clientWidth : scale;
5359
+ const beforeLeft = sc.scrollLeft;
5360
+ const beforeTop = sc.scrollTop;
5361
+ sc.scrollLeft += e.deltaX * scaleX;
5362
+ sc.scrollTop += e.deltaY * scale;
5363
+ if (sc.scrollLeft !== beforeLeft || sc.scrollTop !== beforeTop) {
5364
+ e.preventDefault();
5365
+ }
5366
+ };
5367
+ this._host = host;
5368
+ host.addController(this);
5369
+ }
5370
+ hostConnected() {
5371
+ requestAnimationFrame(() => {
5372
+ if (!this._host.isConnected) return;
5373
+ this._attach();
5374
+ if (!this._scrollContainer && this.scrollSelector) {
5375
+ console.warn(
5376
+ '[dawcore] ScrollSyncController: scroll container not found for "' + this.scrollSelector + '"'
5377
+ );
5378
+ }
5379
+ });
5380
+ }
5381
+ hostDisconnected() {
5382
+ this._scrollContainer?.removeEventListener("scroll", this._onScroll);
5383
+ this._scrollContainer = null;
5384
+ for (const target of this._wheelTargets) {
5385
+ target.removeEventListener("wheel", this._onWheel);
5386
+ }
5387
+ this._wheelTargets.clear();
5388
+ }
5389
+ /**
5390
+ * Re-attach and re-apply transforms from the current scroll position.
5391
+ * Called from the host's updated() so elements created by a re-render
5392
+ * (e.g. the ruler appearing when the first track loads) pick up the
5393
+ * current offset and listeners.
5394
+ */
5395
+ sync() {
5396
+ this._attach();
5397
+ }
5398
+ _query(selector) {
5399
+ return selector ? this._host.shadowRoot?.querySelector(selector) : null;
5400
+ }
5401
+ _queryAll(selector) {
5402
+ if (!selector) return [];
5403
+ return Array.from(this._host.shadowRoot?.querySelectorAll(selector) ?? []);
5404
+ }
5405
+ _attach() {
5406
+ const container = this._query(this.scrollSelector);
5407
+ if (!container) {
5408
+ if (this._scrollContainer && !this._scrollContainer.isConnected) {
5409
+ console.warn(
5410
+ '[dawcore] ScrollSyncController: scroll container "' + this.scrollSelector + '" was removed from the DOM \u2014 detaching listeners until it reappears.'
5411
+ );
5412
+ this._scrollContainer.removeEventListener("scroll", this._onScroll);
5413
+ this._scrollContainer = null;
5414
+ for (const t of this._wheelTargets) t.removeEventListener("wheel", this._onWheel);
5415
+ this._wheelTargets.clear();
5416
+ }
5417
+ return;
5418
+ }
5419
+ if (container !== this._scrollContainer) {
5420
+ this._scrollContainer?.removeEventListener("scroll", this._onScroll);
5421
+ this._scrollContainer = container;
5422
+ container.addEventListener("scroll", this._onScroll, { passive: true });
5423
+ }
5424
+ const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));
5425
+ for (const old of this._wheelTargets) {
5426
+ if (!nextTargets.has(old)) {
5427
+ old.removeEventListener("wheel", this._onWheel);
5428
+ this._wheelTargets.delete(old);
5429
+ }
5430
+ }
5431
+ for (const next of nextTargets) {
5432
+ if (!this._wheelTargets.has(next)) {
4218
5433
  next.addEventListener("wheel", this._onWheel, { passive: false });
4219
5434
  this._wheelTargets.add(next);
4220
5435
  }
@@ -4247,6 +5462,75 @@ var ScrollSyncController = class {
4247
5462
  }
4248
5463
  };
4249
5464
 
5465
+ // src/controllers/animation-controller.ts
5466
+ var AnimationController = class {
5467
+ constructor(host) {
5468
+ this._rafId = null;
5469
+ this._callback = null;
5470
+ host.addController(this);
5471
+ }
5472
+ start(callback) {
5473
+ this.stop();
5474
+ this._callback = callback;
5475
+ const loop = () => {
5476
+ this._callback?.();
5477
+ this._rafId = requestAnimationFrame(loop);
5478
+ };
5479
+ this._rafId = requestAnimationFrame(loop);
5480
+ }
5481
+ stop() {
5482
+ if (this._rafId !== null) {
5483
+ cancelAnimationFrame(this._rafId);
5484
+ this._rafId = null;
5485
+ }
5486
+ this._callback = null;
5487
+ }
5488
+ hostConnected() {
5489
+ }
5490
+ hostDisconnected() {
5491
+ this.stop();
5492
+ }
5493
+ };
5494
+
5495
+ // src/controllers/playback-animation-controller.ts
5496
+ var PlaybackAnimationController = class {
5497
+ constructor(host, options) {
5498
+ this._running = false;
5499
+ this._lastDispatchedTime = null;
5500
+ this._host = host;
5501
+ this._options = options;
5502
+ this._animation = new AnimationController(host);
5503
+ }
5504
+ start(getTime) {
5505
+ this._running = true;
5506
+ this._animation.start(() => {
5507
+ const time = getTime();
5508
+ this._options.getPlayhead()?.setPosition(this._options.timeToPixels(time));
5509
+ this._dispatchTimeUpdate(time);
5510
+ });
5511
+ }
5512
+ stop(finalTime, opts) {
5513
+ const wasRunning = this._running;
5514
+ this._running = false;
5515
+ this._animation.stop();
5516
+ this._options.getPlayhead()?.setPosition(this._options.timeToPixels(finalTime));
5517
+ if (opts?.dispatch === false) return;
5518
+ if (wasRunning || finalTime !== this._lastDispatchedTime) {
5519
+ this._dispatchTimeUpdate(finalTime);
5520
+ }
5521
+ }
5522
+ _dispatchTimeUpdate(time) {
5523
+ this._lastDispatchedTime = time;
5524
+ this._host.dispatchEvent(
5525
+ new CustomEvent("daw-timeupdate", {
5526
+ bubbles: true,
5527
+ composed: true,
5528
+ detail: { time }
5529
+ })
5530
+ );
5531
+ }
5532
+ };
5533
+
4250
5534
  // src/elements/daw-editor.ts
4251
5535
  var RULER_HEIGHT = 30;
4252
5536
  var NO_ADAPTER_ERROR = "No PlayoutAdapter set on <daw-editor>. Set editor.adapter before use.\n\n // Option 1: Native Web Audio (no Tone.js)\n npm install @dawcore/transport\n import { NativePlayoutAdapter } from '@dawcore/transport';\n editor.adapter = new NativePlayoutAdapter(new AudioContext());\n\n // Option 2: Tone.js (effects, MIDI synths)\n npm install @waveform-playlist/playout\n import { createToneAdapter } from '@waveform-playlist/playout';\n editor.adapter = createToneAdapter();";
@@ -4254,6 +5538,7 @@ var DawEditorElement = class extends LitElement11 {
4254
5538
  constructor() {
4255
5539
  super(...arguments);
4256
5540
  this._samplesPerPixel = 1024;
5541
+ this._timeFormat = "hh:mm:ss.sss";
4257
5542
  this.waveHeight = 128;
4258
5543
  this.timescale = false;
4259
5544
  this.mono = false;
@@ -4286,6 +5571,8 @@ var DawEditorElement = class extends LitElement11 {
4286
5571
  this._selectionEndTime = 0;
4287
5572
  this._currentTime = 0;
4288
5573
  this._externalAdapter = null;
5574
+ // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
5575
+ this._effectsManager = null;
4289
5576
  this._engine = null;
4290
5577
  this._warnedMissingTicksToSeconds = false;
4291
5578
  this._warnedMissingSecondsToTicks = false;
@@ -4301,6 +5588,20 @@ var DawEditorElement = class extends LitElement11 {
4301
5588
  this._childObserver = null;
4302
5589
  this._audioResume = new AudioResumeController(this);
4303
5590
  this._recordingController = new RecordingController(this);
5591
+ // Closures (not direct references) — _timeToPixels/_getPlayhead are
5592
+ // declared later in the class body; class-field init order would read
5593
+ // `undefined` for a direct reference here.
5594
+ this._playbackAnimation = new PlaybackAnimationController(this, {
5595
+ timeToPixels: (time) => this._timeToPixels(time),
5596
+ getPlayhead: () => this._getPlayhead()
5597
+ });
5598
+ /**
5599
+ * True while a seek-while-playing stop+play transition is in flight.
5600
+ * Suppresses the transient settle dispatch from the engine 'stop' handler
5601
+ * (which would otherwise leak a backward-jumping daw-timeupdate at the
5602
+ * play-start position). Non-private: pointer-handler's seek path sets it.
5603
+ */
5604
+ this._inSeekTransition = false;
4304
5605
  this._spectrogramController = null;
4305
5606
  this._clipPointer = new ClipPointerHandler(this);
4306
5607
  this._pointer = new PointerHandler(this);
@@ -4506,6 +5807,14 @@ var DawEditorElement = class extends LitElement11 {
4506
5807
  /** Set in togglePauseRecording when Transport is paused alongside the
4507
5808
  * worklet, so resume can restart it. Cleared on resume and on stop. */
4508
5809
  this._wasPlayingDuringRecording = false;
5810
+ // --- Playback animation (single RAF loop: playhead + daw-timeupdate) ---
5811
+ /** Convert playback seconds to a timeline pixel offset for the active mode. */
5812
+ this._timeToPixels = (time) => {
5813
+ if (this.scaleMode === "beats") {
5814
+ return this._secondsToTicks(time) / this.ticksPerPixel;
5815
+ }
5816
+ return time * this.effectiveSampleRate / this.samplesPerPixel;
5817
+ };
4509
5818
  }
4510
5819
  get samplesPerPixel() {
4511
5820
  return this._samplesPerPixel;
@@ -4522,6 +5831,35 @@ var DawEditorElement = class extends LitElement11 {
4522
5831
  this._samplesPerPixel = clamped;
4523
5832
  this.requestUpdate("samplesPerPixel", old);
4524
5833
  }
5834
+ get timeFormat() {
5835
+ return this._timeFormat;
5836
+ }
5837
+ set timeFormat(value) {
5838
+ if (!isTimeDisplayFormat(value)) {
5839
+ console.warn(
5840
+ '[dawcore] timeFormat: invalid format "' + String(value) + '" ignored. Valid formats: ' + TIME_DISPLAY_FORMATS.join(", ")
5841
+ );
5842
+ if (this.hasAttribute("time-format") && this.getAttribute("time-format") !== this._timeFormat) {
5843
+ this.setAttribute("time-format", this._timeFormat);
5844
+ }
5845
+ return;
5846
+ }
5847
+ if (value === this._timeFormat) return;
5848
+ const old = this._timeFormat;
5849
+ this._timeFormat = value;
5850
+ this.requestUpdate("timeFormat", old);
5851
+ this.dispatchEvent(
5852
+ new CustomEvent("daw-time-format-change", {
5853
+ bubbles: true,
5854
+ composed: true,
5855
+ detail: { format: value }
5856
+ })
5857
+ );
5858
+ }
5859
+ /** Set the time display format. Sugar over the `timeFormat` property. */
5860
+ setTimeFormat(format) {
5861
+ this.timeFormat = format;
5862
+ }
4525
5863
  get spectrogramConfig() {
4526
5864
  return this._spectrogramConfig;
4527
5865
  }
@@ -4643,11 +5981,122 @@ var DawEditorElement = class extends LitElement11 {
4643
5981
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
4644
5982
  );
4645
5983
  }
5984
+ if (this._effectsManager) {
5985
+ console.warn(
5986
+ "[dawcore] adapter replaced \u2014 existing effect chains were disposed. Re-add effects on the new adapter."
5987
+ );
5988
+ this._effectsManager.disposeAll();
5989
+ this._effectsManager = null;
5990
+ }
4646
5991
  this._externalAdapter = value;
4647
5992
  }
4648
5993
  get adapter() {
4649
5994
  return this._externalAdapter;
4650
5995
  }
5996
+ get _effects() {
5997
+ if (!this._effectsManager) {
5998
+ this._effectsManager = new EffectsManager(() => this._externalAdapter, this);
5999
+ }
6000
+ return this._effectsManager;
6001
+ }
6002
+ /** Master effects chain — inserted between the master bus and the destination. */
6003
+ addEffect(type, params) {
6004
+ return this._effects.addMasterEffect(type, params);
6005
+ }
6006
+ removeEffect(effectId) {
6007
+ this._effects.masterOp("remove", effectId);
6008
+ }
6009
+ setEffectParams(effectId, params) {
6010
+ this._effects.masterOp("setParams", effectId, params);
6011
+ }
6012
+ setEffectBypassed(effectId, bypassed) {
6013
+ this._effects.masterOp("setBypassed", effectId, bypassed);
6014
+ }
6015
+ moveEffect(effectId, newIndex) {
6016
+ this._effects.masterOp("move", effectId, newIndex);
6017
+ }
6018
+ get effects() {
6019
+ return this._effectsManager?.masterEffects() ?? [];
6020
+ }
6021
+ /** Load a WAM plugin (via the optional @dawcore/wam peer) into the master chain. */
6022
+ addWamPlugin(url, initialState) {
6023
+ return this._effects.addMasterWamPlugin(url, initialState);
6024
+ }
6025
+ /**
6026
+ * Compile Faust DSP source in the browser (via the optional @dawcore/faust
6027
+ * peer) and add the resulting WAM to the master chain. Compile errors keep
6028
+ * their Faust line/column diagnostics and leave the chain untouched.
6029
+ */
6030
+ addFaustEffect(dspCode, options) {
6031
+ return this._effects.addMasterFaustEffect(dspCode, options);
6032
+ }
6033
+ /**
6034
+ * Open (lazily creating) the GUI for a master-chain effect into a
6035
+ * consumer-provided container. WAM plugins mount their own GUI; plugins
6036
+ * without one — and native effects — get the generic parameter panel from
6037
+ * @dawcore/wam. The element is cached: closeEffectGui hides it without
6038
+ * interrupting audio, reopening remounts the same element.
6039
+ */
6040
+ openEffectGui(effectId, container) {
6041
+ return this._effects.openMasterEffectGui(effectId, container);
6042
+ }
6043
+ /** Hide a master-chain effect's GUI (cached for reopen — never destroys). */
6044
+ closeEffectGui(effectId) {
6045
+ this._effects.closeEffectGui(effectId);
6046
+ }
6047
+ /** Snapshot the master chain in its persisted form (see dawcore README). */
6048
+ getEffectsState() {
6049
+ return this._effectsManager?.getMasterEffectsState() ?? Promise.resolve([]);
6050
+ }
6051
+ /** Replace the master chain with a persisted snapshot. */
6052
+ setEffectsState(entries) {
6053
+ return this._effects.setMasterEffectsState(entries);
6054
+ }
6055
+ /**
6056
+ * Render the session offline through all effect chains (per-track +
6057
+ * master), including WAM plugins (re-instantiated on the offline context
6058
+ * with their live state). Returns the rendered AudioBuffer.
6059
+ */
6060
+ exportAudio(options) {
6061
+ return exportAudioImpl(
6062
+ {
6063
+ effectiveSampleRate: this.effectiveSampleRate,
6064
+ duration: this._duration,
6065
+ tracks: [...this._engineTracks.values()],
6066
+ getMasterEffectsState: () => this.getEffectsState(),
6067
+ getTrackEffectsState: (trackId) => this._trackGetEffectsState(trackId)
6068
+ },
6069
+ options
6070
+ );
6071
+ }
6072
+ /** Internal — <daw-track> effects API delegates here (dawcore-internal contract). */
6073
+ _trackAddEffect(trackId, target, type, params) {
6074
+ return this._effects.addTrackEffect(trackId, target, type, params);
6075
+ }
6076
+ _trackEffectOp(trackId, target, op, effectId, arg) {
6077
+ this._effects.trackOp(trackId, target, op, effectId, arg);
6078
+ }
6079
+ _trackEffects(trackId) {
6080
+ return this._effectsManager?.trackEffects(trackId) ?? [];
6081
+ }
6082
+ _trackAddWamPlugin(trackId, target, url, initialState) {
6083
+ return this._effects.addTrackWamPlugin(trackId, target, url, initialState);
6084
+ }
6085
+ _trackAddFaustEffect(trackId, target, dspCode, options) {
6086
+ return this._effects.addTrackFaustEffect(trackId, target, dspCode, options);
6087
+ }
6088
+ _trackOpenEffectGui(trackId, target, effectId, container) {
6089
+ return this._effects.openTrackEffectGui(trackId, target, effectId, container);
6090
+ }
6091
+ _trackCloseEffectGui(_trackId, effectId) {
6092
+ this._effects.closeEffectGui(effectId);
6093
+ }
6094
+ _trackGetEffectsState(trackId) {
6095
+ return this._effectsManager?.getTrackEffectsState(trackId) ?? Promise.resolve([]);
6096
+ }
6097
+ _trackSetEffectsState(trackId, target, entries) {
6098
+ return this._effects.setTrackEffectsState(trackId, target, entries);
6099
+ }
4651
6100
  get audioContext() {
4652
6101
  if (!this._externalAdapter) {
4653
6102
  throw new Error(NO_ADAPTER_ERROR);
@@ -4819,6 +6268,8 @@ var DawEditorElement = class extends LitElement11 {
4819
6268
  }
4820
6269
  disconnectedCallback() {
4821
6270
  super.disconnectedCallback();
6271
+ this._effectsManager?.disposeAll();
6272
+ this._effectsManager = null;
4822
6273
  this.removeEventListener("daw-track-connected", this._onTrackConnected);
4823
6274
  this.removeEventListener("daw-track-update", this._onTrackUpdate);
4824
6275
  this.removeEventListener("daw-track-control", this._onTrackControl);
@@ -4894,6 +6345,7 @@ var DawEditorElement = class extends LitElement11 {
4894
6345
  }
4895
6346
  _onTrackRemoved(trackId) {
4896
6347
  this._trackElements.delete(trackId);
6348
+ this._effectsManager?.disposeTrackChain(trackId);
4897
6349
  const removedTrack = this._engineTracks.get(trackId);
4898
6350
  if (removedTrack) {
4899
6351
  const nextPeaks = new Map(this._peaksData);
@@ -5533,17 +6985,24 @@ var DawEditorElement = class extends LitElement11 {
5533
6985
  zoomLevels: [256, 512, 1024, 2048, 4096, 8192, this.samplesPerPixel].filter((v, i, a) => a.indexOf(v) === i).sort((a, b) => a - b)
5534
6986
  });
5535
6987
  let lastTracksVersion = -1;
6988
+ let lastMixerVersion = -1;
5536
6989
  engine.on("statechange", (engineState) => {
5537
6990
  this._isPlaying = engineState.isPlaying;
5538
6991
  this._duration = engineState.duration;
5539
6992
  this._selectedTrackId = engineState.selectedTrackId;
5540
- if (engineState.tracksVersion !== lastTracksVersion) {
6993
+ const structuralChange = engineState.tracksVersion !== lastTracksVersion;
6994
+ const mixerChange = engineState.mixerVersion !== lastMixerVersion;
6995
+ if (structuralChange || mixerChange) {
5541
6996
  lastTracksVersion = engineState.tracksVersion;
6997
+ lastMixerVersion = engineState.mixerVersion;
5542
6998
  const nextTracks = /* @__PURE__ */ new Map();
5543
6999
  for (const track of engineState.tracks) {
5544
7000
  nextTracks.set(track.id, track);
5545
7001
  }
5546
7002
  this._engineTracks = nextTracks;
7003
+ }
7004
+ if (structuralChange) {
7005
+ this._effectsManager?.rewireTrackChains();
5547
7006
  const audioTracks = engineState.tracks.filter((t) => {
5548
7007
  const desc = this._tracks.get(t.id);
5549
7008
  return desc?.renderMode !== "piano-roll";
@@ -5903,7 +7362,12 @@ var DawEditorElement = class extends LitElement11 {
5903
7362
  return;
5904
7363
  }
5905
7364
  if (this._isPlaying) {
5906
- this.stop();
7365
+ this._inSeekTransition = true;
7366
+ try {
7367
+ this.stop();
7368
+ } finally {
7369
+ this._inSeekTransition = false;
7370
+ }
5907
7371
  this.play(time);
5908
7372
  } else {
5909
7373
  this._engine.seek(time);
@@ -5962,6 +7426,14 @@ var DawEditorElement = class extends LitElement11 {
5962
7426
  }
5963
7427
  return this._currentTime;
5964
7428
  }
7429
+ /** Read-only: whether playback is running (HTMLMediaElement-adjacent). */
7430
+ get isPlaying() {
7431
+ return this._isPlaying;
7432
+ }
7433
+ /** Read-only: total content duration in seconds. */
7434
+ get duration() {
7435
+ return this._duration;
7436
+ }
5965
7437
  get isRecording() {
5966
7438
  return this._recordingController.isRecording;
5967
7439
  }
@@ -6052,33 +7524,15 @@ var DawEditorElement = class extends LitElement11 {
6052
7524
  `;
6053
7525
  });
6054
7526
  }
6055
- // --- Playhead ---
6056
7527
  _startPlayhead() {
6057
- const playhead = this._getPlayhead();
6058
- if (!playhead || !this._engine) return;
7528
+ if (!this._engine) return;
6059
7529
  const engine = this._engine;
6060
- const audibleTime = () => engine.getAudibleTime();
6061
- if (this.scaleMode === "beats") {
6062
- const secondsToTicksFn = (s) => this._secondsToTicks(s);
6063
- playhead.startBeatsAnimationWithMap(audibleTime, secondsToTicksFn, this.ticksPerPixel);
6064
- } else {
6065
- playhead.startAnimation(audibleTime, this.effectiveSampleRate, this.samplesPerPixel);
6066
- }
7530
+ this._playbackAnimation.start(() => engine.getAudibleTime());
6067
7531
  }
6068
7532
  _stopPlayhead() {
6069
- const playhead = this._getPlayhead();
6070
- if (!playhead) return;
6071
7533
  const t = this._currentTime;
6072
7534
  const visualTime = Number.isFinite(t) ? Math.max(0, t) : 0;
6073
- if (this.scaleMode === "beats") {
6074
- playhead.stopBeatsAnimationWithMap(
6075
- visualTime,
6076
- (s) => this._secondsToTicks(s),
6077
- this.ticksPerPixel
6078
- );
6079
- } else {
6080
- playhead.stopAnimation(visualTime, this.effectiveSampleRate, this.samplesPerPixel);
6081
- }
7535
+ this._playbackAnimation.stop(visualTime, { dispatch: !this._inSeekTransition });
6082
7536
  }
6083
7537
  _getPlayhead() {
6084
7538
  return this.shadowRoot?.querySelector("daw-playhead");
@@ -6423,6 +7877,9 @@ DawEditorElement._CONTROL_PROPS = /* @__PURE__ */ new Set(["volume", "pan", "mut
6423
7877
  __decorateClass([
6424
7878
  property9({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
6425
7879
  ], DawEditorElement.prototype, "samplesPerPixel", 1);
7880
+ __decorateClass([
7881
+ property9({ attribute: "time-format", reflect: true, noAccessor: true })
7882
+ ], DawEditorElement.prototype, "timeFormat", 1);
6426
7883
  __decorateClass([
6427
7884
  property9({ type: Number, attribute: "wave-height" })
6428
7885
  ], DawEditorElement.prototype, "waveHeight", 2);
@@ -6603,7 +8060,12 @@ var DawRecordButtonElement = class extends DawTransportButton {
6603
8060
  }
6604
8061
  render() {
6605
8062
  return html12`
6606
- <button part="button" ?data-recording=${this._isRecording} @click=${this._onClick}>
8063
+ <button
8064
+ part="button"
8065
+ ?disabled=${!this.targetSupported}
8066
+ ?data-recording=${this._isRecording}
8067
+ @click=${this._onClick}
8068
+ >
6607
8069
  <slot>Record</slot>
6608
8070
  </button>
6609
8071
  `;
@@ -6612,14 +8074,16 @@ var DawRecordButtonElement = class extends DawTransportButton {
6612
8074
  if (this._isRecording) return;
6613
8075
  const target = this.target;
6614
8076
  if (!target) {
6615
- console.warn(
6616
- '[dawcore] <daw-record-button> has no target. Check <daw-transport for="..."> references a valid <daw-editor> id.'
6617
- );
8077
+ warnNoTargetOnce(this);
6618
8078
  return;
6619
8079
  }
6620
8080
  target.startRecording(target.recordingStream);
6621
8081
  }
6622
8082
  };
8083
+ DawRecordButtonElement.requiredTargetMethods = [
8084
+ "startRecording",
8085
+ "stopRecording"
8086
+ ];
6623
8087
  DawRecordButtonElement.styles = [
6624
8088
  DawTransportButton.styles,
6625
8089
  css12`
@@ -6996,6 +8460,198 @@ __decorateClass([
6996
8460
  DawSpectrogramElement = __decorateClass([
6997
8461
  customElement17("daw-spectrogram")
6998
8462
  ], DawSpectrogramElement);
8463
+
8464
+ // src/elements/daw-time-display.ts
8465
+ import { LitElement as LitElement15, html as html14, css as css14 } from "lit";
8466
+ import { customElement as customElement18, state as state5 } from "lit/decorators.js";
8467
+ var DawTimeDisplayElement = class extends LitElement15 {
8468
+ constructor() {
8469
+ super(...arguments);
8470
+ this._time = null;
8471
+ this._format = "hh:mm:ss.sss";
8472
+ this._onTimeUpdate = (e) => {
8473
+ if (e.target !== this.target) return;
8474
+ if (this._time === null) {
8475
+ const timeFormat = e.target.timeFormat;
8476
+ if (isTimeDisplayFormat(timeFormat)) this._format = timeFormat;
8477
+ }
8478
+ this._time = e.detail.time;
8479
+ };
8480
+ this._onFormatChange = (e) => {
8481
+ if (e.target !== this.target) return;
8482
+ const detail = e.detail;
8483
+ if (isTimeDisplayFormat(detail.format)) {
8484
+ this._format = detail.format;
8485
+ }
8486
+ };
8487
+ }
8488
+ get target() {
8489
+ return resolveTransportTarget(this);
8490
+ }
8491
+ connectedCallback() {
8492
+ super.connectedCallback();
8493
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate);
8494
+ document.addEventListener("daw-time-format-change", this._onFormatChange);
8495
+ requestAnimationFrame(() => this._syncFromTarget());
8496
+ }
8497
+ disconnectedCallback() {
8498
+ super.disconnectedCallback();
8499
+ document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
8500
+ document.removeEventListener("daw-time-format-change", this._onFormatChange);
8501
+ }
8502
+ _syncFromTarget() {
8503
+ if (!this.isConnected) return;
8504
+ const target = this.target;
8505
+ if (!target || typeof target.currentTime !== "number") {
8506
+ warnNoTargetOnce(
8507
+ this,
8508
+ " The display recovers automatically once the target dispatches daw-timeupdate."
8509
+ );
8510
+ return;
8511
+ }
8512
+ this._time = target.currentTime;
8513
+ const fmt = target.timeFormat;
8514
+ if (isTimeDisplayFormat(fmt)) {
8515
+ this._format = fmt;
8516
+ }
8517
+ }
8518
+ render() {
8519
+ const text = this._time === null ? "--:--:--" : formatDisplayTime(this._time, this._format);
8520
+ return html14`<span role="status" aria-label="Playback time" aria-live="off">${text}</span>`;
8521
+ }
8522
+ };
8523
+ DawTimeDisplayElement.styles = css14`
8524
+ span {
8525
+ display: inline-block;
8526
+ font-family: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
8527
+ font-variant-numeric: tabular-nums;
8528
+ color: var(--daw-controls-text, #e0d4c8);
8529
+ background: var(--daw-controls-background, #1a1a2e);
8530
+ border: 1px solid currentColor;
8531
+ padding: 4px 8px;
8532
+ }
8533
+ `;
8534
+ __decorateClass([
8535
+ state5()
8536
+ ], DawTimeDisplayElement.prototype, "_time", 2);
8537
+ __decorateClass([
8538
+ state5()
8539
+ ], DawTimeDisplayElement.prototype, "_format", 2);
8540
+ DawTimeDisplayElement = __decorateClass([
8541
+ customElement18("daw-time-display")
8542
+ ], DawTimeDisplayElement);
8543
+
8544
+ // src/elements/daw-time-format.ts
8545
+ import { LitElement as LitElement16, html as html15, css as css15 } from "lit";
8546
+ import { customElement as customElement19, state as state6 } from "lit/decorators.js";
8547
+ var DawTimeFormatElement = class extends LitElement16 {
8548
+ constructor() {
8549
+ super(...arguments);
8550
+ this._format = "hh:mm:ss.sss";
8551
+ this._onFormatChange = (e) => {
8552
+ if (e.target !== this.target) return;
8553
+ const detail = e.detail;
8554
+ if (isTimeDisplayFormat(detail.format)) {
8555
+ this._format = detail.format;
8556
+ }
8557
+ };
8558
+ this._onPointerEnter = () => {
8559
+ this.requestUpdate();
8560
+ };
8561
+ this._onPointerDown = () => {
8562
+ const target = this.target;
8563
+ if (!target) {
8564
+ warnNoTargetOnce(this);
8565
+ return;
8566
+ }
8567
+ if (!this._targetSupported) {
8568
+ warnUnsupportedOnce(this, ["setTimeFormat"]);
8569
+ }
8570
+ };
8571
+ }
8572
+ get target() {
8573
+ return resolveTransportTarget(this);
8574
+ }
8575
+ /**
8576
+ * False when the target doesn't implement setTimeFormat. An undetermined
8577
+ * target (missing, or a not-yet-upgraded custom element) gets the benefit
8578
+ * of the doubt and stays enabled — interaction-time resolution warns if
8579
+ * it's still unusable.
8580
+ */
8581
+ get _targetSupported() {
8582
+ const target = this.target;
8583
+ if (targetUndetermined(target)) return true;
8584
+ return targetSupports(target, ["setTimeFormat"]);
8585
+ }
8586
+ connectedCallback() {
8587
+ super.connectedCallback();
8588
+ document.addEventListener("daw-time-format-change", this._onFormatChange);
8589
+ this.addEventListener("pointerdown", this._onPointerDown);
8590
+ this.addEventListener("pointerenter", this._onPointerEnter);
8591
+ requestAnimationFrame(() => {
8592
+ if (!this.isConnected) return;
8593
+ const target = this.target;
8594
+ if (target && isTimeDisplayFormat(target.timeFormat)) {
8595
+ this._format = target.timeFormat;
8596
+ }
8597
+ this.requestUpdate();
8598
+ });
8599
+ }
8600
+ disconnectedCallback() {
8601
+ super.disconnectedCallback();
8602
+ document.removeEventListener("daw-time-format-change", this._onFormatChange);
8603
+ this.removeEventListener("pointerdown", this._onPointerDown);
8604
+ this.removeEventListener("pointerenter", this._onPointerEnter);
8605
+ }
8606
+ updated() {
8607
+ const select = this.shadowRoot?.querySelector("select");
8608
+ if (select && select.value !== this._format) {
8609
+ select.value = this._format;
8610
+ }
8611
+ }
8612
+ _onSelectChange(e) {
8613
+ const value = e.target.value;
8614
+ const target = this.target;
8615
+ if (!target) {
8616
+ warnNoTargetOnce(this);
8617
+ return;
8618
+ }
8619
+ target.setTimeFormat?.(value);
8620
+ }
8621
+ render() {
8622
+ return html15`
8623
+ <select
8624
+ aria-label="Time format"
8625
+ ?disabled=${!this._targetSupported}
8626
+ @change=${this._onSelectChange}
8627
+ >
8628
+ ${TIME_DISPLAY_FORMATS.map(
8629
+ (f) => html15`<option value=${f} ?selected=${f === this._format}>${f}</option>`
8630
+ )}
8631
+ </select>
8632
+ `;
8633
+ }
8634
+ };
8635
+ DawTimeFormatElement.styles = css15`
8636
+ select {
8637
+ cursor: pointer;
8638
+ background: var(--daw-controls-background, #1a1a2e);
8639
+ color: var(--daw-controls-text, #e0d4c8);
8640
+ border: 1px solid currentColor;
8641
+ padding: 4px 8px;
8642
+ font: inherit;
8643
+ }
8644
+ select:disabled {
8645
+ opacity: 0.4;
8646
+ cursor: default;
8647
+ }
8648
+ `;
8649
+ __decorateClass([
8650
+ state6()
8651
+ ], DawTimeFormatElement.prototype, "_format", 2);
8652
+ DawTimeFormatElement = __decorateClass([
8653
+ customElement19("daw-time-format")
8654
+ ], DawTimeFormatElement);
6999
8655
  export {
7000
8656
  AudioResumeController,
7001
8657
  ClipPointerHandler,
@@ -7012,14 +8668,28 @@ export {
7012
8668
  DawSelectionElement,
7013
8669
  DawSpectrogramElement,
7014
8670
  DawStopButtonElement,
8671
+ DawTimeDisplayElement,
8672
+ DawTimeFormatElement,
7015
8673
  DawTrackControlsElement,
7016
8674
  DawTrackElement,
7017
8675
  DawTransportButton,
7018
8676
  DawTransportElement,
7019
8677
  DawWaveformElement,
8678
+ PlaybackAnimationController,
7020
8679
  RecordingController,
7021
8680
  SpectrogramController,
8681
+ TIME_DISPLAY_FORMATS,
8682
+ createEffectInstance,
8683
+ formatDisplayTime,
8684
+ getEffectDefinitions,
7022
8685
  isDomClip,
7023
- splitAtPlayhead
8686
+ isTimeDisplayFormat,
8687
+ parseDisplayTime,
8688
+ registerEffect,
8689
+ resolveTransportTarget,
8690
+ splitAtPlayhead,
8691
+ targetSupports,
8692
+ warnOnce,
8693
+ warnUnsupportedOnce
7024
8694
  };
7025
8695
  //# sourceMappingURL=index.mjs.map