From 156f0e6773564b9df63ceba1be8058de865f01e5 Mon Sep 17 00:00:00 2001 From: Dylan Schiemann Date: Mon, 25 Jul 2022 16:26:50 -0500 Subject: [PATCH] Get node performance list normalization (#1707) * improve performance of list normalizations * add changeset * fix return type * better error handling * better error handling, take 3 --- .changeset/curvy-clocks-knock.md | 5 +++++ packages/core/src/slate/node/getNode.ts | 19 ++++++++++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 .changeset/curvy-clocks-knock.md diff --git a/.changeset/curvy-clocks-knock.md b/.changeset/curvy-clocks-knock.md new file mode 100644 index 0000000000..1c878b745c --- /dev/null +++ b/.changeset/curvy-clocks-knock.md @@ -0,0 +1,5 @@ +--- +'@udecode/plate-core': patch +--- + +improve performance of list normalizations diff --git a/packages/core/src/slate/node/getNode.ts b/packages/core/src/slate/node/getNode.ts index 40fc6a9bf5..dffd54041f 100644 --- a/packages/core/src/slate/node/getNode.ts +++ b/packages/core/src/slate/node/getNode.ts @@ -1,18 +1,31 @@ -import { Node, Path } from 'slate'; +import { Path } from 'slate'; +import { isText } from '../text'; import { NodeOf, TNode } from './TNode'; /** * Get the descendant node referred to by a specific path. * If the path is an empty array, it refers to the root node itself. * If the node is not found, return null. + * Based on Slate get and has, performance optimization without overhead of + * stringify on throwing */ export const getNode = , R extends TNode = TNode>( root: R, path: Path ) => { try { - return Node.get(root, path) as N; - } catch (err) { + for (let i = 0; i < path.length; i++) { + const p = path[i]; + + if (isText(root) || !root.children[p]) { + return null; + } + + root = root.children[p] as R; + } + + return root as N; + } catch (e) { return null; } };