@prolibu-suite/cobalt-core 0.11.4 → 0.11.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/custom-elements.json +31 -31
- package/dist/cjs/co-audio-player.cjs.entry.js +198 -46
- package/dist/cjs/index-bHoidDwv.js +4 -4
- package/dist/cobalt/cobalt.esm.js +1 -1
- package/dist/cobalt/p-4a7fd0b4.entry.js +1 -0
- package/dist/collection/components/co-audio-player/co-audio-player.js +40 -47
- package/dist/collection/components/co-audio-player/co-audio-player.peaks-cache.js +104 -0
- package/dist/collection/components/co-audio-player/co-audio-player.utils.js +61 -0
- package/dist/collection/components/co-autocomplete/co-autocomplete.js +1 -1
- package/dist/collection/components/co-avatar-group/co-avatar-group.js +1 -1
- package/dist/collection/components/co-checkbox-group/co-checkbox-group.js +1 -1
- package/dist/collection/components/co-color-area/co-color-area.js +2 -2
- package/dist/collection/components/co-color-slider/co-color-slider.js +1 -1
- package/dist/collection/components/co-combobox/co-combobox.js +1 -1
- package/dist/collection/components/co-command-search/co-command-search.js +1 -1
- package/dist/collection/components/co-data-table/co-data-table.js +1 -1
- package/dist/collection/components/co-date-range-picker/co-date-range-picker.js +2 -2
- package/dist/collection/components/co-document-editor/co-document-editor.js +5 -5
- package/dist/collection/components/co-popover/co-popover.js +1 -1
- package/dist/collection/components/co-radio-group/co-radio-group.js +1 -1
- package/dist/collection/components/co-ref-field/co-ref-field.js +4 -4
- package/dist/collection/components/co-segmented-bar/co-segmented-bar.js +1 -1
- package/dist/collection/components/co-select/co-select.js +1 -1
- package/dist/collection/components/co-sidebar-nav/co-sidebar-nav.js +1 -1
- package/dist/collection/components/co-toast/co-toast.js +2 -2
- package/dist/collection/components/co-transfer-list/co-transfer-list.js +1 -1
- package/dist/collection/components/co-tree-item/co-tree-item.js +2 -2
- package/dist/components/co-audio-player.js +1 -1
- package/dist/esm/co-audio-player.entry.js +198 -46
- package/dist/esm/index-DJkaRtbb.js +4 -4
- package/dist/types/components/co-audio-player/co-audio-player.d.ts +8 -1
- package/dist/types/components/co-audio-player/co-audio-player.peaks-cache.d.ts +58 -0
- package/dist/types/components/co-audio-player/co-audio-player.utils.d.ts +33 -0
- package/package.json +3 -3
- package/dist/cobalt/p-358a6c2a.entry.js +0 -1
|
@@ -51,6 +51,67 @@ function resamplePeaks(channelData, bars) {
|
|
|
51
51
|
}
|
|
52
52
|
return peaks;
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Resolución de la envolvente que se retiene por grabación, en bloques.
|
|
56
|
+
*
|
|
57
|
+
* Las barras EXACTAS del ancho vigente se calculan del PCM antes de soltarlo (ver
|
|
58
|
+
* `co-audio-player.peaks-cache`); la envolvente solo sirve los anchos que aparecen
|
|
59
|
+
* DESPUÉS (resize, o una segunda instancia que llega con el caché ya caliente). El
|
|
60
|
+
* reproductor deriva las barras del ancho (`floor(ancho / barDensity)`, ~853 a
|
|
61
|
+
* 2560 px), así que la envolvente tiene que ir muy por encima de eso: 65 536 bloques
|
|
62
|
+
* = ≥ 76 bloques por barra hasta 2560 px, y pesan 256 KB (Float32) frente a ~32 MB
|
|
63
|
+
* del PCM de 3 min a 44,1 kHz. Medido contra el exacto con PCM sintético de 3 min:
|
|
64
|
+
* desvío máx. ≈ 1 px de 40 en las barras que difieren (≈ 0,8 px con ruido blanco).
|
|
65
|
+
*/
|
|
66
|
+
const PEAK_ENVELOPE_BINS = 65536;
|
|
67
|
+
/** PCM → envolvente de a lo sumo `maxBins` bloques. Con `length ≤ maxBins` el bloque
|
|
68
|
+
* es de 1 muestra y la envolvente ES |PCM| (sin pérdida). */
|
|
69
|
+
function buildPeakEnvelope(channelData, maxBins = PEAK_ENVELOPE_BINS) {
|
|
70
|
+
const length = channelData.length;
|
|
71
|
+
const blockSize = Math.max(1, Math.ceil(length / Math.max(1, maxBins)));
|
|
72
|
+
const bins = Math.ceil(length / blockSize);
|
|
73
|
+
const peaks = new Float32Array(bins);
|
|
74
|
+
for (let b = 0; b < bins; b++) {
|
|
75
|
+
let max = 0;
|
|
76
|
+
const end = Math.min(length, (b + 1) * blockSize);
|
|
77
|
+
for (let j = b * blockSize; j < end; j++) {
|
|
78
|
+
const abs = Math.abs(channelData[j]);
|
|
79
|
+
if (abs > max)
|
|
80
|
+
max = abs;
|
|
81
|
+
}
|
|
82
|
+
peaks[b] = max;
|
|
83
|
+
}
|
|
84
|
+
return { peaks, blockSize, length };
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Las mismas barras que `resamplePeaks(pcm, bars)`, calculadas desde la envolvente:
|
|
88
|
+
* mismo paso (`floor(length / bars)` muestras), mismo recorte de la cola y misma
|
|
89
|
+
* fórmula de altura. Cada barra toma el máximo de los bloques que TOCA su rango de
|
|
90
|
+
* muestras, así que el resultado es IDÉNTICO cuando `blockSize` es 1 o divide el
|
|
91
|
+
* paso, y en el caso general solo puede sumar el pico de un bloque parcial en cada
|
|
92
|
+
* borde (nunca queda por debajo del exacto).
|
|
93
|
+
*/
|
|
94
|
+
function resampleEnvelope(env, bars) {
|
|
95
|
+
const { peaks: blocks, blockSize, length: len } = env;
|
|
96
|
+
if (!len || bars <= 0)
|
|
97
|
+
return [];
|
|
98
|
+
const step = Math.max(1, Math.floor(len / bars));
|
|
99
|
+
const peaks = [];
|
|
100
|
+
for (let i = 0; i < bars; i++) {
|
|
101
|
+
const start = i * step;
|
|
102
|
+
const end = Math.min(start + step, len); // exclusivo, como el bucle de resamplePeaks
|
|
103
|
+
let max = 0;
|
|
104
|
+
if (start < end) {
|
|
105
|
+
const last = Math.floor((end - 1) / blockSize);
|
|
106
|
+
for (let b = Math.floor(start / blockSize); b <= last; b++) {
|
|
107
|
+
if (blocks[b] > max)
|
|
108
|
+
max = blocks[b];
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
peaks.push(0.12 + max * 0.88);
|
|
112
|
+
}
|
|
113
|
+
return peaks;
|
|
114
|
+
}
|
|
54
115
|
/** Deterministic pseudo-waveform (stable render + testable — no Math.random). */
|
|
55
116
|
function fallbackPeaks(bars) {
|
|
56
117
|
if (bars <= 0)
|
|
@@ -70,6 +131,105 @@ function scrubFraction(clientX, rect) {
|
|
|
70
131
|
return Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
|
|
71
132
|
}
|
|
72
133
|
|
|
134
|
+
/** Tope de entradas. Cada una pesa ≤ 256 KB (`PEAK_ENVELOPE_BINS` Float32) más unas
|
|
135
|
+
* pocas listas de barras exactas, así que el caché lleno queda en ~4 MB. Una
|
|
136
|
+
* instancia montada conserva SU envolvente aunque la entrada se desaloje (es la
|
|
137
|
+
* misma referencia, no una copia). */
|
|
138
|
+
const PEAKS_CACHE_MAX = 16;
|
|
139
|
+
// Map conserva el orden de inserción: la primera clave es la menos usada (LRU).
|
|
140
|
+
const cache = new Map();
|
|
141
|
+
const inflight = new Map();
|
|
142
|
+
function remember(url, value) {
|
|
143
|
+
cache.delete(url);
|
|
144
|
+
cache.set(url, value);
|
|
145
|
+
while (cache.size > PEAKS_CACHE_MAX)
|
|
146
|
+
cache.delete(cache.keys().next().value);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Picos + duración de `url`: del caché si están, uniéndose a la carga en vuelo si
|
|
150
|
+
* otra instancia ya la pidió, o cargándolos. Solo se cachea un resultado real: un
|
|
151
|
+
* error (CORS, red, códec) o un `null` se devuelven tal cual y el próximo pedido
|
|
152
|
+
* reintenta.
|
|
153
|
+
*/
|
|
154
|
+
function loadAudioPeaks(url, wantBars, loader = decodeAudioPeaks) {
|
|
155
|
+
const hit = cache.get(url);
|
|
156
|
+
if (hit) {
|
|
157
|
+
remember(url, hit); // refresca su posición LRU
|
|
158
|
+
return Promise.resolve(hit);
|
|
159
|
+
}
|
|
160
|
+
const pending = inflight.get(url);
|
|
161
|
+
if (pending) {
|
|
162
|
+
if (wantBars)
|
|
163
|
+
pending.wanted.add(wantBars);
|
|
164
|
+
return pending.promise;
|
|
165
|
+
}
|
|
166
|
+
const wanted = new Set(wantBars ? [wantBars] : []);
|
|
167
|
+
const p = loader(url, wanted).then((res) => {
|
|
168
|
+
inflight.delete(url);
|
|
169
|
+
if (res)
|
|
170
|
+
remember(url, res);
|
|
171
|
+
return res;
|
|
172
|
+
}, (err) => {
|
|
173
|
+
inflight.delete(url);
|
|
174
|
+
throw err;
|
|
175
|
+
});
|
|
176
|
+
inflight.set(url, { promise: p, wanted });
|
|
177
|
+
return p;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Descarga + decode con Web Audio, reducido a la envolvente. El `AudioBuffer`
|
|
181
|
+
* (y con él el PCM completo) no sale de esta función: queda sin referencias
|
|
182
|
+
* apenas se calcula la envolvente.
|
|
183
|
+
*/
|
|
184
|
+
async function decodeAudioPeaks(url, wanted = new Set()) {
|
|
185
|
+
var _a;
|
|
186
|
+
let ctx;
|
|
187
|
+
try {
|
|
188
|
+
/**
|
|
189
|
+
* `OfflineAudioContext` FIRST, and a live `AudioContext` only as the
|
|
190
|
+
* fallback: decoding a waveform needs no audio OUTPUT, and a live context
|
|
191
|
+
* created before the user has interacted trips the browser's autoplay
|
|
192
|
+
* policy — "The AudioContext was not allowed to start. It must be resumed
|
|
193
|
+
* (or created) after a user gesture on the page", once per player. A page
|
|
194
|
+
* with 15 recordings logged it 15 times. The offline one has no output
|
|
195
|
+
* device, so the policy does not apply to it.
|
|
196
|
+
*
|
|
197
|
+
* Its arguments are placeholders: nothing is ever rendered through this
|
|
198
|
+
* context, it is only the host for `decodeAudioData`.
|
|
199
|
+
*/
|
|
200
|
+
const OfflineCtx = window.OfflineAudioContext || window.webkitOfflineAudioContext;
|
|
201
|
+
const Ctx = window.AudioContext || window.webkitAudioContext;
|
|
202
|
+
if ((!OfflineCtx && !Ctx) || typeof fetch === 'undefined')
|
|
203
|
+
return null;
|
|
204
|
+
ctx = OfflineCtx ? new OfflineCtx(1, 1, 44100) : new Ctx();
|
|
205
|
+
const buf = await (await fetch(url)).arrayBuffer();
|
|
206
|
+
const audioBuf = await ctx.decodeAudioData(buf);
|
|
207
|
+
const pcm = audioBuf.getChannelData(0);
|
|
208
|
+
return { envelope: buildPeakEnvelope(pcm), exact: exactBarsFor(pcm, wanted), duration: audioBuf.duration };
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
// Always release the context. Chrome caps concurrent AudioContexts per
|
|
212
|
+
// document, so leaking one per failed decode would eventually stop every
|
|
213
|
+
// later player on the page from decoding at all. `close()` lives on
|
|
214
|
+
// AudioContext, not on every BaseAudioContext (an OfflineAudioContext
|
|
215
|
+
// needs no closing and may not implement it): optional call, not a cast.
|
|
216
|
+
try {
|
|
217
|
+
await ((_a = ctx === null || ctx === void 0 ? void 0 : ctx.close) === null || _a === void 0 ? void 0 : _a.call(ctx));
|
|
218
|
+
}
|
|
219
|
+
catch ( /* already closed */_b) { /* already closed */ }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** Barras exactas para cada ancho que las instancias en espera quieren ahora mismo. */
|
|
223
|
+
function exactBarsFor(pcm, wanted) {
|
|
224
|
+
const exact = new Map();
|
|
225
|
+
for (const want of wanted) {
|
|
226
|
+
const bars = want();
|
|
227
|
+
if (bars > 0 && !exact.has(bars))
|
|
228
|
+
exact.set(bars, resamplePeaks(pcm, bars));
|
|
229
|
+
}
|
|
230
|
+
return exact;
|
|
231
|
+
}
|
|
232
|
+
|
|
73
233
|
const coAudioPlayerCss = () => `:host{display:block;font-family:var(--co-font-family-primary)}.co-audio-player{display:flex;align-items:center;gap:var(--co-spacing-md);padding:var(--co-spacing-sm) var(--co-spacing-md);border:1px solid var(--co-semantic-border-default);border-radius:var(--co-border-radius-xs);background:var(--co-semantic-surface-secondary);min-width:180px}.co-audio-player--compact{gap:var(--co-spacing-sm2);padding:var(--co-spacing-sm2) var(--co-spacing-sm);min-width:140px}.co-audio-player__play{flex:0 0 auto;width:28px;height:28px;border:none;border-radius:50%;cursor:pointer;background:var(--co-semantic-surface-primary);color:var(--co-semantic-text-inverse);display:inline-flex;align-items:center;justify-content:center}.co-audio-player--compact .co-audio-player__play{width:24px;height:24px}.co-audio-player__play:disabled{opacity:.5;cursor:not-allowed}.co-audio-player__play:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px}.co-audio-player__wave{flex:1;height:40px;min-width:0;cursor:pointer;display:flex;align-items:center}.co-audio-player__wave:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px;border-radius:var(--co-border-radius-xxs)}.co-audio-player__svg{width:100%;height:100%;display:block}.co-audio-player__bar{fill:var(--co-semantic-border-field);transition:fill var(--co-motion-duration-fast)}.co-audio-player__wave:hover .co-audio-player__bar{fill:var(--co-semantic-text-muted)}.co-audio-player__bar--played{fill:var(--co-semantic-surface-primary)}.co-audio-player__time{flex:0 0 auto;font-size:var(--co-font-size-12);color:var(--co-semantic-text-muted);font-variant-numeric:tabular-nums;min-width:62px;text-align:right}.co-audio-player__speed{flex:0 0 auto;border:none;background:transparent;cursor:pointer;padding:2px 4px;color:var(--co-semantic-text-muted);font-family:var(--co-font-family-primary);font-size:var(--co-font-size-12);font-variant-numeric:tabular-nums;min-width:34px;text-align:center}.co-audio-player__speed:hover{color:var(--co-semantic-text-default)}.co-audio-player__speed:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px;border-radius:var(--co-border-radius-xxs)}.co-audio-player__dl{flex:0 0 auto;border:none;background:transparent;cursor:pointer;padding:2px;color:var(--co-semantic-text-muted);display:inline-flex}.co-audio-player__dl:hover{color:var(--co-semantic-text-default)}.co-audio-player__dl:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px}.co-audio-player--error .co-audio-player__wave{opacity:.5}.co-audio-player--error .co-audio-player__play{background:var(--co-color-status-error);color:var(--co-semantic-text-inverse);opacity:1}`;
|
|
74
234
|
|
|
75
235
|
const CoAudioPlayer = class {
|
|
@@ -108,8 +268,15 @@ const CoAudioPlayer = class {
|
|
|
108
268
|
this.containerWidth = 0;
|
|
109
269
|
/** Current playback rate; the speed control cycles through `SPEEDS`. */
|
|
110
270
|
this.playbackRate = 1;
|
|
111
|
-
//
|
|
112
|
-
|
|
271
|
+
// Envolvente acotada del decode (≤ PEAK_ENVELOPE_BINS máximos por bloque), para
|
|
272
|
+
// re-derivar las barras al redimensionar sin volver a descargar. NUNCA el PCM
|
|
273
|
+
// completo: ese pesaba ~32 MB por 3 min de audio y por instancia. La envolvente es
|
|
274
|
+
// la misma referencia que guarda el caché de módulo (compartida, no copiada).
|
|
275
|
+
this.peakEnvelope = null;
|
|
276
|
+
// Barras exactas (del PCM, calculadas dentro del decode) para los anchos que esta
|
|
277
|
+
// instancia —u otra con la misma src— tenía mientras el decode estaba en vuelo.
|
|
278
|
+
// Un ancho que no esté acá sale de la envolvente.
|
|
279
|
+
this.exactPeaks = null;
|
|
113
280
|
// Length reported by the WebAudio decode; NaN when nothing has decoded (yet).
|
|
114
281
|
// It is the only trustworthy duration for a container without a duration header.
|
|
115
282
|
this.decodedDuration = NaN;
|
|
@@ -238,17 +405,22 @@ const CoAudioPlayer = class {
|
|
|
238
405
|
this.resizeObserver = undefined;
|
|
239
406
|
}
|
|
240
407
|
onSrcChange() { this.init(); }
|
|
241
|
-
// Re-derive bars for the current width: from
|
|
408
|
+
// Re-derive bars for the current width: from the decoded envelope if any, else the
|
|
242
409
|
// deterministic fallback shape. Reassign the array so Stencil re-renders.
|
|
243
410
|
rebuildBars() {
|
|
244
|
-
this.peaks = this.
|
|
245
|
-
?
|
|
411
|
+
this.peaks = this.peakEnvelope
|
|
412
|
+
? this.decodedBars(this.effectiveBars)
|
|
246
413
|
: fallbackPeaks(this.effectiveBars);
|
|
247
414
|
}
|
|
415
|
+
decodedBars(bars) {
|
|
416
|
+
var _a, _b;
|
|
417
|
+
return (_b = (_a = this.exactPeaks) === null || _a === void 0 ? void 0 : _a.get(bars)) !== null && _b !== void 0 ? _b : resampleEnvelope(this.peakEnvelope, bars);
|
|
418
|
+
}
|
|
248
419
|
init() {
|
|
249
420
|
this.teardown();
|
|
250
421
|
const token = ++this.loadToken;
|
|
251
|
-
this.
|
|
422
|
+
this.peakEnvelope = null;
|
|
423
|
+
this.exactPeaks = null;
|
|
252
424
|
this.decodedDuration = NaN;
|
|
253
425
|
this.peaks = fallbackPeaks(this.effectiveBars); // draw immediately; refine with real peaks
|
|
254
426
|
this.currentTime = 0;
|
|
@@ -287,56 +459,36 @@ const CoAudioPlayer = class {
|
|
|
287
459
|
}
|
|
288
460
|
this.isPlaying = false;
|
|
289
461
|
}
|
|
462
|
+
/**
|
|
463
|
+
* Picos + duración del decode, vía el caché de módulo (`co-audio-player.peaks-cache`):
|
|
464
|
+
* dos instancias con la misma `src` comparten UNA descarga y UN decode, y lo que
|
|
465
|
+
* vuelve es la envolvente acotada, no el PCM.
|
|
466
|
+
*/
|
|
290
467
|
async extractPeaks(url, token) {
|
|
291
|
-
var _a;
|
|
292
|
-
let ctx;
|
|
293
468
|
try {
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
* created before the user has interacted trips the browser's autoplay
|
|
298
|
-
* policy — "The AudioContext was not allowed to start. It must be resumed
|
|
299
|
-
* (or created) after a user gesture on the page", once per player. A page
|
|
300
|
-
* with 15 recordings logged it 15 times. The offline one has no output
|
|
301
|
-
* device, so the policy does not apply to it.
|
|
302
|
-
*
|
|
303
|
-
* Its arguments are placeholders: nothing is ever rendered through this
|
|
304
|
-
* context, it is only the host for `decodeAudioData`.
|
|
305
|
-
*/
|
|
306
|
-
const OfflineCtx = window.OfflineAudioContext || window.webkitOfflineAudioContext;
|
|
307
|
-
const Ctx = window.AudioContext || window.webkitAudioContext;
|
|
308
|
-
if ((!OfflineCtx && !Ctx) || typeof fetch === 'undefined')
|
|
309
|
-
return; // keep fallback
|
|
310
|
-
ctx = OfflineCtx ? new OfflineCtx(1, 1, 44100) : new Ctx();
|
|
311
|
-
const buf = await (await fetch(url)).arrayBuffer();
|
|
312
|
-
const audioBuf = await ctx.decodeAudioData(buf);
|
|
469
|
+
// El ancho se consulta al TERMINAR el decode (no ahora: acá todavía no se midió);
|
|
470
|
+
// 0 si esta carga ya no es la vigente, para no pagar barras que nadie pinta.
|
|
471
|
+
const res = await loadAudioPeaks(url, () => (token === this.loadToken ? this.effectiveBars : 0));
|
|
313
472
|
if (token !== this.loadToken)
|
|
314
473
|
return; // a newer src superseded this decode
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
this.
|
|
474
|
+
if (!res)
|
|
475
|
+
return; // no WebAudio/fetch here: keep the fallback
|
|
476
|
+
this.peakEnvelope = res.envelope;
|
|
477
|
+
this.exactPeaks = res.exact;
|
|
478
|
+
this.decodedDuration = res.duration;
|
|
479
|
+
this.peaks = this.decodedBars(this.effectiveBars);
|
|
318
480
|
}
|
|
319
|
-
catch (
|
|
481
|
+
catch (_a) {
|
|
320
482
|
if (token !== this.loadToken)
|
|
321
483
|
return;
|
|
322
484
|
// Undecodable (codec WebAudio can't handle, CORS, network): keep the
|
|
323
485
|
// deterministic fallback wave and let <audio> own the duration — playback,
|
|
324
486
|
// seek and the time readout all still work, or degrade to `--:--`.
|
|
325
|
-
this.
|
|
487
|
+
this.peakEnvelope = null;
|
|
488
|
+
this.exactPeaks = null;
|
|
326
489
|
this.decodedDuration = NaN;
|
|
327
490
|
this.peaks = fallbackPeaks(this.effectiveBars); // stays functional
|
|
328
491
|
}
|
|
329
|
-
finally {
|
|
330
|
-
// Always release the context. Chrome caps concurrent AudioContexts per
|
|
331
|
-
// document, so leaking one per failed decode would eventually stop every
|
|
332
|
-
// later player on the page from decoding at all. `close()` lives on
|
|
333
|
-
// AudioContext, not on every BaseAudioContext (an OfflineAudioContext
|
|
334
|
-
// needs no closing and may not implement it): optional call, not a cast.
|
|
335
|
-
try {
|
|
336
|
-
await ((_a = ctx === null || ctx === void 0 ? void 0 : ctx.close) === null || _a === void 0 ? void 0 : _a.call(ctx));
|
|
337
|
-
}
|
|
338
|
-
catch ( /* already closed */_c) { /* already closed */ }
|
|
339
|
-
}
|
|
340
492
|
if (token === this.loadToken)
|
|
341
493
|
this.syncDuration();
|
|
342
494
|
}
|
|
@@ -417,13 +569,13 @@ const CoAudioPlayer = class {
|
|
|
417
569
|
// below `aria-valuenow` the moment playback advances. ARIA 1.2 makes valuemax
|
|
418
570
|
// optional for `slider`, so leaving it off while unknown is well-formed.
|
|
419
571
|
const ariaMax = total ? Math.floor(total) : undefined;
|
|
420
|
-
const bar = (hFrac, i, played = false) => (h("rect", { key: '
|
|
421
|
-
return (h("div", { key: '
|
|
572
|
+
const bar = (hFrac, i, played = false) => (h("rect", { key: 'a3d5a225a904e22ba9905ef8198fa7e1b14e0e2f', x: i * UNIT, y: H / 2 - (hFrac * H) / 2, width: W, height: Math.max(hFrac * H, 2), rx: R, class: { 'co-audio-player__bar': true, 'co-audio-player__bar--played': played } }));
|
|
573
|
+
return (h("div", { key: 'afbbf524713a1146653e69928ee21e263202315f', class: {
|
|
422
574
|
'co-audio-player': true,
|
|
423
575
|
'co-audio-player--compact': this.compact,
|
|
424
576
|
'co-audio-player--error': this.hasError,
|
|
425
577
|
'co-audio-player--playing': this.isPlaying,
|
|
426
|
-
}, part: "player" }, h("button", { key: '
|
|
578
|
+
}, part: "player" }, h("button", { key: '5918385fbd8fb6fad4795e1a75eed5d073e0654c', type: "button", class: "co-audio-player__play", part: "play", "aria-label": this.hasError ? 'Audio no disponible' : this.isPlaying ? 'Pausar' : 'Reproducir', "aria-busy": this.isLoading ? 'true' : 'false', disabled: this.hasError || !this.src, onClick: this.toggle }, h("co-icon", { key: 'e7a566257df253914593712bd20029bb8f1bcdfd', name: this.hasError ? 'warning-circle' : this.isPlaying ? 'pause' : 'play', weight: "fill", size: this.compact ? 12 : 14 })), h("div", { key: '70488015726d0c966fa3e738d9f2893d71b99ebf', class: "co-audio-player__wave", part: "wave", role: "slider", tabindex: "0", "aria-label": "Progreso de reproducci\u00F3n", "aria-valuemin": 0, "aria-valuemax": ariaMax, "aria-valuenow": Math.floor(this.currentTime), ref: (el) => (this.waveEl = el), onClick: (e) => this.seekAt(e.clientX), onKeyDown: this.onWaveKey }, h("svg", { key: '8c70e4f74537e5f8ab6f66bc0da464a72507e81c', class: "co-audio-player__svg", viewBox: `0 0 ${vbW} ${H}`, preserveAspectRatio: "none", "aria-hidden": "true" }, this.peaks.map((hFrac, i) => bar(hFrac, i)), h("clipPath", { key: 'f0d37d76b3d6ab09dbd09582c8657b3fe7cb8c4c', id: "co-ap-clip" }, h("rect", { key: '436de0ce10f98c868760c76505d134f3db2dbb54', x: "0", y: "0", width: (pct / 100) * vbW, height: H })), h("g", { key: '939a1a8851d6e41b4d3c37d7201f87a6403830bb', "clip-path": "url(#co-ap-clip)" }, this.peaks.map((hFrac, i) => bar(hFrac, i, true))))), h("span", { key: 'bd57bdd97a780864aa633ec5174d4f733799a278', class: "co-audio-player__time", part: "time" }, formatTime(this.currentTime), " / ", formatTime(this.duration)), !this.compact && (h("button", { key: 'd1f559546da0b0f97009afca79fe922ce569e67f', type: "button", class: "co-audio-player__speed", part: "speed", "aria-label": `Velocidad de reproducción ${this.playbackRate}x`, onClick: this.cycleSpeed }, this.playbackRate, "x")), !this.compact && !this.noDownload && (h("button", { key: 'a1503b85bb2edf02566dcad9b8e83b1fea20b159', type: "button", class: "co-audio-player__dl", part: "download", "aria-label": "Descargar", onClick: () => this.download() }, h("co-icon", { key: 'dc96b8afdb8036e76a0c515d76c625460f4fc44d', name: "download-simple", size: 14 })))));
|
|
427
579
|
}
|
|
428
580
|
static get watchers() { return {
|
|
429
581
|
"src": [{
|
|
@@ -383,10 +383,6 @@ var loadModule = (cmpMeta, hostRef, hmrVersionId) => {
|
|
|
383
383
|
return import(
|
|
384
384
|
/* webpackMode: "lazy" */
|
|
385
385
|
'./co-loader.entry.js').then(processMod, consoleError);
|
|
386
|
-
case 'co-audio-player':
|
|
387
|
-
return import(
|
|
388
|
-
/* webpackMode: "lazy" */
|
|
389
|
-
'./co-audio-player.entry.js').then(processMod, consoleError);
|
|
390
386
|
case 'co-bottom-sheet':
|
|
391
387
|
return import(
|
|
392
388
|
/* webpackMode: "lazy" */
|
|
@@ -455,6 +451,10 @@ var loadModule = (cmpMeta, hostRef, hmrVersionId) => {
|
|
|
455
451
|
return import(
|
|
456
452
|
/* webpackMode: "lazy" */
|
|
457
453
|
'./co-icon.entry.js').then(processMod, consoleError);
|
|
454
|
+
case 'co-audio-player':
|
|
455
|
+
return import(
|
|
456
|
+
/* webpackMode: "lazy" */
|
|
457
|
+
'./co-audio-player.entry.js').then(processMod, consoleError);
|
|
458
458
|
case 'co-color-picker':
|
|
459
459
|
return import(
|
|
460
460
|
/* webpackMode: "lazy" */
|
|
@@ -60,7 +60,8 @@ export declare class CoAudioPlayer {
|
|
|
60
60
|
}>;
|
|
61
61
|
private audio?;
|
|
62
62
|
private waveEl?;
|
|
63
|
-
private
|
|
63
|
+
private peakEnvelope;
|
|
64
|
+
private exactPeaks;
|
|
64
65
|
private decodedDuration;
|
|
65
66
|
private loadToken;
|
|
66
67
|
private resizeObserver?;
|
|
@@ -77,8 +78,14 @@ export declare class CoAudioPlayer {
|
|
|
77
78
|
disconnectedCallback(): void;
|
|
78
79
|
onSrcChange(): void;
|
|
79
80
|
private rebuildBars;
|
|
81
|
+
private decodedBars;
|
|
80
82
|
private init;
|
|
81
83
|
private teardown;
|
|
84
|
+
/**
|
|
85
|
+
* Picos + duración del decode, vía el caché de módulo (`co-audio-player.peaks-cache`):
|
|
86
|
+
* dos instancias con la misma `src` comparten UNA descarga y UN decode, y lo que
|
|
87
|
+
* vuelve es la envolvente acotada, no el PCM.
|
|
88
|
+
*/
|
|
82
89
|
private extractPeaks;
|
|
83
90
|
/** Re-derive the shown duration from whichever source knows it. Called from both
|
|
84
91
|
* `loadedmetadata` and the end of the decode, because either can land first. */
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type PeakEnvelope } from './co-audio-player.utils';
|
|
2
|
+
/**
|
|
3
|
+
* Caché de picos de `co-audio-player`, a nivel de MÓDULO (compartido por todas las
|
|
4
|
+
* instancias del documento).
|
|
5
|
+
*
|
|
6
|
+
* Por qué: la misma grabación suele estar montada dos veces (la tarjeta de la
|
|
7
|
+
* llamada y su detalle) y cada instancia descargaba y decodificaba el audio
|
|
8
|
+
* completo por su cuenta. Acá se guarda solo lo que la onda necesita —la
|
|
9
|
+
* envolvente acotada y la duración decodificada— y los pedidos simultáneos de la
|
|
10
|
+
* misma URL comparten una sola promesa.
|
|
11
|
+
*
|
|
12
|
+
* Fidelidad de la onda: mientras el PCM existe (dentro del decode) se calculan las
|
|
13
|
+
* barras EXACTAS —`resamplePeaks`, lo mismo que antes— para el ancho vigente de cada
|
|
14
|
+
* instancia que está esperando ese decode; esas se pintan idénticas a como se
|
|
15
|
+
* pintaban. Solo un ancho que aparece después (resize, u otra instancia con el caché
|
|
16
|
+
* ya caliente) sale de la envolvente (`resampleEnvelope`, alta resolución).
|
|
17
|
+
*
|
|
18
|
+
* Key = la URL TAL CUAL. No se normaliza: una URL firmada (S3 `?X-Amz-Signature=…`)
|
|
19
|
+
* que se renueva es otra entrada y vuelve a descargar. Es un límite aceptado: una
|
|
20
|
+
* normalización propia (quitar la query) podría confundir dos recursos distintos.
|
|
21
|
+
*/
|
|
22
|
+
export interface AudioPeaks {
|
|
23
|
+
envelope: PeakEnvelope;
|
|
24
|
+
/** Barras exactas (del PCM) por cantidad de barras, para los anchos pedidos
|
|
25
|
+
* mientras el decode estaba en vuelo. Unas pocas entradas de cientos de valores. */
|
|
26
|
+
exact: ReadonlyMap<number, number[]>;
|
|
27
|
+
/** `AudioBuffer.duration` (s): la única duración fiable de un blob sin cabecera. */
|
|
28
|
+
duration: number;
|
|
29
|
+
}
|
|
30
|
+
/** Cantidad de barras que una instancia quiere AHORA; se consulta al terminar el
|
|
31
|
+
* decode (no al pedirlo: el ancho se mide después de `componentWillLoad`). Un valor
|
|
32
|
+
* no positivo = ya no le interesa (src cambiada, desmontada). */
|
|
33
|
+
export type BarsWanted = () => number;
|
|
34
|
+
/** `null` = el entorno no puede decodificar (sin WebAudio o sin fetch): no es un error.
|
|
35
|
+
* `wanted` es un conjunto VIVO: puede crecer mientras la carga está en vuelo. */
|
|
36
|
+
export type PeaksLoader = (url: string, wanted: ReadonlySet<BarsWanted>) => Promise<AudioPeaks | null>;
|
|
37
|
+
/** Tope de entradas. Cada una pesa ≤ 256 KB (`PEAK_ENVELOPE_BINS` Float32) más unas
|
|
38
|
+
* pocas listas de barras exactas, así que el caché lleno queda en ~4 MB. Una
|
|
39
|
+
* instancia montada conserva SU envolvente aunque la entrada se desaloje (es la
|
|
40
|
+
* misma referencia, no una copia). */
|
|
41
|
+
export declare const PEAKS_CACHE_MAX = 16;
|
|
42
|
+
/**
|
|
43
|
+
* Picos + duración de `url`: del caché si están, uniéndose a la carga en vuelo si
|
|
44
|
+
* otra instancia ya la pidió, o cargándolos. Solo se cachea un resultado real: un
|
|
45
|
+
* error (CORS, red, códec) o un `null` se devuelven tal cual y el próximo pedido
|
|
46
|
+
* reintenta.
|
|
47
|
+
*/
|
|
48
|
+
export declare function loadAudioPeaks(url: string, wantBars?: BarsWanted, loader?: PeaksLoader): Promise<AudioPeaks | null>;
|
|
49
|
+
/** Vacía el caché (tests; y un host que necesite liberar memoria a mano). */
|
|
50
|
+
export declare function clearAudioPeaksCache(): void;
|
|
51
|
+
/**
|
|
52
|
+
* Descarga + decode con Web Audio, reducido a la envolvente. El `AudioBuffer`
|
|
53
|
+
* (y con él el PCM completo) no sale de esta función: queda sin referencias
|
|
54
|
+
* apenas se calcula la envolvente.
|
|
55
|
+
*/
|
|
56
|
+
export declare function decodeAudioPeaks(url: string, wanted?: ReadonlySet<BarsWanted>): Promise<AudioPeaks | null>;
|
|
57
|
+
/** Barras exactas para cada ancho que las instancias en espera quieren ahora mismo. */
|
|
58
|
+
export declare function exactBarsFor(pcm: Float32Array | number[], wanted: ReadonlySet<BarsWanted>): Map<number, number[]>;
|
|
@@ -19,6 +19,39 @@ export declare function formatTime(seconds: number): string;
|
|
|
19
19
|
export declare function resolveDuration(fromAudio: number, fromDecode: number): number;
|
|
20
20
|
/** Downsample raw PCM to `bars` peak heights, each normalized to a 0..1 fraction. */
|
|
21
21
|
export declare function resamplePeaks(channelData: Float32Array | number[], bars: number): number[];
|
|
22
|
+
/**
|
|
23
|
+
* Resolución de la envolvente que se retiene por grabación, en bloques.
|
|
24
|
+
*
|
|
25
|
+
* Las barras EXACTAS del ancho vigente se calculan del PCM antes de soltarlo (ver
|
|
26
|
+
* `co-audio-player.peaks-cache`); la envolvente solo sirve los anchos que aparecen
|
|
27
|
+
* DESPUÉS (resize, o una segunda instancia que llega con el caché ya caliente). El
|
|
28
|
+
* reproductor deriva las barras del ancho (`floor(ancho / barDensity)`, ~853 a
|
|
29
|
+
* 2560 px), así que la envolvente tiene que ir muy por encima de eso: 65 536 bloques
|
|
30
|
+
* = ≥ 76 bloques por barra hasta 2560 px, y pesan 256 KB (Float32) frente a ~32 MB
|
|
31
|
+
* del PCM de 3 min a 44,1 kHz. Medido contra el exacto con PCM sintético de 3 min:
|
|
32
|
+
* desvío máx. ≈ 1 px de 40 en las barras que difieren (≈ 0,8 px con ruido blanco).
|
|
33
|
+
*/
|
|
34
|
+
export declare const PEAK_ENVELOPE_BINS = 65536;
|
|
35
|
+
/** Máximos absolutos por bloque de `blockSize` muestras contiguas: lo único que se
|
|
36
|
+
* retiene de un decode. `length` es la cantidad de muestras del PCM original, que
|
|
37
|
+
* `resampleEnvelope` necesita para reproducir el paso de `resamplePeaks`. */
|
|
38
|
+
export interface PeakEnvelope {
|
|
39
|
+
peaks: Float32Array;
|
|
40
|
+
blockSize: number;
|
|
41
|
+
length: number;
|
|
42
|
+
}
|
|
43
|
+
/** PCM → envolvente de a lo sumo `maxBins` bloques. Con `length ≤ maxBins` el bloque
|
|
44
|
+
* es de 1 muestra y la envolvente ES |PCM| (sin pérdida). */
|
|
45
|
+
export declare function buildPeakEnvelope(channelData: Float32Array | number[], maxBins?: number): PeakEnvelope;
|
|
46
|
+
/**
|
|
47
|
+
* Las mismas barras que `resamplePeaks(pcm, bars)`, calculadas desde la envolvente:
|
|
48
|
+
* mismo paso (`floor(length / bars)` muestras), mismo recorte de la cola y misma
|
|
49
|
+
* fórmula de altura. Cada barra toma el máximo de los bloques que TOCA su rango de
|
|
50
|
+
* muestras, así que el resultado es IDÉNTICO cuando `blockSize` es 1 o divide el
|
|
51
|
+
* paso, y en el caso general solo puede sumar el pico de un bloque parcial en cada
|
|
52
|
+
* borde (nunca queda por debajo del exacto).
|
|
53
|
+
*/
|
|
54
|
+
export declare function resampleEnvelope(env: PeakEnvelope, bars: number): number[];
|
|
22
55
|
/** Deterministic pseudo-waveform (stable render + testable — no Math.random). */
|
|
23
56
|
export declare function fallbackPeaks(bars: number): number[];
|
|
24
57
|
/** Clamped 0..1 position of a click within a track rect. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prolibu-suite/cobalt-core",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.5",
|
|
4
4
|
"description": "Cobalt Design System — Framework-agnostic Web Components built with Stencil",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -51,9 +51,9 @@
|
|
|
51
51
|
"dompurify": "^3.2.6",
|
|
52
52
|
"overlayscrollbars": "^2.16.0",
|
|
53
53
|
"@prolibu-suite/cobalt-date-utils": "0.1.2",
|
|
54
|
-
"@prolibu-suite/cobalt-
|
|
54
|
+
"@prolibu-suite/cobalt-tokens": "0.6.0",
|
|
55
55
|
"@prolibu-suite/cobalt-rich-text": "0.2.1",
|
|
56
|
-
"@prolibu-suite/cobalt-
|
|
56
|
+
"@prolibu-suite/cobalt-calendar-utils": "0.1.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@stencil/core": "^4.43.4",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as t,c as i,h as a}from"./p-DJkaRtbb.js";function s(t){if(!Number.isFinite(t)||t<0)return"--:--";const i=Math.floor(t);return`${Math.floor(i/60)}:${(i%60).toString().padStart(2,"0")}`}function e(t,i){const a=t.length;if(!a||i<=0)return[];const s=Math.max(1,Math.floor(a/i)),e=[];for(let o=0;o<i;o++){let i=0;const r=o*s;for(let e=r;e<r+s&&e<a;e++){const a=Math.abs(t[e]);a>i&&(i=a)}e.push(.12+.88*i)}return e}function o(t){if(t<=0)return[];const i=[];for(let a=0;a<t;a++){const s=.6*Math.sin(a/Math.max(1,t)*Math.PI)+.3,e=.75+.25*Math.abs(Math.sin(1.7*a));i.push(.12+s*e*.88)}return i}const r=class{constructor(a){t(this,a),this.coPlay=i(this,"coPlay",7),this.coPause=i(this,"coPause",7),this.coEnded=i(this,"coEnded",7),this.coError=i(this,"coError",7),this.coTimeUpdate=i(this,"coTimeUpdate",3),this.compact=!1,this.bars=64,this.barDensity=3,this.preload="metadata",this.downloadFilename="audio",this.noDownload=!1,this.isPlaying=!1,this.isLoading=!1,this.hasError=!1,this.currentTime=0,this.duration=NaN,this.peaks=[],this.containerWidth=0,this.playbackRate=1,this.rawChannelData=null,this.decodedDuration=NaN,this.loadToken=0,this.onMeta=()=>{this.syncDuration(),this.applyPendingSeek()},this.pendingSeek=null,this.onCanPlay=()=>{this.isLoading=!1,this.applyPendingSeek()},this.onWaiting=()=>{this.isLoading=!0},this.onTime=()=>{var t;this.currentTime=(null===(t=this.audio)||void 0===t?void 0:t.currentTime)||0,this.coTimeUpdate.emit({currentTime:this.currentTime,duration:this.knownDuration})},this.onEnded=()=>{this.isPlaying=!1,this.currentTime=0,this.coEnded.emit()},this.onErr=t=>{this.isLoading=!1,this.hasError=!0,this.coError.emit(t)},this.toggle=()=>{this.audio&&!this.hasError&&(this.isPlaying?(this.audio.pause(),this.isPlaying=!1,this.coPause.emit()):this.audio.play().then((()=>{this.isPlaying=!0,this.coPlay.emit()})).catch((()=>{})))},this.SPEEDS=[1,1.5,2,.5],this.cycleSpeed=()=>{const t=this.SPEEDS.indexOf(this.playbackRate);this.playbackRate=this.SPEEDS[(t+1)%this.SPEEDS.length],this.audio&&(this.audio.playbackRate=this.playbackRate)},this.seekAt=t=>{const i=this.knownDuration;if(!this.audio||!this.waveEl||!i)return;const a=function(t,i){return i.width?Math.max(0,Math.min(1,(t-i.left)/i.width)):0}(t,this.waveEl.getBoundingClientRect());this.audio.currentTime=a*i,this.currentTime=this.audio.currentTime},this.onWaveKey=t=>{if(" "===t.key||"Enter"===t.key)return t.preventDefault(),void this.toggle();if(!this.audio)return;const i=this.knownDuration,a=this.audio.currentTime;if("ArrowRight"===t.key)this.audio.currentTime=i?Math.min(i,a+5):a+5;else{if("ArrowLeft"!==t.key)return;this.audio.currentTime=Math.max(0,a-5)}this.currentTime=this.audio.currentTime}}get knownDuration(){return Number.isFinite(this.duration)&&this.duration>0?this.duration:0}get effectiveBars(){return this.containerWidth>0?Math.max(24,Math.floor(this.containerWidth/this.barDensity)):this.bars}componentWillLoad(){this.init()}componentDidLoad(){if("undefined"==typeof ResizeObserver||!this.waveEl)return;this.resizeObserver=new ResizeObserver((t=>{var i;for(const a of t){const t=(null===(i=a.contentRect)||void 0===i?void 0:i.width)||a.target.clientWidth||0;t>2&&Math.abs(t-this.containerWidth)>2&&(this.containerWidth=t,this.rebuildBars())}})),this.resizeObserver.observe(this.waveEl);const t=this.waveEl.clientWidth||0;t>2&&(this.containerWidth=t,this.rebuildBars())}disconnectedCallback(){var t;this.loadToken++,this.teardown(),null===(t=this.resizeObserver)||void 0===t||t.disconnect(),this.resizeObserver=void 0}onSrcChange(){this.init()}rebuildBars(){this.peaks=this.rawChannelData?e(this.rawChannelData,this.effectiveBars):o(this.effectiveBars)}init(){this.teardown();const t=++this.loadToken;if(this.rawChannelData=null,this.decodedDuration=NaN,this.peaks=o(this.effectiveBars),this.currentTime=0,this.duration=NaN,this.playbackRate=1,this.hasError=!1,!this.src)return;if(this.isLoading=!0,this.extractPeaks(this.src,t),"undefined"==typeof Audio)return;const i=new Audio;i.preload=this.preload,i.crossOrigin="anonymous",i.src=this.src,i.addEventListener("loadedmetadata",this.onMeta),i.addEventListener("timeupdate",this.onTime),i.addEventListener("ended",this.onEnded),i.addEventListener("error",this.onErr),i.addEventListener("canplay",this.onCanPlay),i.addEventListener("waiting",this.onWaiting),this.audio=i}teardown(){this.audio&&(this.audio.pause(),this.audio.removeEventListener("loadedmetadata",this.onMeta),this.audio.removeEventListener("timeupdate",this.onTime),this.audio.removeEventListener("ended",this.onEnded),this.audio.removeEventListener("error",this.onErr),this.audio.removeEventListener("canplay",this.onCanPlay),this.audio.removeEventListener("waiting",this.onWaiting),this.audio.src="",this.audio=void 0),this.isPlaying=!1}async extractPeaks(t,i){var a;let s;try{const a=window.OfflineAudioContext||window.webkitOfflineAudioContext,o=window.AudioContext||window.webkitAudioContext;if(!a&&!o||"undefined"==typeof fetch)return;s=a?new a(1,1,44100):new o;const r=await(await fetch(t)).arrayBuffer(),h=await s.decodeAudioData(r);if(i!==this.loadToken)return;this.rawChannelData=h.getChannelData(0),this.decodedDuration=h.duration,this.peaks=e(this.rawChannelData,this.effectiveBars)}catch(t){if(i!==this.loadToken)return;this.rawChannelData=null,this.decodedDuration=NaN,this.peaks=o(this.effectiveBars)}finally{try{await(null===(a=null==s?void 0:s.close)||void 0===a?void 0:a.call(s))}catch(t){}}i===this.loadToken&&this.syncDuration()}syncDuration(){var t,i;const a=(s=null!==(i=null===(t=this.audio)||void 0===t?void 0:t.duration)&&void 0!==i?i:NaN,e=this.decodedDuration,Number.isFinite(s)&&s>0?s:Number.isFinite(e)&&e>0?e:NaN);var s,e;Object.is(a,this.duration)||(this.duration=a)}applyPendingSeek(){if(null==this.pendingSeek||!this.audio)return;const t=this.pendingSeek;this.pendingSeek=null,this.audio.currentTime=t,this.currentTime=this.audio.currentTime,this.coTimeUpdate.emit({currentTime:this.currentTime,duration:this.knownDuration})}async seek(t){var i;if(!this.audio||!Number.isFinite(t))return;const a=this.knownDuration,s=a?Math.max(0,Math.min(a,t)):Math.max(0,t);this.audio.currentTime=s,Math.abs((null!==(i=this.audio.currentTime)&&void 0!==i?i:0)-s)>.05&&(this.pendingSeek=s),this.currentTime=s,this.coTimeUpdate.emit({currentTime:this.currentTime,duration:a})}async play(){if(this.audio&&!this.isPlaying&&!this.hasError)try{await this.audio.play(),this.isPlaying=!0,this.coPlay.emit()}catch(t){}}async download(){if(this.src&&"undefined"!=typeof fetch)try{const t=await(await fetch(this.src)).blob(),i=URL.createObjectURL(t),a=document.createElement("a");a.href=i,a.download=this.downloadFilename,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(i)}catch(t){}}render(){const t=Math.max(1,3*this.peaks.length),i=this.knownDuration,e=i?this.currentTime/i*100:0,o=i?Math.floor(i):void 0,r=(t,i,s=!1)=>a("rect",{key:"4b294190b3be5e7cf15282d43e7e51164a3dda4c",x:3*i,y:20-40*t/2,width:1.8,height:Math.max(40*t,2),rx:.6,class:{"co-audio-player__bar":!0,"co-audio-player__bar--played":s}});return a("div",{key:"0758a438c4a71e822de94f8b41219945f62ae62d",class:{"co-audio-player":!0,"co-audio-player--compact":this.compact,"co-audio-player--error":this.hasError,"co-audio-player--playing":this.isPlaying},part:"player"},a("button",{key:"4c4161e7ba7344a9c6a32dcc8fd92c300b750d95",type:"button",class:"co-audio-player__play",part:"play","aria-label":this.hasError?"Audio no disponible":this.isPlaying?"Pausar":"Reproducir","aria-busy":this.isLoading?"true":"false",disabled:this.hasError||!this.src,onClick:this.toggle},a("co-icon",{key:"ea749ee1cf627a49e3859029ca274170c8d69c63",name:this.hasError?"warning-circle":this.isPlaying?"pause":"play",weight:"fill",size:this.compact?12:14})),a("div",{key:"f39bf8bf114860a672979fa53287672dccea1b7f",class:"co-audio-player__wave",part:"wave",role:"slider",tabindex:"0","aria-label":"Progreso de reproducción","aria-valuemin":0,"aria-valuemax":o,"aria-valuenow":Math.floor(this.currentTime),ref:t=>this.waveEl=t,onClick:t=>this.seekAt(t.clientX),onKeyDown:this.onWaveKey},a("svg",{key:"2145f303271ca676988999b5ea7d76ab384c5e2d",class:"co-audio-player__svg",viewBox:`0 0 ${t} 40`,preserveAspectRatio:"none","aria-hidden":"true"},this.peaks.map(((t,i)=>r(t,i))),a("clipPath",{key:"6014c9f96f5df60086265a5e01344be80ebff741",id:"co-ap-clip"},a("rect",{key:"5857fa3098fc0eb9df58b643c2b44316cf819ae8",x:"0",y:"0",width:e/100*t,height:40})),a("g",{key:"241608ddfdb863ba5b18444ed2bffb39e72abeb5","clip-path":"url(#co-ap-clip)"},this.peaks.map(((t,i)=>r(t,i,!0)))))),a("span",{key:"18f190b8b23f8939da5dd2c230214d42a5b330c1",class:"co-audio-player__time",part:"time"},s(this.currentTime)," / ",s(this.duration)),!this.compact&&a("button",{key:"4a29cae938ab347997bc76e0cfe5621b402730f7",type:"button",class:"co-audio-player__speed",part:"speed","aria-label":`Velocidad de reproducción ${this.playbackRate}x`,onClick:this.cycleSpeed},this.playbackRate,"x"),!this.compact&&!this.noDownload&&a("button",{key:"c451449e629584bc3937b27b31b1124e510af91e",type:"button",class:"co-audio-player__dl",part:"download","aria-label":"Descargar",onClick:()=>this.download()},a("co-icon",{key:"f4d014129829ab57ddae0d3e32b1e0930f1bc288",name:"download-simple",size:14})))}static get watchers(){return{src:[{onSrcChange:0}]}}};r.style=":host{display:block;font-family:var(--co-font-family-primary)}.co-audio-player{display:flex;align-items:center;gap:var(--co-spacing-md);padding:var(--co-spacing-sm) var(--co-spacing-md);border:1px solid var(--co-semantic-border-default);border-radius:var(--co-border-radius-xs);background:var(--co-semantic-surface-secondary);min-width:180px}.co-audio-player--compact{gap:var(--co-spacing-sm2);padding:var(--co-spacing-sm2) var(--co-spacing-sm);min-width:140px}.co-audio-player__play{flex:0 0 auto;width:28px;height:28px;border:none;border-radius:50%;cursor:pointer;background:var(--co-semantic-surface-primary);color:var(--co-semantic-text-inverse);display:inline-flex;align-items:center;justify-content:center}.co-audio-player--compact .co-audio-player__play{width:24px;height:24px}.co-audio-player__play:disabled{opacity:.5;cursor:not-allowed}.co-audio-player__play:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px}.co-audio-player__wave{flex:1;height:40px;min-width:0;cursor:pointer;display:flex;align-items:center}.co-audio-player__wave:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px;border-radius:var(--co-border-radius-xxs)}.co-audio-player__svg{width:100%;height:100%;display:block}.co-audio-player__bar{fill:var(--co-semantic-border-field);transition:fill var(--co-motion-duration-fast)}.co-audio-player__wave:hover .co-audio-player__bar{fill:var(--co-semantic-text-muted)}.co-audio-player__bar--played{fill:var(--co-semantic-surface-primary)}.co-audio-player__time{flex:0 0 auto;font-size:var(--co-font-size-12);color:var(--co-semantic-text-muted);font-variant-numeric:tabular-nums;min-width:62px;text-align:right}.co-audio-player__speed{flex:0 0 auto;border:none;background:transparent;cursor:pointer;padding:2px 4px;color:var(--co-semantic-text-muted);font-family:var(--co-font-family-primary);font-size:var(--co-font-size-12);font-variant-numeric:tabular-nums;min-width:34px;text-align:center}.co-audio-player__speed:hover{color:var(--co-semantic-text-default)}.co-audio-player__speed:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px;border-radius:var(--co-border-radius-xxs)}.co-audio-player__dl{flex:0 0 auto;border:none;background:transparent;cursor:pointer;padding:2px;color:var(--co-semantic-text-muted);display:inline-flex}.co-audio-player__dl:hover{color:var(--co-semantic-text-default)}.co-audio-player__dl:focus-visible{outline:2px solid var(--co-semantic-border-focus);outline-offset:2px}.co-audio-player--error .co-audio-player__wave{opacity:.5}.co-audio-player--error .co-audio-player__play{background:var(--co-color-status-error);color:var(--co-semantic-text-inverse);opacity:1}";export{r as co_audio_player}
|