silverbullet/plugs/editor/embed.ts

48 lines
1.1 KiB
TypeScript
Raw Normal View History

import { YAML } from "@silverbulletmd/silverbullet/syscalls";
2024-02-29 22:23:05 +08:00
import type { WidgetContent } from "../../plug-api/types.ts";
2023-01-21 20:37:55 +08:00
type EmbedConfig = {
url: string;
height?: number;
width?: number;
};
2024-02-24 20:16:04 +08:00
export function extractYoutubeVideoId(url: string) {
2023-01-21 20:37:55 +08:00
let match = url.match(/youtube\.com\/watch\?v=([^&]+)/);
if (match) {
return match[1];
}
match = url.match(/youtu.be\/([^&]+)/);
if (match) {
return match[1];
}
return null;
}
export async function embedWidget(
2023-01-21 20:37:55 +08:00
bodyText: string,
): Promise<WidgetContent> {
2023-01-21 20:37:55 +08:00
try {
const data: EmbedConfig = await YAML.parse(bodyText) as any;
2023-01-21 20:37:55 +08:00
let url = data.url;
const youtubeVideoId = extractYoutubeVideoId(url);
if (youtubeVideoId) {
url = `https://www.youtube.com/embed/${youtubeVideoId}`;
// Sensible video defaults
data.width = data.width || 560;
data.height = data.height || 315;
}
return {
url,
height: data.height,
width: data.width,
};
} catch (e: any) {
return {
html: `ERROR: Could not parse body as YAML: ${e.message}`,
script: "",
};
}
}