feat(extension-link): add validate option to link extension

#2779
This commit is contained in:
Dominik Biedebach
2022-05-13 11:36:46 +02:00
committed by Dominik
parent ccc37d5f24
commit 23e67adfa7
10 changed files with 276 additions and 9 deletions

View File

@@ -1,15 +1,17 @@
import {
getMarksBetween,
findChildrenInRange,
combineTransactionSteps,
getChangedRanges,
} from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
import { MarkType } from 'prosemirror-model'
import { find, test } from 'linkifyjs'
import { MarkType } from 'prosemirror-model'
import { Plugin, PluginKey } from 'prosemirror-state'
import {
combineTransactionSteps,
findChildrenInRange,
getChangedRanges,
getMarksBetween,
} from '@tiptap/core'
type AutolinkOptions = {
type: MarkType,
validate?: (url: string) => boolean,
}
export function autolink(options: AutolinkOptions): Plugin {
@@ -70,6 +72,13 @@ export function autolink(options: AutolinkOptions): Plugin {
find(text)
.filter(link => link.isLink)
.filter(link => {
if (options.validate) {
return options.validate(link.value)
}
return true
})
// calculate link position
.map(link => ({
...link,

View File

@@ -1,5 +1,7 @@
import { Mark, markPasteRule, mergeAttributes } from '@tiptap/core'
import { find } from 'linkifyjs'
import { Mark, markPasteRule, mergeAttributes } from '@tiptap/core'
import { autolink } from './helpers/autolink'
import { clickHandler } from './helpers/clickHandler'
import { pasteHandler } from './helpers/pasteHandler'
@@ -21,6 +23,12 @@ export interface LinkOptions {
* A list of HTML attributes to be rendered.
*/
HTMLAttributes: Record<string, any>,
/**
* A validation function that modifies link verification for the auto linker.
* @param url - The url to be validated.
* @returns - True if the url is valid, false otherwise.
*/
validate?: (url: string) => boolean,
}
declare module '@tiptap/core' {
@@ -63,6 +71,7 @@ export const Link = Mark.create<LinkOptions>({
rel: 'noopener noreferrer nofollow',
class: null,
},
validate: undefined,
}
},
@@ -143,6 +152,7 @@ export const Link = Mark.create<LinkOptions>({
if (this.options.autolink) {
plugins.push(autolink({
type: this.type,
validate: this.options.validate,
}))
}