feat: third-party embeds (#423)

* wip

* Add more providers

* icons

* unify embed providers (Youtube)

* fix case

* YT music

* remove redundant code
This commit is contained in:
Philip Okugbe
2024-10-29 18:13:20 +00:00
committed by GitHub
parent 978fadd6b9
commit ab70cee278
21 changed files with 667 additions and 41 deletions

View File

@ -0,0 +1,111 @@
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { useMemo } from "react";
import clsx from "clsx";
import { ActionIcon, AspectRatio, Button, Card, FocusTrap, Group, Popover, Text, TextInput } from "@mantine/core";
import { IconEdit } from "@tabler/icons-react";
import { z } from "zod";
import { useForm, zodResolver } from "@mantine/form";
import {
getEmbedProviderById,
getEmbedUrlAndProvider
} from "@/features/editor/components/embed/providers.ts";
import { notifications } from '@mantine/notifications';
const schema = z.object({
url: z
.string().trim().url({ message: 'please enter a valid url' }),
});
export default function EmbedView(props: NodeViewProps) {
const { node, selected, updateAttributes } = props;
const { src, provider } = node.attrs;
const embedUrl = useMemo(() => {
if (src) {
return getEmbedUrlAndProvider(src).embedUrl;
}
return null;
}, [src]);
const embedForm = useForm<{ url: string }>({
initialValues: {
url: "",
},
validate: zodResolver(schema),
});
async function onSubmit(data: { url: string }) {
if (provider) {
const embedProvider = getEmbedProviderById(provider);
if (embedProvider.regex.test(data.url)) {
updateAttributes({ src: data.url });
} else {
notifications.show({
message: `Invalid ${provider} embed link`,
position: 'top-right',
color: 'red'
});
}
}
}
return (
<NodeViewWrapper>
{embedUrl ? (
<>
<AspectRatio ratio={16 / 9}>
<iframe
src={embedUrl}
allow="encrypted-media"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
allowFullScreen
frameBorder="0"
></iframe>
</AspectRatio>
</>
) : (
<Popover width={300} position="bottom" withArrow shadow="md">
<Popover.Target>
<Card
radius="md"
p="xs"
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
withBorder
className={clsx(selected ? 'ProseMirror-selectednode' : '')}
>
<div style={{ display: 'flex', alignItems: 'center' }}>
<ActionIcon variant="transparent" color="gray">
<IconEdit size={18} />
</ActionIcon>
<Text component="span" size="lg" c="dimmed">
Embed {getEmbedProviderById(provider).name}
</Text>
</div>
</Card>
</Popover.Target>
<Popover.Dropdown bg="var(--mantine-color-body)">
<form onSubmit={embedForm.onSubmit(onSubmit)}>
<FocusTrap active={true}>
<TextInput placeholder={`Enter ${getEmbedProviderById(provider).name} link to embed`}
key={embedForm.key('url')}
{... embedForm.getInputProps('url')}
data-autofocus
/>
</FocusTrap>
<Group justify="center" mt="xs">
<Button type="submit">Embed link</Button>
</Group>
</form>
</Popover.Dropdown>
</Popover>
)}
</NodeViewWrapper>
);
}

View File

@ -0,0 +1,109 @@
export interface IEmbedProvider {
id: string;
name: string;
regex: RegExp;
getEmbedUrl: (match: RegExpMatchArray, url?: string) => string;
}
export const embedProviders: IEmbedProvider[] = [
{
id: 'loom',
name: 'Loom',
regex: /^https?:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-zA-Z]+)\/?/,
getEmbedUrl: (match) => {
return `https://loom.com/embed/${match[1]}`;
}
},
{
id: 'airtable',
name: 'Airtable',
regex: /^https:\/\/(www.)?airtable.com\/([a-zA-Z0-9]{2,})\/.*/,
getEmbedUrl: (match, url: string) => {
const path = url.split('airtable.com/');
return `https://airtable.com/embed/${path[1]}`;
}
},
{
id: 'figma',
name: 'Figma',
regex: /^https:\/\/[\w\.-]+\.?figma.com\/(file|proto|board|design|slides|deck)\/([0-9a-zA-Z]{22,128})/,
getEmbedUrl: (match, url: string) => {
return `https://www.figma.com/embed?url=${url}&embed_host=docmost`;
}
},
{
'id': 'typeform',
name: 'Typeform',
regex: /^(https?:)?(\/\/)?[\w\.]+\.typeform\.com\/to\/.+/,
getEmbedUrl: (match, url: string) => {
return url;
}
},
{
id: 'miro',
name: 'Miro',
regex: /^https:\/\/(www\.)?miro\.com\/app\/board\/([\w-]+=)/,
getEmbedUrl: (match) => {
return `https://miro.com/app/live-embed/${match[2]}?embedMode=view_only_without_ui&autoplay=true&embedSource=docmost`;
}
},
{
id: 'youtube',
name: 'YouTube',
regex: /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/,
getEmbedUrl: (match) => {
return `https://www.youtube-nocookie.com/embed/${match[5]}`;
}
},
{
id: 'vimeo',
name: 'Vimeo',
regex: /^(https:)?\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)/,
getEmbedUrl: (match) => {
return `https://player.vimeo.com/video/${match[4]}`;
}
},
{
id: 'framer',
name: 'Framer',
regex: /^https:\/\/(www\.)?framer\.com\/embed\/([\w-]+)/,
getEmbedUrl: (match, url: string) => {
return url;
}
},
{
id: 'gdrive',
name: 'Google Drive',
regex: /^((?:https?:)?\/\/)?((?:www|m)\.)?(drive\.google\.com)\/file\/d\/([a-zA-Z0-9_-]+)\/.*$/,
getEmbedUrl: (match) => {
return `https://drive.google.com/file/d/${match[4]}/preview`;
}
},
];
export function getEmbedProviderById(id: string) {
return embedProviders.find(provider => provider.id.toLowerCase() === id.toLowerCase());
}
export interface IEmbedResult {
embedUrl: string;
provider: string;
}
export function getEmbedUrlAndProvider(url: string): IEmbedResult {
for (const provider of embedProviders) {
const match = url.match(provider.regex);
if (match) {
return {
embedUrl: provider.getEmbedUrl(match, url),
provider: provider.name.toLowerCase()
};
}
}
return {
embedUrl: url,
provider: 'iframe',
};
}

