70 %

Toast is in Beta!Learn more →

Chris Biscardi

Take advantage of SlateJS Normalizations

SlateJS offers a wide variety of low level methods to insert, remove, or otherwise modify nodes, text, and node contents. normalizeNode may be one of the most important.

Consider the following case, where we want to render headings at different levels depending on the number of # characters at the beginning of the string. We could take a first approach that uses insertText.

insert insertText code here later

This works just fine, but we're doing some weird checking of selection offsets, checking to see whether the selection is collapsed, and other code that looks a bit brittle.

Also check out the ensureHeadingDepth function. Because Slate's hooks operate on every node type, we have to do a bunch of manual checks to see if the current node or parent nodes are paragraphs, headings, or text, etc. Depending on the type we perform different actions by setNodesing properties.

insert ensureHeading code here later