| [7bc636b] | 1 | /**
|
|---|
| 2 | * PrutCMS v10 Audio Player — v9 mini-player + Spotify-style sheet.
|
|---|
| 3 | *
|
|---|
| 4 | * Two surfaces:
|
|---|
| 5 | * 1. .audio-player — bottom strip: cover + meta + controls + progress + volume
|
|---|
| 6 | * 2. .audio-sheet — full-height now-playing panel (slides up from bottom)
|
|---|
| 7 | *
|
|---|
| 8 | * Features:
|
|---|
| 9 | * - Click cover/meta on mini-player → open sheet
|
|---|
| 10 | * - Sheet handle (pill) or backdrop click → close
|
|---|
| 11 | * - Touch swipe-down on the drag-zone → close (mobile only; desktop has the X)
|
|---|
| 12 | * - Reads data-pcms-track-url + data-pcms-track + data-pcms-album from posts
|
|---|
| 13 | * - body.has-audio-player adds bottom padding when player visible
|
|---|
| 14 | * - body.audio-sheet-locked prevents body scroll when sheet open
|
|---|
| 15 | * - Survives HTMX swaps via htmx:afterSettle re-attach
|
|---|
| 16 | *
|
|---|
| 17 | * Singleton — guards against double-init.
|
|---|
| 18 | */
|
|---|
| 19 | (function() {
|
|---|
| 20 | if (window.pcmsAudioPlayer) return;
|
|---|
| 21 |
|
|---|
| 22 | const SVG = {
|
|---|
| 23 | play: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M8 4l12 8-12 8z" fill="currentColor"/></svg>',
|
|---|
| 24 | pause: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4h4v16H7zM13 4h4v16h-4z" fill="currentColor"/></svg>',
|
|---|
| 25 | prev: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 5v14M20 5l-11 7 11 7V5z" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
|---|
| 26 | next: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M17 5v14M4 5l11 7-11 7V5z" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
|---|
| 27 | vol: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 9v6h4l5 5V4L7 9H3zM16 8a5 5 0 010 8M19 5a9 9 0 010 14" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
|---|
| 28 | mute: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 9v6h4l5 5V4L7 9H3zM17 9l5 5M22 9l-5 5" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
|---|
| 29 | musicNote: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 17V5l12-2v12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="6" cy="17" r="3" fill="currentColor"/><circle cx="18" cy="15" r="3" fill="currentColor"/></svg>',
|
|---|
| 30 | };
|
|---|
| 31 |
|
|---|
| 32 | // ============================================================
|
|---|
| 33 | // 1. Build DOM
|
|---|
| 34 | // ============================================================
|
|---|
| 35 | const root = document.createElement('aside');
|
|---|
| 36 | root.id = 'pcms-audio-player';
|
|---|
| 37 | root.className = 'audio-player';
|
|---|
| 38 | root.setAttribute('aria-label', 'Audio speler');
|
|---|
| 39 | root.innerHTML = `
|
|---|
| 40 | <div class="audio-player-inner">
|
|---|
| 41 | <button type="button" class="audio-player-expand-trigger" id="audio-expand-trigger" aria-label="Vergroot speler">
|
|---|
| 42 | <div class="audio-player-cover" id="audio-cover" aria-hidden="true">${SVG.musicNote}</div>
|
|---|
| 43 | <div class="audio-player-meta">
|
|---|
| 44 | <div class="audio-player-title-wrap"><span class="audio-player-title" id="audio-title">No track</span></div>
|
|---|
| 45 | <div class="audio-player-artist" id="audio-artist"></div>
|
|---|
| 46 | </div>
|
|---|
| 47 | </button>
|
|---|
| 48 | <div class="audio-player-controls">
|
|---|
| 49 | <button type="button" class="audio-btn" id="audio-prev" aria-label="Vorige" title="Vorige">${SVG.prev}</button>
|
|---|
| 50 | <button type="button" class="audio-btn audio-btn-play" id="audio-play" aria-label="Afspelen">
|
|---|
| 51 | <span class="icon-play">${SVG.play}</span><span class="icon-pause">${SVG.pause}</span>
|
|---|
| 52 | </button>
|
|---|
| 53 | <button type="button" class="audio-btn" id="audio-next" aria-label="Volgende" title="Volgende">${SVG.next}</button>
|
|---|
| 54 | </div>
|
|---|
| 55 | <div class="audio-player-progress">
|
|---|
| 56 | <span class="audio-time mono" id="audio-current">0:00</span>
|
|---|
| 57 | <div class="audio-seek" id="audio-seek" role="slider" aria-label="Voortgang" tabindex="0">
|
|---|
| 58 | <div class="audio-seek-bar"><div class="audio-seek-fill" id="audio-seek-fill"></div></div>
|
|---|
| 59 | </div>
|
|---|
| 60 | <span class="audio-time mono" id="audio-total">0:00</span>
|
|---|
| 61 | </div>
|
|---|
| 62 | <div class="audio-player-volume">
|
|---|
| 63 | <button type="button" class="audio-btn" id="audio-mute" aria-label="Mute">
|
|---|
| 64 | <span class="icon-vol">${SVG.vol}</span><span class="icon-mute">${SVG.mute}</span>
|
|---|
| 65 | </button>
|
|---|
| 66 | <div class="audio-volume-popup">
|
|---|
| 67 | <input type="range" id="audio-volume" min="0" max="100" value="80" aria-label="Volume">
|
|---|
| 68 | </div>
|
|---|
| 69 | </div>
|
|---|
| 70 | </div>
|
|---|
| 71 | <audio id="audio-element" preload="none" playsinline webkit-playsinline controlsList="nodownload"></audio>
|
|---|
| 72 |
|
|---|
| 73 | <div class="audio-sheet" id="audio-sheet" aria-hidden="true">
|
|---|
| 74 | <div class="audio-sheet-backdrop" id="audio-sheet-backdrop"></div>
|
|---|
| 75 | <div class="audio-sheet-panel" role="dialog" aria-label="Now playing">
|
|---|
| 76 | <div class="audio-sheet-drag-zone" id="audio-sheet-drag-zone">
|
|---|
| 77 | <button type="button" class="audio-sheet-handle" id="audio-sheet-close" aria-label="Speler verkleinen"></button>
|
|---|
| 78 | <div class="audio-sheet-cover" id="audio-sheet-cover" aria-hidden="true">${SVG.musicNote}</div>
|
|---|
| 79 | </div>
|
|---|
| 80 | <div class="audio-sheet-info">
|
|---|
| 81 | <div class="audio-sheet-title" id="audio-sheet-title">—</div>
|
|---|
| 82 | <div class="audio-sheet-artist" id="audio-sheet-artist"></div>
|
|---|
| 83 | <div class="audio-sheet-album" id="audio-sheet-album"></div>
|
|---|
| 84 | </div>
|
|---|
| 85 | <div class="audio-sheet-progress">
|
|---|
| 86 | <span class="audio-time mono" id="audio-sheet-current">0:00</span>
|
|---|
| 87 | <div class="audio-seek" id="audio-sheet-seek" role="slider" aria-label="Voortgang" tabindex="0">
|
|---|
| 88 | <div class="audio-seek-bar"><div class="audio-seek-fill" id="audio-sheet-seek-fill"></div></div>
|
|---|
| 89 | </div>
|
|---|
| 90 | <span class="audio-time mono" id="audio-sheet-total">0:00</span>
|
|---|
| 91 | </div>
|
|---|
| 92 | <div class="audio-sheet-controls">
|
|---|
| 93 | <button type="button" class="audio-btn audio-sheet-btn" id="audio-sheet-prev" aria-label="Vorige">${SVG.prev}</button>
|
|---|
| 94 | <button type="button" class="audio-btn audio-sheet-play" id="audio-sheet-play" aria-label="Afspelen">
|
|---|
| 95 | <span class="icon-play">${SVG.play}</span><span class="icon-pause">${SVG.pause}</span>
|
|---|
| 96 | </button>
|
|---|
| 97 | <button type="button" class="audio-btn audio-sheet-btn" id="audio-sheet-next" aria-label="Volgende">${SVG.next}</button>
|
|---|
| 98 | </div>
|
|---|
| 99 | <div class="audio-sheet-queue" id="audio-sheet-queue" hidden>
|
|---|
| 100 | <div class="audio-sheet-queue-label">Queue</div>
|
|---|
| 101 | <ol class="audio-sheet-queue-list" id="audio-sheet-queue-list"></ol>
|
|---|
| 102 | </div>
|
|---|
| 103 | </div>
|
|---|
| 104 | </div>
|
|---|
| 105 | `;
|
|---|
| 106 | document.body.appendChild(root);
|
|---|
| 107 |
|
|---|
| 108 | // FIX: Move .audio-sheet out of the .audio-player root so its
|
|---|
| 109 | // position:fixed is anchored to the viewport, not to the mini-bar.
|
|---|
| 110 | // The mini-bar has backdrop-filter, which makes it a containing
|
|---|
| 111 | // block for fixed descendants — that broke the sheet's left/right/top/bottom.
|
|---|
| 112 | const _detachedSheet = root.querySelector('.audio-sheet');
|
|---|
| 113 | if (_detachedSheet) document.body.appendChild(_detachedSheet);
|
|---|
| 114 |
|
|---|
| 115 | // ============================================================
|
|---|
| 116 | // 2. Element references
|
|---|
| 117 | // ============================================================
|
|---|
| 118 | const $ = (id) => document.getElementById(id);
|
|---|
| 119 | const audio = $('audio-element');
|
|---|
| 120 | const cover = $('audio-cover');
|
|---|
| 121 | const titleEl = $('audio-title');
|
|---|
| 122 | const artistEl = $('audio-artist');
|
|---|
| 123 | const seek = $('audio-seek');
|
|---|
| 124 | const seekFill = $('audio-seek-fill');
|
|---|
| 125 | const currentEl = $('audio-current');
|
|---|
| 126 | const totalEl = $('audio-total');
|
|---|
| 127 | const playBtn = $('audio-play');
|
|---|
| 128 | const prevBtn = $('audio-prev');
|
|---|
| 129 | const nextBtn = $('audio-next');
|
|---|
| 130 | const muteBtn = $('audio-mute');
|
|---|
| 131 | const volumeSlider = $('audio-volume');
|
|---|
| 132 | const expandTrigger = $('audio-expand-trigger');
|
|---|
| 133 |
|
|---|
| 134 | const sheet = $('audio-sheet');
|
|---|
| 135 | const sheetBackdrop = $('audio-sheet-backdrop');
|
|---|
| 136 | const sheetPanel = sheet.querySelector('.audio-sheet-panel');
|
|---|
| 137 | const sheetClose = $('audio-sheet-close');
|
|---|
| 138 | const sheetCover = $('audio-sheet-cover');
|
|---|
| 139 | const sheetTitle = $('audio-sheet-title');
|
|---|
| 140 | const sheetArtist = $('audio-sheet-artist');
|
|---|
| 141 | const sheetAlbum = $('audio-sheet-album');
|
|---|
| 142 | const sheetSeek = $('audio-sheet-seek');
|
|---|
| 143 | const sheetSeekFill = $('audio-sheet-seek-fill');
|
|---|
| 144 | const sheetCurrent = $('audio-sheet-current');
|
|---|
| 145 | const sheetTotal = $('audio-sheet-total');
|
|---|
| 146 | const sheetPlay = $('audio-sheet-play');
|
|---|
| 147 | const sheetPrev = $('audio-sheet-prev');
|
|---|
| 148 | const sheetNext = $('audio-sheet-next');
|
|---|
| 149 | const sheetQueue = $('audio-sheet-queue');
|
|---|
| 150 | const sheetQueueList = $('audio-sheet-queue-list');
|
|---|
| 151 | const dragZone = $('audio-sheet-drag-zone');
|
|---|
| 152 |
|
|---|
| 153 | // ============================================================
|
|---|
| 154 | // 3. State
|
|---|
| 155 | // ============================================================
|
|---|
| 156 | let queue = [];
|
|---|
| 157 | let currentIndex = 0;
|
|---|
| 158 | let isPlaying = false;
|
|---|
| 159 | let albumName = '';
|
|---|
| [21522ae] | 160 | // Blob playback state. We fetch each track's bytes and play from a blob:
|
|---|
| 161 | // object URL — no plain media URL is ever exposed to the page. currentObjectUrl
|
|---|
| 162 | // is revoked when we move on, so we don't leak one Blob per track in memory.
|
|---|
| 163 | let currentObjectUrl = null;
|
|---|
| 164 | // Monotonic load token: a fast prev/next can fire several loads before an
|
|---|
| 165 | // earlier fetch resolves. Only the latest load may set audio.src.
|
|---|
| 166 | let loadSeq = 0;
|
|---|
| [b5bae24] | 167 | // Next-track prefetch. While the current track plays we download the *next*
|
|---|
| 168 | // track's bytes into a held blob, so `ended` → next() can swap src instantly
|
|---|
| 169 | // (no silent gap, and no long async window where the browser's autoplay
|
|---|
| 170 | // activation can lapse and reject play()). At most one track ahead is held.
|
|---|
| 171 | // Shape: { url, objUrl } — objUrl is null while the fetch is still in flight.
|
|---|
| 172 | let preload = null;
|
|---|
| [7bc636b] | 173 |
|
|---|
| 174 | // Hide initially
|
|---|
| 175 | root.classList.add('audio-player-hidden');
|
|---|
| 176 |
|
|---|
| 177 | // ============================================================
|
|---|
| 178 | // 4. Track / queue loading
|
|---|
| 179 | // ============================================================
|
|---|
| 180 | function setCoverImage(el, url) {
|
|---|
| 181 | if (url) {
|
|---|
| 182 | el.style.backgroundImage = `url("${url}")`;
|
|---|
| 183 | el.classList.add('has-image');
|
|---|
| 184 | el.innerHTML = '';
|
|---|
| 185 | } else {
|
|---|
| 186 | el.style.backgroundImage = '';
|
|---|
| 187 | el.classList.remove('has-image');
|
|---|
| 188 | el.innerHTML = SVG.musicNote;
|
|---|
| 189 | }
|
|---|
| 190 | }
|
|---|
| 191 |
|
|---|
| [21522ae] | 192 | // Fetch the track bytes and hand back a blob: object URL. The X-Audio-Player
|
|---|
| 193 | // header + same-origin credentials get us past the stream route's access gate.
|
|---|
| [b5bae24] | 194 | // Retries a few times with backoff: a single transient network blip used to
|
|---|
| 195 | // bump the error counter and SKIP the song (auto-advance past it). Now one
|
|---|
| 196 | // hiccup just costs a retry, and we only give up after genuinely failing.
|
|---|
| 197 | async function fetchAsObjectUrl(url, attempts) {
|
|---|
| 198 | attempts = attempts || 1;
|
|---|
| 199 | let lastErr;
|
|---|
| 200 | for (let i = 0; i < attempts; i++) {
|
|---|
| 201 | try {
|
|---|
| 202 | const r = await fetch(url, {
|
|---|
| 203 | credentials: 'same-origin',
|
|---|
| 204 | headers: { 'X-Audio-Player': '1' },
|
|---|
| 205 | });
|
|---|
| 206 | if (!r.ok) throw new Error('HTTP ' + r.status);
|
|---|
| 207 | const blob = await r.blob();
|
|---|
| 208 | return URL.createObjectURL(blob);
|
|---|
| 209 | } catch (e) {
|
|---|
| 210 | lastErr = e;
|
|---|
| 211 | if (i < attempts - 1) {
|
|---|
| 212 | await new Promise((res) => setTimeout(res, 350 * (i + 1)));
|
|---|
| 213 | }
|
|---|
| 214 | }
|
|---|
| 215 | }
|
|---|
| 216 | throw lastErr;
|
|---|
| 217 | }
|
|---|
| 218 |
|
|---|
| 219 | // Apply a ready blob URL to the <audio> element. Single source of truth for
|
|---|
| 220 | // "swap the playing source": used by both the cached-preload path and the
|
|---|
| 221 | // fresh-fetch path so there's one place that touches audio.src.
|
|---|
| 222 | function applyBlob(objUrl, autoplay, mySeq) {
|
|---|
| 223 | if (mySeq !== loadSeq) { try { URL.revokeObjectURL(objUrl); } catch (e) {} return; } // superseded
|
|---|
| 224 | root.classList.remove('audio-loading');
|
|---|
| 225 | // Free the previously-playing track's blob — otherwise each track leaks a
|
|---|
| 226 | // copy. Never the same handle as objUrl (createObjectURL is unique), so this
|
|---|
| 227 | // can't revoke the source we're about to play.
|
|---|
| 228 | if (currentObjectUrl && currentObjectUrl !== objUrl) {
|
|---|
| 229 | try { URL.revokeObjectURL(currentObjectUrl); } catch (e) {}
|
|---|
| 230 | }
|
|---|
| 231 | currentObjectUrl = objUrl;
|
|---|
| 232 | // Schone overgang: pause + load forceert reset van internal state na
|
|---|
| 233 | // meerdere src-changes (voorkomt state-corruption van het audio-element).
|
|---|
| 234 | try { audio.pause(); } catch (e) {}
|
|---|
| 235 | audio.src = objUrl;
|
|---|
| 236 | try { audio.load(); } catch (e) {}
|
|---|
| 237 | if (autoplay) play();
|
|---|
| 238 | }
|
|---|
| 239 |
|
|---|
| 240 | function onLoadError(err, mySeq) {
|
|---|
| 241 | if (mySeq !== loadSeq) return; // superseded — ignore stale failure
|
|---|
| 242 | root.classList.remove('audio-loading');
|
|---|
| 243 | console.error('[pcms-audio] track load failed after retries', err);
|
|---|
| 244 | // Genuine failure (after retries): bump the counter and auto-skip, but stop
|
|---|
| 245 | // after 3 in a row so a fully-broken queue can't loop "next" forever.
|
|---|
| 246 | consecutiveErrors++;
|
|---|
| 247 | if (consecutiveErrors < 3 && queue.length > 1) setTimeout(next, 400);
|
|---|
| 248 | }
|
|---|
| 249 |
|
|---|
| 250 | // Discard any held/in-flight preload and free its blob if resolved.
|
|---|
| 251 | function dropPreload() {
|
|---|
| 252 | if (preload && preload.objUrl) { try { URL.revokeObjectURL(preload.objUrl); } catch (e) {} }
|
|---|
| 253 | preload = null;
|
|---|
| 254 | }
|
|---|
| 255 |
|
|---|
| 256 | // Prefetch the *next* track's bytes in the background. Idempotent: re-calling
|
|---|
| 257 | // while the same track is already cached / in flight is a no-op. Called from
|
|---|
| 258 | // the `playing` event so the network is otherwise idle.
|
|---|
| 259 | function preloadNext() {
|
|---|
| 260 | if (queue.length < 2) return;
|
|---|
| 261 | const ni = (currentIndex + 1) % queue.length;
|
|---|
| 262 | const t = queue[ni];
|
|---|
| 263 | if (!t || !t.url) return;
|
|---|
| 264 | if (preload && preload.url === t.url) return; // already held or in flight
|
|---|
| 265 | dropPreload(); // different track queued before → free it
|
|---|
| 266 | const marker = { url: t.url, objUrl: null };
|
|---|
| 267 | preload = marker;
|
|---|
| 268 | fetchAsObjectUrl(t.url, 2).then((obj) => {
|
|---|
| 269 | // Only keep it if this is still the track we want next; otherwise free it.
|
|---|
| 270 | if (preload === marker) { marker.objUrl = obj; }
|
|---|
| 271 | else { try { URL.revokeObjectURL(obj); } catch (e) {} }
|
|---|
| 272 | }).catch(() => { if (preload === marker) preload = null; });
|
|---|
| [21522ae] | 273 | }
|
|---|
| 274 |
|
|---|
| 275 | // metaOnly: show the track in the UI but DON'T download its bytes yet.
|
|---|
| 276 | // Used by the site pre-seed so opening a page doesn't auto-download audio;
|
|---|
| 277 | // the blob is fetched lazily on the first play().
|
|---|
| 278 | function loadTrack(index, autoplay, metaOnly) {
|
|---|
| [7bc636b] | 279 | if (!queue[index]) {
|
|---|
| 280 | console.warn('[pcms-audio] loadTrack: no track at index', index);
|
|---|
| 281 | return;
|
|---|
| 282 | }
|
|---|
| 283 | currentIndex = index;
|
|---|
| 284 | const t = queue[index];
|
|---|
| 285 | if (!t.url) {
|
|---|
| 286 | console.error('[pcms-audio] track has no url', t);
|
|---|
| 287 | return;
|
|---|
| 288 | }
|
|---|
| [21522ae] | 289 | console.log('[pcms-audio] loading', t.title, t.url, metaOnly ? '(meta only)' : '');
|
|---|
| 290 | // Metadata + chrome update synchronously so the UI reacts instantly while
|
|---|
| 291 | // the bytes download.
|
|---|
| [7bc636b] | 292 | titleEl.textContent = t.title || 'Untitled';
|
|---|
| 293 | artistEl.textContent = t.artist || '';
|
|---|
| 294 | sheetTitle.textContent = t.title || 'Untitled';
|
|---|
| 295 | sheetArtist.textContent = t.artist || '';
|
|---|
| 296 | sheetAlbum.textContent = albumName || '';
|
|---|
| 297 | setCoverImage(cover, t.cover);
|
|---|
| 298 | setCoverImage(sheetCover, t.cover);
|
|---|
| 299 | root.classList.remove('audio-player-hidden');
|
|---|
| 300 | document.body.classList.add('has-audio-player');
|
|---|
| 301 | renderQueue();
|
|---|
| [21522ae] | 302 |
|
|---|
| 303 | if (metaOnly) return;
|
|---|
| 304 |
|
|---|
| 305 | const mySeq = ++loadSeq;
|
|---|
| [b5bae24] | 306 |
|
|---|
| 307 | // Fast path: the bytes for this exact track were already prefetched while
|
|---|
| 308 | // the previous track played → swap in instantly, no gap, no fetch window.
|
|---|
| 309 | if (preload && preload.url === t.url && preload.objUrl) {
|
|---|
| 310 | const obj = preload.objUrl;
|
|---|
| 311 | preload = null; // ownership moves to applyBlob (becomes currentObjectUrl)
|
|---|
| 312 | applyBlob(obj, autoplay, mySeq);
|
|---|
| 313 | return;
|
|---|
| 314 | }
|
|---|
| 315 |
|
|---|
| 316 | // Not preloaded (or preload still in flight) → drop any stale preload and
|
|---|
| 317 | // fetch fresh, retrying transient failures before giving up.
|
|---|
| 318 | dropPreload();
|
|---|
| [21522ae] | 319 | root.classList.add('audio-loading');
|
|---|
| [b5bae24] | 320 | fetchAsObjectUrl(t.url, 3)
|
|---|
| 321 | .then((objUrl) => applyBlob(objUrl, autoplay, mySeq))
|
|---|
| 322 | .catch((err) => onLoadError(err, mySeq));
|
|---|
| [7bc636b] | 323 | }
|
|---|
| 324 |
|
|---|
| 325 | function setQueue(tracks, startIdx, opts) {
|
|---|
| 326 | queue = Array.isArray(tracks) ? tracks.slice() : [];
|
|---|
| 327 | albumName = (opts && opts.albumName) || '';
|
|---|
| 328 | if (!queue.length) return;
|
|---|
| [21522ae] | 329 | loadTrack(typeof startIdx === 'number' ? Math.max(0, Math.min(startIdx, queue.length - 1)) : 0, true);
|
|---|
| [7bc636b] | 330 | }
|
|---|
| 331 |
|
|---|
| 332 | function play() {
|
|---|
| [21522ae] | 333 | if (!audio.src) {
|
|---|
| 334 | // Nothing fetched yet (pre-seed showed metadata only, or a load is still
|
|---|
| 335 | // in flight). Kick off the blob load for the current track and autoplay.
|
|---|
| 336 | if (queue[currentIndex]) loadTrack(currentIndex, true);
|
|---|
| 337 | return;
|
|---|
| 338 | }
|
|---|
| [7bc636b] | 339 | const p = audio.play();
|
|---|
| 340 | if (p && typeof p.catch === 'function') {
|
|---|
| [8681239] | 341 | p.catch((err) => {
|
|---|
| 342 | console.warn('[pcms-audio] play() rejected:', err.name, err.message);
|
|---|
| 343 | // Browser-autoplay-policy heeft 't gestopt (typisch na 3-4
|
|---|
| 344 | // automatische plays op iOS Safari, of als tab tijdelijk inactive
|
|---|
| 345 | // was). Visuele hint dat user op play moet tappen.
|
|---|
| 346 | if (err && err.name === 'NotAllowedError') {
|
|---|
| 347 | root.classList.add('audio-needs-tap');
|
|---|
| 348 | isPlaying = false;
|
|---|
| 349 | root.classList.remove('is-playing');
|
|---|
| 350 | }
|
|---|
| 351 | });
|
|---|
| [7bc636b] | 352 | }
|
|---|
| 353 | }
|
|---|
| 354 | function pause() { audio.pause(); }
|
|---|
| 355 | function togglePlay() { audio.paused ? play() : pause(); }
|
|---|
| 356 | function next() {
|
|---|
| 357 | if (!queue.length) return;
|
|---|
| [21522ae] | 358 | loadTrack((currentIndex + 1) % queue.length, true);
|
|---|
| [7bc636b] | 359 | }
|
|---|
| 360 | function prev() {
|
|---|
| 361 | if (!queue.length) return;
|
|---|
| [21522ae] | 362 | loadTrack(currentIndex === 0 ? queue.length - 1 : currentIndex - 1, true);
|
|---|
| [7bc636b] | 363 | }
|
|---|
| 364 | function close() {
|
|---|
| 365 | pause();
|
|---|
| 366 | root.classList.add('audio-player-hidden');
|
|---|
| 367 | document.body.classList.remove('has-audio-player');
|
|---|
| 368 | closeSheet();
|
|---|
| 369 | queue = [];
|
|---|
| 370 | albumName = '';
|
|---|
| [21522ae] | 371 | loadSeq++; // cancel any in-flight load
|
|---|
| [b5bae24] | 372 | dropPreload(); // free any prefetched next-track blob
|
|---|
| [21522ae] | 373 | if (currentObjectUrl) { try { URL.revokeObjectURL(currentObjectUrl); } catch (e) {} }
|
|---|
| 374 | currentObjectUrl = null;
|
|---|
| 375 | try { audio.removeAttribute('src'); audio.load(); } catch (e) {}
|
|---|
| [7bc636b] | 376 | }
|
|---|
| 377 |
|
|---|
| 378 | function renderQueue() {
|
|---|
| 379 | if (!queue.length) { sheetQueue.hidden = true; return; }
|
|---|
| 380 | sheetQueueList.innerHTML = '';
|
|---|
| 381 | queue.forEach((t, i) => {
|
|---|
| 382 | const li = document.createElement('li');
|
|---|
| 383 | li.className = 'audio-sheet-queue-item' + (i === currentIndex ? ' is-current' : '');
|
|---|
| 384 | li.dataset.idx = String(i);
|
|---|
| 385 | li.innerHTML = `<span class="aqi-num">${i + 1}.</span> <span class="aqi-title">${escapeHtml(t.title || 'Untitled')}</span>`
|
|---|
| 386 | + (t.artist ? `<span class="aqi-artist">${escapeHtml(t.artist)}</span>` : '');
|
|---|
| 387 | sheetQueueList.appendChild(li);
|
|---|
| 388 | });
|
|---|
| 389 | sheetQueueList.querySelectorAll('.audio-sheet-queue-item').forEach((li) => {
|
|---|
| 390 | li.addEventListener('click', () => {
|
|---|
| 391 | const idx = parseInt(li.dataset.idx, 10);
|
|---|
| 392 | if (!isNaN(idx) && idx !== currentIndex) {
|
|---|
| [21522ae] | 393 | loadTrack(idx, true);
|
|---|
| [7bc636b] | 394 | }
|
|---|
| 395 | });
|
|---|
| 396 | });
|
|---|
| 397 | sheetQueue.hidden = queue.length < 2;
|
|---|
| 398 | }
|
|---|
| 399 |
|
|---|
| 400 | function escapeHtml(s) {
|
|---|
| 401 | return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
|---|
| 402 | }
|
|---|
| 403 |
|
|---|
| 404 | // ============================================================
|
|---|
| 405 | // 5. Audio element events → UI sync
|
|---|
| 406 | // ============================================================
|
|---|
| [8681239] | 407 | // Error-counter voorkomt infinite-loop als ALLE tracks broken zijn.
|
|---|
| 408 | let consecutiveErrors = 0;
|
|---|
| 409 |
|
|---|
| 410 | audio.addEventListener('play', () => {
|
|---|
| 411 | isPlaying = true;
|
|---|
| 412 | root.classList.add('is-playing');
|
|---|
| 413 | root.classList.remove('audio-needs-tap'); // verstop tap-hint
|
|---|
| 414 | });
|
|---|
| [21522ae] | 415 | // Reset de error-teller pas bij ECHTE playback-start (`playing`), niet bij
|
|---|
| 416 | // het eager `play`-event. `play` vuurt vóór een eventuele netwerk-/decode-
|
|---|
| 417 | // fout, dus resetten daar zou de 3-strikes-stop nooit laten triggeren bij
|
|---|
| 418 | // een kapotte track → infinite "next"-loop. `playing` vuurt alleen als er
|
|---|
| 419 | // daadwerkelijk audio speelt.
|
|---|
| [b5bae24] | 420 | audio.addEventListener('playing', () => { consecutiveErrors = 0; preloadNext(); });
|
|---|
| [7bc636b] | 421 | audio.addEventListener('pause', () => { isPlaying = false; root.classList.remove('is-playing'); });
|
|---|
| 422 | audio.addEventListener('ended', next);
|
|---|
| 423 | audio.addEventListener('error', (e) => {
|
|---|
| 424 | const code = audio.error ? audio.error.code : '?';
|
|---|
| 425 | console.error('[pcms-audio] playback error', code, audio.src, e);
|
|---|
| [8681239] | 426 | consecutiveErrors++;
|
|---|
| 427 | // Bij netwerk/decode-fout: skip naar volgende track ipv stilstaan.
|
|---|
| 428 | // Max 3 fouten op rij voordat we opgeven (anders infinite loop).
|
|---|
| 429 | if (consecutiveErrors < 3 && queue.length > 1) {
|
|---|
| 430 | console.warn('[pcms-audio] auto-skip naar volgende na error', consecutiveErrors);
|
|---|
| 431 | setTimeout(next, 400);
|
|---|
| 432 | }
|
|---|
| [7bc636b] | 433 | });
|
|---|
| [8681239] | 434 | audio.addEventListener('stalled', () => console.warn('[pcms-audio] stalled at', audio.currentTime));
|
|---|
| [7bc636b] | 435 | audio.addEventListener('volumechange', () => { root.classList.toggle('is-muted', audio.muted || audio.volume === 0); });
|
|---|
| 436 | audio.addEventListener('timeupdate', () => {
|
|---|
| 437 | if (!audio.duration || isNaN(audio.duration)) return;
|
|---|
| 438 | const pct = (audio.currentTime / audio.duration) * 100;
|
|---|
| 439 | seekFill.style.width = pct + '%';
|
|---|
| 440 | sheetSeekFill.style.width = pct + '%';
|
|---|
| 441 | currentEl.textContent = formatTime(audio.currentTime);
|
|---|
| 442 | totalEl.textContent = formatTime(audio.duration);
|
|---|
| 443 | sheetCurrent.textContent = formatTime(audio.currentTime);
|
|---|
| 444 | sheetTotal.textContent = formatTime(audio.duration);
|
|---|
| 445 | });
|
|---|
| 446 |
|
|---|
| 447 | function formatTime(s) {
|
|---|
| 448 | if (!s || isNaN(s)) return '0:00';
|
|---|
| 449 | const m = Math.floor(s / 60), sec = Math.floor(s % 60);
|
|---|
| 450 | return m + ':' + (sec < 10 ? '0' : '') + sec;
|
|---|
| 451 | }
|
|---|
| 452 |
|
|---|
| 453 | function attachSeek(seekEl) {
|
|---|
| 454 | seekEl.addEventListener('click', (e) => {
|
|---|
| 455 | if (!audio.duration) return;
|
|---|
| 456 | const rect = seekEl.getBoundingClientRect();
|
|---|
| 457 | const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
|
|---|
| 458 | audio.currentTime = ratio * audio.duration;
|
|---|
| 459 | });
|
|---|
| 460 | }
|
|---|
| 461 | attachSeek(seek);
|
|---|
| 462 | attachSeek(sheetSeek);
|
|---|
| 463 |
|
|---|
| 464 | audio.volume = 0.8;
|
|---|
| 465 | volumeSlider.addEventListener('input', () => {
|
|---|
| 466 | audio.volume = volumeSlider.value / 100;
|
|---|
| 467 | if (volumeSlider.value > 0) audio.muted = false;
|
|---|
| 468 | });
|
|---|
| 469 | muteBtn.addEventListener('click', () => { audio.muted = !audio.muted; });
|
|---|
| 470 |
|
|---|
| 471 | // ============================================================
|
|---|
| 472 | // 6. Control wiring
|
|---|
| 473 | // ============================================================
|
|---|
| 474 | playBtn.addEventListener('click', togglePlay);
|
|---|
| 475 | prevBtn.addEventListener('click', prev);
|
|---|
| 476 | nextBtn.addEventListener('click', next);
|
|---|
| 477 | sheetPlay.addEventListener('click', togglePlay);
|
|---|
| 478 | sheetPrev.addEventListener('click', prev);
|
|---|
| 479 | sheetNext.addEventListener('click', next);
|
|---|
| 480 |
|
|---|
| 481 | // ============================================================
|
|---|
| 482 | // 7. Sheet expand/close + drag-down-to-close
|
|---|
| 483 | // ============================================================
|
|---|
| 484 | function openSheet() {
|
|---|
| 485 | sheet.classList.add('is-open');
|
|---|
| 486 | sheet.setAttribute('aria-hidden', 'false');
|
|---|
| 487 | document.body.classList.add('audio-sheet-locked');
|
|---|
| 488 | }
|
|---|
| 489 | function closeSheet() {
|
|---|
| 490 | sheet.classList.remove('is-open');
|
|---|
| 491 | sheet.setAttribute('aria-hidden', 'true');
|
|---|
| 492 | document.body.classList.remove('audio-sheet-locked');
|
|---|
| 493 | sheetPanel.style.removeProperty('--pcms-drag-y');
|
|---|
| 494 | sheetBackdrop.style.removeProperty('--pcms-sheet-progress');
|
|---|
| 495 | }
|
|---|
| 496 | expandTrigger.addEventListener('click', openSheet);
|
|---|
| 497 | sheetClose.addEventListener('click', closeSheet);
|
|---|
| 498 | sheetBackdrop.addEventListener('click', closeSheet);
|
|---|
| 499 | document.addEventListener('keydown', (e) => {
|
|---|
| 500 | if (e.key === 'Escape' && sheet.classList.contains('is-open')) closeSheet();
|
|---|
| 501 | });
|
|---|
| 502 |
|
|---|
| 503 | // Drag-down-to-close on touch devices.
|
|---|
| 504 | //
|
|---|
| 505 | // We set --pcms-drag-y as a CSS custom prop instead of writing
|
|---|
| 506 | // sheetPanel.style.transform directly. The reason: on desktop the panel
|
|---|
| 507 | // uses `transform: translate(-50%, 0)` for horizontal centering. Writing
|
|---|
| 508 | // `style.transform = translateY(...)` would obliterate the -50% and the
|
|---|
| 509 | // panel would jump rightward. With a custom prop, audio.css composes the
|
|---|
| 510 | // final transform per breakpoint:
|
|---|
| 511 | // mobile: transform: translateY(var(--pcms-drag-y, 0))
|
|---|
| 512 | // desktop: transform: translate(-50%, var(--pcms-drag-y, 0))
|
|---|
| 513 | let dragStartY = 0, dragLastY = 0, isDragging = false;
|
|---|
| 514 | function onPointerDown(e) {
|
|---|
| 515 | if (e.pointerType !== 'touch') return;
|
|---|
| 516 | if (sheetPanel.scrollTop > 0) return; // queue is scrolled, don't drag
|
|---|
| 517 | dragStartY = dragLastY = e.clientY;
|
|---|
| 518 | isDragging = true;
|
|---|
| 519 | sheetPanel.classList.add('is-dragging');
|
|---|
| 520 | sheetBackdrop.classList.add('is-dragging');
|
|---|
| 521 | }
|
|---|
| 522 | function onPointerMove(e) {
|
|---|
| 523 | if (!isDragging) return;
|
|---|
| 524 | dragLastY = e.clientY;
|
|---|
| 525 | const dy = Math.max(0, dragLastY - dragStartY);
|
|---|
| 526 | sheetPanel.style.setProperty('--pcms-drag-y', dy + 'px');
|
|---|
| 527 | const progress = Math.max(0, 1 - dy / sheetPanel.offsetHeight);
|
|---|
| 528 | sheetBackdrop.style.setProperty('--pcms-sheet-progress', String(progress));
|
|---|
| 529 | }
|
|---|
| 530 | function onPointerUp() {
|
|---|
| 531 | if (!isDragging) return;
|
|---|
| 532 | isDragging = false;
|
|---|
| 533 | sheetPanel.classList.remove('is-dragging');
|
|---|
| 534 | sheetBackdrop.classList.remove('is-dragging');
|
|---|
| 535 | const dy = dragLastY - dragStartY;
|
|---|
| 536 | if (dy > 100) {
|
|---|
| 537 | closeSheet();
|
|---|
| 538 | } else {
|
|---|
| 539 | sheetPanel.style.removeProperty('--pcms-drag-y');
|
|---|
| 540 | sheetBackdrop.style.removeProperty('--pcms-sheet-progress');
|
|---|
| 541 | }
|
|---|
| 542 | }
|
|---|
| 543 | if (window.PointerEvent) {
|
|---|
| 544 | dragZone.addEventListener('pointerdown', onPointerDown);
|
|---|
| 545 | document.addEventListener('pointermove', onPointerMove);
|
|---|
| 546 | document.addEventListener('pointerup', onPointerUp);
|
|---|
| 547 | document.addEventListener('pointercancel', onPointerUp);
|
|---|
| 548 | }
|
|---|
| 549 |
|
|---|
| 550 | // ============================================================
|
|---|
| 551 | // 8. Hook up post-audio-track + post-album-cover-btn + .pat-row + .post-album-playall
|
|---|
| 552 | // ============================================================
|
|---|
| 553 | // Four entry points fire the same play action:
|
|---|
| 554 | // - .pat-play → single-track widget in a post
|
|---|
| 555 | // - .pat-row → track row inside an album/playlist tracklist
|
|---|
| 556 | // - .post-album-cover-btn → big cover button (plays album from track 0)
|
|---|
| 557 | // - .post-album-playall → "Speel album" / "Speel playlist" button
|
|---|
| 558 | //
|
|---|
| 559 | // For .pat-play the metadata lives on the surrounding .post-audio-track
|
|---|
| 560 | // wrapper. For the other three the data is on the button itself. The
|
|---|
| 561 | // handler reads from button-first, falls back to wrapper.
|
|---|
| 562 | function attachListeners() {
|
|---|
| 563 | const playBtns = document.querySelectorAll(
|
|---|
| 564 | '.post-audio-track .pat-play, ' +
|
|---|
| 565 | '.post-album-tracks .pat-row, ' +
|
|---|
| 566 | '.post-album-cover-btn, ' +
|
|---|
| 567 | '.post-album-playall'
|
|---|
| 568 | );
|
|---|
| 569 | if (playBtns.length) console.log('[pcms-audio] attaching to', playBtns.length, 'play buttons');
|
|---|
| 570 |
|
|---|
| 571 | playBtns.forEach((btn) => {
|
|---|
| 572 | if (btn.dataset.pcmsAttached) return;
|
|---|
| 573 | btn.dataset.pcmsAttached = '1';
|
|---|
| 574 |
|
|---|
| 575 | btn.addEventListener('click', (e) => {
|
|---|
| 576 | e.preventDefault();
|
|---|
| 577 | e.stopPropagation();
|
|---|
| 578 | // Resolve metadata: button-first, then closest .post-audio-track wrapper
|
|---|
| 579 | // (only inline single-track widgets put the data on the wrapper).
|
|---|
| 580 | const wrapper = btn.closest('.post-audio-track');
|
|---|
| 581 | const albumId = btn.dataset.pcmsAlbumId || (wrapper && wrapper.dataset.pcmsAlbumId);
|
|---|
| 582 | const trackData = btn.dataset.pcmsTrack || (wrapper && wrapper.dataset.pcmsTrack);
|
|---|
| 583 | const trackUrl = btn.dataset.pcmsTrackUrl || (wrapper && wrapper.dataset.pcmsTrackUrl);
|
|---|
| 584 | console.log('[pcms-audio] click', { btn: btn.className, albumId, trackUrl, hasTrackData: !!trackData });
|
|---|
| 585 |
|
|---|
| 586 | if (albumId) {
|
|---|
| 587 | const album = document.getElementById(albumId);
|
|---|
| 588 | if (!album) { console.error('[pcms-audio] album not found:', albumId); return; }
|
|---|
| 589 | try {
|
|---|
| 590 | const tracks = JSON.parse(album.dataset.pcmsAlbum);
|
|---|
| 591 | // Start at the clicked track if we know its URL, else start at 0
|
|---|
| 592 | // (cover-btn and playall both want to start from the beginning).
|
|---|
| 593 | const startIdx = trackUrl ? tracks.findIndex(t => t.url === trackUrl) : 0;
|
|---|
| 594 | setQueue(tracks, startIdx >= 0 ? startIdx : 0, { albumName: album.dataset.pcmsAlbumTitle || '' });
|
|---|
| 595 | } catch(err) { console.error('[pcms-audio] bad album JSON', err, album.dataset.pcmsAlbum); }
|
|---|
| 596 | } else if (trackData) {
|
|---|
| 597 | try {
|
|---|
| 598 | const t = JSON.parse(trackData);
|
|---|
| 599 | setQueue([t], 0);
|
|---|
| 600 | } catch(err) { console.error('[pcms-audio] bad track JSON', err, trackData); }
|
|---|
| 601 | } else if (trackUrl) {
|
|---|
| 602 | // Fallback: at minimum we have the signed URL
|
|---|
| 603 | setQueue([{ url: trackUrl, title: 'Track', artist: '', cover: '' }], 0);
|
|---|
| 604 | } else {
|
|---|
| 605 | console.error('[pcms-audio] no track data or url on button or wrapper', btn);
|
|---|
| 606 | }
|
|---|
| 607 | });
|
|---|
| 608 | });
|
|---|
| 609 | }
|
|---|
| 610 |
|
|---|
| 611 | attachListeners();
|
|---|
| 612 | document.body.addEventListener('htmx:afterSettle', attachListeners);
|
|---|
| 613 |
|
|---|
| 614 | // ============================================================
|
|---|
| 615 | // 8b. Admin playlist delete (event delegation)
|
|---|
| 616 | // ============================================================
|
|---|
| 617 | // The post-album embed renders a [data-pcms-playlist-delete] button
|
|---|
| 618 | // top-right when the viewer is admin (server decides; not client).
|
|---|
| 619 | // We delegate from document.body so HTMX-swapped content works too.
|
|---|
| 620 | document.body.addEventListener('click', async (e) => {
|
|---|
| 621 | const btn = e.target.closest('[data-pcms-playlist-delete]');
|
|---|
| 622 | if (!btn) return;
|
|---|
| 623 | e.preventDefault();
|
|---|
| 624 | e.stopPropagation();
|
|---|
| 625 | const id = btn.dataset.pcmsPlaylistDelete;
|
|---|
| 626 | const title = btn.dataset.pcmsPlaylistTitle || id;
|
|---|
| 627 | if (!id) return;
|
|---|
| 628 | if (!confirm(`Playlist "${title}" verwijderen? De embed in deze post toont vanaf nu een placeholder.`)) return;
|
|---|
| 629 | btn.disabled = true;
|
|---|
| 630 | try {
|
|---|
| 631 | const r = await fetch(`/admin/playlists/api/${encodeURIComponent(id)}/delete`, {
|
|---|
| 632 | method: 'POST',
|
|---|
| 633 | headers: { 'X-CSRF-Token': '' },
|
|---|
| 634 | credentials: 'same-origin',
|
|---|
| 635 | });
|
|---|
| 636 | const j = await r.json().catch(() => ({}));
|
|---|
| 637 | if (j && j.ok) {
|
|---|
| 638 | location.reload();
|
|---|
| 639 | } else {
|
|---|
| 640 | alert('Verwijderen mislukt: ' + ((j && j.error) || 'onbekende fout'));
|
|---|
| 641 | btn.disabled = false;
|
|---|
| 642 | }
|
|---|
| 643 | } catch (err) {
|
|---|
| 644 | alert('Verwijderen mislukt: ' + err.message);
|
|---|
| 645 | btn.disabled = false;
|
|---|
| 646 | }
|
|---|
| 647 | });
|
|---|
| 648 |
|
|---|
| 649 | // ============================================================
|
|---|
| 650 | // 9. Public API
|
|---|
| 651 | // ============================================================
|
|---|
| 652 | window.pcmsAudioPlayer = {
|
|---|
| 653 | setQueue, play, pause, next, prev, close, openSheet, closeSheet,
|
|---|
| 654 | isPlaying: () => isPlaying,
|
|---|
| 655 | currentTrack: () => queue[currentIndex] || null,
|
|---|
| 656 | };
|
|---|
| 657 |
|
|---|
| 658 | // ============================================================
|
|---|
| 659 | // 10. Site-level pre-seed (window.PCMS_SITE_TRACKS)
|
|---|
| 660 | // ============================================================
|
|---|
| 661 | if (Array.isArray(window.PCMS_SITE_TRACKS) && window.PCMS_SITE_TRACKS.length) {
|
|---|
| 662 | queue = window.PCMS_SITE_TRACKS.map(t => ({
|
|---|
| 663 | url: t.media_url || t.url,
|
|---|
| 664 | title: t.title || 'Untitled',
|
|---|
| 665 | artist: t.artist || '',
|
|---|
| 666 | cover: t.cover_url || t.cover || '',
|
|---|
| 667 | }));
|
|---|
| [21522ae] | 668 | if (queue.length) loadTrack(0, false, true); // metadata only — fetch on first play
|
|---|
| [7bc636b] | 669 | }
|
|---|
| 670 | })();
|
|---|