From 4470f370570ed1f2dce8b4b58d6117d3a87fa6c0 Mon Sep 17 00:00:00 2001 From: John Costa <69081170+JohnCosta27@users.noreply.github.com> Date: Tue, 2 Apr 2024 00:19:54 +0100 Subject: [PATCH] feat(normalize-node): Adding `children` field to prevent erronous nodes from breaking notebooks. (#5620) * FEAT: Adding children array to erronous node to prevent various `children undefined` errors * CHORE: Adding changeset --- .changeset/lazy-radios-smile.md | 5 +++++ packages/slate/src/core/normalize-node.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 .changeset/lazy-radios-smile.md diff --git a/.changeset/lazy-radios-smile.md b/.changeset/lazy-radios-smile.md new file mode 100644 index 000000000..99a73769b --- /dev/null +++ b/.changeset/lazy-radios-smile.md @@ -0,0 +1,5 @@ +--- +'slate': patch +--- + +Making `normalizeNode` capable of normalizing erronous nodes, making slate more resilient. diff --git a/packages/slate/src/core/normalize-node.ts b/packages/slate/src/core/normalize-node.ts index 284f9c3cf..467f96b3b 100644 --- a/packages/slate/src/core/normalize-node.ts +++ b/packages/slate/src/core/normalize-node.ts @@ -75,6 +75,19 @@ export const normalizeNode: WithEditorFirstArg = ( } } } else { + // If the child is not a text node, and doesn't have a `children` field, + // then we have an invalid node that will upset slate. + // + // eg: `{ type: 'some_node' }`. + // + // To prevent slate from breaking, we can add the `children` field, + // and now that it is valid, we can to many more operations easily, + // such as extend normalizers to fix erronous structure. + if (!Text.isText(child) && !('children' in child)) { + const elementChild = child as Element + elementChild.children = [] + } + // Merge adjacent text nodes that are empty or match. if (prev != null && Text.isText(prev)) { if (Text.equals(child, prev, { loose: true })) {