tiptap/packages/extension-link/index.ts

116 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-09-25 04:26:23 +08:00
import {
2020-10-22 18:34:49 +08:00
Command, createMark, 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-10-22 18:34:49 +08:00
// export type LinkCommand = (options: {href?: string, target?: string}) => Command
2020-09-25 04:26:23 +08:00
2020-10-22 18:34:49 +08:00
// declare module '@tiptap/core/src/Editor' {
// interface Commands {
// link: LinkCommand,
// }
// }
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-22 18:34:49 +08:00
export default createMark({
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,
2020-10-22 18:34:49 +08:00
rendered: false,
2020-09-25 04:26:23 +08:00
},
target: {
default: null,
2020-10-22 18:34:49 +08:00
rendered: false,
2020-09-25 04:26:23 +08:00
},
2020-10-22 18:34:49 +08:00
}
},
parseHTML() {
return [
2020-09-25 04:26:23 +08:00
{
tag: 'a[href]',
getAttrs: node => ({
href: (node as HTMLElement).getAttribute('href'),
target: (node as HTMLElement).getAttribute('target'),
}),
},
2020-10-22 18:34:49 +08:00
]
},
renderHTML({ mark, attributes }) {
return ['a', {
...attributes,
...mark.attrs,
rel: this.options.rel,
target: mark.attrs.target ? mark.attrs.target : this.options.target,
}, 0]
},
addCommands() {
return {
link: attributes => ({ commands }) => {
if (!attributes.href) {
return commands.removeMark('link')
}
return commands.updateMark('link', attributes)
},
}
},
addKeyboardShortcuts() {
return {
'Mod-i': () => this.editor.italic(),
}
},
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
},
})