From fc4792d3ca485a136627beb719febe4722774683 Mon Sep 17 00:00:00 2001 From: Jonas Carlsen Date: Mon, 5 May 2025 10:17:22 +0200 Subject: [PATCH] feat: remove all block elements inside heading --- .../__tests__/headingNormalizer-test.ts | 47 +++++++++++++++++++ .../src/plugins/heading/headingPlugin.ts | 22 +++++---- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/packages/editor/src/plugins/heading/__tests__/headingNormalizer-test.ts b/packages/editor/src/plugins/heading/__tests__/headingNormalizer-test.ts index f3fd6c8744..3e6cdaf222 100644 --- a/packages/editor/src/plugins/heading/__tests__/headingNormalizer-test.ts +++ b/packages/editor/src/plugins/heading/__tests__/headingNormalizer-test.ts @@ -171,3 +171,50 @@ test("remove bold marker on header", () => { editor.normalize({ force: true }); expect(editor.children).toEqual(expectedValue); }); + +test("removes invalid elements from heading children", () => { + const editorValue: Descendant[] = [ + { + type: SECTION_ELEMENT_TYPE, + children: [ + { + type: PARAGRAPH_ELEMENT_TYPE, + children: [{ text: "" }], + }, + { + type: HEADING_ELEMENT_TYPE, + level: 2, + children: [{ text: "Test" }, { text: "Paragraf" }, { text: "Test 2" }], + }, + { + type: PARAGRAPH_ELEMENT_TYPE, + children: [{ text: "" }], + }, + ], + }, + ]; + + const expectedValue: Descendant[] = [ + { + type: SECTION_ELEMENT_TYPE, + children: [ + { + type: PARAGRAPH_ELEMENT_TYPE, + children: [{ text: "" }], + }, + { + type: HEADING_ELEMENT_TYPE, + level: 2, + children: [{ text: "TestParagrafTest 2" }], + }, + { + type: PARAGRAPH_ELEMENT_TYPE, + children: [{ text: "" }], + }, + ], + }, + ]; + editor.children = editorValue; + editor.normalize({ force: true }); + expect(editor.children).toEqual(expectedValue); +}); diff --git a/packages/editor/src/plugins/heading/headingPlugin.ts b/packages/editor/src/plugins/heading/headingPlugin.ts index 79587527ed..f1f0bfccfb 100644 --- a/packages/editor/src/plugins/heading/headingPlugin.ts +++ b/packages/editor/src/plugins/heading/headingPlugin.ts @@ -37,15 +37,21 @@ export const headingPlugin = createPlugin({ return true; } - const boldEntries = Array.from(editor.nodes({ match: (n) => Text.isText(n) && !!n.bold }), (n) => n); - if (boldEntries.length) { - logger.log("Removing bold from nodes within heading."); - editor.withoutNormalizing(() => { - boldEntries.forEach(([_, path]) => { - Transforms.setNodes(editor, { bold: undefined }, { at: path }); - }); + for (const [index, child] of node.children.entries()) { + if (Text.isText(child)) { + if (child.bold) { + logger.log("Removing bold from text within heading"); + Transforms.setNodes(editor, { bold: undefined }, { at: path.concat(index) }); + return true; + } + continue; + } + + if (!editor.isInline(child)) { + logger.log("Heading contains block element, unwrapping."); + Transforms.unwrapNodes(editor, { at: path.concat(index) }); return true; - }); + } } return false;