tiptap/packages/extension-link/index.ts

91 lines
2.0 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,
2020-09-26 01:05:21 +08:00
rel: string,
2020-09-25 04:26:23 +08:00
}
2020-09-26 01:05:21 +08:00
export type LinkCommand = (options: {href?: string, target?: string}) => Command
2020-09-25 04:26:23 +08:00
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,
2020-09-26 01:05:21 +08:00
target: '_self',
rel: 'noopener noreferrer nofollow',
2020-09-25 04:26:23 +08:00
})
.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,
2020-09-26 01:05:21 +08:00
rel: options.rel,
target: node.attrs.target ? node.attrs.target : options.target,
2020-09-25 04:26:23 +08:00
}, 0],
}))
.commands(({ name }) => ({
2020-09-26 01:05:21 +08:00
link: attributes => ({ commands }) => {
if (!attributes.href) {
2020-09-25 20:17:53 +08:00
return commands.removeMark(name)
}
2020-09-26 01:05:21 +08:00
return commands.updateMark(name, attributes)
2020-09-25 04:26:23 +08:00
},
}))
.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()