From 471bc01746e06050015c5be538e8b89b1eb65d92 Mon Sep 17 00:00:00 2001 From: Dominik Biedebach Date: Sun, 26 Feb 2023 03:05:40 +0100 Subject: [PATCH] feat(core): allow getParentNode to accept resolved pos and pos --- demos/src/Helpers/GetParentNode/Vue/index.vue | 4 +++- packages/core/src/helpers/getParentNode.ts | 22 +++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/demos/src/Helpers/GetParentNode/Vue/index.vue b/demos/src/Helpers/GetParentNode/Vue/index.vue index 38a41815a..fe0b4f231 100644 --- a/demos/src/Helpers/GetParentNode/Vue/index.vue +++ b/demos/src/Helpers/GetParentNode/Vue/index.vue @@ -75,7 +75,9 @@ export default { 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)) }, }, } diff --git a/packages/core/src/helpers/getParentNode.ts b/packages/core/src/helpers/getParentNode.ts index 6add3fe86..0daa81c52 100644 --- a/packages/core/src/helpers/getParentNode.ts +++ b/packages/core/src/helpers/getParentNode.ts @@ -1,4 +1,4 @@ -import { Node } from '@tiptap/pm/model' +import { Node, ResolvedPos } from '@tiptap/pm/model' import { Editor } from '../Editor' import { getNodePosition } from './getNodePosition' @@ -8,14 +8,28 @@ import { getNodePosition } from './getNodePosition' * @param node The ProseMirror node to get the parent of * @param editor The Tiptap editor instance */ -export const getParentNode = (node: Node, editor: Editor) => { - const pos = getNodePosition(node, editor) +export const getParentNode = (nodeOrPos: Node | ResolvedPos | number, editor: 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) // 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 // otherwise we can just go with depth - 1 - if (pos.depth === 1 && !node.childCount) { + if (pos.depth === 1 && !currentNode.childCount) { return pos.node(1) }