fix: preserve attributes of set node

This commit is contained in:
Armando Guarino 2024-10-29 13:49:21 +01:00
parent f029d9228d
commit 48cba5493a
2 changed files with 14 additions and 2 deletions

View File

@ -0,0 +1,5 @@
---
"@tiptap/core": patch
---
preserve existing node attributes when running setNode

View File

@ -21,6 +21,13 @@ declare module '@tiptap/core' {
export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => { export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
const type = getNodeType(typeOrName, state.schema) const type = getNodeType(typeOrName, state.schema)
let attributesToCopy: Record<string, any> | undefined
if (state.selection.$anchor.sameParent(state.selection.$head)) {
// only copy attributes if the selection is pointing to a node of the same type
attributesToCopy = state.selection.$anchor.parent.attrs
}
// TODO: use a fallback like insertContent? // TODO: use a fallback like insertContent?
if (!type.isTextblock) { if (!type.isTextblock) {
console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.') console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.')
@ -32,7 +39,7 @@ export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) =>
chain() chain()
// try to convert node to default node if needed // try to convert node to default node if needed
.command(({ commands }) => { .command(({ commands }) => {
const canSetBlock = setBlockType(type, attributes)(state) const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state)
if (canSetBlock) { if (canSetBlock) {
return true return true
@ -41,7 +48,7 @@ export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) =>
return commands.clearNodes() return commands.clearNodes()
}) })
.command(({ state: updatedState }) => { .command(({ state: updatedState }) => {
return setBlockType(type, attributes)(updatedState, dispatch) return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch)
}) })
.run() .run()
) )