From 2ada5ff3760b994e268f87b3b28c2b50531996a0 Mon Sep 17 00:00:00 2001 From: Jonas Date: Wed, 12 Jun 2024 15:52:51 +0200 Subject: [PATCH] feat(link): Add input rule to insert links using markdown syntax Fixes: #55 Code ideas taken from https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/content_editor/extensions/link.js Signed-off-by: Jonas --- src/marks/Link.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/marks/Link.js b/src/marks/Link.js index 545cf758a92..f5d713183a7 100644 --- a/src/marks/Link.js +++ b/src/marks/Link.js @@ -20,10 +20,27 @@ * */ +import { markInputRule } from '@tiptap/core' import TipTapLink from '@tiptap/extension-link' import { domHref, parseHref } from './../helpers/links.js' import { linkClicking } from '../plugins/links.js' +const extractHrefFromMatch = (match) => { + return { href: match.groups.href } +} + +const extractHrefFromMarkdownLink = (match) => { + /** + * Removes the last capture group from the match to satisfy + * Tiptap markInputRule expectation of having the content as + * the last capture group in the match. + * + * https://github.com/ueberdosis/tiptap/blob/%40tiptap/core%402.0.0-beta.75/packages/core/src/inputRules/markInputRule.ts#L11 + */ + match.pop() + return extractHrefFromMatch(match) +} + const Link = TipTapLink.extend({ addOptions() { @@ -66,6 +83,17 @@ const Link = TipTapLink.extend({ }, 0] }, + addInputRules() { + const linkInputRegex = /(?:^|\s)\[([\w|\s|-]+)\]\((?.+?)\)$/gm + return [ + markInputRule({ + find: linkInputRegex, + type: this.type, + getAttributes: extractHrefFromMarkdownLink, + }), + ] + }, + addProseMirrorPlugins() { const plugins = this.parent() // remove upstream link click handle plugin