feat: add updateAttributes() command, deprecate updateNodeAttributes(), fix #254

This commit is contained in:
Philipp Kühn
2021-04-07 21:17:02 +02:00
parent e61b2a51ed
commit aac32b4df6
5 changed files with 73 additions and 2 deletions

View File

@@ -0,0 +1,66 @@
import { NodeType, MarkType } from 'prosemirror-model'
import getNodeType from '../helpers/getNodeType'
import getMarkType from '../helpers/getMarkType'
import getSchemaTypeNameByName from '../helpers/getSchemaTypeNameByName'
import { AnyObject, Command, RawCommands } from '../types'
declare module '@tiptap/core' {
interface Commands {
updateAttributes: {
/**
* Update attributes of a node or mark.
*/
updateAttributes: (typeOrName: string | NodeType | MarkType, attributes: AnyObject) => Command,
}
}
}
export const updateAttributes: RawCommands['updateAttributes'] = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
let nodeType: NodeType | null = null
let markType: MarkType | null = null
const schemaType = getSchemaTypeNameByName(
typeof typeOrName === 'string'
? typeOrName
: typeOrName.name,
state.schema,
)
if (!schemaType) {
return false
}
if (schemaType === 'node') {
nodeType = getNodeType(typeOrName as NodeType, state.schema)
}
if (schemaType === 'mark') {
markType = getMarkType(typeOrName as MarkType, state.schema)
}
if (dispatch) {
tr.selection.ranges.forEach(range => {
state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
if (nodeType && nodeType === node.type) {
tr.setNodeMarkup(pos, undefined, {
...node.attrs,
...attributes,
})
}
if (markType && node.marks.length) {
node.marks.forEach(mark => {
if (markType === mark.type) {
tr.addMark(pos, pos + node.nodeSize, markType.create({
...mark.attrs,
...attributes,
}))
}
})
}
})
})
}
return true
}