merge attributes

This commit is contained in:
Philipp Kühn
2020-10-23 15:02:52 +02:00
parent e01a0b8484
commit ecadf7ea0a
4 changed files with 32 additions and 8 deletions

View File

@@ -38,3 +38,7 @@ export type Diff<T extends keyof any, U extends keyof any> =
({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T]
export type Overwrite<T, U> = Pick<T, Diff<keyof T, keyof U>> & U;
export type AnyObject = {
[key: string]: any
}

View File

@@ -1,5 +1,6 @@
import { Node, Mark } from 'prosemirror-model'
import { ExtensionAttribute } from '../types'
import mergeAttributes from './mergeAttributes'
export default function getRenderedAttributes(nodeOrMark: Node | Mark, extensionAttributes: ExtensionAttribute[]): { [key: string]: any } {
return extensionAttributes
@@ -9,10 +10,6 @@ export default function getRenderedAttributes(nodeOrMark: Node | Mark, extension
return item.attribute.renderHTML(nodeOrMark.attrs)
})
.reduce((attributes, attribute) => {
// TODO: add support for "class" and "style" merge
return {
...attributes,
...attribute,
}
return mergeAttributes(attributes, attribute)
}, {})
}

View File

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

View File

@@ -16,7 +16,7 @@ const Paragraph = createNode({
// align: {
// default: 'right',
// renderHTML: attributes => ({
// class: 'global',
// class: 'foo',
// style: `text-align: ${attributes.align}`,
// }),
// },
@@ -31,8 +31,8 @@ const Paragraph = createNode({
// default: '123',
// rendered: true,
// renderHTML: attributes => ({
// class: `foo-${attributes.id}`,
// id: 'foo',
// class: 'bar',
// style: 'color: red',
// }),
// },
// }