From 4e070551c588a5ec1fef2f48d48744cd2d936296 Mon Sep 17 00:00:00 2001 From: "plebeius.eth" Date: Sun, 24 Mar 2024 11:04:23 +0100 Subject: [PATCH] feat(media utils): add embed support for custom youtube links, eg from invidious instances --- src/components/post/embed/embed.tsx | 43 +++++--- src/lib/utils/media-utils.ts | 154 ++++++++++++---------------- 2 files changed, 91 insertions(+), 106 deletions(-) diff --git a/src/components/post/embed/embed.tsx b/src/components/post/embed/embed.tsx index 7d7d3a8e..d1d27f25 100644 --- a/src/components/post/embed/embed.tsx +++ b/src/components/post/embed/embed.tsx @@ -7,7 +7,13 @@ interface EmbedProps { const Embed = ({ url }: EmbedProps) => { const parsedUrl = new URL(url); - if (youtubeHosts.has(parsedUrl.host)) { + const isYoutubeVideoUrl = (parsedUrl: URL): boolean => { + const youtubeVideoPattern = /\/watch\?v=/; + const youtubeHostPatterns = /^(www\.)?(youtube\.com|youtu\.be|yt\.)$/; + return youtubeVideoPattern.test(parsedUrl.pathname + parsedUrl.search) || youtubeHostPatterns.test(parsedUrl.host); + }; + + if (isYoutubeVideoUrl(parsedUrl)) { return ; } if (xHosts.has(parsedUrl.host)) { @@ -46,23 +52,26 @@ interface EmbedComponentProps { const youtubeHosts = new Set(['youtube.com', 'www.youtube.com', 'youtu.be', 'www.youtu.be', 'm.youtube.com']); const YoutubeEmbed = ({ parsedUrl }: EmbedComponentProps) => { - let youtubeId; - if (parsedUrl.host.endsWith('youtu.be')) { - youtubeId = parsedUrl.pathname.replaceAll('/', ''); - } else { - youtubeId = parsedUrl.searchParams.get('v'); + let youtubeId = parsedUrl.searchParams.get('v'); + + if (!youtubeId && parsedUrl.host.includes('youtu.be')) { + youtubeId = parsedUrl.pathname.substring(1); } - return ( -