Skip to content

Commit

Permalink
Merge pull request #5781 from ueberdosis/preserve-attributes-of-set-node
Browse files Browse the repository at this point in the history
fix: preserve attributes of set node
  • Loading branch information
guarmo authored Oct 29, 2024
2 parents d2f366d + 48cba54 commit 4874933
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 13 deletions.
5 changes: 5 additions & 0 deletions .changeset/chatty-pianos-learn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tiptap/core": patch
---

preserve existing node attributes when running setNode
11 changes: 0 additions & 11 deletions docs/api/utilities.md

This file was deleted.

11 changes: 9 additions & 2 deletions packages/core/src/commands/setNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ declare module '@tiptap/core' {
export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
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?
if (!type.isTextblock) {
console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.')
Expand All @@ -32,7 +39,7 @@ export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) =>
chain()
// try to convert node to default node if needed
.command(({ commands }) => {
const canSetBlock = setBlockType(type, attributes)(state)
const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state)

if (canSetBlock) {
return true
Expand All @@ -41,7 +48,7 @@ export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) =>
return commands.clearNodes()
})
.command(({ state: updatedState }) => {
return setBlockType(type, attributes)(updatedState, dispatch)
return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch)
})
.run()
)
Expand Down

0 comments on commit 4874933

Please sign in to comment.