source: Klonkt/src/assets/js/embed-player.js@ cc24fa1

main
Last change on this file since cc24fa1 was 834bcc3, checked in by Robin Genis <roboburr@…>, 3 months ago

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 25.5 KB
Line 
1/**
2 * Klonkt Embed Player — custom, on-brand media embeds on top of the REAL
3 * player APIs (YouTube IFrame API, SoundCloud Widget API, Spotify iFrame API).
4 *
5 * The server (AudioEmbedService) renders a placeholder per embed:
6 * <div class="folio-embed folio-embed--<provider> pcms-embed-card"
7 * data-embed-provider data-embed-ref data-embed-type data-embed-url></div>
8 * This script wraps it in our own card (cover/poster + our play button +
9 * progress bar in brand style) and controls the underlying player via the
10 * platform API, so play/pause/progress are in OUR hands.
11 *
12 * Capability honesty:
13 * - youtube/soundcloud → fully custom controls (native chrome hidden).
14 * - spotify → controls + our frame around it; Spotify's own UI
15 * stays inside (no alternative without Premium+OAuth).
16 *
17 * Mutual exclusion: every player (incl. the site audio player in audio-player.js)
18 * registers itself in window.pcmsMediaRegistry. Starting one pauses the previous.
19 * This replaces the old focus/blur heuristic with real play events.
20 *
21 * Singleton — guard against double-init (HTMX can reload scripts).
22 */
23(function () {
24 if (window.pcmsEmbedPlayer) return;
25
26 // ============================================================
27 // 0. Shared playback registry (also used by audio-player.js)
28 // ============================================================
29 function registry() {
30 if (window.pcmsMediaRegistry) return window.pcmsMediaRegistry;
31 const r = {
32 _active: null,
33 // Mark `player` as the sole active one; pause the previous.
34 setActive(player) {
35 if (this._active && this._active !== player && this._active.pause) {
36 try { this._active.pause(); } catch (e) {}
37 }
38 this._active = player;
39 },
40 release(player) { if (this._active === player) this._active = null; },
41 };
42 window.pcmsMediaRegistry = r;
43 return r;
44 }
45
46 // ============================================================
47 // 1. Lazy script loaders — 1 promise per platform, shared across N embeds.
48 // A platform script is only loaded when an embed from that platform
49 // is actually started on the page.
50 // ============================================================
51 const scripts = {};
52 function loadScript(src) {
53 return new Promise((resolve, reject) => {
54 const s = document.createElement('script');
55 s.src = src; s.async = true;
56 s.onload = () => resolve();
57 s.onerror = () => reject(new Error('embed script failed: ' + src));
58 document.head.appendChild(s);
59 });
60 }
61 // Important: all loaders REJECT on script errors (e.g. an ad-blocker blocking
62 // the API script) and on timeout — so the caller can gracefully fall back to
63 // the plain platform iframe instead of hanging indefinitely.
64 const API_TIMEOUT = 8000;
65
66 // YouTube: global callback onYouTubeIframeAPIReady (once) → wrap in a promise.
67 function ytApi() {
68 if (scripts.yt) return scripts.yt;
69 scripts.yt = new Promise((resolve, reject) => {
70 if (window.YT && window.YT.Player) return resolve(window.YT);
71 const prev = window.onYouTubeIframeAPIReady;
72 window.onYouTubeIframeAPIReady = function () {
73 if (typeof prev === 'function') { try { prev(); } catch (e) {} }
74 resolve(window.YT);
75 };
76 loadScript('https://www.youtube.com/iframe_api').catch(reject);
77 setTimeout(() => reject(new Error('YT API timeout')), API_TIMEOUT);
78 });
79 return scripts.yt;
80 }
81 // SoundCloud: no global ready callback; resolve on script onload, then
82 // each widget waits for its own SC.Widget.Events.READY.
83 function scApi() {
84 if (scripts.sc) return scripts.sc;
85 scripts.sc = new Promise((resolve, reject) => {
86 if (window.SC && window.SC.Widget) return resolve(window.SC);
87 loadScript('https://w.soundcloud.com/player/api.js')
88 .then(() => resolve(window.SC)).catch(reject);
89 setTimeout(() => { (window.SC && window.SC.Widget) ? resolve(window.SC) : reject(new Error('SC API timeout')); }, API_TIMEOUT);
90 });
91 return scripts.sc;
92 }
93 // Spotify: global callback onSpotifyIframeApiReady(IFrameAPI) (once) → wrap in a promise.
94 function spotifyApi() {
95 if (scripts.sp) return scripts.sp;
96 scripts.sp = new Promise((resolve, reject) => {
97 if (window.__spotifyIframeApi) return resolve(window.__spotifyIframeApi);
98 window.onSpotifyIframeApiReady = function (IFrameAPI) {
99 window.__spotifyIframeApi = IFrameAPI;
100 resolve(IFrameAPI);
101 };
102 loadScript('https://open.spotify.com/embed/iframe-api/v1').catch(reject);
103 // Shorter than API_TIMEOUT: Spotify's bundle initialises quickly or not at all
104 // (CDN 503 / origin-gating). No need to wait 8 s before the iframe fallback.
105 setTimeout(() => reject(new Error('Spotify API timeout')), 4000);
106 });
107 return scripts.sp;
108 }
109
110 // Plain platform iframe as fallback when the JS API is blocked/unreachable.
111 // Ad-blockers generally let embed iframes through. Autoplay parameter
112 // is safe here because we're always in a user-gesture context (play click).
113 function fallbackIframe(provider, ref, url) {
114 if (provider === 'youtube') {
115 const id = ytId(ref, url);
116 return { src: 'https://www.youtube-nocookie.com/embed/' + encodeURIComponent(id) + '?autoplay=1&rel=0', ratio: true, fs: true };
117 }
118 if (provider === 'soundcloud') {
119 return { src: 'https://w.soundcloud.com/player/?url=' + encodeURIComponent(ref || url) + '&auto_play=true&visual=true&hide_related=true', h: '300px' };
120 }
121 if (provider === 'spotify') {
122 const m = (ref || '').match(/^spotify:(\w+):(\w+)$/);
123 return { src: m ? `https://open.spotify.com/embed/${m[1]}/${m[2]}` : (url || ''), h: '152px' };
124 }
125 return { src: url || '' };
126 }
127
128 // ============================================================
129 // 2. Helpers
130 // ============================================================
131 function fmt(sec) {
132 if (!sec || isNaN(sec) || sec < 0) return '0:00';
133 const m = Math.floor(sec / 60), s = Math.floor(sec % 60);
134 return m + ':' + (s < 10 ? '0' : '') + s;
135 }
136 function ytId(ref, url) {
137 if (ref && /^[A-Za-z0-9_-]{11}$/.test(ref)) return ref;
138 const m = (url || '').match(/(?:youtube\.com\/(?:watch\?(?:.*&)?v=|embed\/|shorts\/|live\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);
139 if (m) return m[1];
140 return null; // no blind slice — an invalid ref returns nothing rather than a broken id
141 }
142 // Only allow http(s) as href (defense-in-depth against javascript:/data: URIs).
143 function safeHref(u) {
144 try { const p = new URL(u, location.href); return (p.protocol === 'http:' || p.protocol === 'https:') ? u : '#'; }
145 catch (e) { return '#'; }
146 }
147 const ICON = {
148 play: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M8 4l12 8-12 8z" fill="currentColor"/></svg>',
149 pause: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4h4v16H7zM13 4h4v16h-4z" fill="currentColor"/></svg>',
150 volume: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 9v6h4l5 5V4L7 9H3z" fill="currentColor"/><path d="M16 8a5 5 0 010 8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
151 muted: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 9v6h4l5 5V4L7 9H3z" fill="currentColor"/><path d="M16 9l5 6M21 9l-5 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
152 };
153 const LABEL = { youtube: 'YouTube', soundcloud: 'SoundCloud', spotify: 'Spotify' };
154
155 // ============================================================
156 // 3. Card controller — builds the on-brand card + delegates to an adapter
157 // ============================================================
158 function buildCard(el) {
159 const provider = el.dataset.embedProvider;
160 const ref = el.dataset.embedRef || '';
161 const url = el.dataset.embedUrl || '';
162 if (!provider) return;
163
164 el.classList.add('pcms-embed-card', 'pcms-embed-card--' + provider);
165 el.classList.remove('pcms-embed-loading');
166
167 // Our player side (registry peer). pause() points to the adapter once
168 // mounted; before that it's a no-op.
169 let adapter = null;
170 const self = { pause() { if (adapter && adapter.pause) { try { adapter.pause(); } catch (e) {} } } };
171
172 // Teardown hook: called by the MutationObserver when this card leaves the
173 // DOM (HTMX swap) → clean up the adapter (timers/iframes) + release the registry,
174 // so no poll timers or players keep leaking.
175 el._pcmsDestroy = function () {
176 try { if (adapter && adapter.destroy) adapter.destroy(); } catch (e) {}
177 registry().release(self);
178 };
179
180 let playing = false;
181 let mounted = false;
182 let dur = 0;
183
184 // --- Mount the UI (differs per provider type) ---
185 const isVideo = provider === 'youtube';
186 const custom = provider === 'youtube' || provider === 'soundcloud'; // eigen controls
187 const poster = provider === 'youtube'
188 ? `https://i.ytimg.com/vi/${ytId(ref, url)}/hqdefault.jpg` : '';
189
190 el.innerHTML = ''
191 + (isVideo
192 ? `<div class="pcms-embed-stage"><div class="pcms-embed-mount"></div>`
193 + `<button type="button" class="pcms-embed-poster"${poster ? ` style="background-image:url('${poster}')"` : ''} aria-label="Afspelen">`
194 + `<span class="pcms-embed-bigplay">${ICON.play}</span></button></div>`
195 : `<div class="pcms-embed-audio">`
196 + `<button type="button" class="pcms-embed-art" aria-label="Afspelen"><span class="pcms-embed-bigplay">${ICON.play}</span></button>`
197 + `<div class="pcms-embed-info"><div class="pcms-embed-title">${LABEL[provider] || provider}</div>`
198 + `<div class="pcms-embed-sub"></div></div>`
199 + `<div class="pcms-embed-mount"></div></div>`)
200 + (custom
201 ? `<div class="pcms-embed-bar">`
202 + `<button type="button" class="pcms-embed-pp" aria-label="Afspelen/pauzeren">${ICON.play}</button>`
203 + `<span class="pcms-embed-cur mono">0:00</span>`
204 + `<div class="pcms-embed-seek" role="slider" aria-label="Voortgang" tabindex="0"><div class="pcms-embed-seek-fill"></div></div>`
205 + `<span class="pcms-embed-dur mono">0:00</span>`
206 + `<button type="button" class="pcms-embed-mute" aria-label="Dempen">${ICON.volume}</button>`
207 + `<input type="range" class="pcms-embed-vol" min="0" max="100" value="100" aria-label="Volume">`
208 + `<a class="pcms-embed-badge" href="${escAttr(safeHref(url))}" target="_blank" rel="noopener">${LABEL[provider] || provider}</a>`
209 + `</div>`
210 : `<div class="pcms-embed-frame-badge"><a href="${escAttr(safeHref(url))}" target="_blank" rel="noopener">via ${LABEL[provider] || provider}</a></div>`);
211
212 const mountEl = el.querySelector('.pcms-embed-mount');
213 const ppBtn = el.querySelector('.pcms-embed-pp');
214 const curEl = el.querySelector('.pcms-embed-cur');
215 const durEl = el.querySelector('.pcms-embed-dur');
216 const seekEl = el.querySelector('.pcms-embed-seek');
217 const seekFill = el.querySelector('.pcms-embed-seek-fill');
218 const posterBtn = el.querySelector('.pcms-embed-poster, .pcms-embed-art');
219 const subEl = el.querySelector('.pcms-embed-sub');
220 const volEl = el.querySelector('.pcms-embed-vol');
221 const muteBtn = el.querySelector('.pcms-embed-mute');
222 let vol = 100; // current volume 0-100 (applied to the adapter)
223 let preMuteVol = 100;
224
225 function setPlayingUI(on) {
226 playing = on;
227 el.classList.toggle('is-playing', on);
228 if (ppBtn) ppBtn.innerHTML = on ? ICON.pause : ICON.play;
229 }
230 function setProgress(cur, total) {
231 if (total > 0) { dur = total; if (durEl) durEl.textContent = fmt(total); }
232 if (curEl) curEl.textContent = fmt(cur);
233 if (seekFill && dur > 0) seekFill.style.width = Math.max(0, Math.min(100, (cur / dur) * 100)) + '%';
234 }
235
236 const hooks = {
237 onReady(meta) {
238 el.classList.add('is-ready');
239 el.classList.remove('pcms-embed-busy');
240 if (meta && meta.title && subEl) subEl.textContent = meta.title;
241 if (meta && meta.artwork) {
242 const art = el.querySelector('.pcms-embed-art');
243 if (art) { art.style.backgroundImage = `url('${meta.artwork}')`; art.classList.add('has-art'); }
244 }
245 if (meta && meta.duration) setProgress(0, meta.duration);
246 },
247 onPlay() { setPlayingUI(true); registry().setActive(self); },
248 onPause() { setPlayingUI(false); },
249 onEnded() { setPlayingUI(false); setProgress(0, dur); registry().release(self); },
250 onProgress(cur, total) { setProgress(cur, total); },
251 };
252
253 // API blocked/unreachable → plain platform iframe (graceful degradation).
254 // Mutual exclusion for this fallback runs via the blur heuristic
255 // (audio-player.js), because the card never gets .is-mounted.
256 function renderFallback() {
257 const fb = fallbackIframe(provider, ref, url);
258 if (!fb.src) { el.classList.remove('pcms-embed-busy'); el.classList.add('pcms-embed-error'); return; }
259 const iframe = document.createElement('iframe');
260 iframe.src = fb.src;
261 iframe.loading = 'lazy';
262 iframe.title = LABEL[provider] || provider;
263 iframe.setAttribute('allow', 'autoplay; encrypted-media; clipboard-write; picture-in-picture; fullscreen');
264 if (fb.fs) iframe.allowFullscreen = true;
265 iframe.style.cssText = fb.ratio
266 ? 'width:100%;aspect-ratio:16/9;border:0;display:block;'
267 : 'width:100%;height:' + (fb.h || '152px') + ';border:0;display:block;';
268 el.classList.remove('is-mounted', 'pcms-embed-busy');
269 el.classList.add('pcms-embed-fallback');
270 el.innerHTML = '';
271 el.appendChild(iframe);
272
273 // Mutual exclusion also for the fallback iframe. A cross-origin iframe
274 // cannot be paused via an API, so 'pause' = reload WITHOUT
275 // autoplay (= stops the audio, player stays visible/restartable).
276 // We register it as active: now (= user starts the embed) the
277 // site player/other embeds pause; and when the site player starts later,
278 // the registry pauses this fallback.
279 self.pause = function () {
280 try {
281 const noAuto = fb.src
282 .replace(/([?&])(?:autoplay=1|auto_play=true)(&|$)/gi, '$1')
283 .replace(/[?&]$/, '');
284 if (iframe.src === noAuto) {
285 // src ongewijzigd (bv. Spotify zonder autoplay) → forceer een reload
286 iframe.src = 'about:blank';
287 setTimeout(() => { try { iframe.src = noAuto; } catch (e) {} }, 30);
288 } else {
289 iframe.src = noAuto;
290 }
291 } catch (e) {}
292 };
293 registry().setActive(self);
294 }
295
296 // First interaction → mount the adapter + play. The button toggles after that.
297 async function ensureMountedAndPlay() {
298 if (mounted) { if (adapter) adapter.play(); return; }
299 mounted = true;
300 // Spotify: their player cannot be skinned (controls-only) and the
301 // iFrame API bundle often fails to initialise in practice (CDN-gating/503)
302 // → don't wait for the API, show the plain Spotify iframe immediately.
303 if (provider === 'spotify') { renderFallback(); return; }
304 el.classList.add('pcms-embed-busy');
305 try {
306 adapter = await MOUNTERS[provider](mountEl, { ref, url }, hooks);
307 if (el._pcmsApplyVol) el._pcmsApplyVol(); // onthouden volume toepassen
308 // is-mounted: CSS hides the poster (video) or Spotify facade and
309 // shows the real player. For SoundCloud our card+bar stays visible and
310 // the (functional) iframe remains hidden off-screen.
311 el.classList.add('is-mounted');
312 adapter.play();
313 } catch (err) {
314 console.warn('[pcms-embed] API unavailable, falling back to plain iframe', provider, err);
315 renderFallback();
316 }
317 }
318
319 if (posterBtn) posterBtn.addEventListener('click', ensureMountedAndPlay);
320 if (ppBtn) ppBtn.addEventListener('click', () => {
321 if (!mounted) return ensureMountedAndPlay();
322 if (playing) { adapter && adapter.pause(); } else { adapter && adapter.play(); }
323 });
324 if (seekEl) seekEl.addEventListener('click', (e) => {
325 if (!adapter || !adapter.seek || !dur) return;
326 const rect = seekEl.getBoundingClientRect();
327 const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
328 adapter.seek(ratio * dur);
329 });
330 // Volume: slider sets vol (0-100) and applies it to the adapter (YT/SC support
331 // setVolume). The value is remembered and reapplied after mounting.
332 function applyVol() {
333 if (adapter && adapter.setVolume) { try { adapter.setVolume(vol); } catch (e) {} }
334 if (muteBtn) muteBtn.innerHTML = vol === 0 ? ICON.muted : ICON.volume;
335 if (volEl && String(volEl.value) !== String(vol)) volEl.value = vol;
336 el.classList.toggle('is-muted', vol === 0);
337 }
338 if (volEl) volEl.addEventListener('input', () => { vol = parseInt(volEl.value, 10) || 0; if (vol > 0) preMuteVol = vol; applyVol(); });
339 if (muteBtn) muteBtn.addEventListener('click', () => {
340 if (vol > 0) { preMuteVol = vol; vol = 0; } else { vol = preMuteVol || 100; }
341 applyVol();
342 });
343 el._pcmsApplyVol = applyVol; // called by ensureMountedAndPlay after mount
344 }
345
346 function escAttr(s) {
347 return String(s || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
348 }
349
350 // ============================================================
351 // 4. Adapters — normalise the 3 very different APIs to one common shape.
352 // Each mounter returns { play, pause, seek } and calls hooks with
353 // seconds (units are normalised here).
354 // ============================================================
355 const MOUNTERS = {
356 // ---- YouTube: IFrame Player API, eigen controls (controls:0) ----
357 async youtube(mountEl, { ref, url }, hooks) {
358 const YT = await ytApi();
359 const id = ytId(ref, url);
360 return new Promise((resolve, reject) => {
361 let pollTimer = null;
362 const player = new YT.Player(mountEl, {
363 videoId: id,
364 host: 'https://www.youtube-nocookie.com',
365 playerVars: {
366 controls: 0, modestbranding: 1, rel: 0, playsinline: 1, fs: 0,
367 disablekb: 1, iv_load_policy: 3, origin: window.location.origin,
368 },
369 events: {
370 onReady() {
371 let d = 0; try { d = player.getDuration() || 0; } catch (e) {}
372 hooks.onReady({ duration: d });
373 resolve({
374 play() { try { player.playVideo(); } catch (e) {} },
375 pause() { try { player.pauseVideo(); } catch (e) {} },
376 seek(sec) { try { player.seekTo(sec, true); } catch (e) {} },
377 setVolume(pct) { try { if (pct <= 0) player.mute(); else { player.unMute(); player.setVolume(pct); } } catch (e) {} },
378 destroy() {
379 if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
380 try { player.destroy(); } catch (e) {}
381 },
382 });
383 },
384 onStateChange(e) {
385 // -1 unstarted, 0 ended, 1 playing, 2 paused, 3 buffering, 5 cued
386 if (e.data === 1) {
387 hooks.onPlay();
388 if (!pollTimer) pollTimer = setInterval(() => {
389 try { hooks.onProgress(player.getCurrentTime() || 0, player.getDuration() || 0); } catch (e) {}
390 }, 250);
391 } else if (e.data === 2) {
392 hooks.onPause();
393 if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
394 } else if (e.data === 0) {
395 hooks.onEnded();
396 if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
397 }
398 },
399 onError() { reject(new Error('YT error')); },
400 },
401 });
402 });
403 },
404
405 // ---- SoundCloud: Widget API, visual=false, custom controls ----
406 async soundcloud(mountEl, { ref, url }, hooks) {
407 const SC = await scApi();
408 // Build the iframe ourselves (bare bar) and then attach SC.Widget to it.
409 const iframe = document.createElement('iframe');
410 iframe.allow = 'autoplay';
411 iframe.title = 'SoundCloud';
412 const params = new URLSearchParams({
413 url: ref || url, visual: 'false', auto_play: 'false', hide_related: 'true',
414 show_comments: 'false', show_user: 'false', show_teaser: 'false',
415 sharing: 'false', buy: 'false', download: 'false', show_artwork: 'true',
416 single_active: 'true', color: 'ff5500',
417 });
418 iframe.src = 'https://w.soundcloud.com/player/?' + params.toString();
419 mountEl.appendChild(iframe);
420 const widget = SC.Widget(iframe);
421 const E = SC.Widget.Events;
422 return new Promise((resolve, reject) => {
423 let resolved = false;
424 widget.bind(E.READY, () => {
425 widget.getCurrentSound((sound) => {
426 const meta = sound ? {
427 title: sound.title || '',
428 artwork: (sound.artwork_url || (sound.user && sound.user.avatar_url) || '').replace('-large', '-t300x300'),
429 } : {};
430 widget.getDuration((ms) => { meta.duration = (ms || 0) / 1000; hooks.onReady(meta); });
431 });
432 resolved = true;
433 resolve({
434 play() { widget.play(); },
435 pause() { widget.pause(); },
436 seek(sec) { widget.seekTo(sec * 1000); },
437 setVolume(pct) { try { widget.setVolume(pct); } catch (e) {} },
438 destroy() {
439 try { ['READY', 'PLAY', 'PAUSE', 'FINISH', 'PLAY_PROGRESS', 'ERROR'].forEach((k) => E[k] && widget.unbind(E[k])); } catch (e) {}
440 try { iframe.remove(); } catch (e) {}
441 },
442 });
443 });
444 widget.bind(E.PLAY, () => hooks.onPlay());
445 widget.bind(E.PAUSE, () => hooks.onPause());
446 widget.bind(E.FINISH, () => hooks.onEnded());
447 widget.bind(E.PLAY_PROGRESS, (d) => {
448 hooks.onProgress((d.currentPosition || 0) / 1000, 0);
449 });
450 widget.bind(E.ERROR, () => { if (!resolved) reject(new Error('SC error')); });
451 setTimeout(() => { if (!resolved) reject(new Error('SC timeout')); }, 12000);
452 });
453 },
454
455 // ---- Spotify: iFrame API — controls + our frame; no custom skin ----
456 async spotify(mountEl, { ref, url }, hooks) {
457 const IFrameAPI = await spotifyApi();
458 const uri = ref || url;
459 return new Promise((resolve, reject) => {
460 let lastPaused = true, resolved = false;
461 IFrameAPI.createController(mountEl, { uri, width: '100%', height: 152 }, (controller) => {
462 controller.addListener('ready', () => {
463 hooks.onReady({});
464 resolved = true;
465 resolve({
466 play() { try { controller.resume(); } catch (e) { try { controller.play(); } catch (e2) {} } },
467 pause() { try { controller.pause(); } catch (e) {} },
468 seek(sec) { try { controller.seek(sec); } catch (e) {} },
469 destroy() { try { controller.destroy(); } catch (e) {} },
470 });
471 });
472 controller.addListener('playback_update', (e) => {
473 const d = e && e.data ? e.data : {};
474 hooks.onProgress((d.position || 0) / 1000, (d.duration || 0) / 1000);
475 // No reliable 'ended' event from Spotify; we treat every
476 // isPaused transition as play/pause. End = just a pause (the bar
477 // stays at the end position rather than misleadingly jumping to 0).
478 if (d.isPaused === false && lastPaused) { lastPaused = false; hooks.onPlay(); }
479 else if (d.isPaused === true && !lastPaused) { lastPaused = true; hooks.onPause(); }
480 });
481 });
482 setTimeout(() => { if (!resolved) reject(new Error('Spotify timeout')); }, 12000);
483 });
484 },
485 };
486
487 // ============================================================
488 // 5. Scan + HTMX/DOM-mutation-aware (the site partially navigates via HTMX swaps)
489 // ============================================================
490 function scan(root) {
491 (root || document).querySelectorAll('.folio-embed[data-embed-provider]').forEach((el) => {
492 if (el.dataset.embedInit) return;
493 el.dataset.embedInit = '1';
494 try { buildCard(el); } catch (e) { console.error('[pcms-embed] buildCard failed', e); }
495 });
496 }
497
498 if (document.readyState === 'loading') {
499 document.addEventListener('DOMContentLoaded', () => scan(document));
500 } else {
501 scan(document);
502 }
503 // HTMX replaces #pcms-main on internal navigation → rescan.
504 document.body.addEventListener('htmx:afterSwap', (e) => scan(e.target || document));
505 document.body.addEventListener('htmx:load', (e) => scan(e.target || document));
506
507 // Teardown on DOM removal (HTMX replaces #pcms-main innerHTML, or an SPA-like
508 // swap). Without this, YouTube poll timers + adapters/iframes linger when
509 // navigating away while an embed is playing → CPU/memory leak that accumulates
510 // per navigation. We call el._pcmsDestroy() for every card that truly leaves the document.
511 const teardownObserver = new MutationObserver((muts) => {
512 for (const m of muts) {
513 m.removedNodes.forEach((node) => {
514 if (node.nodeType !== 1) return;
515 const cards = [];
516 if (node.matches && node.matches('.folio-embed[data-embed-init]')) cards.push(node);
517 if (node.querySelectorAll) node.querySelectorAll('.folio-embed[data-embed-init]').forEach((c) => cards.push(c));
518 cards.forEach((c) => {
519 if (typeof c._pcmsDestroy === 'function' && !document.contains(c)) {
520 try { c._pcmsDestroy(); } catch (e) {}
521 }
522 });
523 });
524 }
525 });
526 try { teardownObserver.observe(document.body, { childList: true, subtree: true }); } catch (e) {}
527
528 window.pcmsEmbedPlayer = { scan, registry };
529})();
Note: See TracBrowser for help on using the repository browser.