tiptap/packages/extension-link/index.ts

85 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-09-25 04:26:23 +08:00
import {
2020-09-25 05:50:02 +08:00
Command, Mark, markPasteRule,
2020-09-25 04:26:23 +08:00
} from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
export interface LinkOptions {
openOnClick: boolean,
target: string,
}
export type LinkCommand = () => Command
declare module '@tiptap/core/src/Editor' {
interface Commands {
link: LinkCommand,
}
}
2020-09-25 05:42:04 +08:00
export const pasteRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%_+.~#?&//=]*)/gi
2020-09-25 04:26:23 +08:00
export default new Mark<LinkOptions>()
.name('link')
.defaults({
openOnClick: true,
target: '',
})
.schema(({ options }) => ({
attrs: {
href: {
default: null,
},
target: {
default: null,
},
},
inclusive: false,
parseDOM: [
{
tag: 'a[href]',
getAttrs: node => ({
href: (node as HTMLElement).getAttribute('href'),
target: (node as HTMLElement).getAttribute('target'),
}),
},
],
toDOM: node => ['a', {
...node.attrs,
rel: 'noopener noreferrer nofollow',
target: options.target,
}, 0],
}))
.commands(({ name }) => ({
link: () => ({ commands }) => {
return commands.toggleMark(name)
},
}))
.pasteRules(({ type }) => [
2020-09-25 05:42:04 +08:00
markPasteRule(pasteRegex, type, (url: string) => ({ href: url })),
2020-09-25 04:26:23 +08:00
])
2020-09-25 05:50:02 +08:00
.plugins(({ editor, options, name }) => {
2020-09-25 04:26:23 +08:00
if (!options.openOnClick) {
return []
}
return [
new Plugin({
key: new PluginKey('handleClick'),
props: {
handleClick: (view, pos, event) => {
2020-09-25 05:50:02 +08:00
const attrs = editor.getMarkAttrs(name)
2020-09-25 04:26:23 +08:00
if (attrs.href && event.target instanceof HTMLAnchorElement) {
window.open(attrs.href, attrs.target)
return false
}
return true
},
},
}),
]
})
.create()