refactor link extension

This commit is contained in:
Philipp Kühn 2020-10-25 22:11:53 +01:00
parent 16d52d05a0
commit ac9fdf6481
3 changed files with 38 additions and 36 deletions

View File

@ -18,3 +18,4 @@ export { default as getSchema } from './src/utils/getSchema'
export { default as generateHtml } from './src/utils/generateHtml'
export { default as getHtmlFromFragment } from './src/utils/getHtmlFromFragment'
export { default as getMarkAttrs } from './src/utils/getMarkAttrs'
export { default as mergeAttributes } from './src/utils/mergeAttributes'

View File

@ -1,23 +1,25 @@
import { AnyObject } from '../types'
export default function mergeAttributes(attributes1: AnyObject, attributes2: AnyObject) {
const mergedAttributes = { ...attributes1 }
export default function mergeAttributes(...object: AnyObject[]) {
return object.reduce((items, item) => {
const mergedAttributes = { ...items }
Object.entries(attributes2).forEach(([key, value]) => {
if (!mergedAttributes[key]) {
mergedAttributes[key] = value
return
}
Object.entries(item).forEach(([key, value]) => {
if (!mergedAttributes[key]) {
mergedAttributes[key] = value
return
}
if (key === 'class') {
mergedAttributes[key] = [mergedAttributes[key], value].join(' ')
return
}
if (key === 'class') {
mergedAttributes[key] = [mergedAttributes[key], value].join(' ')
return
}
if (key === 'style') {
mergedAttributes[key] = [mergedAttributes[key], value].join('; ')
}
})
if (key === 'style') {
mergedAttributes[key] = [mergedAttributes[key], value].join('; ')
}
})
return mergedAttributes
return mergedAttributes
}, {})
}

View File

@ -1,4 +1,6 @@
import { Command, createMark, markPasteRule } from '@tiptap/core'
import {
Command, createMark, markPasteRule, mergeAttributes,
} from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
export interface LinkOptions {
@ -24,34 +26,31 @@ const Link = createMark({
return {
href: {
default: null,
rendered: false,
renderHTML: attributes => ({
href: attributes.href,
}),
parseHTML: node => ({
href: node.getAttribute('href'),
}),
},
target: {
default: null,
rendered: false,
default: this.options.target,
renderHTML: attributes => ({
target: attributes.target,
}),
parseHTML: node => ({
target: node.getAttribute('target'),
}),
},
}
},
parseHTML() {
return [
{
tag: 'a[href]',
getAttrs: node => ({
href: (node as HTMLElement).getAttribute('href'),
target: (node as HTMLElement).getAttribute('target'),
}),
},
]
return [{ tag: 'a[href]' }]
},
renderHTML({ mark, attributes }) {
return ['a', {
...attributes,
...mark.attrs,
rel: this.options.rel,
target: mark.attrs.target ? mark.attrs.target : this.options.target,
}, 0]
renderHTML({ attributes }) {
return ['a', mergeAttributes(attributes, { rel: this.options.rel }), 0]
},
addCommands() {