feat(core): allow getParentNode to accept resolved pos and pos

This commit is contained in:
Dominik Biedebach 2023-02-26 03:05:40 +01:00
parent efc4ee764b
commit 471bc01746
2 changed files with 21 additions and 5 deletions

View File

@ -75,7 +75,9 @@ export default {
currentNode = this.editor.state.doc.nodeAt(this.editor.state.selection.head - 1) currentNode = this.editor.state.doc.nodeAt(this.editor.state.selection.head - 1)
} }
console.log(getParentNode(currentNode, this.editor)) console.log('byNode', getParentNode(currentNode, this.editor))
console.log('byNumber', getParentNode(this.editor.state.selection.head, this.editor))
console.log('byPos', getParentNode(this.editor.state.selection.$head, this.editor))
}, },
}, },
} }

View File

@ -1,4 +1,4 @@
import { Node } from '@tiptap/pm/model' import { Node, ResolvedPos } from '@tiptap/pm/model'
import { Editor } from '../Editor' import { Editor } from '../Editor'
import { getNodePosition } from './getNodePosition' import { getNodePosition } from './getNodePosition'
@ -8,14 +8,28 @@ import { getNodePosition } from './getNodePosition'
* @param node The ProseMirror node to get the parent of * @param node The ProseMirror node to get the parent of
* @param editor The Tiptap editor instance * @param editor The Tiptap editor instance
*/ */
export const getParentNode = (node: Node, editor: Editor) => { export const getParentNode = (nodeOrPos: Node | ResolvedPos | number, editor: Editor) => {
const pos = getNodePosition(node, editor) let currentNode: Node | null = null
if (typeof nodeOrPos === 'number') {
currentNode = editor.state.doc.nodeAt(nodeOrPos)
} else if (nodeOrPos instanceof ResolvedPos) {
currentNode = editor.state.doc.nodeAt(nodeOrPos.pos)
} else {
currentNode = nodeOrPos
}
if (!currentNode) {
return null
}
const pos = getNodePosition(currentNode, editor)
// if the position is already 1, the next depth will be 0 (doc) // if the position is already 1, the next depth will be 0 (doc)
// since text nodes don't increase the depth, we will need to check if // since text nodes don't increase the depth, we will need to check if
// the current node has children and if not, we'll check on depth 1 // the current node has children and if not, we'll check on depth 1
// otherwise we can just go with depth - 1 // otherwise we can just go with depth - 1
if (pos.depth === 1 && !node.childCount) { if (pos.depth === 1 && !currentNode.childCount) {
return pos.node(1) return pos.node(1)
} }