| [4c9f29a] | 1 | /**
|
|---|
| [8453812] | 2 | * Klonkt Embed Player — eigen, in-huisstijl media-embeds bovenop de ÉCHTE
|
|---|
| [4c9f29a] | 3 | * player-API's (YouTube IFrame API, SoundCloud Widget API, Spotify iFrame API).
|
|---|
| 4 | *
|
|---|
| 5 | * De server (AudioEmbedService) rendert per embed een placeholder:
|
|---|
| 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 | * Dit script bouwt daar onze eigen kaart omheen (cover/poster + onze play-knop +
|
|---|
| 9 | * voortgangsbalk in huisstijl) en bestuurt de onderliggende speler via de
|
|---|
| 10 | * platform-API, zodat play/pause/voortgang in ÓNZE handen liggen.
|
|---|
| 11 | *
|
|---|
| 12 | * Capability-eerlijkheid:
|
|---|
| 13 | * - youtube/soundcloud → volledig eigen controls (native chrome verborgen).
|
|---|
| 14 | * - spotify → besturing + onze frame eromheen; Spotify's eigen UI
|
|---|
| 15 | * blijft binnenin (kan niet anders zonder Premium+OAuth).
|
|---|
| 16 | *
|
|---|
| 17 | * Mutual exclusion: elke speler (incl. de site-audiospeler in audio-player.js)
|
|---|
| 18 | * registreert zich in window.pcmsMediaRegistry. Start er één → de vorige pauzeert.
|
|---|
| 19 | * Dit vervangt de oude focus/blur-heuristiek door echte play-events.
|
|---|
| 20 | *
|
|---|
| 21 | * Singleton — guard tegen dubbel-init (HTMX laadt scripts soms opnieuw).
|
|---|
| 22 | */
|
|---|
| 23 | (function () {
|
|---|
| 24 | if (window.pcmsEmbedPlayer) return;
|
|---|
| 25 |
|
|---|
| 26 | // ============================================================
|
|---|
| 27 | // 0. Gedeelde playback-registry (ook door audio-player.js gebruikt)
|
|---|
| 28 | // ============================================================
|
|---|
| 29 | function registry() {
|
|---|
| 30 | if (window.pcmsMediaRegistry) return window.pcmsMediaRegistry;
|
|---|
| 31 | const r = {
|
|---|
| 32 | _active: null,
|
|---|
| 33 | // Markeer `player` als de enige actieve; pauzeer de vorige.
|
|---|
| 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, gedeeld over N embeds.
|
|---|
| 48 | // We laden een platform-script PAS als er een embed van dat platform op de
|
|---|
| 49 | // pagina daadwerkelijk wordt gestart.
|
|---|
| 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 faalde: ' + src));
|
|---|
| 58 | document.head.appendChild(s);
|
|---|
| 59 | });
|
|---|
| 60 | }
|
|---|
| 61 | // Belangrijk: alle loaders REJECTEN bij een script-fout (bv. een ad-blocker die
|
|---|
| 62 | // het API-script blokkeert) én na een time-out — zodat de aanroeper netjes kan
|
|---|
| 63 | // terugvallen op het kale platform-iframe i.p.v. eeuwig te hangen.
|
|---|
| 64 | const API_TIMEOUT = 8000;
|
|---|
| 65 |
|
|---|
| 66 | // YouTube: globale callback onYouTubeIframeAPIReady (1×) → in promise wikkelen.
|
|---|
| 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: geen globale ready-callback; resolve op script-onload, daarna
|
|---|
| 82 | // wacht elke widget op z'n eigen 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: globale callback onSpotifyIframeApiReady(IFrameAPI) (1×) → wrappen.
|
|---|
| 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);
|
|---|
| [16b0c00] | 103 | // Korter dan API_TIMEOUT: Spotify's bundle initialiseert snel óf helemaal
|
|---|
| 104 | // niet (CDN 503 / origin-gating). Niet 8s wachten vóór de iframe-fallback.
|
|---|
| 105 | setTimeout(() => reject(new Error('Spotify API timeout')), 4000);
|
|---|
| [4c9f29a] | 106 | });
|
|---|
| 107 | return scripts.sp;
|
|---|
| 108 | }
|
|---|
| 109 |
|
|---|
| 110 | // Kaal platform-iframe als fallback wanneer de JS-API geblokkeerd/onbereikbaar
|
|---|
| 111 | // is. Ad-blockers laten de embed-iframes doorgaans wél door. Autoplay-param
|
|---|
| 112 | // omdat we hier altijd in een user-gesture-context zitten (klik op play).
|
|---|
| 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; // geen blinde slice — een ongeldige ref geeft liever niets dan een kapotte id
|
|---|
| 141 | }
|
|---|
| 142 | // Alleen http(s) als href toelaten (defense-in-depth tegen javascript:/data:).
|
|---|
| 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>',
|
|---|
| [557a76f] | 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>',
|
|---|
| [4c9f29a] | 152 | };
|
|---|
| 153 | const LABEL = { youtube: 'YouTube', soundcloud: 'SoundCloud', spotify: 'Spotify' };
|
|---|
| 154 |
|
|---|
| 155 | // ============================================================
|
|---|
| 156 | // 3. Card controller — bouwt de huisstijl-kaart + delegeert naar een 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 | // Onze speler-zijde (registry-peer). pause() wijst naar de adapter zodra die
|
|---|
| 168 | // gemount is; ervoor is 't een no-op.
|
|---|
| 169 | let adapter = null;
|
|---|
| 170 | const self = { pause() { if (adapter && adapter.pause) { try { adapter.pause(); } catch (e) {} } } };
|
|---|
| 171 |
|
|---|
| 172 | // Teardown-hook: aangeroepen door de MutationObserver als deze kaart uit de
|
|---|
| 173 | // DOM verdwijnt (HTMX-swap) → adapter opruimen (timers/iframes) + registry
|
|---|
| 174 | // vrijgeven, zodat er geen poll-timers of spelers blijven lekken.
|
|---|
| 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 | // --- UI ophangen (verschilt per provider-type) ---
|
|---|
| [fef781e] | 185 | const isVideo = provider === 'youtube';
|
|---|
| 186 | const custom = provider === 'youtube' || provider === 'soundcloud'; // eigen controls
|
|---|
| [4c9f29a] | 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>`
|
|---|
| [557a76f] | 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">`
|
|---|
| [4c9f29a] | 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');
|
|---|
| [557a76f] | 220 | const volEl = el.querySelector('.pcms-embed-vol');
|
|---|
| 221 | const muteBtn = el.querySelector('.pcms-embed-mute');
|
|---|
| 222 | let vol = 100; // huidige volume 0-100 (wordt op de adapter toegepast)
|
|---|
| 223 | let preMuteVol = 100;
|
|---|
| [4c9f29a] | 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 geblokkeerd/onbereikbaar → kaal platform-iframe (graceful degradation).
|
|---|
| 254 | // De mutual-exclusion loopt voor deze fallback via de blur-heuristiek
|
|---|
| 255 | // (audio-player.js), want de kaart krijgt geen .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);
|
|---|
| [33886fb] | 272 |
|
|---|
| 273 | // Mutual exclusion óók voor de fallback-iframe. Een cross-origin iframe
|
|---|
| 274 | // kunnen we niet via een API pauzeren, dus 'pauze' = herladen ZONDER
|
|---|
| 275 | // autoplay (= stopt het geluid, speler blijft zichtbaar/herstartbaar).
|
|---|
| 276 | // We registreren 'm als actief: nu (= gebruiker start de embed) pauzeert de
|
|---|
| 277 | // site-speler/andere embeds; en als de site-speler later start, pauzeert de
|
|---|
| 278 | // registry deze 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);
|
|---|
| [4c9f29a] | 294 | }
|
|---|
| 295 |
|
|---|
| 296 | // Eerste interactie → adapter mounten + spelen. Daarna toggelt de knop.
|
|---|
| 297 | async function ensureMountedAndPlay() {
|
|---|
| 298 | if (mounted) { if (adapter) adapter.play(); return; }
|
|---|
| 299 | mounted = true;
|
|---|
| [2873b30] | 300 | // Spotify: hun speler is toch niet te skinnen (besturing-only) én de
|
|---|
| 301 | // iFrame-API-bundle initialiseert in de praktijk vaak niet (CDN-gating/503)
|
|---|
| 302 | // → niet op de API wachten, meteen het kale Spotify-iframe tonen. Instant.
|
|---|
| 303 | if (provider === 'spotify') { renderFallback(); return; }
|
|---|
| [4c9f29a] | 304 | el.classList.add('pcms-embed-busy');
|
|---|
| 305 | try {
|
|---|
| 306 | adapter = await MOUNTERS[provider](mountEl, { ref, url }, hooks);
|
|---|
| [557a76f] | 307 | if (el._pcmsApplyVol) el._pcmsApplyVol(); // onthouden volume toepassen
|
|---|
| [4c9f29a] | 308 | // is-mounted: CSS verbergt de poster (video) of de Spotify-facade en
|
|---|
| 309 | // toont de echte speler. Voor SoundCloud blijft onze kaart+balk staan en
|
|---|
| 310 | // blijft het (functionele) iframe off-screen verborgen.
|
|---|
| 311 | el.classList.add('is-mounted');
|
|---|
| 312 | adapter.play();
|
|---|
| 313 | } catch (err) {
|
|---|
| 314 | console.warn('[pcms-embed] API niet beschikbaar, val terug op kaal 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 | });
|
|---|
| [557a76f] | 330 | // Volume: schuif zet vol (0-100) en past 'm toe op de adapter (YT/SC hebben
|
|---|
| 331 | // setVolume). De waarde wordt onthouden en na het mounten opnieuw toegepast.
|
|---|
| 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; // door ensureMountedAndPlay aangeroepen na mount
|
|---|
| [4c9f29a] | 344 | }
|
|---|
| 345 |
|
|---|
| 346 | function escAttr(s) {
|
|---|
| 347 | return String(s || '').replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
|---|
| 348 | }
|
|---|
| 349 |
|
|---|
| 350 | // ============================================================
|
|---|
| 351 | // 4. Adapters — normaliseren de 3 zeer verschillende API's naar 1 vorm.
|
|---|
| 352 | // Elke mounter geeft { play, pause, seek } terug en roept hooks aan met
|
|---|
| 353 | // seconden (units worden hier rechtgetrokken).
|
|---|
| 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() {
|
|---|
| [fef781e] | 371 | let d = 0; try { d = player.getDuration() || 0; } catch (e) {}
|
|---|
| 372 | hooks.onReady({ duration: d });
|
|---|
| [4c9f29a] | 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) {} },
|
|---|
| [557a76f] | 377 | setVolume(pct) { try { if (pct <= 0) player.mute(); else { player.unMute(); player.setVolume(pct); } } catch (e) {} },
|
|---|
| [4c9f29a] | 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, eigen controls ----
|
|---|
| 406 | async soundcloud(mountEl, { ref, url }, hooks) {
|
|---|
| 407 | const SC = await scApi();
|
|---|
| 408 | // Iframe zelf bouwen (kale balk) en daarna SC.Widget eraan hangen.
|
|---|
| 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); },
|
|---|
| [557a76f] | 437 | setVolume(pct) { try { widget.setVolume(pct); } catch (e) {} },
|
|---|
| [4c9f29a] | 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 — besturing + onze frame; geen eigen 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 | // Geen betrouwbare 'ended'-event bij Spotify; we behandelen elke
|
|---|
| 476 | // isPaused-overgang als play/pause. Einde = gewoon een pauze (de balk
|
|---|
| 477 | // blijft op de eindpositie i.p.v. misleidend naar 0 te springen).
|
|---|
| 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-mutatie-aware (de site navigeert deels 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 faalde', e); }
|
|---|
| 495 | });
|
|---|
| 496 | }
|
|---|
| 497 |
|
|---|
| 498 | if (document.readyState === 'loading') {
|
|---|
| 499 | document.addEventListener('DOMContentLoaded', () => scan(document));
|
|---|
| 500 | } else {
|
|---|
| 501 | scan(document);
|
|---|
| 502 | }
|
|---|
| 503 | // HTMX vervangt #pcms-main bij interne navigatie → opnieuw scannen.
|
|---|
| 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 bij verwijdering uit de DOM (HTMX vervangt #pcms-main innerHTML, of
|
|---|
| 508 | // een SPA-achtige swap). Zonder dit blijven YouTube-poll-timers + adapters/
|
|---|
| 509 | // iframes hangen als je wegnavigeert terwijl een embed speelt → CPU/geheugenlek
|
|---|
| 510 | // dat per navigatie opstapelt. We roepen el._pcmsDestroy() aan voor elke kaart
|
|---|
| 511 | // die echt uit het document verdwijnt.
|
|---|
| 512 | const teardownObserver = new MutationObserver((muts) => {
|
|---|
| 513 | for (const m of muts) {
|
|---|
| 514 | m.removedNodes.forEach((node) => {
|
|---|
| 515 | if (node.nodeType !== 1) return;
|
|---|
| 516 | const cards = [];
|
|---|
| 517 | if (node.matches && node.matches('.folio-embed[data-embed-init]')) cards.push(node);
|
|---|
| 518 | if (node.querySelectorAll) node.querySelectorAll('.folio-embed[data-embed-init]').forEach((c) => cards.push(c));
|
|---|
| 519 | cards.forEach((c) => {
|
|---|
| 520 | if (typeof c._pcmsDestroy === 'function' && !document.contains(c)) {
|
|---|
| 521 | try { c._pcmsDestroy(); } catch (e) {}
|
|---|
| 522 | }
|
|---|
| 523 | });
|
|---|
| 524 | });
|
|---|
| 525 | }
|
|---|
| 526 | });
|
|---|
| 527 | try { teardownObserver.observe(document.body, { childList: true, subtree: true }); } catch (e) {}
|
|---|
| 528 |
|
|---|
| 529 | window.pcmsEmbedPlayer = { scan, registry };
|
|---|
| 530 | })();
|
|---|