Skip to content

Commit

Permalink
Fixed regression in #4208 where normalization on empty block nodes co…
Browse files Browse the repository at this point in the history
…uld not be overridden (#4431)
  • Loading branch information
TheSpyder authored Aug 11, 2021
1 parent 6f47cbb commit 55ff8f0
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/popular-ways-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate': minor
---

Fixed regression in #4208 where normalization on empty block nodes could not be overridden
18 changes: 10 additions & 8 deletions packages/slate/src/interfaces/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -997,16 +997,18 @@ export const Editor: EditorInterface = {
*/
for (const dirtyPath of getDirtyPaths(editor)) {
if (Node.has(editor, dirtyPath)) {
const [node, _] = Editor.node(editor, dirtyPath)
const entry = Editor.node(editor, dirtyPath)
const [node, _] = entry

/*
The default normalizer inserts an empty text node in this scenario, but it can be customised.
So there is some risk here.
// Add a text child to elements with no children.
// This is safe to do in any order, by definition it can't cause other paths to change.
As long as the normalizer only inserts child nodes for this case it is safe to do in any order;
by definition adding children to an empty node can't cause other paths to change.
*/
if (Element.isElement(node) && node.children.length === 0) {
const child = { text: '' }
Transforms.insertNodes(editor, child, {
at: dirtyPath.concat(0),
voids: true,
})
editor.normalizeNode(entry)
}
}
}
Expand Down
40 changes: 40 additions & 0 deletions packages/slate/test/normalization/block/insert-custom-block.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/** @jsx jsx */
import { jsx } from '../..'
import { Editor, Element, Transforms } from 'slate'

export const input = (
<editor>
<element type="body" />
</editor>
)

// patch in a custom normalizer that inserts empty paragraphs in the body instead of text nodes
// this test also verifies the new node itself is also normalized, because it's inserting a non-normalized node
const editor = (input as unknown) as Editor
const defaultNormalize = editor.normalizeNode
editor.normalizeNode = entry => {
const [node, path] = entry
if (
Element.isElement(node) &&
node.children.length === 0 &&
(node as any).type === 'body'
) {
const child = { type: 'paragraph', children: [] }
Transforms.insertNodes(editor, child, {
at: path.concat(0),
voids: true,
})
} else {
defaultNormalize(entry)
}
}

export const output = (
<editor>
<element type="body">
<element type="paragraph">
<text />
</element>
</element>
</editor>
)

0 comments on commit 55ff8f0

Please sign in to comment.