2020-10-25 05:53:56 +08:00
|
|
|
import { ParseRule } from 'prosemirror-model'
|
|
|
|
import { ExtensionAttribute } from '../types'
|
2020-11-01 06:35:30 +08:00
|
|
|
import fromString from './fromString'
|
2020-10-25 05:53:56 +08:00
|
|
|
|
2020-10-27 20:19:23 +08:00
|
|
|
/**
|
|
|
|
* This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).
|
|
|
|
* Cancels when `getAttrs` returned `false`.
|
|
|
|
* @param parseRule ProseMirror ParseRule
|
|
|
|
* @param extensionAttributes List of attributes to inject
|
|
|
|
*/
|
2020-10-25 05:53:56 +08:00
|
|
|
export default function injectExtensionAttributesToParseRule(parseRule: ParseRule, extensionAttributes: ExtensionAttribute[]): ParseRule {
|
|
|
|
if (parseRule.style) {
|
|
|
|
return parseRule
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...parseRule,
|
|
|
|
getAttrs: node => {
|
|
|
|
const oldAttributes = parseRule.getAttrs
|
|
|
|
? parseRule.getAttrs(node)
|
|
|
|
: parseRule.attrs
|
|
|
|
|
|
|
|
if (oldAttributes === false) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
const newAttributes = extensionAttributes
|
|
|
|
.filter(item => item.attribute.rendered)
|
|
|
|
.reduce((items, item) => {
|
|
|
|
const attributes = item.attribute.parseHTML
|
2020-10-27 21:53:08 +08:00
|
|
|
? item.attribute.parseHTML(node as HTMLElement) || {}
|
2020-10-25 05:53:56 +08:00
|
|
|
: {
|
2020-11-01 06:35:30 +08:00
|
|
|
[item.name]: fromString((node as HTMLElement).getAttribute(item.name)),
|
2020-10-25 05:53:56 +08:00
|
|
|
}
|
|
|
|
|
2020-10-27 03:04:55 +08:00
|
|
|
const filteredAttributes = Object.fromEntries(Object.entries(attributes)
|
|
|
|
.filter(([, value]) => value !== undefined && value !== null))
|
|
|
|
|
2020-10-25 05:53:56 +08:00
|
|
|
return {
|
|
|
|
...items,
|
2020-10-27 03:04:55 +08:00
|
|
|
...filteredAttributes,
|
2020-10-25 05:53:56 +08:00
|
|
|
}
|
|
|
|
}, {})
|
|
|
|
|
|
|
|
return { ...oldAttributes, ...newAttributes }
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|