tiptap/packages/core/src/commands/updateNodeAttributes.ts

32 lines
869 B
TypeScript
Raw Normal View History

import { NodeType } from 'prosemirror-model'
2020-11-30 16:42:53 +08:00
import getNodeType from '../helpers/getNodeType'
2021-02-10 16:59:35 +08:00
import { AnyObject, Command, Commands } from '../types'
2020-11-05 05:38:52 +08:00
2021-02-11 01:05:02 +08:00
declare module '@tiptap/core' {
2021-02-16 18:27:58 +08:00
interface AllCommands {
updateNodeAttributes: {
/**
* Update attributes of a node.
*/
updateNodeAttributes: (typeOrName: string | NodeType, attributes: AnyObject) => Command,
}
2021-02-11 01:05:02 +08:00
}
}
2021-02-10 16:59:35 +08:00
export const updateNodeAttributes: Commands['updateNodeAttributes'] = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
const type = getNodeType(typeOrName, state.schema)
2020-11-05 05:38:52 +08:00
const { selection } = tr
const { from, to } = selection
state.doc.nodesBetween(from, to, (node, pos) => {
if (node.type === type && dispatch) {
tr.setNodeMarkup(pos, undefined, {
...node.attrs,
...attributes,
})
2020-11-05 05:38:52 +08:00
}
})
return true
}