your personal website on atproto - mirror
blento.app
1import type { CardDefinition } from '../types';
2import YoutubeCard from './YoutubeCard.svelte';
3import YoutubeCardSettings from './YoutubeCardSettings.svelte';
4
5export const YoutubeCardDefinition = {
6 type: 'youtubeVideo',
7 contentComponent: YoutubeCard,
8 settingsComponent: YoutubeCardSettings,
9 createNew: (card) => {
10 card.cardType = 'youtubeVideo';
11 card.cardData = {};
12 card.w = 4;
13 card.mobileW = 8;
14 },
15
16 onUrlHandler: (url, item) => {
17 const id = matcher(url);
18 if (!id) return;
19
20 const posterFile = 'hqdefault';
21 const posterURL = `https://i.ytimg.com/vi/${id}/${posterFile}.jpg`;
22
23 item.cardData.poster = posterURL;
24 item.cardData.youtubeId = id;
25 item.cardData.href = url;
26 item.cardData.showInline = true;
27
28 item.w = 4;
29 item.mobileW = 8;
30 item.h = 3;
31 item.mobileH = 5;
32
33 return item;
34 },
35 urlHandlerPriority: 2,
36
37 canChange: (item) => Boolean(matcher(item.cardData.href)),
38
39 change: (item) => {
40 const href = item.cardData?.href;
41
42 const id = matcher(href);
43 if (!id) return;
44
45 const posterFile = 'hqdefault';
46 const posterURL = `https://i.ytimg.com/vi/${id}/${posterFile}.jpg`;
47
48 item.cardData.poster = posterURL;
49 item.cardData.youtubeId = id;
50 item.cardData.showInline ??= true;
51
52 return item;
53 },
54 name: 'Youtube Video'
55} as CardDefinition & { type: 'youtubeVideo' };
56
57// Thanks to eleventy-plugin-youtube-embed
58// https://github.com/gfscott/eleventy-plugin-youtube-embed/blob/main/lib/extractMatches.js
59const urlPattern =
60 /(?=(\s*))\1(?:<a [^>]*?>)??(?=(\s*))\2(?:https?:\/\/)??(?:w{3}\.)??(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|shorts\/)??([A-Za-z0-9-_]{11})(?:[^\s<>]*)(?=(\s*))\4(?:<\/a>)??(?=(\s*))\5/;
61
62/**
63 * Extract a YouTube ID from a URL if it matches the pattern.
64 * @param url URL to test
65 * @returns A YouTube video ID or undefined if none matched
66 */
67export function matcher(url: string | undefined): string | undefined {
68 if (!url) return;
69
70 const match = url.match(urlPattern);
71 return match?.[3];
72}