merge HTMLAttributes

This commit is contained in:
Philipp Kühn
2020-11-14 17:27:59 +01:00
parent 9d7e022ccb
commit 2a321f6739
4 changed files with 41 additions and 28 deletions

View File

@@ -6,6 +6,7 @@ import getRenderedAttributes from './getRenderedAttributes'
import isEmptyObject from './isEmptyObject'
import injectExtensionAttributesToParseRule from './injectExtensionAttributesToParseRule'
import callOrReturn from './callOrReturn'
import mergeAttributes from './mergeAttributes'
function cleanUpSchemaItem<T>(data: T) {
return Object.fromEntries(Object.entries(data).filter(([key, value]) => {
@@ -50,7 +51,10 @@ export default function getSchema(extensions: Extensions): Schema {
if (extension.renderHTML) {
schema.toDOM = node => (extension.renderHTML as Function)?.bind(context)({
node,
HTMLAttributes: getRenderedAttributes(node, extensionAttributes),
HTMLAttributes: mergeAttributes(
extension.options.HTMLAttributes,
getRenderedAttributes(node, extensionAttributes),
),
})
}
@@ -79,7 +83,10 @@ export default function getSchema(extensions: Extensions): Schema {
if (extension.renderHTML) {
schema.toDOM = mark => (extension.renderHTML as Function)?.bind(context)({
mark,
HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),
HTMLAttributes: mergeAttributes(
extension.options.HTMLAttributes,
getRenderedAttributes(mark, extensionAttributes),
),
})
}

View File

@@ -1,7 +1,9 @@
import { AnyObject } from '../types'
export default function mergeAttributes(...object: AnyObject[]) {
return object.reduce((items, item) => {
export default function mergeAttributes(...objects: AnyObject[]) {
return objects
.filter(item => !!item)
.reduce((items, item) => {
const mergedAttributes = { ...items }
Object.entries(item).forEach(([key, value]) => {

View File

@@ -1,9 +1,4 @@
import {
Command,
createMark,
markPasteRule,
mergeAttributes,
} from '@tiptap/core'
import { Command, createMark, markPasteRule } from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
export interface LinkOptions {
@@ -46,7 +41,7 @@ const Link = createMark({
},
renderHTML({ HTMLAttributes }) {
return ['a', mergeAttributes(HTMLAttributes, { rel: this.options.HTMLAttributes.rel }), 0]
return ['a', HTMLAttributes, 0]
},
addCommands() {

View File

@@ -57,4 +57,13 @@ describe('mergeAttributes', () => {
style: 'color: red; background: green',
})
})
it('should ignore falsy values', () => {
// @ts-expect-error
const value = mergeAttributes(undefined, { class: 'foo' })
expect(value).to.deep.eq({
class: 'foo',
})
})
})