source: Klonkt/src/services/AudioEmbedService.js@ 73b41eb

main
Last change on this file since 73b41eb was 73b41eb, checked in by roboburr <roboburr@…>, 3 months ago

feat(embed): YouTube audio-only option in posts

Per embed you now choose audio-only or video. [[embed:audio:URL]] (YouTube)
renders as an audio card with our controls (play/seek/volume + thumbnail as
cover); the YT player runs hidden off-screen and provides only the sound.
[[embed:URL]] stays video. The editor embed button asks for audio or video
when a YouTube URL is given. Server: audio:/video: prefix in the shortcode
→ data-embed-mode. busters embed-player.js?v=8, embed.css?v=5.

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

  • Property mode set to 100644
File size: 23.8 KB
Line 
1/**
2 * AudioEmbedService — Parse URLs and return embed HTML
3 * Supports: Spotify, Bandcamp, SoundCloud, Apple Music, YouTube, Vimeo
4 *
5 * Usage in post content:
6 * <p>https://open.spotify.com/track/123abc</p>
7 * →
8 * <figure class="folio-embed folio-embed--spotify">
9 * <iframe src="..."></iframe>
10 * </figure>
11 */
12
13class AudioEmbedService {
14 static detectProvider(url) {
15 if (!url || typeof url !== 'string') return null;
16 url = url.trim();
17
18 // Alleen http(s)-URL's embedden. De provider-regexes hieronder zijn NIET
19 // verankerd, dus zonder deze check zou bv. `javascript:alert(1)//youtu.be/x`
20 // matchen en als embed-URL belanden (stored XSS via een [[embed:...]]-
21 // shortcode — die tekst gaat niet langs de HTML-sanitizer omdat 'ie in een
22 // text-node zit). De scheme-guard sluit javascript:/data:/vbscript: enz. uit.
23 if (!/^https?:\/\//i.test(url)) return null;
24
25 // Spotify
26 if (/open\.spotify\.com\/(track|album|playlist|episode|show)\/([A-Za-z0-9]+)/i.test(url)) {
27 const match = url.match(/\/(track|album|playlist|episode|show)\/([A-Za-z0-9]+)/i);
28 return { provider: 'spotify', type: match[1], id: match[2], url };
29 }
30
31 // Bandcamp
32 if (/bandcamp\.com\/(track|album)/i.test(url)) {
33 return { provider: 'bandcamp', url };
34 }
35
36 // SoundCloud
37 if (/soundcloud\.com/i.test(url)) {
38 return { provider: 'soundcloud', url };
39 }
40
41 // Apple Music
42 if (/music\.apple\.com\/([a-z]{2})\/(?:album|playlist|song)\//i.test(url)) {
43 return { provider: 'applemusic', url };
44 }
45
46 // YouTube — video-id is altijd exact 11 tekens (lijnt uit met de client-side
47 // ytId() in embed-player.js, die ook {11} verwacht).
48 if (/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/|youtube\.com\/live\/)([A-Za-z0-9_-]{11})/i.test(url)) {
49 const match = url.match(/(?:v=|youtu\.be\/|embed\/|shorts\/|live\/)([A-Za-z0-9_-]{11})/i);
50 return { provider: 'youtube', id: match[1], url };
51 }
52
53 // Vimeo
54 if (/vimeo\.com\/(?:video\/)?(\d+)/i.test(url)) {
55 const match = url.match(/\d+/);
56 return { provider: 'vimeo', id: match[0], url };
57 }
58
59 return null;
60 }
61
62 static generateIframe(provider, config) {
63 switch (provider) {
64 // Eigen custom-spelers (client-side via embed-player.js + de echte
65 // platform-API's). We renderen een placeholder met data-attributen i.p.v.
66 // het kale platform-iframe, zodat de embed in ÓNZE huisstijl verschijnt.
67 case 'youtube':
68 return this.embedPlaceholder('youtube', config.id, 'video',
69 config.url || `https://youtu.be/${config.id}`, config.mode);
70 case 'soundcloud':
71 return this.embedPlaceholder('soundcloud', config.url, 'track', config.url);
72 case 'spotify':
73 return this.embedPlaceholder('spotify', `spotify:${config.type}:${config.id}`,
74 config.type, config.url || `https://open.spotify.com/${config.type}/${config.id}`);
75 // Geen JS-API (Bandcamp/Apple) of niet-prioritair (Vimeo): blijven een
76 // iframe; mutual-exclusion loopt voor deze via de blur-fallback.
77 case 'bandcamp':
78 return this.bandcampIframe(config);
79 case 'applemusic':
80 return this.applemusicIframe(config);
81 case 'vimeo':
82 return this.vimeoIframe(config);
83 default:
84 return null;
85 }
86 }
87
88 /**
89 * Placeholder voor een eigen custom-speler. embed-player.js pikt
90 * .folio-embed[data-embed-provider] op en bouwt de kaart + speler client-side.
91 * ALLE waarden via escape() — post.content_html wordt ongeescaped uitgevoerd.
92 */
93 static embedPlaceholder(provider, ref, type, url, mode) {
94 const attrs = [
95 `data-embed-provider="${this.escape(provider)}"`,
96 `data-embed-ref="${this.escape(ref)}"`,
97 type ? `data-embed-type="${this.escape(type)}"` : '',
98 mode ? `data-embed-mode="${this.escape(mode)}"` : '',
99 `data-embed-url="${this.escape(url)}"`,
100 ].filter(Boolean).join(' ');
101 return `<div class="folio-embed folio-embed--${this.escape(provider)} pcms-embed pcms-embed-card pcms-embed-loading" ${attrs}></div>`;
102 }
103
104 static spotifyIframe({ type, id }) {
105 const src = `https://open.spotify.com/embed/${type}/${id}`;
106 return `
107 <figure class="folio-embed folio-embed--spotify">
108 <iframe src="${this.escape(src)}"
109 style="width:100%;height:152px;border:0;"
110 loading="lazy"
111 allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
112 title="Spotify ${type}"></iframe>
113 </figure>
114 `.trim();
115 }
116
117 static bandcampIframe({ url }) {
118 const encodedUrl = encodeURIComponent(url);
119 const src = `https://bandcamp.com/EmbeddedPlayer/url=${encodedUrl}/size=large/bgcol=faf8f3/linkcol=c2410c/tracklist=false/transparent=true/`;
120 return `
121 <figure class="folio-embed folio-embed--bandcamp">
122 <iframe src="${this.escape(src)}"
123 style="width:100%;height:470px;border:0;"
124 loading="lazy"
125 allow="encrypted-media"
126 title="Bandcamp player"></iframe>
127 </figure>
128 `.trim();
129 }
130
131 static soundcloudIframe({ url }) {
132 const params = {
133 url: url,
134 color: '#ff5500',
135 auto_play: 'false',
136 hide_related: 'true',
137 show_comments: 'false',
138 show_user: 'true',
139 show_reposts: 'false',
140 show_teaser: 'false',
141 visual: 'true'
142 };
143 const query = new URLSearchParams(params).toString();
144 const src = `https://w.soundcloud.com/player/?${query}`;
145 return `
146 <figure class="folio-embed folio-embed--soundcloud">
147 <iframe src="${this.escape(src)}"
148 style="width:100%;height:300px;border:0;"
149 loading="lazy"
150 allow="autoplay; clipboard-write; encrypted-media"
151 title="SoundCloud player"></iframe>
152 </figure>
153 `.trim();
154 }
155
156 static applemusicIframe({ url }) {
157 const match = url.match(/music\.apple\.com\/([a-z]{2}\/(?:album|playlist|song)\/[^/?#]+\/[0-9]+)/i);
158 if (!match) return null;
159 const src = `https://embed.music.apple.com/${match[1]}`;
160 return `
161 <figure class="folio-embed folio-embed--applemusic">
162 <iframe src="${this.escape(src)}"
163 style="width:100%;height:175px;border:0;overflow:hidden;border-radius:8px;"
164 loading="lazy"
165 allow="autoplay; clipboard-write; encrypted-media"
166 title="Apple Music"></iframe>
167 </figure>
168 `.trim();
169 }
170
171 static youtubeIframe({ id }) {
172 const src = `https://www.youtube-nocookie.com/embed/${id}`;
173 return `
174 <figure class="folio-embed folio-embed--youtube">
175 <iframe src="${this.escape(src)}"
176 style="aspect-ratio:16/9;width:100%;height:auto;border:0;"
177 loading="lazy"
178 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
179 allowfullscreen
180 title="YouTube video"></iframe>
181 </figure>
182 `.trim();
183 }
184
185 static vimeoIframe({ id }) {
186 const src = `https://player.vimeo.com/video/${id}`;
187 return `
188 <figure class="folio-embed folio-embed--vimeo">
189 <iframe src="${this.escape(src)}"
190 style="aspect-ratio:16/9;width:100%;height:auto;border:0;"
191 loading="lazy"
192 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
193 allowfullscreen
194 title="Vimeo video"></iframe>
195 </figure>
196 `.trim();
197 }
198
199 /**
200 * Auto-embed: Scan paragraphs containing only a URL.
201 * Handles two markdown-rendered shapes:
202 * <p>https://url</p> (bare URL — when GFM auto-link is off)
203 * <p><a href="https://url">https://url</a></p> (marked GFM auto-link — what we get)
204 * Either way → <figure class="folio-embed">...
205 */
206 static autoembed(html) {
207 if (!html) return html;
208 return html.replace(
209 /<p>\s*(?:<a\b[^>]*?\shref="([^"]+)"[^>]*>[^<]*<\/a>|(https?:\/\/[^\s<>"']+))\s*<\/p>/gi,
210 (match, hrefUrl, bareUrl) => {
211 const url = hrefUrl || bareUrl;
212 const detected = this.detectProvider(url);
213 if (detected) {
214 const iframe = this.generateIframe(detected.provider, detected);
215 return iframe || match;
216 }
217 return match;
218 }
219 );
220 }
221
222 /**
223 * Replace [[embed:<url>]] shortcodes met de platform-iframe (YouTube, Spotify,
224 * SoundCloud, Apple Music, Bandcamp, Vimeo). De editor-knop voegt deze
225 * shortcode in; losse URL-regels embedden ook automatisch via autoembed().
226 * Niet-ondersteunde/ongeldige URLs krijgen een nette inline-melding.
227 */
228 static embedMediaShortcodes(html) {
229 if (!html) return html;
230 return html.replace(/\[\[embed:([^\]]+)\]\]/gi, (match, rawSpec) => {
231 // Optionele modus-prefix: [[embed:audio:URL]] = alleen-audio speler,
232 // [[embed:video:URL]] / [[embed:URL]] = normaal (video waar van toepassing).
233 let spec = rawSpec.trim();
234 let mode = null;
235 const mm = spec.match(/^(audio|video):(.+)$/i);
236 if (mm) { mode = mm[1].toLowerCase(); spec = mm[2].trim(); }
237 const url = spec.replace(/&amp;/g, '&');
238 const detected = this.detectProvider(url);
239 if (!detected) {
240 return `<div class="post-embed-missing"><em>Embed: niet-ondersteunde of ongeldige URL.</em></div>`;
241 }
242 return this.generateIframe(detected.provider, { ...detected, mode }) || match;
243 });
244 }
245
246 /**
247 * Replace [[track:<id>]] shortcodes with v9-style player markup.
248 * Caller passes a lookup function (id) -> { id, title, artist, url, cover }
249 * where url is already a signed /audio/stream/... URL. Unknown ids → left as-is.
250 */
251 static embedTrackShortcodes(html, trackLookup) {
252 if (!html || typeof trackLookup !== 'function') return html;
253 return html.replace(/\[\[track:([A-Za-z0-9_-]+)\]\]/g, (match, id) => {
254 const t = trackLookup(id);
255 if (!t || !t.url) return match;
256 const trackJson = JSON.stringify({
257 id,
258 url: t.url,
259 title: t.title || 'Untitled',
260 artist: t.artist || '',
261 cover: t.cover || '',
262 });
263 const titleH = this.escape(t.title || 'Untitled');
264 const artistH = this.escape(t.artist || '');
265 const urlH = this.escape(t.url);
266 const dataAttr = trackJson
267 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
268 // id="track-<id>" = anker zodat de mini-speler hierheen kan scrollen.
269 return `<div class="post-audio-track" id="track-${id}" data-pcms-track-id="${id}" data-pcms-track-url="${urlH}" data-pcms-track='${dataAttr}'>
270 <button type="button" class="pat-play" aria-label="Play ${titleH}">
271 <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 4l12 8-12 8z"/></svg>
272 </button>
273 <div class="pat-info">
274 <div class="pat-title">${titleH}</div>
275 ${artistH ? `<div class="pat-artist">${artistH}</div>` : ''}
276 </div>
277</div>`;
278 });
279 }
280
281 /**
282 * Replace [[album:<name>]] shortcodes with a v9-style album block.
283 * Caller passes a lookup function (name) -> { title, artist, cover, tracks: [{url,title,artist,cover}, ...] }
284 * Tracks must already have signed URLs. Unknown albums → left as-is.
285 * The wrapper carries the full album JSON so audio-player.js can queue it
286 * when any track or the album play button is clicked.
287 */
288 static embedAlbumShortcodes(html, albumLookup) {
289 if (!html || typeof albumLookup !== 'function') return html;
290 return html.replace(/\[\[album:([^\]]+)\]\]/g, (match, rawName) => {
291 const name = rawName.trim();
292 const album = albumLookup(name);
293 if (!album || !album.tracks || !album.tracks.length) return match;
294
295 // Stable DOM id for this rendering — used as data-pcms-album-id on tracks
296 const albumDomId = 'album-' + Math.random().toString(36).slice(2, 10);
297 const albumJson = JSON.stringify(album.tracks)
298 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
299 const titleH = this.escape(album.title || name);
300 const artistH = this.escape(album.artist || '');
301 const coverH = album.cover ? this.escape(album.cover) : '';
302
303 const trackItems = album.tracks.map((t, i) => {
304 const tTitle = this.escape(t.title || ('Track ' + (i + 1)));
305 const tArtist = this.escape(t.artist || '');
306 const tUrl = this.escape(t.url);
307 return ` <li class="post-audio-track"${t.id ? ` id="track-${t.id}" data-pcms-track-id="${t.id}"` : ''} data-pcms-track-url="${tUrl}" data-pcms-album-id="${albumDomId}">
308 <button type="button" class="pat-play" aria-label="Play ${tTitle}">
309 <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 4l12 8-12 8z"/></svg>
310 </button>
311 <div class="pat-info">
312 <span class="pat-track-num">${i + 1}.</span>
313 <div class="pat-title">${tTitle}</div>
314 ${tArtist && tArtist !== artistH ? `<div class="pat-artist">${tArtist}</div>` : ''}
315 </div>
316 </li>`;
317 }).join('\n');
318
319 return `<div class="post-album" id="${albumDomId}" data-pcms-album='${albumJson}' data-pcms-album-title="${titleH}">
320 <div class="post-album-header">
321 <button type="button" class="post-album-cover-btn" data-pcms-album-id="${albumDomId}" aria-label="Play album ${titleH}">
322 ${coverH
323 ? `<img src="${coverH}" alt="" class="post-album-cover-img">`
324 : `<svg class="post-album-cover-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M9 17V5l12-2v12"/><circle cx="6" cy="17" r="3"/><circle cx="18" cy="15" r="3"/></svg>`}
325 <span class="post-album-play-overlay" aria-hidden="true">
326 <svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 4l12 8-12 8z"/></svg>
327 </span>
328 </button>
329 <div class="post-album-info">
330 <h3 class="post-album-title">${titleH}</h3>
331 ${artistH ? `<p class="post-album-artist">${artistH}</p>` : ''}
332 <p class="post-album-count">${album.tracks.length} track${album.tracks.length === 1 ? '' : 's'}</p>
333 </div>
334 </div>
335 <ol class="post-album-tracks">
336${trackItems}
337 </ol>
338</div>`;
339 });
340 }
341
342 /**
343 * Replace [[playlist:<id>]] shortcodes with a v9-style album block.
344 * Caller passes a lookup function (id) -> hydrated playlist object from
345 * PlaylistService.get(), or null. Unknown playlists render an inline
346 * "niet gevonden" placeholder so the post still validates as HTML.
347 *
348 * Shape returned by lookup:
349 * { id, title, artist, year, cover, kind, tracks: [{url,title,artist,cover,duration}, ...] }
350 *
351 * `kind` is honored:
352 * - 'album' → ordered list with track numbers
353 * - 'playlist' → list with per-track cover thumbnails (mixtape feel)
354 *
355 * opts: { isAdmin: boolean } — when true, an edit/delete action overlay
356 * is rendered top-right of each card. The handlers are wired up in
357 * audio-player.js via event delegation on data-pcms-playlist-delete.
358 */
359 static embedPlaylistShortcodes(html, playlistLookup, opts = {}) {
360 if (!html || typeof playlistLookup !== 'function') return html;
361 const isAdmin = !!opts.isAdmin;
362 return html.replace(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi, (match, rawId) => {
363 const id = rawId.toLowerCase();
364 const pl = playlistLookup(id);
365
366 if (!pl) {
367 return `<div class="post-playlist-missing"><em>Playlist "${this.escape(id)}" niet gevonden.</em></div>`;
368 }
369 if (!pl.tracks || !pl.tracks.length) {
370 return `<div class="post-playlist-empty"><em>Playlist "${this.escape(pl.title)}" heeft geen beschikbare tracks.</em></div>`;
371 }
372
373 const albumDomId = 'album-' + id;
374 const kind = (pl.kind === 'playlist') ? 'playlist' : 'album';
375 const kindLabel = kind === 'playlist' ? '📃 Playlist' : '💿 Album';
376 const titleH = this.escape(pl.title || 'Naamloos');
377 const artistH = this.escape(pl.artist || '');
378 const coverH = pl.cover ? this.escape(pl.cover) : '';
379
380 // Audio-player.js reads data-pcms-album for queue. Same shape as
381 // embedAlbumShortcodes — keep both in sync.
382 const tracksData = pl.tracks.map(t => ({
383 id: t.id,
384 url: t.url,
385 title: t.title,
386 artist: t.artist || pl.artist || '',
387 cover: t.cover || pl.cover || '',
388 }));
389 const albumJson = JSON.stringify(tracksData)
390 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
391
392 // Total duration for the meta line
393 const totalSec = pl.tracks.reduce((s, t) => s + (t.duration || 0), 0);
394 const metaParts = [];
395 if (pl.year) metaParts.push(String(pl.year));
396 metaParts.push(pl.tracks.length + (pl.tracks.length === 1 ? ' track' : ' tracks'));
397 if (totalSec > 0) {
398 const h = Math.floor(totalSec / 3600);
399 const m = Math.floor((totalSec % 3600) / 60);
400 if (h > 0) metaParts.push(`${h}h ${m}m`);
401 else metaParts.push(`${Math.max(1, m)} min`);
402 }
403 const metaLine = this.escape(metaParts.join(' · '));
404 const firstUrl = this.escape(pl.tracks[0].url);
405
406 // Track items — playlist-kind shows per-track cover thumbs, album-kind shows numbers
407 const trackItems = pl.tracks.map((t, i) => {
408 const tTitleH = this.escape(t.title || ('Track ' + (i + 1)));
409 const tArtistH = this.escape(t.artist || '');
410 const tUrl = this.escape(t.url);
411 const showArtist = tArtistH && tArtistH !== artistH;
412
413 // Duration cell — render even when 0 for consistent column layout
414 const durHtml = t.duration > 0
415 ? `<span class="pat-duration">${Math.floor(t.duration / 60)}:${String(t.duration % 60).padStart(2, '0')}</span>`
416 : `<span class="pat-duration pat-duration-empty">—:—</span>`;
417
418 // Leader cell — number for albums, cover thumb for playlists
419 const leader = (kind === 'playlist' && t.cover)
420 ? `<span class="pat-cover" style="background-image:url(${this.escape(t.cover)})" aria-hidden="true"></span>`
421 : `<span class="pat-num">${i + 1}</span>`;
422
423 const trackBase = String(t.url).split('?')[0];
424 return ` <li class="post-album-track-compact"${t.id ? ` id="track-${t.id}" data-pcms-track-id="${t.id}"` : ''}>
425 <button type="button" class="pat-row"
426 data-pcms-track-url="${tUrl}"
427 data-pcms-album-id="${albumDomId}"
428 data-pcms-track-base="${this.escape(trackBase)}"
429 aria-label="Speel ${tTitleH}">
430 ${leader}
431 <span class="pat-meta">
432 <span class="pat-title">${tTitleH}</span>
433 ${showArtist ? `<span class="pat-artist">${tArtistH}</span>` : ''}
434 </span>
435 ${durHtml}
436 </button>
437 </li>`;
438 }).join('\n');
439
440 return `<div class="post-album" id="${albumDomId}"
441 data-pcms-album='${albumJson}'
442 data-pcms-album-title="${titleH}"
443 data-pcms-album-kind="${kind}"
444 data-pcms-playlist-id="${this.escape(id)}">
445${isAdmin ? ` <div class="post-album-actions" role="group" aria-label="Playlist beheren">
446 <a class="post-album-action" href="/admin/playlists?edit=${this.escape(id)}" title="Bewerk playlist" aria-label="Bewerk playlist">
447 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
448 </a>
449 <button type="button" class="post-album-action is-danger" data-pcms-playlist-delete="${this.escape(id)}" data-pcms-playlist-title="${titleH}" title="Verwijder playlist" aria-label="Verwijder playlist">
450 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/></svg>
451 </button>
452 </div>
453` : ''} <div class="post-album-header">
454 <button type="button" class="post-album-cover-btn"
455 data-pcms-track-url="${firstUrl}"
456 data-pcms-album-id="${albumDomId}"
457 aria-label="Speel ${kind === 'playlist' ? 'playlist' : 'album'}">
458 ${coverH
459 ? `<span class="post-album-cover" style="background-image:url('${coverH}')"></span>`
460 : `<span class="post-album-cover post-album-cover-empty">
461 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 17V5l12-2v12"/><circle cx="6" cy="17" r="3" fill="currentColor"/><circle cx="18" cy="15" r="3" fill="currentColor"/></svg>
462 </span>`}
463 <span class="post-album-cover-play" aria-hidden="true">
464 <svg viewBox="0 0 24 24"><path d="M8 4l12 8-12 8z" fill="currentColor"/></svg>
465 </span>
466 </button>
467 <div class="post-album-info">
468 <p class="post-album-label">${kindLabel}</p>
469 <h3 class="post-album-title">${titleH}</h3>
470 ${artistH ? `<p class="post-album-artist">${artistH}</p>` : ''}
471 <p class="post-album-meta">${metaLine}</p>
472 </div>
473 </div>
474 <ol class="post-album-tracks post-album-tracks-compact" data-album-kind="${kind}">
475${trackItems}
476 </ol>
477</div>`;
478 });
479 }
480
481 /**
482 * Human-readable label for a provider slug. Used by external-link buttons.
483 */
484 static platformLabel(provider) {
485 return ({
486 spotify: 'Spotify',
487 bandcamp: 'Bandcamp',
488 soundcloud: 'SoundCloud',
489 applemusic: 'Apple Music',
490 youtube: 'YouTube',
491 vimeo: 'Vimeo',
492 tidal: 'Tidal',
493 deezer: 'Deezer',
494 mixcloud: 'Mixcloud',
495 })[provider] || 'External link';
496 }
497
498 /**
499 * Detect platform from URL purely by hostname (covers more services than
500 * detectProvider, which is embed-focused). Used for [[link:url]] rendering.
501 */
502 static detectLinkPlatform(url) {
503 try {
504 const host = new URL(url).hostname.toLowerCase();
505 if (host.includes('open.spotify.com') || host === 'spotify.com') return 'spotify';
506 if (host.includes('bandcamp.com')) return 'bandcamp';
507 if (host.includes('soundcloud.com')) return 'soundcloud';
508 if (host.includes('music.apple.com') || host.includes('itunes.apple.com')) return 'applemusic';
509 if (host.includes('youtube.com') || host.includes('youtu.be') || host.includes('music.youtube.com')) return 'youtube';
510 if (host.includes('vimeo.com')) return 'vimeo';
511 if (host.includes('tidal.com')) return 'tidal';
512 if (host.includes('deezer.com')) return 'deezer';
513 if (host.includes('mixcloud.com')) return 'mixcloud';
514 return 'other';
515 } catch (e) {
516 return null;
517 }
518 }
519
520 /**
521 * Replace [[link:url]] or [[link:url|Custom Label]] shortcodes with a
522 * branded "Open in <Platform>" anchor (no iframe). Opens in new tab.
523 * Per Robin's v9: "Externe link, klik = open platform (target _blank)".
524 */
525 static embedExternalLinkShortcodes(html) {
526 if (!html) return html;
527 return html.replace(/\[\[link:([^\]|]+)(?:\|([^\]]+))?\]\]/g, (match, rawUrl, customLabel) => {
528 const url = rawUrl.trim();
529 if (!/^https?:\/\//i.test(url)) return match;
530 const platform = this.detectLinkPlatform(url) || 'other';
531 const label = (customLabel || '').trim();
532 const platformLabel = this.platformLabel(platform);
533 const buttonText = label || `Open in ${platformLabel}`;
534 const urlH = this.escape(url);
535 const textH = this.escape(buttonText);
536 return `<a class="post-audio-external post-audio-external--${platform}" href="${urlH}" target="_blank" rel="noopener noreferrer" data-platform="${platform}">
537 <span class="pae-icon" aria-hidden="true">▶</span>
538 <span class="pae-text">${textH}</span>
539 <span class="pae-arrow" aria-hidden="true">↗</span>
540</a>`;
541 });
542 }
543
544 static escape(str) {
545 return str
546 .replace(/&/g, '&amp;')
547 .replace(/</g, '&lt;')
548 .replace(/>/g, '&gt;')
549 .replace(/"/g, '&quot;')
550 .replace(/'/g, '&#39;');
551 }
552}
553
554export default AudioEmbedService;
Note: See TracBrowser for help on using the repository browser.