From 073f18478264e74da414899de7d53d66eeb8a25c Mon Sep 17 00:00:00 2001 From: Mirone Date: Sat, 24 Aug 2024 23:50:32 +0800 Subject: [PATCH] chore: optimize --- .../src/__internal__/select-node-by-dom.ts | 71 ++++++++++--------- 1 file changed, 38 insertions(+), 33 deletions(-) diff --git a/packages/plugins/plugin-block/src/__internal__/select-node-by-dom.ts b/packages/plugins/plugin-block/src/__internal__/select-node-by-dom.ts index 2ee08ba6e08..e45d07a5e73 100644 --- a/packages/plugins/plugin-block/src/__internal__/select-node-by-dom.ts +++ b/packages/plugins/plugin-block/src/__internal__/select-node-by-dom.ts @@ -8,39 +8,44 @@ export function selectRootNodeByDom(view: EditorView, coords: { x: number, y: nu if (!root) return null - const pos = view.posAtCoords({ - left: coords.x, - top: coords.y, - })?.inside - if (pos == null || pos < 0) - return null - - let $pos = view.state.doc.resolve(pos) - let node = view.state.doc.nodeAt(pos) - let element = view.nodeDOM(pos) as HTMLElement | null - - const filter = (needLookup: boolean) => { - const checkDepth = $pos.depth >= 1 && $pos.index($pos.depth) === 0 - const shouldLookUp = needLookup || checkDepth - - if (!shouldLookUp) - return - - const ancestorPos = $pos.before($pos.depth) - node = view.state.doc.nodeAt(ancestorPos) - element = view.nodeDOM(ancestorPos) as HTMLElement | null - $pos = view.state.doc.resolve(ancestorPos) - - if (!filterNodes($pos, node!)) - filter(true) + try { + const pos = view.posAtCoords({ + left: coords.x, + top: coords.y, + })?.inside + if (pos == null || pos < 0) + return null + + let $pos = view.state.doc.resolve(pos) + let node = view.state.doc.nodeAt(pos) + let element = view.nodeDOM(pos) as HTMLElement | null + + const filter = (needLookup: boolean) => { + const checkDepth = $pos.depth >= 1 && $pos.index($pos.depth) === 0 + const shouldLookUp = needLookup || checkDepth + + if (!shouldLookUp) + return + + const ancestorPos = $pos.before($pos.depth) + node = view.state.doc.nodeAt(ancestorPos) + element = view.nodeDOM(ancestorPos) as HTMLElement | null + $pos = view.state.doc.resolve(ancestorPos) + + if (!filterNodes($pos, node!)) + filter(true) + } + + // If filterNodes returns false, we should look up the parent node. + const filterResult = filterNodes($pos, node!) + filter(!filterResult) + + if (!element || !node) + return null + + return { node, $pos, el: element } } - - // If filterNodes returns false, we should look up the parent node. - const filterResult = filterNodes($pos, node!) - filter(!filterResult) - - if (!element || !node) + catch { return null - - return { node, $pos, el: element } + } }