tiptap/packages/extension-link/index.ts

97 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-10-26 05:11:53 +08:00
import {
Command, createMark, markPasteRule, mergeAttributes,
} from '@tiptap/core'
2020-09-25 04:26:23 +08:00
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-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
2020-10-23 04:40:40 +08:00
const Link = createMark({
2020-10-22 18:34:49 +08:00
name: 'link',
inclusive: false,
defaultOptions: <LinkOptions>{
2020-09-25 04:26:23 +08:00
openOnClick: true,
2020-09-27 16:41:20 +08:00
target: '_blank',
2020-09-26 01:05:21 +08:00
rel: 'noopener noreferrer nofollow',
2020-10-22 18:34:49 +08:00
},
addAttributes() {
return {
2020-09-25 04:26:23 +08:00
href: {
default: null,
},
target: {
2020-10-26 05:11:53 +08:00
default: this.options.target,
2020-09-25 04:26:23 +08:00
},
2020-10-22 18:34:49 +08:00
}
},
parseHTML() {
2020-10-27 19:59:18 +08:00
return [
{ tag: 'a[href]' },
]
2020-10-22 18:34:49 +08:00
},
2020-10-26 05:11:53 +08:00
renderHTML({ attributes }) {
return ['a', mergeAttributes(attributes, { rel: this.options.rel }), 0]
2020-10-22 18:34:49 +08:00
},
addCommands() {
return {
2020-10-23 17:41:24 +08:00
link: (options: { href?: string, target?: string } = {}): Command => ({ commands }) => {
2020-10-23 04:40:40 +08:00
if (!options.href) {
2020-10-22 18:34:49 +08:00
return commands.removeMark('link')
}
2020-10-23 04:40:40 +08:00
return commands.updateMark('link', options)
2020-10-22 18:34:49 +08:00
},
}
},
addPasteRules() {
return [
markPasteRule(pasteRegex, this.type, (url: string) => ({ href: url })),
]
},
addProseMirrorPlugins() {
if (!this.options.openOnClick) {
2020-09-25 04:26:23 +08:00
return []
}
return [
new Plugin({
key: new PluginKey('handleClick'),
props: {
handleClick: (view, pos, event) => {
2020-10-22 18:34:49 +08:00
const attrs = this.editor.getMarkAttrs('link')
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
},
},
}),
]
2020-10-22 18:34:49 +08:00
},
})
2020-10-23 04:40:40 +08:00
export default Link
declare module '@tiptap/core/src/Editor' {
interface AllExtensions {
Link: typeof Link,
}
}