From ec595ff8037319efa10cea995c62442c3d8d3959 Mon Sep 17 00:00:00 2001 From: Dominik Biedebach Date: Sat, 25 Jun 2022 11:16:17 +0200 Subject: [PATCH] feat(extension/youtube): add paste handlers for youtube extension --- packages/extension-youtube/src/utils.ts | 5 ++- packages/extension-youtube/src/youtube.ts | 48 +++++++++++++++++------ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/packages/extension-youtube/src/utils.ts b/packages/extension-youtube/src/utils.ts index b381cad2..e0d69cf7 100644 --- a/packages/extension-youtube/src/utils.ts +++ b/packages/extension-youtube/src/utils.ts @@ -1,5 +1,8 @@ +export const YOUTUBE_REGEX = /^(https?:\/\/)?(www\.|music\.)?(youtube\.com|youtu\.be)(.+)?$/ +export const YOUTUBE_REGEX_GLOBAL = /^(https?:\/\/)?(www\.|music\.)?(youtube\.com|youtu\.be)(.+)?$/g + export const isValidYoutubeUrl = (url: string) => { - return url.match(/^(https?:\/\/)?(www\.|music\.)?(youtube\.com|youtu\.be)(.+)?$/) + return url.match(YOUTUBE_REGEX) } export interface GetEmbedUrlOptions { diff --git a/packages/extension-youtube/src/youtube.ts b/packages/extension-youtube/src/youtube.ts index 524feb01..d0cdb5bb 100644 --- a/packages/extension-youtube/src/youtube.ts +++ b/packages/extension-youtube/src/youtube.ts @@ -1,15 +1,16 @@ -import { mergeAttributes, Node } from '@tiptap/core' +import { mergeAttributes, Node, PasteRule } from '@tiptap/core' -import { getEmbedURLFromYoutubeURL, isValidYoutubeUrl } from './utils' +import { getEmbedURLFromYoutubeURL, isValidYoutubeUrl, YOUTUBE_REGEX_GLOBAL } from './utils' export interface YoutubeOptions { - inline: boolean; - width: number; - height: number; - controls: boolean; - nocookie: boolean; + addPasteHandler: boolean; allowFullscreen: boolean; + controls: boolean; + height: number; HTMLAttributes: Record, + inline: boolean; + nocookie: boolean; + width: number; } declare module '@tiptap/core' { @@ -28,13 +29,14 @@ export const Youtube = Node.create({ addOptions() { return { - inline: false, - controls: true, - HTMLAttributes: {}, - nocookie: false, + addPasteHandler: true, allowFullscreen: false, - width: 640, + controls: true, height: 480, + HTMLAttributes: {}, + inline: false, + nocookie: false, + width: 640, } }, @@ -88,6 +90,28 @@ export const Youtube = Node.create({ } }, + addPasteRules() { + if (!this.options.addPasteHandler) { + return [] + } + + return [ + new PasteRule({ + find: YOUTUBE_REGEX_GLOBAL, + + handler({ match, chain, range }) { + if (match.input) { + chain() + .deleteRange(range) + .setYoutubeVideo({ + src: match.input, + }) + } + }, + }), + ] + }, + renderHTML({ HTMLAttributes }) { const embedUrl = getEmbedURLFromYoutubeURL({ url: HTMLAttributes.src,