View File

@ -29,6 +29,16 @@ import { uploadAttachmentAction } from "@/features/editor/components/attachment/
import IconExcalidraw from "@/components/icons/icon-excalidraw";
import IconMermaid from "@/components/icons/icon-mermaid";
import IconDrawio from "@/components/icons/icon-drawio";
import {
AirtableIcon,
FigmaIcon,
FramerIcon,
GoogleDriveIcon,
LoomIcon,
MiroIcon,
TypeformIcon,
VimeoIcon, YoutubeIcon
} from "@/components/icons";
const CommandGroups: SlashMenuGroupedItemsType = {
basic: [
@ -343,7 +353,7 @@ const CommandGroups: SlashMenuGroupedItemsType = {
day: "numeric",
});
return editor
editor
.chain()
.focus()
.deleteRange(range)
@ -351,6 +361,87 @@ const CommandGroups: SlashMenuGroupedItemsType = {
.run();
},
},
{
title: "Airtable",
description: "Embed Airtable",
searchTerms: ["airtable"],
icon: AirtableIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'airtable' }).run();
},
},
{
title: "Loom",
description: "Embed Loom video",
searchTerms: ["loom"],
icon: LoomIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'loom' }).run();
},
},
{
title: "Figma",
description: "Embed Figma files",
searchTerms: ["figma"],
icon: FigmaIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'figma' }).run();
},
},
{
title: "Typeform",
description: "Embed Typeform",
searchTerms: ["typeform"],
icon: TypeformIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'typeform' }).run();
},
},
{
title: "Miro",
description: "Embed Miro board",
searchTerms: ["miro"],
icon: MiroIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'miro' }).run();
},
},
{
title: "YouTube",
description: "Embed YouTube video",
searchTerms: ["youtube", "yt"],
icon: YoutubeIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'youtube' }).run();
},
},
{
title: "Vimeo",
description: "Embed Vimeo video",
searchTerms: ["vimeo"],
icon: VimeoIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'vimeo' }).run();
},
},
{
title: "Framer",
description: "Embed Framer prototype",
searchTerms: ["framer"],
icon: FramerIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'framer' }).run();
},
},
{
title: "Google Drive",
description: "Embed Google Drive content",
searchTerms: ["google drive", "gdrive"],
icon: GoogleDriveIcon,
command: ({ editor, range }: CommandProps) => {
editor.chain().focus().deleteRange(range).setEmbed({ provider: 'gdrive' }).run();
},
},
],
};
@ -362,7 +453,7 @@ export const getSuggestionItems = ({
const search = query.toLowerCase();
const filteredGroups: SlashMenuGroupedItemsType = {};
const fuzzyMatch = (query, target) => {
const fuzzyMatch = (query: string, target: string) => {
let queryIndex = 0;
target = target.toLowerCase();
for (let char of target) {

View File

@ -35,6 +35,7 @@ import {
CustomCodeBlock,
Drawio,
Excalidraw,
Embed
} from "@docmost/editor-ext";
import {
randomElement,
@ -53,6 +54,7 @@ import AttachmentView from "@/features/editor/components/attachment/attachment-v
import CodeBlockView from "@/features/editor/components/code-block/code-block-view.tsx";
import DrawioView from "../components/drawio/drawio-view";
import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-view.tsx";
import EmbedView from "@/features/editor/components/embed/embed-view.tsx";
import plaintext from "highlight.js/lib/languages/plaintext";
import powershell from "highlight.js/lib/languages/powershell";
import elixir from "highlight.js/lib/languages/elixir";
@ -149,6 +151,7 @@ export const mainExtensions = [
DetailsSummary,
DetailsContent,
Youtube.configure({
addPasteHandler: false,
controls: true,
nocookie: true,
}),
@ -179,6 +182,9 @@ export const mainExtensions = [
Excalidraw.configure({
view: ExcalidrawView,
}),
Embed.configure({
view: EmbedView,
})
] as any;
type CollabExtensions = (provider: HocuspocusProvider, user: IUser) => any[];