Skip to content

Commit

Permalink
fix youtube embeds and add support for vimeo and twitter
Browse files Browse the repository at this point in the history
  • Loading branch information
laughedelic committed Nov 13, 2024
1 parent 22b4161 commit 9669bab
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,20 @@ const convertFrontmatter: ConversionRule = {
},
};

const PATTERNS = {
// Matches Vimeo video URLs, capturing the video ID
vimeo:
/(?:https?:\/\/)?(?:(?:www|player)\.)?vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|video\/|)(\d+)(?:$|\/|\?|#|\&)/,

// Matches YouTube URLs (regular videos, shorts, and embeds), capturing the video ID
youtube:
/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/).*$/,

// Matches Twitter/X status URLs, capturing the tweet ID
twitter:
/(?:https?:\/\/)?(?:www\.)?(?:twitter\.com|x\.com)\/(?:\w+)\/status\/(\d+)(?:\/?\w*\/?)*(?:\?.*)?$/,
};

const convertEmbeds: ConversionRule = {
name: "embeds",
convert: (content: string) => {
Expand All @@ -407,17 +421,19 @@ const convertEmbeds: ConversionRule = {
return `{{embed [[${embed}]]}}`;
});

// Convert video embeds from YouTube and Vimeo
// NOTE: might not handle all possible short URLs
// Convert embeds from YouTube, Vimeo, and Twitter
content = content.replace(
/!\[(.*?)\]\((https:\/\/(?:www\.)?(youtube\.com\/watch\?v=|youtu\.be\/|vimeo\.com\/)[^\s)]+)\)/g,
/!\[(.*?)\]\((https:\/\/[^\s)]+)\)/g,
(_match, _altText, url) => {
return `{{video ${url}}}`;
if (PATTERNS.youtube.test(url) || PATTERNS.vimeo.test(url)) {
return `{{video ${url}}}`;
} else if (PATTERNS.twitter.test(url)) {
return `{{tweet ${url}}}`;
}
return _match; // Preserve other URLs as is
},
);

// TODO: another case for tweets/x

return content;
},
};
Expand Down

0 comments on commit 9669bab

Please sign in to comment.